Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ The `rig` CLI is installed on this machine. It is _your_ CLI. You own its variou
- Run `rig remove <tool>` to remove a local tool.
- Run `rig cron --help` to schedule and manage tool commands.
- Run `rig typecheck <tool>` 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 <tool> KEY=VALUE` to configure tool secrets/settings; run `rig env <tool> remove KEY` to remove them.
- Run `rig list` to discover tools and available `rig run ...` commands.
- Run `rig help <topic>` for concept docs (collections, cache, kv, db, env, log, shell, run, tool, args, paths).
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ The `rig` CLI is installed on this machine. It is _your_ CLI. You own its variou
- Run `rig remove <tool>` to remove a local tool.
- Run `rig cron --help` to schedule and manage tool commands.
- Run `rig typecheck <tool>` 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 <tool> KEY=VALUE` to configure tool secrets/settings; run `rig env <tool> remove KEY` to remove them.
- Run `rig list` to discover tools and available `rig run ...` commands.
- Run `rig help <topic>` for concept docs (collections, cache, kv, db, env, log, shell, run, tool, args, paths).
Expand Down
1 change: 1 addition & 0 deletions src/agents/instructions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export const RigAgentInstructions = `The \`rig\` CLI is installed on this machin
- Run \`rig remove <tool>\` to remove a local tool.
- Run \`rig cron --help\` to schedule and manage tool commands.
- Run \`rig typecheck <tool>\` 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 <tool> KEY=VALUE\` to configure tool secrets/settings; run \`rig env <tool> remove KEY\` to remove them.
- Run \`rig list\` to discover tools and available \`rig run ...\` commands.
- Run \`rig help <topic>\` for concept docs (collections, cache, kv, db, env, log, shell, run, tool, args, paths).
Expand Down
27 changes: 27 additions & 0 deletions src/application/cli/cli-application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export class CliApplicationClass {
this.configureRunCommand();
this.configureCronCommands();
this.configureTypecheckCommand();
this.configureMigrateCommand();
this.configureDevCommands();
this.configureUpdateCommand();
this.program
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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);
}

Expand Down Expand Up @@ -540,6 +558,7 @@ export class CliApplicationClass {
}
console.log(`Tools: ${tools.length}`);
console.log("\nStatus: OK");
await this.printToolApiMigrationNotice();
await this.printUpdateNotice(this.version());
}

Expand Down Expand Up @@ -574,6 +593,14 @@ export class CliApplicationClass {
});
}

private async printToolApiMigrationNotice(): Promise<void> {
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;
}
Expand Down
81 changes: 81 additions & 0 deletions src/cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,62 @@ 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("Move predeclared commands into the `commands` callback");
expect(prompt).toContain("pass `command` into them");
expect(prompt).toContain("rig typecheck <tool>");

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");
Expand All @@ -259,6 +315,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.");
Expand Down
12 changes: 9 additions & 3 deletions src/generated/agent/agent-instruction-sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 });
}

Expand All @@ -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),
Expand Down Expand Up @@ -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
Expand Down
94 changes: 86 additions & 8 deletions src/generated/runtime/runtime-support.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -269,6 +271,42 @@ import type { z } from "zod";

export type RigSchema = z.ZodTypeAny;

export type RigCollectionDefinition<T extends z.ZodObject<any> = z.ZodObject<any>> = {
schema?: T;
generateId?: (data: z.input<T>) => string;
};

export type RigCollectionEntry<T = Record<string, unknown>> = {
id: string;
data: T;
body: string;
createdAt: string;
updatedAt: string;
};

export type RigCollectionHandle<T = Record<string, unknown>> = {
readonly name: string;
readonly path: string;
create(entry: { id?: string; data: T; body?: string }): Promise<RigCollectionEntry<T>>;
getEntry(id: string): Promise<RigCollectionEntry<T> | null>;
update(id: string, patch: { data?: Partial<T>; body?: string }): Promise<RigCollectionEntry<T>>;
upsert(entry: { id: string; data: T; body?: string }): Promise<{ id: string; created: boolean }>;
remove(id: string): Promise<boolean>;
list(options?: { where?: Record<string, unknown>; sort?: string; limit?: number; offset?: number }): Promise<{ entries: RigCollectionEntry<T>[]; total: number }>;
search(query: string, options?: { limit?: number }): Promise<{ entries: Array<RigCollectionEntry<T> & { snippet: string; rank: number }> }>;
count(where?: Record<string, unknown>): Promise<number>;
getCollection(filter?: (entry: RigCollectionEntry<T>) => boolean): Promise<RigCollectionEntry<T>[]>;
clear(): Promise<void>;
};

export type RigToolCollectionDefinitions = Record<string, RigCollectionDefinition>;

export type RigToolCollectionHandles<Collections extends RigToolCollectionDefinitions> = {
[Name in keyof Collections]: Collections[Name] extends RigCollectionDefinition<infer Schema>
? RigCollectionHandle<z.output<Schema>>
: RigCollectionHandle;
};

export type RigShellOptions = {
cwd?: string;
env?: Record<string, string | undefined>;
Expand Down Expand Up @@ -359,7 +397,11 @@ export type RigToolLogger = {
child(bindings: Record<string, unknown>): RigToolLogger;
};

export type RigToolRunContext<Input, Env = unknown> = {
export type RigToolRunContext<
Input,
Env = unknown,
Collections = Record<string, RigCollectionHandle>,
> = {
input: Input;
env: Env;
processEnv: NodeJS.ProcessEnv;
Expand All @@ -369,6 +411,7 @@ export type RigToolRunContext<Input, Env = unknown> = {
cache: RigToolCache;
log: RigToolLogger;
rig: RigToolKit;
collections: Collections;
};

export type RigToolExample<Input = any, Output = any> = {
Expand All @@ -382,25 +425,60 @@ export type RigCommandDefinition<
Input extends RigSchema = RigSchema,
Output extends RigSchema = RigSchema,
Env = unknown,
Collections = Record<string, RigCollectionHandle>,
> = {
description: string;
input: Input;
output: Output;
examples?: RigToolExample<z.input<Input>, z.output<Output>>[];
run: (ctx: RigToolRunContext<z.output<Input>, Env>) => z.input<Output> | Promise<z.input<Output>>;
run: (ctx: RigToolRunContext<z.output<Input>, Env, Collections>) => z.input<Output> | Promise<z.input<Output>>;
};

export type RigToolDefinition<Env extends RigSchema = RigSchema> = {
name: string;
export type RigToolCommandBuilder<
Env,
Collections,
> = <Input extends RigSchema, Output extends RigSchema>(
definition: RigCommandDefinition<Input, Output, Env, Collections>,
) => RigCommandDefinition<Input, Output, Env, Collections>;

export type RigToolCommandMap = Record<string, RigCommandDefinition<any, any, any, any>>;

export type RigToolCommandsFactory<
Env,
Collections,
Commands extends RigToolCommandMap,
> = (command: RigToolCommandBuilder<Env, Collections>) => 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<void>;
commands: Record<string, RigCommandDefinition<RigSchema, RigSchema, z.output<Env>>>;
collections?: Collections;
commands:
| Commands
| RigToolCommandsFactory<z.output<Env>, RigToolCollectionHandles<Collections>, Commands>;
};

export type RigNormalizedToolDefinition<
Env extends RigSchema = RigSchema,
Collections extends RigToolCollectionDefinitions = RigToolCollectionDefinitions,
Commands extends RigToolCommandMap = RigToolCommandMap,
> = Omit<RigToolDefinition<Env, Collections, Commands>, "commands"> & {
commands: Commands;
};

export type RigToolKit = {
z: typeof z;
defineTool<T extends RigToolDefinition>(definition: T): T;
defineTool<
Env extends RigSchema = RigSchema,
Collections extends RigToolCollectionDefinitions = RigToolCollectionDefinitions,
const Commands extends RigToolCommandMap = RigToolCommandMap,
>(definition: RigToolDefinition<Env, Collections, Commands>): RigNormalizedToolDefinition<Env, Collections, Commands>;
defineCommand<I extends RigSchema, O extends RigSchema>(definition: RigCommandDefinition<I, O>): RigCommandDefinition<I, O>;
run<T = unknown>(options: RigRunOptions): Promise<T>;
$(strings: TemplateStringsArray, ...values: unknown[]): Promise<RigShellResult>;
Expand All @@ -409,7 +487,7 @@ export type RigToolKit = {
shell: RigShell;
};

export type RigToolFactory = (rig: RigToolKit) => RigToolDefinition | Promise<RigToolDefinition>;
export type RigToolFactory = (rig: RigToolKit) => RigToolDefinition<any, any, any> | Promise<RigToolDefinition<any, any, any>>;
`;
}

Expand Down
Loading