@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,300 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { spawnSync } from "node:child_process";
3
+ import { resolve } from "node:path";
4
+ import { resolveEngine } from "./engine.js";
5
+ import { runSketchbook } from "./runner.js";
6
+ import { parseEnvelope } from "../shared/envelope.js";
7
+ import { validateManifest, } from "../shared/manifest.js";
8
+ import { assertPermission, commandPermissions, directoryInputFrom } from "./permissions.js";
9
+ export class OperationError extends Error {
10
+ command;
11
+ code = "SKETCHBOOK_OPERATION_ERROR";
12
+ constructor(command, message) {
13
+ super(message);
14
+ this.command = command;
15
+ }
16
+ }
17
+ export class StalePreviewError extends Error {
18
+ code = "SKETCHBOOK_STALE_PREVIEW";
19
+ constructor(message) {
20
+ super(message);
21
+ }
22
+ }
23
+ // Validated manifests are cached per location and engine identity. Rebuilding the
24
+ // registry is cheap, but spawning a project-local engine is not.
25
+ const capabilityCache = new Map();
26
+ const CAPABILITY_CACHE_LIMIT = 32;
27
+ export async function loadCapabilities(root, { refresh = false, permission, sessionID } = {}) {
28
+ const engine = resolveEngine(root);
29
+ const key = `${resolve(root)}\u0000${engine.path}\u0000${engine.version}`;
30
+ if (!refresh) {
31
+ const cached = capabilityCache.get(key);
32
+ if (cached)
33
+ return cached;
34
+ }
35
+ // Loading capabilities executes the project-local engine, so it needs explicit
36
+ // engine trust. The bundled fallback is the plugin's own reviewed dependency.
37
+ if (engine.source === "project" && permission && sessionID) {
38
+ await permission.assert({
39
+ sessionID: sessionID,
40
+ action: "sketchbook.engine",
41
+ resources: [engine.path],
42
+ metadata: { root, version: engine.version },
43
+ });
44
+ }
45
+ const result = spawnSync(process.execPath, [engine.path, "capabilities", "--json"], { cwd: root, shell: false, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
46
+ if (result.status !== 0) {
47
+ throw new OperationError("capabilities", `sketchbook capabilities failed (${result.status ?? "killed"}): ${result.stderr || result.stdout}`);
48
+ }
49
+ const envelope = parseEnvelope(result.stdout, "capabilities");
50
+ const manifest = validateManifest(envelope.data);
51
+ if (capabilityCache.size >= CAPABILITY_CACHE_LIMIT) {
52
+ const oldest = capabilityCache.keys().next().value;
53
+ if (oldest)
54
+ capabilityCache.delete(oldest);
55
+ }
56
+ capabilityCache.set(key, manifest);
57
+ return manifest;
58
+ }
59
+ export function findCommand(manifest, command, subcommand) {
60
+ const found = manifest.commands.find((c) => c.name === command);
61
+ if (!found) {
62
+ throw new OperationError(command, `Sketchbook engine has no command named ${command}.`);
63
+ }
64
+ if (subcommand && !found.subcommands?.some((s) => s.name === subcommand)) {
65
+ throw new OperationError(command, `Sketchbook ${command} has no subcommand named ${subcommand}.`);
66
+ }
67
+ return found;
68
+ }
69
+ export function splitInput(input, command) {
70
+ const options = {};
71
+ const args = [];
72
+ for (const arg of command.args) {
73
+ const value = input[arg.name];
74
+ if (value === undefined)
75
+ continue;
76
+ if (Array.isArray(value)) {
77
+ args.push(...value.map(String));
78
+ }
79
+ else {
80
+ args.push(String(value));
81
+ }
82
+ }
83
+ for (const name of Object.keys(command.options)) {
84
+ if (name in input)
85
+ options[name] = input[name];
86
+ }
87
+ return { args, options };
88
+ }
89
+ // One write at a time per resolved project location. Read operations stay concurrent.
90
+ const mutationQueues = new Map();
91
+ const DEFAULT_OPERATION_TIMEOUT_MS = 300_000;
92
+ const DEFAULT_MAX_OUTPUT_BYTES = 4 * 1024 * 1024;
93
+ /**
94
+ * Runs one validated Sketchbook operation.
95
+ *
96
+ * The manifest is supplied by the caller so this function can later be reused by
97
+ * tools, RPC, TUI, and Desktop without re-executing the engine for registration.
98
+ */
99
+ export async function executeOperation(input) {
100
+ const engine = resolveEngine(input.root);
101
+ if (engine.source === "project" && input.permission && input.sessionID) {
102
+ await input.permission.assert({
103
+ sessionID: input.sessionID,
104
+ action: "sketchbook.engine",
105
+ resources: [engine.path],
106
+ metadata: { root: input.root, version: engine.version },
107
+ });
108
+ }
109
+ const manifest = input.manifest ?? await loadCapabilities(input.root, {
110
+ permission: input.permission,
111
+ sessionID: input.sessionID,
112
+ });
113
+ const command = findCommand(manifest, input.command, input.subcommand);
114
+ if (input.dryRun === true && !command.dryRun) {
115
+ throw new OperationError(command.name, `sketchbook ${command.name} does not support --dry-run.`);
116
+ }
117
+ // Mutating operations preview by default so a missing apply flag cannot write.
118
+ const dryRun = command.dryRun ? (input.dryRun ?? true) : false;
119
+ // A directory-like option (init --dir) moves the permission target; the
120
+ // shared commandPermissions logic decides whether that asserts
121
+ // external_directory.
122
+ const directory = directoryInputFrom(input.options);
123
+ const permissionInput = {
124
+ subcommand: input.subcommand,
125
+ dryRun,
126
+ ...(directory ? { directory } : {}),
127
+ };
128
+ if (input.permission && input.sessionID) {
129
+ await assertPermission(input.permission, input.sessionID, commandPermissions(input.root, command, permissionInput));
130
+ }
131
+ const run = async () => {
132
+ const { engine, envelope } = await runSketchbook({
133
+ root: input.root,
134
+ command: command.name,
135
+ subcommand: input.subcommand,
136
+ args: input.args,
137
+ options: input.options,
138
+ dryRun,
139
+ signal: input.signal,
140
+ onLine: input.onLine,
141
+ timeoutMs: input.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS,
142
+ maxOutputBytes: input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
143
+ });
144
+ return { engine, envelope, command, dryRun };
145
+ };
146
+ if (!command.mutates)
147
+ return run();
148
+ const key = resolve(input.root);
149
+ const previous = mutationQueues.get(key) ?? Promise.resolve();
150
+ const current = previous.catch(() => { }).then(run);
151
+ // The tail is what stays in the map; it must swallow rejections so a queued
152
+ // operation rejected by a later eviction never leaks an unhandled rejection.
153
+ const tail = current
154
+ .finally(() => {
155
+ if (mutationQueues.get(key) === tail)
156
+ mutationQueues.delete(key);
157
+ })
158
+ .catch(() => { });
159
+ mutationQueues.set(key, tail);
160
+ return current;
161
+ }
162
+ const stableValue = (value) => {
163
+ if (value === undefined)
164
+ return null;
165
+ if (Array.isArray(value))
166
+ return value.map(stableValue);
167
+ if (value && typeof value === "object") {
168
+ return Object.fromEntries(Object.entries(value)
169
+ .filter(([, item]) => item !== undefined)
170
+ .sort(([a], [b]) => a.localeCompare(b))
171
+ .map(([key, item]) => [key, stableValue(item)]));
172
+ }
173
+ return value;
174
+ };
175
+ export function stableStringify(value) {
176
+ return JSON.stringify(stableValue(value));
177
+ }
178
+ export function operationIdentity(input, engine, dryRun) {
179
+ return {
180
+ root: resolve(input.root),
181
+ engine: { path: engine.path, version: engine.version },
182
+ command: input.command,
183
+ ...(input.subcommand ? { subcommand: input.subcommand } : {}),
184
+ args: [...(input.args ?? [])],
185
+ options: Object.fromEntries(Object.entries(input.options ?? {})
186
+ .filter(([, value]) => value !== undefined)
187
+ .sort(([a], [b]) => a.localeCompare(b))),
188
+ dryRun,
189
+ };
190
+ }
191
+ export function fingerprintOperation(identity, plan) {
192
+ const canonical = stableStringify({
193
+ identity,
194
+ plan: {
195
+ changed: plan.changed,
196
+ warnings: plan.warnings,
197
+ errors: plan.errors,
198
+ next: plan.next,
199
+ data: plan.data,
200
+ },
201
+ });
202
+ return createHash("sha256").update(canonical).digest("hex");
203
+ }
204
+ // A bounded preview cache shared by all surfaces. Entries are isolated by
205
+ // operation ID and validated against the stored location before use.
206
+ const previewStore = new Map();
207
+ const PREVIEW_STORE_LIMIT = 64;
208
+ function rememberPreview(record) {
209
+ if (previewStore.size >= PREVIEW_STORE_LIMIT) {
210
+ const oldest = previewStore.keys().next().value;
211
+ if (oldest)
212
+ previewStore.delete(oldest);
213
+ }
214
+ previewStore.set(record.id, record);
215
+ }
216
+ export async function previewOperation(input) {
217
+ const result = await executeOperation({ ...input, dryRun: true });
218
+ const identity = operationIdentity(input, result.engine, true);
219
+ const fingerprint = fingerprintOperation(identity, result.envelope);
220
+ const record = {
221
+ id: randomUUID(),
222
+ createdAt: new Date().toISOString(),
223
+ status: "pending",
224
+ identity,
225
+ fingerprint,
226
+ plan: result.envelope,
227
+ ...(input.manifest ? { manifest: input.manifest } : {}),
228
+ };
229
+ rememberPreview(record);
230
+ return record;
231
+ }
232
+ export async function applyPreview(input) {
233
+ const record = previewStore.get(input.operationID);
234
+ if (!record) {
235
+ throw new StalePreviewError(`Unknown Sketchbook preview ${input.operationID}.`);
236
+ }
237
+ if (resolve(input.root) !== record.identity.root) {
238
+ throw new StalePreviewError(`Sketchbook preview ${input.operationID} belongs to ${record.identity.root}.`);
239
+ }
240
+ const run = async () => {
241
+ if (record.status === "applied") {
242
+ throw new StalePreviewError(`Sketchbook preview ${record.id} was already applied.`);
243
+ }
244
+ if (record.status === "stale") {
245
+ throw new StalePreviewError(`Sketchbook preview ${record.id} is stale.`);
246
+ }
247
+ const engine = resolveEngine(record.identity.root);
248
+ if (engine.path !== record.identity.engine.path
249
+ || engine.version !== record.identity.engine.version) {
250
+ record.status = "stale";
251
+ throw new StalePreviewError(`Sketchbook preview ${record.id} was made with ${record.identity.engine.version}; the active engine is ${engine.version}.`);
252
+ }
253
+ // Re-run the same operation as a preview. If the current plan differs, the
254
+ // stored preview is stale and no apply is attempted.
255
+ const current = await executeOperation({
256
+ root: record.identity.root,
257
+ manifest: record.manifest,
258
+ command: record.identity.command,
259
+ subcommand: record.identity.subcommand,
260
+ args: record.identity.args,
261
+ options: record.identity.options,
262
+ dryRun: true,
263
+ permission: input.permission,
264
+ sessionID: input.sessionID,
265
+ signal: input.signal,
266
+ onLine: input.onLine,
267
+ timeoutMs: input.timeoutMs,
268
+ maxOutputBytes: input.maxOutputBytes,
269
+ });
270
+ const currentFingerprint = fingerprintOperation(record.identity, current.envelope);
271
+ if (currentFingerprint !== record.fingerprint) {
272
+ record.status = "stale";
273
+ throw new StalePreviewError(`Sketchbook preview ${record.id} is stale: the project or command result changed since it was made.`);
274
+ }
275
+ const applied = await executeOperation({
276
+ root: record.identity.root,
277
+ manifest: record.manifest,
278
+ command: record.identity.command,
279
+ subcommand: record.identity.subcommand,
280
+ args: record.identity.args,
281
+ options: record.identity.options,
282
+ dryRun: false,
283
+ permission: input.permission,
284
+ sessionID: input.sessionID,
285
+ signal: input.signal,
286
+ onLine: input.onLine,
287
+ timeoutMs: input.timeoutMs,
288
+ maxOutputBytes: input.maxOutputBytes,
289
+ });
290
+ record.status = "applied";
291
+ return applied;
292
+ };
293
+ const previous = record.lock ?? Promise.resolve();
294
+ const current = previous.catch(() => { }).then(run);
295
+ record.lock = current;
296
+ return current;
297
+ }
298
+ export function getPreview(operationID) {
299
+ return previewStore.get(operationID);
300
+ }
@@ -0,0 +1,29 @@
1
+ import type { Plugin } from "@opencode/plugin";
2
+ import type { ManifestCommand } from "../shared/manifest.js";
3
+ export declare const ACTIONS: {
4
+ readonly run: "sketchbook.run";
5
+ readonly mutate: "sketchbook.mutate";
6
+ readonly delete: "sketchbook.delete";
7
+ readonly external: "sketchbook.external";
8
+ readonly install: "sketchbook.install";
9
+ readonly upgrade: "sketchbook.upgrade";
10
+ readonly privileged: "sketchbook.privileged";
11
+ readonly init: "sketchbook.init";
12
+ readonly edit: "edit";
13
+ readonly externalDirectory: "external_directory";
14
+ };
15
+ export interface PermissionCheck {
16
+ action: string;
17
+ resource: string;
18
+ }
19
+ export interface CommandPermissions {
20
+ actions: string[];
21
+ resources: string[];
22
+ checks: PermissionCheck[];
23
+ metadata: Record<string, unknown>;
24
+ }
25
+ export declare function isWithin(root: string, target: string): boolean;
26
+ /** The directory-like option in a normalized operation input, if any. */
27
+ export declare function directoryInputFrom(input: Record<string, unknown> | undefined): string | undefined;
28
+ export declare function commandPermissions(root: string, command: ManifestCommand, input: Record<string, unknown>): CommandPermissions;
29
+ export declare function assertPermission(permission: Plugin.Context["permission"], sessionID: string, perm: CommandPermissions): Promise<void>;
@@ -0,0 +1,97 @@
1
+ import { isAbsolute, relative, resolve } from "node:path";
2
+ export const ACTIONS = {
3
+ run: "sketchbook.run",
4
+ mutate: "sketchbook.mutate",
5
+ delete: "sketchbook.delete",
6
+ external: "sketchbook.external",
7
+ install: "sketchbook.install",
8
+ upgrade: "sketchbook.upgrade",
9
+ privileged: "sketchbook.privileged",
10
+ init: "sketchbook.init",
11
+ edit: "edit",
12
+ externalDirectory: "external_directory",
13
+ };
14
+ export function isWithin(root, target) {
15
+ const rel = relative(resolve(root), resolve(target));
16
+ return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
17
+ }
18
+ /**
19
+ * Option keys that may carry an operation's target directory. The CLI spells
20
+ * it `--dir`; manifests and callers may use either name.
21
+ */
22
+ const DIRECTORY_INPUT_KEYS = ["directory", "dir"];
23
+ /** The directory-like option in a normalized operation input, if any. */
24
+ export function directoryInputFrom(input) {
25
+ if (!input)
26
+ return undefined;
27
+ for (const key of DIRECTORY_INPUT_KEYS) {
28
+ const value = input[key];
29
+ if (typeof value === "string" && value.trim())
30
+ return value;
31
+ }
32
+ return undefined;
33
+ }
34
+ export function commandPermissions(root, command, input) {
35
+ const actions = [ACTIONS.run];
36
+ // Nested operations may be safer or riskier than their parent command. Use the
37
+ // selected subcommand first, then the command risk, then the conservative
38
+ // mutation-based default for older manifests.
39
+ const subcommand = typeof input.subcommand === "string"
40
+ ? command.subcommands?.find((s) => s.name === input.subcommand)
41
+ : undefined;
42
+ const risk = subcommand?.risk
43
+ ?? command.risk
44
+ ?? (command.mutates ? "write" : "read");
45
+ if (risk !== "read")
46
+ actions.push(ACTIONS.mutate);
47
+ if (risk === "delete")
48
+ actions.push(ACTIONS.delete);
49
+ if (risk === "external-write")
50
+ actions.push(ACTIONS.external);
51
+ if (risk === "install")
52
+ actions.push(ACTIONS.install);
53
+ if (risk === "upgrade")
54
+ actions.push(ACTIONS.upgrade);
55
+ if (risk === "privileged")
56
+ actions.push(ACTIONS.privileged);
57
+ if (command.name === "init")
58
+ actions.push(ACTIONS.init);
59
+ // Commands that explicitly say they do not need a project may still receive a directory;
60
+ // init is the exception because it may create the directory itself.
61
+ const requestedDirectory = directoryInputFrom(input);
62
+ const target = command.name === "init" && requestedDirectory
63
+ ? requestedDirectory
64
+ : root;
65
+ const resolvedTarget = resolve(target);
66
+ // Sketchbook tools are not a way around OpenCode's own boundaries. File
67
+ // mutations still assert `edit`, and targets outside the active location also
68
+ // assert `external_directory`.
69
+ const checks = actions.map((action) => ({ action, resource: target }));
70
+ if (risk !== "read")
71
+ checks.push({ action: ACTIONS.edit, resource: resolvedTarget });
72
+ if (!isWithin(root, resolvedTarget)) {
73
+ checks.push({ action: ACTIONS.externalDirectory, resource: `${resolvedTarget}/*` });
74
+ }
75
+ return {
76
+ actions,
77
+ resources: [target],
78
+ checks,
79
+ metadata: {
80
+ command: command.name,
81
+ subcommand: input.subcommand,
82
+ mutates: command.mutates,
83
+ risk,
84
+ dryRun: input.dryRun === true,
85
+ },
86
+ };
87
+ }
88
+ export async function assertPermission(permission, sessionID, perm) {
89
+ for (const check of perm.checks) {
90
+ await permission.assert({
91
+ sessionID: sessionID,
92
+ action: check.action,
93
+ resources: [check.resource],
94
+ metadata: perm.metadata,
95
+ });
96
+ }
97
+ }
@@ -0,0 +1,126 @@
1
+ import type { Plugin } from "@opencode/plugin";
2
+ import { SketchbookRpc } from "../rpc.js";
3
+ /**
4
+ * Typed RPC error. The `code` extends the SKETCHBOOK_* convention and maps to
5
+ * one of the named errors in the SketchbookRpc definition, so clients never
6
+ * have to parse message text.
7
+ */
8
+ export declare class RpcMethodError extends Error {
9
+ readonly code: string;
10
+ readonly details: {
11
+ command?: string;
12
+ operationID?: string;
13
+ };
14
+ constructor(code: string, message: string, details?: {
15
+ command?: string;
16
+ operationID?: string;
17
+ });
18
+ }
19
+ export declare const RPC_ERROR_CODES: {
20
+ readonly stalePreview: "SKETCHBOOK_STALE_PREVIEW";
21
+ readonly notFound: "SKETCHBOOK_NOT_FOUND";
22
+ readonly cancelled: "SKETCHBOOK_CANCELLED";
23
+ readonly timeout: "SKETCHBOOK_TIMEOUT";
24
+ readonly outputLimit: "SKETCHBOOK_OUTPUT_LIMIT";
25
+ readonly permission: "SKETCHBOOK_PERMISSION_DENIED";
26
+ };
27
+ export type RpcErrorName = "sketchbook_operation" | "sketchbook_stale_preview" | "sketchbook_not_found" | "sketchbook_cancelled" | "sketchbook_timeout" | "sketchbook_output_limit" | "sketchbook_permission";
28
+ export interface RpcErrorData {
29
+ code: string;
30
+ message: string;
31
+ command?: string;
32
+ operationID?: string;
33
+ }
34
+ /**
35
+ * Converts any operation-service failure into a typed RPC handler error
36
+ * ({ type, message, data }). Used directly by handlers and by tests.
37
+ */
38
+ export declare function toRpcError(error: unknown, context?: {
39
+ command?: string;
40
+ operationID?: string;
41
+ }): {
42
+ type: RpcErrorName;
43
+ message: string;
44
+ data: RpcErrorData;
45
+ };
46
+ export type OperationStatus = "running" | "completed" | "cancelled" | "failed";
47
+ export interface OperationEntry {
48
+ readonly operationID: string;
49
+ readonly command: string;
50
+ status: OperationStatus;
51
+ readonly startedAt: string;
52
+ finishedAt?: string;
53
+ readonly controller: AbortController;
54
+ readonly progress: Array<{
55
+ sequence: number;
56
+ source: "stdout" | "stderr";
57
+ line: string;
58
+ }>;
59
+ /** Resolves when the operation settles, so cancel can await a terminal state. */
60
+ readonly settled: Promise<void>;
61
+ /** @internal resolves `settled`; called by the run/preview handlers. */
62
+ readonly settle: () => void;
63
+ }
64
+ export declare function getOperation(operationID: string): OperationEntry | undefined;
65
+ export declare function resetOperations(): void;
66
+ export interface RpcEnvelope {
67
+ root: string;
68
+ permission?: Plugin.Context["permission"];
69
+ /**
70
+ * Session attribution for permission checks. RPC calls run outside a tool
71
+ * session, so a stable plugin-scoped identity is used unless the host
72
+ * provides one.
73
+ */
74
+ sessionID?: string;
75
+ /** Emits a SketchbookRpc event; the host registration forwards to the bus. */
76
+ emit?: (event: "progress" | "operation", data: Record<string, unknown>) => void;
77
+ }
78
+ export declare const RPC_SESSION_ID = "sketchbook-rpc";
79
+ interface OperationRunInput {
80
+ command: string;
81
+ subcommand?: string;
82
+ args?: string[];
83
+ options?: Record<string, string | boolean | undefined>;
84
+ dryRun?: boolean;
85
+ operationID?: string;
86
+ timeoutMs?: number;
87
+ maxOutputBytes?: number;
88
+ }
89
+ type MethodInput<I> = I & {
90
+ operationID?: string;
91
+ };
92
+ type RunMethodInput = MethodInput<OperationRunInput>;
93
+ export interface RpcCallContext {
94
+ signal?: AbortSignal;
95
+ }
96
+ export type SketchbookRpcHandlers = {
97
+ capabilities: (input: Record<string, never>, context: RpcCallContext) => Promise<Record<string, unknown>>;
98
+ run: (input: RunMethodInput, context: RpcCallContext) => Promise<Record<string, unknown>>;
99
+ preview: (input: RunMethodInput, context: RpcCallContext) => Promise<Record<string, unknown>>;
100
+ apply: (input: {
101
+ operationID: string;
102
+ }, context: RpcCallContext) => Promise<Record<string, unknown>>;
103
+ cancel: (input: {
104
+ operationID: string;
105
+ }, context: RpcCallContext) => Promise<Record<string, unknown>>;
106
+ status: (input: {
107
+ operationID?: string;
108
+ }, context: RpcCallContext) => Promise<Record<string, unknown>>;
109
+ };
110
+ /**
111
+ * Builds the RPC method handlers over the shared operation service. Pure with
112
+ * respect to the engine: nothing executes until a method is invoked, so plugin
113
+ * setup stays free of engine runs. `signal` from the RPC call context is
114
+ * chained onto the operation's own AbortController for cancellation
115
+ * propagation.
116
+ */
117
+ export declare function createSketchbookRpcHandlers(env: RpcEnvelope): SketchbookRpcHandlers;
118
+ /**
119
+ * Registers the full Sketchbook RPC surface with the host. Registration itself
120
+ * performs no engine execution: the manifest is only loaded when the
121
+ * `capabilities` method is invoked, and the bundled baseline is never needed
122
+ * here because method inputs are hand-written schemas.
123
+ */
124
+ export declare function setupRpc(ctx: Plugin.Context): Promise<void>;
125
+ export type SketchbookRpcDefinition = typeof SketchbookRpc;
126
+ export {};