From 69d7681a41d276a62c8c09d55cbd808a5285a96b Mon Sep 17 00:00:00 2001 From: rendotdev <294850895+rendotdev@users.noreply.github.com> Date: Wed, 15 Jul 2026 09:22:12 -0400 Subject: [PATCH 1/2] Simplify tool definitions and add migration guidance --- AGENTS.md | 1 + README.md | 1 + src/agents/instructions.ts | 1 + src/application/cli/cli-application.ts | 27 ++++ src/cli.test.ts | 79 ++++++++++++ src/generated/agent/agent-instruction-sync.ts | 12 +- src/generated/runtime/runtime-support.ts | 94 ++++++++++++-- .../tool/tool-runtime-instruction-sync.ts | 25 +++- src/runtime/support.test.ts | 103 +++++++++++++++- src/tools/domain/tool-api.ts | 1 + src/tools/domain/tool-types.ts | 69 +++++++++-- src/tools/loading/tool-loader.ts | 33 +++-- src/tools/management/tool-files.ts | 27 ++-- src/tools/migration/tool-api-migration.ts | 116 ++++++++++++++++++ src/tools/presentation/help-topics.ts | 6 +- src/tools/run.test.ts | 2 +- src/tools/sdk/tool-sdk.ts | 28 ++++- .../fixtures/distribution/collection-tool.ts | 3 +- 18 files changed, 560 insertions(+), 68 deletions(-) create mode 100644 src/tools/domain/tool-api.ts create mode 100644 src/tools/migration/tool-api-migration.ts diff --git a/AGENTS.md b/AGENTS.md index 72ed458..2eba2c5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,6 +17,7 @@ The `rig` CLI is installed on this machine. It is _your_ CLI. You own its variou - Run `rig remove ` to remove a local tool. - Run `rig cron --help` to schedule and manage tool commands. - Run `rig typecheck ` to validate a tool's TypeScript and runtime types. +- Run `rig migrate` after updates to inspect tool API compatibility and get exact agent migration instructions. - Run `rig env KEY=VALUE` to configure tool secrets/settings; run `rig env remove KEY` to remove them. - Run `rig list` to discover tools and available `rig run ...` commands. - Run `rig help ` for concept docs (collections, cache, kv, db, env, log, shell, run, tool, args, paths). diff --git a/README.md b/README.md index 6214d1f..10a08d4 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,7 @@ The `rig` CLI is installed on this machine. It is _your_ CLI. You own its variou - Run `rig remove ` to remove a local tool. - Run `rig cron --help` to schedule and manage tool commands. - Run `rig typecheck ` to validate a tool's TypeScript and runtime types. +- Run `rig migrate` after updates to inspect tool API compatibility and get exact agent migration instructions. - Run `rig env KEY=VALUE` to configure tool secrets/settings; run `rig env remove KEY` to remove them. - Run `rig list` to discover tools and available `rig run ...` commands. - Run `rig help ` for concept docs (collections, cache, kv, db, env, log, shell, run, tool, args, paths). diff --git a/src/agents/instructions.ts b/src/agents/instructions.ts index 0d69c69..afe2ca7 100644 --- a/src/agents/instructions.ts +++ b/src/agents/instructions.ts @@ -7,6 +7,7 @@ export const RigAgentInstructions = `The \`rig\` CLI is installed on this machin - Run \`rig remove \` to remove a local tool. - Run \`rig cron --help\` to schedule and manage tool commands. - Run \`rig typecheck \` to validate a tool's TypeScript and runtime types. +- Run \`rig migrate\` after updates to inspect tool API compatibility and get exact agent migration instructions. - Run \`rig env KEY=VALUE\` to configure tool secrets/settings; run \`rig env remove KEY\` to remove them. - Run \`rig list\` to discover tools and available \`rig run ...\` commands. - Run \`rig help \` for concept docs (collections, cache, kv, db, env, log, shell, run, tool, args, paths). diff --git a/src/application/cli/cli-application.ts b/src/application/cli/cli-application.ts index e3f5f72..c450c08 100644 --- a/src/application/cli/cli-application.ts +++ b/src/application/cli/cli-application.ts @@ -49,6 +49,7 @@ export class CliApplicationClass { this.configureRunCommand(); this.configureCronCommands(); this.configureTypecheckCommand(); + this.configureMigrateCommand(); this.configureDevCommands(); this.configureUpdateCommand(); this.program @@ -350,6 +351,22 @@ export class CliApplicationClass { }); } + private configureMigrateCommand(): void { + this.program + .command("migrate") + .description("Inspect local tools for Rig tool API migrations.") + .option("--json", "Print the migration report as JSON.") + .action(async (commandOptions: { json?: boolean }) => { + const { ToolApiMigrationServiceClass } = + await import("../../tools/migration/tool-api-migration"); + const service = new ToolApiMigrationServiceClass(this.pathOptions(), {}); + const report = await service.inspect(); + if (commandOptions.json) this.printJson(report); + else console.log(service.renderCli({ report })); + process.exitCode = report.unsupported.length > 0 ? 2 : 0; + }); + } + /* v8 ignore next 20 */ private configureUpdateCommand(): void { this.program @@ -493,6 +510,7 @@ export class CliApplicationClass { console.log("\nNext steps:"); console.log(" rig list"); console.log('\nRun "rig doctor" if you want to verify your setup.'); + await this.printToolApiMigrationNotice(); await this.printUpdateNotice(currentVersion); } @@ -540,6 +558,7 @@ export class CliApplicationClass { } console.log(`Tools: ${tools.length}`); console.log("\nStatus: OK"); + await this.printToolApiMigrationNotice(); await this.printUpdateNotice(this.version()); } @@ -574,6 +593,14 @@ export class CliApplicationClass { }); } + private async printToolApiMigrationNotice(): Promise { + const { ToolApiMigrationServiceClass } = + await import("../../tools/migration/tool-api-migration"); + const service = new ToolApiMigrationServiceClass(this.pathOptions(), {}); + const report = await service.inspect(); + if (!report.ready) console.log(`\n${service.renderCli({ report })}`); + } + private requestGeneratedSync(): void { this.generatedSyncRequested = true; } diff --git a/src/cli.test.ts b/src/cli.test.ts index 798064c..d73378f 100644 --- a/src/cli.test.ts +++ b/src/cli.test.ts @@ -236,6 +236,60 @@ describe("cli application", () => { expect(await cli.run(["list"])).toContain("No Rig tools found."); }); + test("reports versioned tool API migrations with an agent-ready prompt", async () => { + const home = await workspaces.create(); + const cli = new CliHarness(home); + await new ToolCreatorClass({ homeDir: home }).create("current"); + + expect(await cli.run(["migrate"])).toContain("All tools use Rig tool API v2."); + + const legacyDir = join(home, "rig", "tools", "legacy"); + await mkdir(legacyDir, { recursive: true }); + await writeFile( + join(legacyDir, "index.rig.ts"), + `export default (rig) => rig.defineTool({ + name: "legacy", + description: "Legacy tool.", + commands: { + read: rig.defineCommand({ + description: "Read.", + input: rig.z.object({}), + output: rig.z.object({ ok: rig.z.boolean() }), + run: async () => ({ ok: true }), + }), + }, +}); +`, + "utf8", + ); + + cli.logs.length = 0; + const prompt = await cli.run(["migrate"]); + expect(prompt).toContain("Rig tool migration required"); + expect(prompt).toContain("legacy: v1 to v2"); + expect(prompt).toContain("Remove the redundant `name`"); + expect(prompt).toContain("`commands` as `(command) => ({ ... })`"); + expect(prompt).toContain("rig typecheck "); + + cli.logs.length = 0; + const report = await cli.run(["migrate", "--json"]); + expect(report).toContain('"currentVersion": 2'); + expect(report).toContain('"name": "legacy"'); + + const futureDir = join(home, "rig", "tools", "future"); + await mkdir(futureDir, { recursive: true }); + await writeFile( + join(futureDir, "index.rig.ts"), + "// rig:tool-api-version 3\nexport default {};\n", + "utf8", + ); + cli.logs.length = 0; + const unsupported = await cli.run(["migrate"]); + expect(unsupported).toContain("newer API than this Rig installation supports"); + expect(unsupported).toContain("future: v3"); + expect(process.exitCode).toBe(2); + }); + test("syncs agent instruction files after commands", async () => { const home = await workspaces.create(); const project = join(home, "project"); @@ -259,6 +313,31 @@ describe("cli application", () => { expect(synced).toContain("The `rig` CLI is installed on this machine. It is *your* CLI."); expect(synced).toContain("sample.example"); + const legacyDir = join(home, "rig", "tools", "legacy"); + await mkdir(legacyDir, { recursive: true }); + await writeFile( + join(legacyDir, "index.rig.ts"), + `export default (rig) => rig.defineTool({ + name: "legacy", + description: "Legacy tool.", + commands: { + read: rig.defineCommand({ + description: "Read.", + input: rig.z.object({}), + output: rig.z.object({ ok: rig.z.boolean() }), + run: async () => ({ ok: true }), + }), + }, +}); +`, + "utf8", + ); + expect(await cli.run(["init"])).toContain("Rig tool migration required"); + const migratedInstructions = await readFile(join(project, "AGENTS.md"), "utf8"); + expect(migratedInstructions).toContain("### Rig tool migration required"); + expect(migratedInstructions).toContain("legacy: v1 to v2"); + + expect(await cli.run(["remove", "legacy"])).toContain("Removed tool legacy"); expect(await cli.run(["remove", "sample"])).toContain("Removed tool sample"); const updated = await readFile(join(project, "AGENTS.md"), "utf8"); expect(updated).toContain("No Rig tools found."); diff --git a/src/generated/agent/agent-instruction-sync.ts b/src/generated/agent/agent-instruction-sync.ts index 2720d6c..9329425 100644 --- a/src/generated/agent/agent-instruction-sync.ts +++ b/src/generated/agent/agent-instruction-sync.ts @@ -7,6 +7,7 @@ import { type ConfigOptions } from "../../config/config"; import { RigPathsClass } from "../../config/paths"; import { RigToolEntryFiles } from "../../registry/discover"; import { ToolListServiceClass } from "../../tools/list"; +import { ToolApiMigrationServiceClass } from "../../tools/migration/tool-api-migration"; export type AgentInstructionSyncOptions = ConfigOptions & { cwd?: string; @@ -128,12 +129,14 @@ export class AgentInstructionSyncServiceClass { private readonly cwd: string; private readonly paths: RigPathsClass; private readonly listService: ToolListServiceClass; + private readonly migrationService: ToolApiMigrationServiceClass; private readonly fingerprint: AgentSyncFingerprintClass; constructor(options: AgentInstructionSyncOptions = {}) { this.cwd = resolve(options.cwd ?? process.cwd()); this.paths = new RigPathsClass(options); this.listService = new ToolListServiceClass(options); + this.migrationService = new ToolApiMigrationServiceClass(options, {}); this.fingerprint = new AgentSyncFingerprintClass({ paths: this.paths }); } @@ -151,13 +154,16 @@ export class AgentInstructionSyncServiceClass { }; } + const migrationInstructions = this.migrationService.renderAgentInstructions({ + report: await this.migrationService.inspect(), + }); const updates = await Promise.all( targets.map(async (target) => { /* v8 ignore next 3 */ if (target.scope === "visible" && !(await this.projectHasRegistry())) { return { ...target, changed: await this.removeManagedBlock(target) }; } - const block = this.renderBlock(await this.renderToolList(target)); + const block = this.renderBlock(await this.renderToolList(target), migrationInstructions); return { ...target, changed: await this.upsertManagedBlock(target, block), @@ -237,12 +243,12 @@ export class AgentInstructionSyncServiceClass { return [...targets.values()].toSorted((left, right) => left.path.localeCompare(right.path)); } - renderBlock(toolList: string): string { + renderBlock(toolList: string, migrationInstructions = ""): string { return `${StartMarker} ## Rig local tools -${RigAgentInstructions} +${RigAgentInstructions}${migrationInstructions ? `${migrationInstructions}\n\n` : ""} ### Available Rig tools \`\`\`text diff --git a/src/generated/runtime/runtime-support.ts b/src/generated/runtime/runtime-support.ts index 78b2c9b..6098eef 100644 --- a/src/generated/runtime/runtime-support.ts +++ b/src/generated/runtime/runtime-support.ts @@ -239,7 +239,9 @@ const rigShell = new RigShellRuntimeClass(); export const rig: RigToolKit = { z, - defineTool: (definition) => definition, + defineTool: (definition) => typeof definition.commands === "function" + ? { ...definition, commands: definition.commands((command) => command) } + : definition, defineCommand: (definition) => definition, run: (options) => new RigCommandRunnerRuntimeClass().run(options), $: (strings, ...values) => rigShell.$(strings, ...values), @@ -269,6 +271,42 @@ import type { z } from "zod"; export type RigSchema = z.ZodTypeAny; +export type RigCollectionDefinition = z.ZodObject> = { + schema?: T; + generateId?: (data: z.input) => string; +}; + +export type RigCollectionEntry> = { + id: string; + data: T; + body: string; + createdAt: string; + updatedAt: string; +}; + +export type RigCollectionHandle> = { + readonly name: string; + readonly path: string; + create(entry: { id?: string; data: T; body?: string }): Promise>; + getEntry(id: string): Promise | null>; + update(id: string, patch: { data?: Partial; body?: string }): Promise>; + upsert(entry: { id: string; data: T; body?: string }): Promise<{ id: string; created: boolean }>; + remove(id: string): Promise; + list(options?: { where?: Record; sort?: string; limit?: number; offset?: number }): Promise<{ entries: RigCollectionEntry[]; total: number }>; + search(query: string, options?: { limit?: number }): Promise<{ entries: Array & { snippet: string; rank: number }> }>; + count(where?: Record): Promise; + getCollection(filter?: (entry: RigCollectionEntry) => boolean): Promise[]>; + clear(): Promise; +}; + +export type RigToolCollectionDefinitions = Record; + +export type RigToolCollectionHandles = { + [Name in keyof Collections]: Collections[Name] extends RigCollectionDefinition + ? RigCollectionHandle> + : RigCollectionHandle; +}; + export type RigShellOptions = { cwd?: string; env?: Record; @@ -359,7 +397,11 @@ export type RigToolLogger = { child(bindings: Record): RigToolLogger; }; -export type RigToolRunContext = { +export type RigToolRunContext< + Input, + Env = unknown, + Collections = Record, +> = { input: Input; env: Env; processEnv: NodeJS.ProcessEnv; @@ -369,6 +411,7 @@ export type RigToolRunContext = { cache: RigToolCache; log: RigToolLogger; rig: RigToolKit; + collections: Collections; }; export type RigToolExample = { @@ -382,25 +425,60 @@ export type RigCommandDefinition< Input extends RigSchema = RigSchema, Output extends RigSchema = RigSchema, Env = unknown, + Collections = Record, > = { description: string; input: Input; output: Output; examples?: RigToolExample, z.output>[]; - run: (ctx: RigToolRunContext, Env>) => z.input | Promise>; + run: (ctx: RigToolRunContext, Env, Collections>) => z.input | Promise>; }; -export type RigToolDefinition = { - name: string; +export type RigToolCommandBuilder< + Env, + Collections, +> = ( + definition: RigCommandDefinition, +) => RigCommandDefinition; + +export type RigToolCommandMap = Record>; + +export type RigToolCommandsFactory< + Env, + Collections, + Commands extends RigToolCommandMap, +> = (command: RigToolCommandBuilder) => Commands; + +export type RigToolDefinition< + Env extends RigSchema = RigSchema, + Collections extends RigToolCollectionDefinitions = RigToolCollectionDefinitions, + Commands extends RigToolCommandMap = RigToolCommandMap, +> = { + name?: string; description: string; env?: Env; setupDb?: (db: RigToolDatabase) => void | Promise; - commands: Record>>; + collections?: Collections; + commands: + | Commands + | RigToolCommandsFactory, RigToolCollectionHandles, Commands>; +}; + +export type RigNormalizedToolDefinition< + Env extends RigSchema = RigSchema, + Collections extends RigToolCollectionDefinitions = RigToolCollectionDefinitions, + Commands extends RigToolCommandMap = RigToolCommandMap, +> = Omit, "commands"> & { + commands: Commands; }; export type RigToolKit = { z: typeof z; - defineTool(definition: T): T; + defineTool< + Env extends RigSchema = RigSchema, + Collections extends RigToolCollectionDefinitions = RigToolCollectionDefinitions, + const Commands extends RigToolCommandMap = RigToolCommandMap, + >(definition: RigToolDefinition): RigNormalizedToolDefinition; defineCommand(definition: RigCommandDefinition): RigCommandDefinition; run(options: RigRunOptions): Promise; $(strings: TemplateStringsArray, ...values: unknown[]): Promise; @@ -409,7 +487,7 @@ export type RigToolKit = { shell: RigShell; }; -export type RigToolFactory = (rig: RigToolKit) => RigToolDefinition | Promise; +export type RigToolFactory = (rig: RigToolKit) => RigToolDefinition | Promise>; `; } diff --git a/src/generated/tool/tool-runtime-instruction-sync.ts b/src/generated/tool/tool-runtime-instruction-sync.ts index 959c031..fd24218 100644 --- a/src/generated/tool/tool-runtime-instruction-sync.ts +++ b/src/generated/tool/tool-runtime-instruction-sync.ts @@ -1,6 +1,7 @@ import { readFile, writeFile } from "node:fs/promises"; import type { ConfigOptions } from "../../config/config"; import { ToolDiscoveryServiceClass } from "../../registry/discover"; +import { CurrentRigToolApiVersion } from "../../tools/domain/tool-api"; type BunFileApi = { file(path: string): { text(): Promise }; @@ -19,14 +20,16 @@ export type ToolRuntimeInstructionSyncResult = { const StartMarker = "// rig:runtime-reference:start"; const EndMarker = "// rig:runtime-reference:end"; +const ToolApiVersionMarker = "// rig:tool-api-version"; const RuntimeReference = `Generated by Rig. This block is refreshed automatically. Rig tool runtime: -- Export a default \`RigToolFactory\`: \`const tool: RigToolFactory = (rig) => rig.defineTool({ ... }); export default tool;\`. +- Tool API v2 uses a direct factory export: \`export default (rig: RigToolKit) => rig.defineTool({ ... });\`. +- Rig derives the tool name from its folder. The \`name\` property remains supported for v1 tools. - \`rig.z\` is Zod. Docs: https://zod.dev/ - \`rig.defineTool(definition)\` defines the tool. -- \`rig.defineCommand(definition)\` defines one command with \`{ description, input, output, run }\`. +- Define \`commands\` as \`(command) => ({ ... })\`, then define each command with the bound \`command({ description, input, output, run })\` helper. \`rig.defineCommand\` remains supported for v1 tools. - Use \`rig.z.object({ ... })\` for input/output schemas. - Tools run under Bun with fallback auto-install enabled, so tool files can import npm packages; add explicit package versions when reproducibility matters. Example: \`import sharp from "sharp@0.34.4";\`. - \`rig.run({ command: "tool.command", input })\` runs another registered Rig command and returns its data. @@ -98,9 +101,10 @@ export class ToolRuntimeInstructionSyncServiceClass { return { tools: updates }; } - renderPrefix(): string { + renderPrefix(version = CurrentRigToolApiVersion): string { return [ StartMarker, + `${ToolApiVersionMarker} ${version}`, ...RuntimeReference.trimEnd() .split("\n") .map((line) => (line ? `// ${line}` : "//")), @@ -109,9 +113,13 @@ export class ToolRuntimeInstructionSyncServiceClass { } upsertPrefix(source: string): string { - const withoutExisting = source.replace(this.managedBlockPattern(), "").trimStart(); + const version = this.sourceVersion(source); + const withoutExisting = source + .replace(this.managedBlockPattern(), "") + .replace(/^\/\/ rig:tool-api-version \d+\s*$/gm, "") + .trimStart(); const shebang = withoutExisting.match(/^(#!.*\n)/); - const prefix = this.renderPrefix(); + const prefix = this.renderPrefix(version); const body = shebang ? withoutExisting.slice(shebang[0].length).trimStart() : withoutExisting; const next = [prefix, body.trimEnd()].filter(Boolean).join("\n\n"); return `${shebang?.[0] ?? ""}${next}\n`; @@ -157,6 +165,13 @@ export class ToolRuntimeInstructionSyncServiceClass { ); } + private sourceVersion(source: string): number { + const match = /^\/\/ rig:tool-api-version (\d+)\s*$/m.exec(source); + if (!match) return 1; + const version = Number.parseInt(match[1]!, 10); + return Number.isSafeInteger(version) && version > 0 ? version : 1; + } + private escapeRegExp(value: string): string { return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } diff --git a/src/runtime/support.test.ts b/src/runtime/support.test.ts index d288b2d..0420134 100644 --- a/src/runtime/support.test.ts +++ b/src/runtime/support.test.ts @@ -33,6 +33,7 @@ import { ToolCreatorClass } from "../tools/create"; import { ToolHelpRendererClass, ToolHelpServiceClass } from "../tools/help"; import { ToolInspectorClass } from "../tools/inspect"; import { ToolDefinitionValidatorClass, ToolLoaderClass } from "../tools/loader"; +import { ToolApiMigrationServiceClass } from "../tools/migration/tool-api-migration"; import { ToolRunnerClass } from "../tools/run"; import { ToolRuntimeInstructionSyncServiceClass } from "../tools/runtime-instruction"; import { schemaRenderer } from "../tools/schema"; @@ -106,15 +107,23 @@ describe("coverage support", () => { expect(service.renderPrefix()).toContain("rig.$"); expect(service.renderPrefix()).toContain("context.cache.query"); + expect(service.renderPrefix()).toContain("// rig:tool-api-version 2"); expect(service.upsertPrefix("#!/usr/bin/env bun\nconsole.log(1);\n")).toMatch( /^#!\/usr\/bin\/env bun\n\/\/ rig:runtime-reference:start/, ); + expect(service.upsertPrefix("#!/usr/bin/env bun\nconsole.log(1);\n")).toContain( + "// rig:tool-api-version 1", + ); + expect(service.upsertPrefix("// rig:tool-api-version 0\nconsole.log(1);\n")).toContain( + "// rig:tool-api-version 1", + ); expect(service.upsertPrefix("")).toContain("Rig tool runtime"); const first = await service.sync(); expect(first.tools).toEqual([{ name: "sample", path: created.toolPath, changed: true }]); const synced = await readFile(created.toolPath, "utf8"); expect(synced).toMatch(/^\/\/ rig:runtime-reference:start/); + expect(synced).toContain("// rig:tool-api-version 2"); expect(synced).toContain("Rig tool runtime"); expect(synced).toContain("Bun Shell"); @@ -672,6 +681,8 @@ describe("coverage support", () => { expect(runtimeTypes).toContain("cache: RigToolCache"); expect(runtimeTypes).toContain("log: RigToolLogger"); expect(runtimeTypes).toContain("shell: RigShell"); + expect(runtimeTypes).toContain("collections: Collections"); + expect(runtimeTypes).toContain("collections?: Collections"); await writeFile(join(registry, "tsconfig.json"), "{}\n", "utf8"); await support.ensure([registry]); expect(await readFile(join(registry, "tsconfig.json"), "utf8")).toBe("{}\n"); @@ -882,12 +893,19 @@ describe("coverage support", () => { commands: { echo: validCommand }, }; expect(validator.validateToolDefinition(validTool, "valid")).toBe(validTool); + expect( + validator.validateToolDefinition( + { description: "Derived name.", commands: { echo: validCommand } }, + "derived", + ).name, + ).toBe("derived"); + expect(() => validator.validateToolDefinition({}, undefined)).toThrow("Tool needs a name"); expect(() => validator.validateToolName("")).toThrow("Invalid tool name"); expect(() => validator.validateCommandName("")).toThrow("Invalid command name"); const invalidDefinitions: Array<[unknown, string]> = [ [null, "Tool default export must be an object"], - [{}, "Tool needs a name"], + [{}, "needs a description"], [{ name: "bad-name", description: "x", commands: {} }, "does not match its folder"], [{ name: "valid", description: "", commands: {} }, "needs a description"], [{ name: "valid", description: "x" }, "needs a commands object"], @@ -1180,4 +1198,87 @@ describe("coverage support", () => { }), ).toThrow("Unable to parse generated Rig tool tsconfig."); }); + + test("type-checks v2 env and collection context from a plain command definition", async () => { + const home = await workspaces.create(); + const source = `// rig:tool-api-version 2 +export default (rig: RigToolKit) => rig.defineTool({ + description: "Type-check the complete v2 authoring contract.", + env: rig.z.object({ TOKEN: rig.z.string() }), + collections: { + notes: { schema: rig.z.object({ title: rig.z.string() }) }, + }, + commands: (command) => ({ + add: command({ + description: "Add a note.", + input: rig.z.object({ title: rig.z.string() }), + output: rig.z.object({ title: rig.z.string(), token: rig.z.string() }), + run: async ({ input, env, collections }) => { + const entry = await collections.notes.create({ data: { title: input.title } }); + return { title: entry.data.title, token: env.TOKEN }; + }, + }), + }), +}); +`; + await writeTool(home, "contract", source); + + const typecheck = await new ToolTypecheckServiceClass({ homeDir: home }).typecheck("contract"); + expect(typecheck).toMatchObject({ ok: true, exitCode: 0 }); + const loaded = await new ToolLoaderClass({ homeDir: home }).loadDefinition("contract"); + expect(loaded.definition.name).toBe("contract"); + }); + + test("supports injected tool API migration collaborators", async () => { + const home = await workspaces.create(); + await new ToolCreatorClass({ homeDir: home }).create("current"); + let source = "// rig:tool-api-version 2\n"; + const service = new ToolApiMigrationServiceClass( + { homeDir: home }, + { + discovery: new ToolDiscoveryServiceClass({ homeDir: home }), + readSource: async () => source, + }, + ); + + await expect(service.inspect({ visibleFromPath: home })).resolves.toMatchObject({ + ready: true, + migrations: [], + unsupported: [], + }); + + source = "// rig:tool-api-version 999999999999999999999999\n"; + await expect(service.inspect()).resolves.toMatchObject({ + ready: false, + migrations: [{ fromVersion: 1, toVersion: 2 }], + }); + + expect( + service.renderAgentInstructions({ + report: { + currentVersion: 2, + ready: false, + migrations: [], + unsupported: [{ name: "future", path: "/future", fromVersion: 3, toVersion: 2 }], + }, + }), + ).toContain("newer API than this Rig installation supports"); + + const bunDiscovery = new ToolDiscoveryServiceClass({ homeDir: home }); + vi.spyOn(bunDiscovery, "discover").mockResolvedValue([ + { + name: "bun-source", + registryKind: "base", + registryPath: home, + toolDir: home, + toolPath: join(home, "index.rig.ts"), + }, + ]); + vi.stubGlobal("Bun", { + file: () => ({ text: async () => "// rig:tool-api-version 2\n" }), + }); + await expect( + new ToolApiMigrationServiceClass({ homeDir: home }, { discovery: bunDiscovery }).inspect(), + ).resolves.toMatchObject({ ready: true }); + }); }); diff --git a/src/tools/domain/tool-api.ts b/src/tools/domain/tool-api.ts new file mode 100644 index 0000000..190526b --- /dev/null +++ b/src/tools/domain/tool-api.ts @@ -0,0 +1 @@ +export const CurrentRigToolApiVersion = 2; diff --git a/src/tools/domain/tool-types.ts b/src/tools/domain/tool-types.ts index f386bfc..6860f70 100644 --- a/src/tools/domain/tool-types.ts +++ b/src/tools/domain/tool-types.ts @@ -121,29 +121,82 @@ export type CommandDefinition< Input extends RigSchema = RigSchema, Output extends RigSchema = RigSchema, Env = unknown, + Collections = Record, > = { description: string; input: Input; output: Output; examples?: ToolExample, z.output>[]; - run: (ctx: ToolRunContext, Env>) => MaybePromise>; + run: (ctx: ToolRunContext, Env, Collections>) => MaybePromise>; }; -export type ToolDefinition = { - name: string; +export type ToolCollectionDefinitions = Record; + +export type ToolCollectionHandles = { + [Name in keyof Collections]: Collections[Name] extends CollectionDefinition + ? CollectionHandle> + : CollectionHandle; +}; + +export type ToolCommandBuilder = < + Input extends RigSchema, + Output extends RigSchema, +>( + definition: CommandDefinition, +) => CommandDefinition; + +export type ToolCommandMap = Record>; + +export type ToolCommandsFactory = ( + command: ToolCommandBuilder, +) => Commands; + +export type ToolDefinitionInput< + Env extends RigSchema = RigSchema, + Collections extends ToolCollectionDefinitions = ToolCollectionDefinitions, + Commands extends ToolCommandMap = ToolCommandMap, +> = { + name?: string; description: string; env?: Env; setupDb?: (db: RigToolDatabase) => MaybePromise; - collections?: Record; - commands: Record>>; + collections?: Collections; + commands: + | Commands + | ToolCommandsFactory, ToolCollectionHandles, Commands>; +}; + +export type NormalizedToolDefinitionInput< + Env extends RigSchema = RigSchema, + Collections extends ToolCollectionDefinitions = ToolCollectionDefinitions, + Commands extends ToolCommandMap = ToolCommandMap, +> = Omit, "commands"> & { + commands: Commands; +}; + +export type ToolDefinition = { + name: string; + description: string; + env?: RigSchema; + setupDb?: (db: RigToolDatabase) => MaybePromise; + collections?: ToolCollectionDefinitions; + commands: Record; }; -export type ToolFactory = (rig: RigToolKit) => ToolDefinition | Promise; -export type ToolModuleDefault = ToolDefinition | ToolFactory; +export type ToolFactory = ( + rig: RigToolKit, +) => ToolDefinitionInput | Promise>; +export type ToolModuleDefault = ToolDefinitionInput | ToolDefinition | ToolFactory; export type RigToolKit = { z: typeof z; - defineTool(definition: T): T; + defineTool< + Env extends RigSchema = RigSchema, + Collections extends ToolCollectionDefinitions = ToolCollectionDefinitions, + const Commands extends ToolCommandMap = ToolCommandMap, + >( + definition: ToolDefinitionInput, + ): NormalizedToolDefinitionInput; defineCommand( definition: CommandDefinition, ): CommandDefinition; diff --git a/src/tools/loading/tool-loader.ts b/src/tools/loading/tool-loader.ts index 0e7ce88..6e31565 100644 --- a/src/tools/loading/tool-loader.ts +++ b/src/tools/loading/tool-loader.ts @@ -24,44 +24,46 @@ export class ToolDefinitionValidatorClass { if (!this.isRecord(value)) { throw new RigErrorClass("TOOL_INVALID", "Tool default export must be an object."); } - if (typeof value.name !== "string" || value.name.length === 0) { + const name = + typeof value.name === "string" && value.name.length > 0 ? value.name : expectedName; + if (!name) { throw new RigErrorClass("TOOL_INVALID", "Tool needs a name.", { - expected: "non-empty string", + expected: "non-empty string or a discovered tool folder", }); } - this.validateToolName(value.name); + this.validateToolName(name); - if (expectedName && value.name !== expectedName) { + if (expectedName && name !== expectedName) { throw new RigErrorClass( "TOOL_INVALID", - `Tool name does not match its folder: ${value.name} should be ${expectedName}.`, + `Tool name does not match its folder: ${name} should be ${expectedName}.`, { expectedName, - actualName: value.name, + actualName: name, }, ); } if (typeof value.description !== "string" || value.description.length === 0) { - throw new RigErrorClass("TOOL_INVALID", `Tool ${value.name} needs a description.`, { + throw new RigErrorClass("TOOL_INVALID", `Tool ${name} needs a description.`, { expected: "non-empty string", }); } if (value.setupDb !== undefined && typeof value.setupDb !== "function") { - throw new RigErrorClass("TOOL_INVALID", `Tool ${value.name} setupDb must be a function.`, { + throw new RigErrorClass("TOOL_INVALID", `Tool ${name} setupDb must be a function.`, { expected: "function", }); } if (value.env !== undefined) { - this.validateSchema(value.env, "env", value.name); + this.validateSchema(value.env, "env", name); } if (value.collections !== undefined) { if (!this.isRecord(value.collections)) { - throw new RigErrorClass("TOOL_INVALID", `Tool ${value.name} needs a collections object.`, { + throw new RigErrorClass("TOOL_INVALID", `Tool ${name} needs a collections object.`, { expected: "object", }); } @@ -71,24 +73,21 @@ export class ToolDefinitionValidatorClass { } if (!this.isRecord(value.commands)) { - throw new RigErrorClass("TOOL_INVALID", `Tool ${value.name} needs a commands object.`, { + throw new RigErrorClass("TOOL_INVALID", `Tool ${name} needs a commands object.`, { expected: "object", }); } const entries = Object.entries(value.commands); if (entries.length === 0) { - throw new RigErrorClass( - "TOOL_INVALID", - `Tool ${value.name} must define at least one command.`, - ); + throw new RigErrorClass("TOOL_INVALID", `Tool ${name} must define at least one command.`); } for (const [commandName, command] of entries) { - this.validateCommand(commandName, command, value.name); + this.validateCommand(commandName, command, name); } - return value as ToolDefinition; + return (value.name === name ? value : { ...value, name }) as ToolDefinition; } private validateCommand( diff --git a/src/tools/management/tool-files.ts b/src/tools/management/tool-files.ts index 433c121..75f5094 100644 --- a/src/tools/management/tool-files.ts +++ b/src/tools/management/tool-files.ts @@ -4,6 +4,7 @@ import { join } from "node:path"; import { RigConfigStoreClass, type ConfigOptions } from "../../config/config"; import { RigErrorClass } from "../../errors/RigError"; import { RigToolEntryFiles, ToolDiscoveryServiceClass } from "../../registry/discover"; +import { CurrentRigToolApiVersion } from "../domain/tool-api"; import { ToolLoaderClass } from "../loader"; export type ToolFileResult = { @@ -33,7 +34,7 @@ export class ToolCreatorClass { } await mkdir(toolDir, { recursive: true }); - await writeFile(toolPath, this.generatedToolSource(name), "utf8"); + await writeFile(toolPath, this.generatedToolSource(), "utf8"); return { name, @@ -45,12 +46,12 @@ export class ToolCreatorClass { }; } - private generatedToolSource(name: string): string { - return `const tool: RigToolFactory = (rig) => rig.defineTool({ - name: ${JSON.stringify(name)}, + private generatedToolSource(): string { + return `// rig:tool-api-version ${CurrentRigToolApiVersion} +export default (rig: RigToolKit) => rig.defineTool({ description: "Describe what this tool does.", - commands: { - example: rig.defineCommand({ + commands: (command) => ({ + example: command({ description: "Example command. Replace this with a real command.", input: rig.z.object({ text: rig.z.string().default("example"), @@ -65,23 +66,15 @@ export class ToolCreatorClass { input: { text: "example" }, output: { text: "example" }, }, - { - title: "Pass custom text", - text: "Use this to see how arguments map into command input.", - input: { text: "custom" }, - output: { text: "custom" }, - }, ], - run: async (context) => { + run: async ({ input }) => { return { - text: context.input.text, + text: input.text, }; }, }), - }, + }), }); - -export default tool; `; } } diff --git a/src/tools/migration/tool-api-migration.ts b/src/tools/migration/tool-api-migration.ts new file mode 100644 index 0000000..e850db8 --- /dev/null +++ b/src/tools/migration/tool-api-migration.ts @@ -0,0 +1,116 @@ +import { readFile } from "node:fs/promises"; +import type { ConfigOptions } from "../../config/config"; +import { DomainClass } from "../../domain/domain-class"; +import { ToolDiscoveryServiceClass, type DiscoveredTool } from "../../registry/discover"; +import { CurrentRigToolApiVersion } from "../domain/tool-api"; + +export type ToolApiMigrationEntry = { + name: string; + path: string; + fromVersion: number; + toVersion: number; +}; + +export type ToolApiMigrationReport = { + currentVersion: number; + ready: boolean; + migrations: ToolApiMigrationEntry[]; + unsupported: ToolApiMigrationEntry[]; +}; + +export type ToolApiMigrationServiceDeps = { + discovery?: ToolDiscoveryServiceClass; + readSource?: (path: string) => Promise; +}; + +export class ToolApiMigrationServiceClass extends DomainClass< + ConfigOptions, + ToolApiMigrationServiceDeps +> { + private readonly discovery: ToolDiscoveryServiceClass; + private readonly readSource: (path: string) => Promise; + + public constructor(params: ConfigOptions, deps: ToolApiMigrationServiceDeps) { + super(params, deps); + this.discovery = this.deps.discovery ?? new ToolDiscoveryServiceClass(this.params); + this.readSource = + this.deps.readSource ?? + ((path) => (typeof Bun !== "undefined" ? Bun.file(path).text() : readFile(path, "utf8"))); + } + + public async inspect(params: { visibleFromPath?: string } = {}): Promise { + const tools = await this.discovery.discover(params); + const entries = await Promise.all(tools.map((tool) => this.inspectTool({ tool }))); + const migrations = entries.filter((entry) => entry.fromVersion < entry.toVersion); + const unsupported = entries.filter((entry) => entry.fromVersion > entry.toVersion); + return { + currentVersion: CurrentRigToolApiVersion, + ready: migrations.length === 0 && unsupported.length === 0, + migrations, + unsupported, + }; + } + + public renderAgentInstructions(params: { report: ToolApiMigrationReport }): string { + if (params.report.ready) return ""; + + const lines = ["### Rig tool migration required", ""]; + if (params.report.migrations.length > 0) { + lines.push( + `Migrate these tools to Rig tool API v${params.report.currentVersion}:`, + "", + ...params.report.migrations.map( + (entry) => + `- ${entry.name}: v${entry.fromVersion} to v${entry.toVersion} (${entry.path})`, + ), + "", + "For each tool:", + "", + "1. Export the factory directly as `(rig: RigToolKit) => rig.defineTool({ ... })`.", + "2. Remove the redundant `name`; Rig derives it from the folder.", + "3. Define `commands` as `(command) => ({ ... })` and replace each `rig.defineCommand({ ... })` with `command({ ... })`.", + `4. Set the header to \`// rig:tool-api-version ${params.report.currentVersion}\`.`, + "5. Run `rig typecheck ` and execute the command examples before considering the migration complete.", + ); + } + + if (params.report.unsupported.length > 0) { + lines.push( + "", + "These tools declare a newer API than this Rig installation supports:", + "", + ...params.report.unsupported.map( + (entry) => `- ${entry.name}: v${entry.fromVersion} (${entry.path})`, + ), + "", + "Update Rig before editing or running these tools.", + ); + } + + return lines.join("\n"); + } + + public renderCli(params: { report: ToolApiMigrationReport }): string { + if (params.report.ready) { + return `All tools use Rig tool API v${params.report.currentVersion}.`; + } + return this.renderAgentInstructions(params).replace(/^### /, ""); + } + + private async inspectTool(params: { tool: DiscoveredTool }): Promise { + const source = await this.readSource(params.tool.toolPath); + return { + name: params.tool.name, + path: params.tool.toolPath, + fromVersion: this.sourceVersion({ source }), + toVersion: CurrentRigToolApiVersion, + }; + } + + private sourceVersion(params: { source: string }): number { + const match = /^\/\/ rig:tool-api-version (\d+)\s*$/m.exec(params.source); + if (!match) return 1; + const version = Number.parseInt(match[1]!, 10); + return Number.isSafeInteger(version) && version > 0 ? version : 1; + } +} diff --git a/src/tools/presentation/help-topics.ts b/src/tools/presentation/help-topics.ts index 8738f07..fb77d47 100644 --- a/src/tools/presentation/help-topics.ts +++ b/src/tools/presentation/help-topics.ts @@ -126,10 +126,12 @@ CLI pipelines: title: "Creating Tools", content: `- Tools live at rig-tools//index.rig.ts - Create with \`rig create \` -- Export default a RigToolFactory: \`(rig) => rig.defineTool({...})\` +- Export the factory directly: \`export default (rig: RigToolKit) => rig.defineTool({...})\` +- Rig derives the tool name from its folder +- Define \`commands\` as \`(command) => ({ ... })\` and each command with \`command({...})\` +- \`rig.defineCommand({...})\` remains supported for v1 tools Definition keys: -- \`name\` tool name (matches folder) - \`description\` one-line summary - \`env?\` Zod schema for secrets - \`setupDb?\` migration function for raw sqlite diff --git a/src/tools/run.test.ts b/src/tools/run.test.ts index e798cbb..4d6eeab 100644 --- a/src/tools/run.test.ts +++ b/src/tools/run.test.ts @@ -275,7 +275,7 @@ describe("tool commands", () => { /^Tool: sample\nCommand: example\nRun: rig run sample\.example \[args\.\.\.\]/, ); expect(commandIdHelp).not.toContain("```bash"); - expect(help).toContain("Pass custom text"); + expect(help).toContain("Run the example command"); expect(help).toContain("rig run sample.example"); expect(help).toContain("Input:"); expect(help).toContain("Output:"); diff --git a/src/tools/sdk/tool-sdk.ts b/src/tools/sdk/tool-sdk.ts index e8f0a21..6d049ee 100644 --- a/src/tools/sdk/tool-sdk.ts +++ b/src/tools/sdk/tool-sdk.ts @@ -15,7 +15,10 @@ import { type RigRunOptions, type RigSchema, type RigToolKit, - type ToolDefinition, + type ToolCollectionDefinitions, + type ToolCommandMap, + type ToolDefinitionInput, + type NormalizedToolDefinitionInput, type ToolFactory, type ToolModuleDefault, } from "../types"; @@ -126,7 +129,16 @@ class RigToolKitFactoryClass { const shell = new BunRigShellClass(); return { z, - defineTool: (definition: T) => definition, + defineTool: < + Env extends RigSchema = RigSchema, + Collections extends ToolCollectionDefinitions = ToolCollectionDefinitions, + const Commands extends ToolCommandMap = ToolCommandMap, + >( + definition: ToolDefinitionInput, + ) => + typeof definition.commands === "function" + ? { ...definition, commands: definition.commands((command) => command) } + : definition, defineCommand: ( definition: CommandDefinition, ) => definition, @@ -142,10 +154,16 @@ class RigToolKitFactoryClass { export const rig = new RigToolKitFactoryClass().create(); -export function defineTool(definition: ToolDefinition): ToolDefinition; +export function defineTool< + Env extends RigSchema = RigSchema, + Collections extends ToolCollectionDefinitions = ToolCollectionDefinitions, + const Commands extends ToolCommandMap = ToolCommandMap, +>( + definition: ToolDefinitionInput, +): NormalizedToolDefinitionInput; export function defineTool(factory: ToolFactory): ToolFactory; export function defineTool(value: ToolModuleDefault): ToolModuleDefault { - return typeof value === "function" ? value : rig.defineTool(value); + return typeof value === "function" ? value : rig.defineTool(value as never); } export const defineCommand = rig.defineCommand; @@ -154,7 +172,7 @@ export const args = rig.args; export const paths = rig.paths; export class RigToolClass { - define(value: ToolDefinition): ToolDefinition; + define(value: ToolDefinitionInput): ToolDefinitionInput; define(value: ToolFactory): ToolFactory; define(value: ToolModuleDefault): ToolModuleDefault { return defineTool(value as never); diff --git a/test/e2e/fixtures/distribution/collection-tool.ts b/test/e2e/fixtures/distribution/collection-tool.ts index fd62786..d9062a0 100644 --- a/test/e2e/fixtures/distribution/collection-tool.ts +++ b/test/e2e/fixtures/distribution/collection-tool.ts @@ -5,7 +5,8 @@ const tool: RigToolFactory = (rig) => collections: { notes: { schema: rig.z.object({ title: rig.z.string() }), - generateId: (data) => String(data.title).toLowerCase().replaceAll(" ", "-"), + generateId: (data: Record) => + String(data.title).toLowerCase().replaceAll(" ", "-"), }, }, commands: { From 63c0f6e57301e21c6b2c406d9408960d800f800f Mon Sep 17 00:00:00 2001 From: rendotdev <294850895+rendotdev@users.noreply.github.com> Date: Wed, 15 Jul 2026 09:34:43 -0400 Subject: [PATCH 2/2] Clarify command helper migration guidance --- src/cli.test.ts | 2 ++ src/tools/migration/tool-api-migration.ts | 7 ++++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/cli.test.ts b/src/cli.test.ts index d73378f..da60ec3 100644 --- a/src/cli.test.ts +++ b/src/cli.test.ts @@ -269,6 +269,8 @@ describe("cli application", () => { expect(prompt).toContain("legacy: v1 to v2"); expect(prompt).toContain("Remove the redundant `name`"); expect(prompt).toContain("`commands` as `(command) => ({ ... })`"); + expect(prompt).toContain("Move predeclared commands into the `commands` callback"); + expect(prompt).toContain("pass `command` into them"); expect(prompt).toContain("rig typecheck "); cli.logs.length = 0; diff --git a/src/tools/migration/tool-api-migration.ts b/src/tools/migration/tool-api-migration.ts index e850db8..c1e28d6 100644 --- a/src/tools/migration/tool-api-migration.ts +++ b/src/tools/migration/tool-api-migration.ts @@ -68,9 +68,10 @@ export class ToolApiMigrationServiceClass extends DomainClass< "", "1. Export the factory directly as `(rig: RigToolKit) => rig.defineTool({ ... })`.", "2. Remove the redundant `name`; Rig derives it from the folder.", - "3. Define `commands` as `(command) => ({ ... })` and replace each `rig.defineCommand({ ... })` with `command({ ... })`.", - `4. Set the header to \`// rig:tool-api-version ${params.report.currentVersion}\`.`, - "5. Run `rig typecheck ` and execute the command examples before considering the migration complete.", + "3. Define `commands` as `(command) => ({ ... })` and replace each inline `rig.defineCommand({ ... })` with `command({ ... })`.", + "4. Move predeclared commands into the `commands` callback. Declare reusable command factories inside the callback or pass `command` into them.", + `5. Set the header to \`// rig:tool-api-version ${params.report.currentVersion}\`.`, + "6. Run `rig typecheck ` and execute the command examples before considering the migration complete.", ); }