@usesketchbook/opencode-plugin 0.0.0-stage → 0.1.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +123 -2
  3. package/dist/generated/baseline-manifest.d.ts +2 -0
  4. package/dist/generated/baseline-manifest.js +1590 -0
  5. package/dist/generated/catalog-baseline.d.ts +2 -0
  6. package/dist/generated/catalog-baseline.js +255 -0
  7. package/dist/gui-experimental.cjs +111 -0
  8. package/dist/gui.d.ts +22 -0
  9. package/dist/gui.js +34 -0
  10. package/dist/index.d.ts +3 -0
  11. package/dist/index.js +20 -0
  12. package/dist/rpc.d.ts +1173 -0
  13. package/dist/rpc.js +212 -0
  14. package/dist/server/catalog.d.ts +9 -0
  15. package/dist/server/catalog.js +74 -0
  16. package/dist/server/decision-guard-hooks.d.ts +2 -0
  17. package/dist/server/decision-guard-hooks.js +57 -0
  18. package/dist/server/decision-guards.d.ts +11 -0
  19. package/dist/server/decision-guards.js +36 -0
  20. package/dist/server/engine.d.ts +6 -0
  21. package/dist/server/engine.js +38 -0
  22. package/dist/server/guard-hooks.d.ts +3 -0
  23. package/dist/server/guard-hooks.js +35 -0
  24. package/dist/server/guards.d.ts +13 -0
  25. package/dist/server/guards.js +42 -0
  26. package/dist/server/operations.d.ts +93 -0
  27. package/dist/server/operations.js +300 -0
  28. package/dist/server/permissions.d.ts +29 -0
  29. package/dist/server/permissions.js +97 -0
  30. package/dist/server/rpc.d.ts +126 -0
  31. package/dist/server/rpc.js +308 -0
  32. package/dist/server/runner.d.ts +27 -0
  33. package/dist/server/runner.js +136 -0
  34. package/dist/server/schema.d.ts +4 -0
  35. package/dist/server/schema.js +66 -0
  36. package/dist/server/tools.d.ts +2 -0
  37. package/dist/server/tools.js +176 -0
  38. package/dist/server/tui.d.ts +70 -0
  39. package/dist/server/tui.js +172 -0
  40. package/dist/shared/catalog.d.ts +52 -0
  41. package/dist/shared/catalog.js +84 -0
  42. package/dist/shared/envelope.d.ts +24 -0
  43. package/dist/shared/envelope.js +28 -0
  44. package/dist/shared/manifest.d.ts +53 -0
  45. package/dist/shared/manifest.js +135 -0
  46. package/dist/test/baseline.test.d.ts +1 -0
  47. package/dist/test/baseline.test.js +11 -0
  48. package/dist/test/catalog.test.d.ts +1 -0
  49. package/dist/test/catalog.test.js +232 -0
  50. package/dist/test/decision-guards.test.d.ts +1 -0
  51. package/dist/test/decision-guards.test.js +30 -0
  52. package/dist/test/engine.test.d.ts +1 -0
  53. package/dist/test/engine.test.js +23 -0
  54. package/dist/test/fixtures.d.ts +12 -0
  55. package/dist/test/fixtures.js +55 -0
  56. package/dist/test/guard-hooks.integration.test.d.ts +1 -0
  57. package/dist/test/guard-hooks.integration.test.js +321 -0
  58. package/dist/test/guard-hooks.test.d.ts +1 -0
  59. package/dist/test/guard-hooks.test.js +14 -0
  60. package/dist/test/guards.test.d.ts +1 -0
  61. package/dist/test/guards.test.js +24 -0
  62. package/dist/test/gui.test.d.ts +1 -0
  63. package/dist/test/gui.test.js +61 -0
  64. package/dist/test/manifest.test.d.ts +1 -0
  65. package/dist/test/manifest.test.js +86 -0
  66. package/dist/test/operations.test.d.ts +1 -0
  67. package/dist/test/operations.test.js +263 -0
  68. package/dist/test/parity.test.d.ts +1 -0
  69. package/dist/test/parity.test.js +56 -0
  70. package/dist/test/permissions.integration.test.d.ts +1 -0
  71. package/dist/test/permissions.integration.test.js +535 -0
  72. package/dist/test/permissions.test.d.ts +1 -0
  73. package/dist/test/permissions.test.js +42 -0
  74. package/dist/test/rpc.test.d.ts +1 -0
  75. package/dist/test/rpc.test.js +389 -0
  76. package/dist/test/runner.test.d.ts +1 -0
  77. package/dist/test/runner.test.js +47 -0
  78. package/dist/test/schema.test.d.ts +1 -0
  79. package/dist/test/schema.test.js +51 -0
  80. package/dist/test/tui.test.d.ts +1 -0
  81. package/dist/test/tui.test.js +226 -0
  82. package/dist/tprobe.d.ts +1 -0
  83. package/dist/tprobe.js +2 -0
  84. package/dist/tui.d.ts +10 -0
  85. package/dist/tui.js +21 -0
  86. package/dist/views/operations.d.ts +50 -0
  87. package/dist/views/operations.js +80 -0
  88. package/package.json +71 -4
@@ -0,0 +1,308 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { SketchbookRpc } from "../rpc.js";
3
+ import { resolveEngine } from "./engine.js";
4
+ import { OperationError, StalePreviewError, applyPreview, executeOperation, loadCapabilities, previewOperation, } from "./operations.js";
5
+ import { RUN_ERROR_CODES } from "./runner.js";
6
+ /**
7
+ * Typed RPC error. The `code` extends the SKETCHBOOK_* convention and maps to
8
+ * one of the named errors in the SketchbookRpc definition, so clients never
9
+ * have to parse message text.
10
+ */
11
+ export class RpcMethodError extends Error {
12
+ code;
13
+ details;
14
+ constructor(code, message, details = {}) {
15
+ super(message);
16
+ this.code = code;
17
+ this.details = details;
18
+ }
19
+ }
20
+ export const RPC_ERROR_CODES = {
21
+ stalePreview: "SKETCHBOOK_STALE_PREVIEW",
22
+ notFound: "SKETCHBOOK_NOT_FOUND",
23
+ cancelled: "SKETCHBOOK_CANCELLED",
24
+ timeout: "SKETCHBOOK_TIMEOUT",
25
+ outputLimit: "SKETCHBOOK_OUTPUT_LIMIT",
26
+ permission: "SKETCHBOOK_PERMISSION_DENIED",
27
+ };
28
+ const errorNameFor = (code) => {
29
+ switch (code) {
30
+ case RPC_ERROR_CODES.stalePreview:
31
+ return "sketchbook_stale_preview";
32
+ case RPC_ERROR_CODES.notFound:
33
+ return "sketchbook_not_found";
34
+ case RPC_ERROR_CODES.cancelled:
35
+ return "sketchbook_cancelled";
36
+ case RPC_ERROR_CODES.timeout:
37
+ return "sketchbook_timeout";
38
+ case RPC_ERROR_CODES.outputLimit:
39
+ return "sketchbook_output_limit";
40
+ case RPC_ERROR_CODES.permission:
41
+ return "sketchbook_permission";
42
+ default:
43
+ return "sketchbook_operation";
44
+ }
45
+ };
46
+ /**
47
+ * Converts any operation-service failure into a typed RPC handler error
48
+ * ({ type, message, data }). Used directly by handlers and by tests.
49
+ */
50
+ export function toRpcError(error, context = {}) {
51
+ const code = error instanceof OperationError
52
+ ? error.code
53
+ : error instanceof StalePreviewError
54
+ ? RPC_ERROR_CODES.stalePreview
55
+ : error instanceof RpcMethodError
56
+ ? error.code
57
+ : error?.code === RUN_ERROR_CODES.cancelled
58
+ ? RPC_ERROR_CODES.cancelled
59
+ : error?.code === RUN_ERROR_CODES.timeout
60
+ ? RPC_ERROR_CODES.timeout
61
+ : error?.code === RUN_ERROR_CODES.outputLimit
62
+ ? RPC_ERROR_CODES.outputLimit
63
+ : undefined;
64
+ const message = error instanceof Error ? error.message : String(error);
65
+ const isPermission = /permission|not allowed|denied/i.test(message);
66
+ const name = errorNameFor(code ?? (isPermission ? RPC_ERROR_CODES.permission : ""));
67
+ const command = context.command
68
+ ?? (error instanceof OperationError ? error.command : undefined);
69
+ const data = {
70
+ code: code ?? (isPermission ? RPC_ERROR_CODES.permission : "SKETCHBOOK_OPERATION_ERROR"),
71
+ message,
72
+ ...(command ? { command } : {}),
73
+ ...(context.operationID ? { operationID: context.operationID } : {}),
74
+ };
75
+ return { type: name, message, data };
76
+ }
77
+ // Bounded registry shared by run/cancel/status. Finished operations stay
78
+ // listed for status queries until evicted by the oldest-entry rule.
79
+ const operations = new Map();
80
+ const OPERATION_REGISTRY_LIMIT = 256;
81
+ function rememberOperation(entry) {
82
+ if (operations.size >= OPERATION_REGISTRY_LIMIT) {
83
+ const oldest = operations.keys().next().value;
84
+ if (oldest)
85
+ operations.delete(oldest);
86
+ }
87
+ operations.set(entry.operationID, entry);
88
+ }
89
+ export function getOperation(operationID) {
90
+ return operations.get(operationID);
91
+ }
92
+ export function resetOperations() {
93
+ operations.clear();
94
+ }
95
+ export const RPC_SESSION_ID = "sketchbook-rpc";
96
+ /**
97
+ * Builds the RPC method handlers over the shared operation service. Pure with
98
+ * respect to the engine: nothing executes until a method is invoked, so plugin
99
+ * setup stays free of engine runs. `signal` from the RPC call context is
100
+ * chained onto the operation's own AbortController for cancellation
101
+ * propagation.
102
+ */
103
+ export function createSketchbookRpcHandlers(env) {
104
+ const chainSignal = (entry, callSignal) => {
105
+ if (!callSignal)
106
+ return;
107
+ if (callSignal.aborted) {
108
+ entry.controller.abort();
109
+ return;
110
+ }
111
+ callSignal.addEventListener("abort", () => entry.controller.abort(), { once: true });
112
+ };
113
+ const track = (input) => {
114
+ let resolveSettled;
115
+ const settled = new Promise((r) => {
116
+ resolveSettled = r;
117
+ });
118
+ const entry = {
119
+ operationID: input.operationID || randomUUID(),
120
+ command: input.command,
121
+ status: "running",
122
+ startedAt: new Date().toISOString(),
123
+ controller: new AbortController(),
124
+ progress: [],
125
+ settled,
126
+ settle: resolveSettled,
127
+ };
128
+ rememberOperation(entry);
129
+ return entry;
130
+ };
131
+ const onProgress = (entry) => (line, source) => {
132
+ const sequence = entry.progress.length + 1;
133
+ entry.progress.push({ sequence, source, line });
134
+ env.emit?.("progress", {
135
+ operationID: entry.operationID,
136
+ command: entry.command,
137
+ sequence,
138
+ source,
139
+ line,
140
+ });
141
+ };
142
+ const setStatus = (entry, status) => {
143
+ if (entry.status !== "running")
144
+ return;
145
+ entry.status = status;
146
+ entry.finishedAt = new Date().toISOString();
147
+ entry.settle();
148
+ env.emit?.("operation", {
149
+ operationID: entry.operationID,
150
+ command: entry.command,
151
+ status,
152
+ });
153
+ };
154
+ const execute = async (entry, input, context, mode) => {
155
+ chainSignal(entry, context.signal);
156
+ const operation = {
157
+ root: env.root,
158
+ command: input.command,
159
+ ...(input.subcommand ? { subcommand: input.subcommand } : {}),
160
+ args: input.args,
161
+ options: input.options,
162
+ signal: entry.controller.signal,
163
+ onLine: onProgress(entry),
164
+ permission: env.permission,
165
+ sessionID: env.sessionID ?? RPC_SESSION_ID,
166
+ timeoutMs: input.timeoutMs,
167
+ maxOutputBytes: input.maxOutputBytes,
168
+ };
169
+ try {
170
+ if (mode === "preview") {
171
+ const record = await previewOperation({ ...operation, signal: entry.controller.signal });
172
+ setStatus(entry, "completed");
173
+ const engine = resolveEngine(env.root);
174
+ return {
175
+ ok: record.plan.ok,
176
+ operationID: entry.operationID,
177
+ command: record.identity.command,
178
+ dryRun: true,
179
+ envelope: record.plan,
180
+ engine,
181
+ preview: { id: record.id, fingerprint: record.fingerprint, status: record.status },
182
+ };
183
+ }
184
+ const result = await executeOperation({
185
+ ...operation,
186
+ dryRun: input.dryRun,
187
+ signal: entry.controller.signal,
188
+ });
189
+ setStatus(entry, "completed");
190
+ return {
191
+ ok: result.envelope.ok,
192
+ operationID: entry.operationID,
193
+ command: result.command.name,
194
+ dryRun: result.dryRun,
195
+ envelope: result.envelope,
196
+ engine: result.engine,
197
+ };
198
+ }
199
+ catch (error) {
200
+ const aborted = entry.controller.signal.aborted;
201
+ setStatus(entry, aborted ? "cancelled" : "failed");
202
+ throw toRpcError(error, { command: input.command, operationID: entry.operationID });
203
+ }
204
+ };
205
+ return {
206
+ capabilities: async () => {
207
+ try {
208
+ const manifest = await loadCapabilities(env.root, {
209
+ permission: env.permission,
210
+ sessionID: env.sessionID ?? RPC_SESSION_ID,
211
+ });
212
+ return {
213
+ protocolVersion: manifest.protocolVersion,
214
+ envelopeVersion: manifest.envelopeVersion,
215
+ engine: manifest.engine,
216
+ commands: manifest.commands,
217
+ };
218
+ }
219
+ catch (error) {
220
+ throw toRpcError(error, { command: "capabilities" });
221
+ }
222
+ },
223
+ run: (input, context) => execute(track({ command: input.command, operationID: input.operationID }), input, context, "run"),
224
+ preview: (input, context) => execute(track({ command: input.command, operationID: input.operationID }), input, context, "preview"),
225
+ apply: async (input, context) => {
226
+ try {
227
+ const result = await applyPreview({
228
+ operationID: input.operationID,
229
+ root: env.root,
230
+ permission: env.permission,
231
+ sessionID: env.sessionID ?? RPC_SESSION_ID,
232
+ signal: context.signal,
233
+ });
234
+ return {
235
+ ok: result.envelope.ok,
236
+ operationID: input.operationID,
237
+ command: result.command.name,
238
+ envelope: result.envelope,
239
+ engine: result.engine,
240
+ };
241
+ }
242
+ catch (error) {
243
+ throw toRpcError(error, { operationID: input.operationID });
244
+ }
245
+ },
246
+ cancel: async (input) => {
247
+ const entry = getOperation(input.operationID);
248
+ if (!entry) {
249
+ throw toRpcError(new RpcMethodError(RPC_ERROR_CODES.notFound, `Unknown Sketchbook operation ${input.operationID}.`, { operationID: input.operationID }), { operationID: input.operationID });
250
+ }
251
+ if (entry.status === "running") {
252
+ entry.controller.abort();
253
+ // Wait for the run handler to observe the abort and record the final
254
+ // state, so the response reflects a terminal status.
255
+ await entry.settled;
256
+ return {
257
+ ok: true,
258
+ operationID: entry.operationID,
259
+ cancelled: true,
260
+ status: entry.status,
261
+ };
262
+ }
263
+ return {
264
+ ok: true,
265
+ operationID: entry.operationID,
266
+ cancelled: false,
267
+ status: entry.status,
268
+ };
269
+ },
270
+ status: async (input) => {
271
+ if (input.operationID !== undefined) {
272
+ const entry = getOperation(input.operationID);
273
+ if (!entry) {
274
+ throw toRpcError(new RpcMethodError(RPC_ERROR_CODES.notFound, `Unknown Sketchbook operation ${input.operationID}.`, { operationID: input.operationID }), { operationID: input.operationID });
275
+ }
276
+ return { ok: true, operations: [serializeOperation(entry)] };
277
+ }
278
+ return {
279
+ ok: true,
280
+ operations: [...operations.values()].map(serializeOperation),
281
+ };
282
+ },
283
+ };
284
+ }
285
+ function serializeOperation(entry) {
286
+ return {
287
+ operationID: entry.operationID,
288
+ command: entry.command,
289
+ status: entry.status,
290
+ startedAt: entry.startedAt,
291
+ ...(entry.finishedAt ? { finishedAt: entry.finishedAt } : {}),
292
+ progressCount: entry.progress.length,
293
+ };
294
+ }
295
+ /**
296
+ * Registers the full Sketchbook RPC surface with the host. Registration itself
297
+ * performs no engine execution: the manifest is only loaded when the
298
+ * `capabilities` method is invoked, and the bundled baseline is never needed
299
+ * here because method inputs are hand-written schemas.
300
+ */
301
+ export async function setupRpc(ctx) {
302
+ const env = {
303
+ root: ctx.location.directory,
304
+ permission: ctx.permission,
305
+ };
306
+ const handlers = createSketchbookRpcHandlers(env);
307
+ await ctx.rpc.register(SketchbookRpc, handlers);
308
+ }
@@ -0,0 +1,27 @@
1
+ import { type ResolvedEngine } from "./engine.js";
2
+ import { type Envelope } from "../shared/envelope.js";
3
+ export interface RunOptions {
4
+ root: string;
5
+ command: string;
6
+ subcommand?: string;
7
+ args?: string[];
8
+ options?: Record<string, string | boolean | undefined>;
9
+ dryRun?: boolean;
10
+ signal?: AbortSignal;
11
+ onLine?: (line: string, source: "stdout" | "stderr") => void;
12
+ timeoutMs?: number;
13
+ maxOutputBytes?: number;
14
+ }
15
+ export interface RunResult {
16
+ engine: ResolvedEngine;
17
+ envelope: Envelope;
18
+ }
19
+ export declare const RUN_ERROR_CODES: {
20
+ readonly cancelled: "SKETCHBOOK_CANCELLED";
21
+ readonly timeout: "SKETCHBOOK_TIMEOUT";
22
+ readonly outputLimit: "SKETCHBOOK_OUTPUT_LIMIT";
23
+ };
24
+ export interface RunError extends Error {
25
+ readonly code?: (typeof RUN_ERROR_CODES)[keyof typeof RUN_ERROR_CODES];
26
+ }
27
+ export declare function runSketchbook(options: RunOptions): Promise<RunResult>;
@@ -0,0 +1,136 @@
1
+ import { spawn } from "node:child_process";
2
+ import { resolveEngine } from "./engine.js";
3
+ import { parseEnvelope } from "../shared/envelope.js";
4
+ // Typed codes let RPC, tools, and TUI classify failures without matching on
5
+ // error text. Messages are kept stable for tests and human readers.
6
+ export const RUN_ERROR_CODES = {
7
+ cancelled: "SKETCHBOOK_CANCELLED",
8
+ timeout: "SKETCHBOOK_TIMEOUT",
9
+ outputLimit: "SKETCHBOOK_OUTPUT_LIMIT",
10
+ };
11
+ const runError = (code, message) => {
12
+ const error = new Error(message);
13
+ if (code)
14
+ error.code = code;
15
+ return error;
16
+ };
17
+ export async function runSketchbook(options) {
18
+ if (options.signal?.aborted) {
19
+ throw runError(RUN_ERROR_CODES.cancelled, `sketchbook ${options.command} aborted before it could start`);
20
+ }
21
+ const engine = resolveEngine(options.root);
22
+ const argv = buildArgv(options.command, options.subcommand, options.args, options.options, options.dryRun);
23
+ return new Promise((resolve, reject) => {
24
+ let settled = false;
25
+ let stdout = "";
26
+ let stderr = "";
27
+ let outputBytes = 0;
28
+ let timer;
29
+ const finish = (fn) => {
30
+ if (settled)
31
+ return;
32
+ settled = true;
33
+ cleanupTimer();
34
+ options.signal?.removeEventListener("abort", abort);
35
+ fn();
36
+ };
37
+ const cleanupTimer = () => {
38
+ if (timer !== undefined) {
39
+ clearTimeout(timer);
40
+ timer = undefined;
41
+ }
42
+ };
43
+ const child = spawn(process.execPath, [engine.path, ...argv], {
44
+ cwd: options.root,
45
+ shell: false,
46
+ stdio: ["ignore", "pipe", "pipe"],
47
+ // On POSIX this gives the CLI its own process group so cancellation can
48
+ // stop descendants such as check subprocesses.
49
+ detached: process.platform !== "win32",
50
+ });
51
+ const killTree = () => {
52
+ if (child.pid && process.platform !== "win32") {
53
+ try {
54
+ process.kill(-child.pid, "SIGTERM");
55
+ return;
56
+ }
57
+ catch {
58
+ // Fall through to the direct-child kill.
59
+ }
60
+ }
61
+ child.kill("SIGTERM");
62
+ };
63
+ const abort = () => {
64
+ cleanupTimer();
65
+ killTree();
66
+ };
67
+ options.signal?.addEventListener("abort", abort);
68
+ if (options.timeoutMs !== undefined) {
69
+ timer = setTimeout(() => {
70
+ abort();
71
+ finish(() => reject(runError(RUN_ERROR_CODES.timeout, `sketchbook ${options.command} timed out after ${options.timeoutMs}ms`)));
72
+ }, options.timeoutMs);
73
+ }
74
+ const record = (text, source) => {
75
+ if (options.maxOutputBytes !== undefined) {
76
+ outputBytes += Buffer.byteLength(text, "utf8");
77
+ if (outputBytes > options.maxOutputBytes) {
78
+ abort();
79
+ finish(() => reject(runError(RUN_ERROR_CODES.outputLimit, `sketchbook ${options.command} output exceeded ${options.maxOutputBytes} bytes`)));
80
+ return;
81
+ }
82
+ }
83
+ if (source === "stdout")
84
+ stdout += text;
85
+ else
86
+ stderr += text;
87
+ for (const line of text.split("\n")) {
88
+ if (line)
89
+ options.onLine?.(line, source);
90
+ }
91
+ };
92
+ child.stdout?.on("data", (chunk) => record(chunk.toString("utf8"), "stdout"));
93
+ child.stderr?.on("data", (chunk) => record(chunk.toString("utf8"), "stderr"));
94
+ child.on("error", (err) => {
95
+ finish(() => reject(err));
96
+ });
97
+ child.on("close", (code) => {
98
+ // The CLI uses 0 for success, 1 for failure, and 2 for success with flags
99
+ // such as retained overrides. Treat 2 as a parseable success outcome.
100
+ finish(() => {
101
+ if (code !== 0 && code !== 2) {
102
+ reject(runError(options.signal?.aborted ? RUN_ERROR_CODES.cancelled : undefined, `sketchbook ${options.command} failed (${code ?? "killed"}): ${stderr || stdout}`));
103
+ return;
104
+ }
105
+ try {
106
+ const envelope = parseEnvelope(stdout, options.command);
107
+ resolve({ engine, envelope });
108
+ }
109
+ catch (err) {
110
+ reject(err);
111
+ }
112
+ });
113
+ });
114
+ });
115
+ }
116
+ function buildArgv(command, subcommand, args = [], options = {}, dryRun) {
117
+ const argv = [command];
118
+ if (subcommand)
119
+ argv.push(subcommand);
120
+ for (const [key, value] of Object.entries(options)) {
121
+ if (value === undefined)
122
+ continue;
123
+ const flag = `--${key}`;
124
+ if (value === true) {
125
+ argv.push(flag);
126
+ }
127
+ else if (value !== false) {
128
+ argv.push(flag, String(value));
129
+ }
130
+ }
131
+ argv.push(...args);
132
+ if (dryRun)
133
+ argv.push("--dry-run");
134
+ argv.push("--json");
135
+ return argv;
136
+ }
@@ -0,0 +1,4 @@
1
+ import type { JsonSchema } from "effect";
2
+ import type { ManifestCommand } from "../shared/manifest.js";
3
+ export type ToolInputSchema = JsonSchema.JsonSchema;
4
+ export declare function commandInputSchema(command: ManifestCommand): ToolInputSchema;
@@ -0,0 +1,66 @@
1
+ export function commandInputSchema(command) {
2
+ const properties = {};
3
+ const required = [];
4
+ const subcommandArg = command.args.find((arg) => arg.name === "subcommand");
5
+ if (command.subcommands && command.subcommands.length > 0) {
6
+ properties.subcommand = {
7
+ type: "string",
8
+ enum: command.subcommands.map((s) => s.name),
9
+ description: subcommandArg?.description ?? `Subcommand for ${command.name}.`,
10
+ };
11
+ if (subcommandArg?.required ?? true)
12
+ required.push("subcommand");
13
+ }
14
+ for (const arg of command.args) {
15
+ if (arg.name === "subcommand" && command.subcommands?.length)
16
+ continue;
17
+ properties[arg.name] = argSchema(arg);
18
+ if (arg.required)
19
+ required.push(arg.name);
20
+ }
21
+ for (const [name, option] of Object.entries(command.options)) {
22
+ properties[name] = optionSchema(option);
23
+ }
24
+ if (command.dryRun) {
25
+ properties.dryRun = {
26
+ type: "boolean",
27
+ description: "Preview changes without writing files.",
28
+ };
29
+ }
30
+ return {
31
+ type: "object",
32
+ properties,
33
+ required,
34
+ additionalProperties: false,
35
+ description: `${command.summary} Usage: ${command.usage}`,
36
+ };
37
+ }
38
+ function argSchema(arg) {
39
+ if (arg.variadic) {
40
+ return {
41
+ type: "array",
42
+ items: { type: "string" },
43
+ description: arg.description,
44
+ };
45
+ }
46
+ return {
47
+ type: "string",
48
+ description: arg.description,
49
+ };
50
+ }
51
+ function optionSchema(option) {
52
+ if (option.type === "boolean") {
53
+ return {
54
+ type: "boolean",
55
+ description: option.description,
56
+ };
57
+ }
58
+ const schema = {
59
+ type: "string",
60
+ description: option.description,
61
+ };
62
+ if (option.value) {
63
+ schema.enum = [option.value];
64
+ }
65
+ return schema;
66
+ }
@@ -0,0 +1,2 @@
1
+ import type { Plugin } from "@opencode/plugin";
2
+ export declare function setupTools(ctx: Plugin.Context): Promise<void>;