@usesketchbook/opencode-plugin 0.0.0-stage → 0.1.0

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,176 @@
1
+ import { commandInputSchema } from "./schema.js";
2
+ import { executeOperation, loadCapabilities, previewOperation, applyPreview, splitInput, StalePreviewError } from "./operations.js";
3
+ import { resolveEngine } from "./engine.js";
4
+ import { BASELINE_MANIFEST } from "../generated/baseline-manifest.js";
5
+ const NAMESPACE = "sketchbook";
6
+ export async function setupTools(ctx) {
7
+ const root = ctx.location.directory;
8
+ const permission = ctx.permission;
9
+ // Registration uses the bundled baseline so plugin setup never executes a
10
+ // project-local engine. Operations and explicit capabilities requests still
11
+ // load and validate the active engine lazily.
12
+ const manifest = BASELINE_MANIFEST;
13
+ await ctx.tool.transform((editor) => {
14
+ editor.namespace({
15
+ name: NAMESPACE,
16
+ description: `Sketchbook design-system operations (baseline protocol ${manifest.protocolVersion}).`,
17
+ });
18
+ for (const command of manifest.commands) {
19
+ if (command.name === "capabilities") {
20
+ // The capabilities tool is registered explicitly so it can be called without the project.
21
+ continue;
22
+ }
23
+ // Interactive terminal workflows get native TUI/Desktop experiences instead
24
+ // of being embedded in a child process.
25
+ if (command.interactiveOnly)
26
+ continue;
27
+ registerCommandTool(editor, root, permission, command);
28
+ }
29
+ registerApplyPreviewTool(editor, root, permission);
30
+ editor.add({
31
+ name: "capabilities",
32
+ description: "Return the Sketchbook engine capabilities manifest for the active location, including every available command and its automation contract.",
33
+ input: {
34
+ type: "object",
35
+ properties: {},
36
+ additionalProperties: false,
37
+ },
38
+ options: { namespace: NAMESPACE, codemode: true },
39
+ execute: async (input, context) => {
40
+ const manifest = await loadCapabilities(root, {
41
+ permission,
42
+ sessionID: context.sessionID,
43
+ });
44
+ return {
45
+ content: JSON.stringify(manifest, null, 2),
46
+ metadata: { engine: manifest.engine },
47
+ };
48
+ },
49
+ });
50
+ });
51
+ }
52
+ function registerApplyPreviewTool(editor, root, permission) {
53
+ editor.add({
54
+ name: "apply_preview",
55
+ description: "Apply a previously created Sketchbook preview after revalidating its current plan. Use the preview ID returned by a supported mutation tool.",
56
+ input: {
57
+ type: "object",
58
+ properties: {
59
+ operationID: {
60
+ type: "string",
61
+ description: "The preview operation ID returned by a Sketchbook mutation preview.",
62
+ },
63
+ },
64
+ required: ["operationID"],
65
+ additionalProperties: false,
66
+ },
67
+ options: { namespace: NAMESPACE, codemode: true },
68
+ execute: async (input, context) => {
69
+ const params = input;
70
+ const operationID = typeof params.operationID === "string" ? params.operationID : "";
71
+ try {
72
+ const result = await applyPreview({
73
+ operationID,
74
+ root,
75
+ permission,
76
+ sessionID: context.sessionID,
77
+ signal: context.signal,
78
+ });
79
+ return {
80
+ content: JSON.stringify(result.envelope, null, 2),
81
+ metadata: {
82
+ ok: true,
83
+ changed: result.envelope.changed,
84
+ engine: result.engine,
85
+ appliedPreview: operationID,
86
+ },
87
+ };
88
+ }
89
+ catch (error) {
90
+ if (error instanceof StalePreviewError) {
91
+ return {
92
+ content: JSON.stringify({
93
+ ok: false,
94
+ command: "apply_preview",
95
+ code: error.code,
96
+ message: error.message,
97
+ }, null, 2),
98
+ metadata: { ok: false, stale: true },
99
+ };
100
+ }
101
+ throw error;
102
+ }
103
+ },
104
+ });
105
+ }
106
+ function registerCommandTool(editor, root, permission, command) {
107
+ const toolName = command.name.replace(/\//g, "_");
108
+ const inputSchema = commandInputSchema(command);
109
+ editor.add({
110
+ name: toolName,
111
+ description: `${command.summary} Examples: ${command.examples.join("; ") || command.usage}`,
112
+ input: inputSchema,
113
+ options: { namespace: NAMESPACE, codemode: true },
114
+ execute: async (input, context) => {
115
+ const params = input;
116
+ const subcommand = typeof params.subcommand === "string" ? params.subcommand : undefined;
117
+ // Let the operation service choose the safe preview default; only an explicit
118
+ // false from the caller means "apply".
119
+ const dryRun = typeof params.dryRun === "boolean" ? params.dryRun : undefined;
120
+ const engineInfo = resolveEngine(root);
121
+ const { args, options } = splitInput(params, command);
122
+ const operation = {
123
+ root,
124
+ command: command.name,
125
+ subcommand,
126
+ args,
127
+ options,
128
+ signal: context.signal,
129
+ permission,
130
+ sessionID: context.sessionID,
131
+ onLine: (line, source) => {
132
+ context.progress({
133
+ command: command.name,
134
+ source,
135
+ line,
136
+ engine: engineInfo.source,
137
+ }).catch(() => {
138
+ // Progress failures are best-effort.
139
+ });
140
+ },
141
+ };
142
+ // Supported mutations use the shared preview store. Direct apply remains
143
+ // available for explicitly requested, non-previewable operations.
144
+ const result = command.mutates && command.dryRun && dryRun !== false
145
+ ? await previewOperation(operation)
146
+ : await executeOperation({ ...operation, dryRun });
147
+ if ("id" in result && "fingerprint" in result) {
148
+ return {
149
+ content: JSON.stringify(result.plan, null, 2),
150
+ metadata: {
151
+ ok: true,
152
+ preview: {
153
+ id: result.id,
154
+ fingerprint: result.fingerprint,
155
+ status: result.status,
156
+ },
157
+ engine: engineInfo,
158
+ },
159
+ };
160
+ }
161
+ const envelope = result.envelope;
162
+ const engine = result.engine;
163
+ const text = JSON.stringify(envelope, null, 2);
164
+ if (!envelope.ok) {
165
+ return {
166
+ content: text,
167
+ metadata: { ok: false, engine },
168
+ };
169
+ }
170
+ return {
171
+ content: text,
172
+ metadata: { ok: true, changed: envelope.changed, engine },
173
+ };
174
+ },
175
+ });
176
+ }
@@ -0,0 +1,70 @@
1
+ import type { SketchbookRpcHandlers } from "./rpc.js";
2
+ /**
3
+ * TUI workflows over the Sketchbook RPC surface. Everything the workflows
4
+ * show or do goes through the typed RPC handlers (`capabilities`, `status`,
5
+ * `preview`, `apply`), never around them, so the TUI has exactly the same
6
+ * permission and dry-run behavior as every other client.
7
+ *
8
+ * The host may lack TUI APIs (headless server plugin context, older host):
9
+ * every touch point is feature-detected and the setup degrades to a report
10
+ * with `supported: false` instead of throwing, so the rest of the plugin is
11
+ * never destabilized by a missing UI.
12
+ */
13
+ export declare const TUI_COMMAND_IDS: {
14
+ readonly status: "sketchbook.status";
15
+ readonly operations: "sketchbook.operations";
16
+ readonly apply: "sketchbook.apply";
17
+ };
18
+ export type TuiCommandId = (typeof TUI_COMMAND_IDS)[keyof typeof TUI_COMMAND_IDS];
19
+ export interface TuiSetupReport {
20
+ /** False when the host context lacks the TUI APIs the workflows need. */
21
+ supported: boolean;
22
+ /** Palette command ids registered with `keymap.layer`. */
23
+ commands: TuiCommandId[];
24
+ /** Host APIs that were absent, driving the graceful degradation. */
25
+ missing: string[];
26
+ }
27
+ /** Minimal structural view of the TUI plugin context we feature-detect. */
28
+ export interface TuiHostContext {
29
+ readonly location?: {
30
+ readonly directory?: string;
31
+ };
32
+ readonly keymap?: {
33
+ readonly layer: (factory: () => unknown) => void;
34
+ };
35
+ readonly ui?: {
36
+ readonly dialog: {
37
+ readonly alert: (options: {
38
+ title: string;
39
+ message: string;
40
+ }) => Promise<void>;
41
+ readonly confirm: (options: {
42
+ title: string;
43
+ message: string;
44
+ label?: {
45
+ readonly confirm?: string;
46
+ readonly cancel?: string;
47
+ };
48
+ }) => Promise<boolean | undefined>;
49
+ readonly select: <Value>(options: {
50
+ title: string;
51
+ options: readonly {
52
+ readonly title: string;
53
+ readonly value: Value;
54
+ readonly description?: string;
55
+ }[];
56
+ }) => Promise<Value | undefined>;
57
+ };
58
+ };
59
+ }
60
+ export interface SetupTuiOptions {
61
+ /** Prebuilt handlers (tests inject fakes). Built from `root` when omitted. */
62
+ handlers?: SketchbookRpcHandlers;
63
+ /** Project root used to build handlers when `handlers` is omitted. */
64
+ root?: string;
65
+ }
66
+ /**
67
+ * Registers the Sketchbook TUI workflows. Pure with respect to the engine:
68
+ * handlers are created but nothing is invoked until a command runs.
69
+ */
70
+ export declare function setupTui(ctx: TuiHostContext, options?: SetupTuiOptions): Promise<TuiSetupReport>;
@@ -0,0 +1,172 @@
1
+ import { createSketchbookRpcHandlers } from "./rpc.js";
2
+ import { formatApplyResult, formatOperationProgress, formatPreviewPlan, formatStatusOverview, } from "../views/operations.js";
3
+ /**
4
+ * TUI workflows over the Sketchbook RPC surface. Everything the workflows
5
+ * show or do goes through the typed RPC handlers (`capabilities`, `status`,
6
+ * `preview`, `apply`), never around them, so the TUI has exactly the same
7
+ * permission and dry-run behavior as every other client.
8
+ *
9
+ * The host may lack TUI APIs (headless server plugin context, older host):
10
+ * every touch point is feature-detected and the setup degrades to a report
11
+ * with `supported: false` instead of throwing, so the rest of the plugin is
12
+ * never destabilized by a missing UI.
13
+ */
14
+ export const TUI_COMMAND_IDS = {
15
+ status: "sketchbook.status",
16
+ operations: "sketchbook.operations",
17
+ apply: "sketchbook.apply",
18
+ };
19
+ const TUI_TITLE = "Sketchbook";
20
+ /**
21
+ * Registers the Sketchbook TUI workflows. Pure with respect to the engine:
22
+ * handlers are created but nothing is invoked until a command runs.
23
+ */
24
+ export async function setupTui(ctx, options = {}) {
25
+ const missing = [];
26
+ if (!ctx.ui?.dialog)
27
+ missing.push("ui.dialog");
28
+ if (!ctx.keymap?.layer)
29
+ missing.push("keymap.layer");
30
+ if (missing.length > 0) {
31
+ return { supported: false, commands: [], missing };
32
+ }
33
+ const handlers = options.handlers
34
+ ?? createSketchbookRpcHandlers({ root: options.root ?? ctx.location?.directory ?? process.cwd() });
35
+ const ui = ctx.ui;
36
+ const dialog = ui.dialog;
37
+ const alert = async (title, lines) => {
38
+ await dialog.alert({ title, message: lines.join("\n") });
39
+ };
40
+ const describeError = (error) => error instanceof Error ? error.message : String(error);
41
+ /** Status overview: engine, protocol surface, and recent operations. */
42
+ const showStatus = async () => {
43
+ const [capabilities, status] = await Promise.allSettled([
44
+ handlers.capabilities({}, {}),
45
+ handlers.status({}, {}),
46
+ ]);
47
+ const caps = capabilities.status === "fulfilled" ? capabilities.value : undefined;
48
+ const ops = status.status === "fulfilled"
49
+ ? (status.value.operations ?? [])
50
+ : [];
51
+ const lines = formatStatusOverview({
52
+ engine: caps?.engine,
53
+ protocolVersion: caps?.protocolVersion,
54
+ envelopeVersion: caps?.envelopeVersion,
55
+ commandCount: caps?.commands?.length,
56
+ operations: ops,
57
+ });
58
+ if (capabilities.status === "rejected") {
59
+ lines.push(`Capabilities unavailable: ${describeError(capabilities.reason)}`);
60
+ }
61
+ await alert(`${TUI_TITLE} — status`, lines);
62
+ };
63
+ /** Operation progress view for every operation known to this session. */
64
+ const showOperations = async () => {
65
+ try {
66
+ const result = (await handlers.status({}, {}));
67
+ const ops = result.operations ?? [];
68
+ const lines = ops.length === 0
69
+ ? ["No Sketchbook operations in this session yet."]
70
+ : ops.flatMap((operation) => formatOperationProgress(operation));
71
+ await alert(`${TUI_TITLE} — operations`, lines);
72
+ }
73
+ catch (error) {
74
+ await alert(`${TUI_TITLE} — operations`, [`Status unavailable: ${describeError(error)}`]);
75
+ }
76
+ };
77
+ /**
78
+ * Preview/apply flow: pick a command, review its dry-run plan, then apply
79
+ * after an explicit confirmation. Cancelling discards the preview; the
80
+ * only project writes happen through `apply` after that confirmation.
81
+ */
82
+ const showApplyFlow = async () => {
83
+ let commands;
84
+ try {
85
+ const caps = (await handlers.capabilities({}, {}));
86
+ commands = (caps.commands ?? []).map((command) => command);
87
+ }
88
+ catch (error) {
89
+ await alert(TUI_TITLE, [`Capabilities unavailable: ${describeError(error)}`]);
90
+ return;
91
+ }
92
+ if (commands === undefined || commands.length === 0) {
93
+ await alert(TUI_TITLE, ["The engine exposes no commands."]);
94
+ return;
95
+ }
96
+ const picked = await dialog.select({
97
+ title: `${TUI_TITLE}: preview a command`,
98
+ options: commands.map((command) => ({
99
+ title: command.name,
100
+ value: command.name,
101
+ ...(command.summary ? { description: command.summary } : {}),
102
+ })),
103
+ });
104
+ if (picked === undefined)
105
+ return;
106
+ let operationID;
107
+ let planLines;
108
+ try {
109
+ const previewed = (await handlers.preview({ command: picked }, {}));
110
+ operationID = previewed.operationID;
111
+ planLines = formatPreviewPlan(previewed.envelope, previewed.preview);
112
+ }
113
+ catch (error) {
114
+ await alert(TUI_TITLE, [`Preview failed: ${describeError(error)}`]);
115
+ return;
116
+ }
117
+ const confirmed = await dialog.confirm({
118
+ title: `${TUI_TITLE}: apply preview`,
119
+ message: planLines.join("\n"),
120
+ label: { confirm: "Apply", cancel: "Discard" },
121
+ });
122
+ if (confirmed !== true) {
123
+ await alert(TUI_TITLE, [`Preview discarded for ${picked}; nothing was written.`]);
124
+ return;
125
+ }
126
+ try {
127
+ const applied = (await handlers.apply({ operationID }, {}));
128
+ await alert(TUI_TITLE, formatApplyResult(applied));
129
+ }
130
+ catch (error) {
131
+ // Includes SKETCHBOOK_STALE_PREVIEW: the project moved on since the
132
+ // preview, so the apply was rejected and nothing was written.
133
+ await alert(TUI_TITLE, [`Apply rejected: ${describeError(error)}`]);
134
+ }
135
+ };
136
+ ctx.keymap.layer(() => ({
137
+ mode: "global",
138
+ commands: [
139
+ {
140
+ id: TUI_COMMAND_IDS.status,
141
+ title: "Sketchbook: status overview",
142
+ description: "Engine, protocol surface, and recent Sketchbook operations",
143
+ group: "Sketchbook",
144
+ palette: true,
145
+ run: () => {
146
+ void showStatus();
147
+ },
148
+ },
149
+ {
150
+ id: TUI_COMMAND_IDS.operations,
151
+ title: "Sketchbook: operation progress",
152
+ description: "Progress of every Sketchbook operation in this session",
153
+ group: "Sketchbook",
154
+ palette: true,
155
+ run: () => {
156
+ void showOperations();
157
+ },
158
+ },
159
+ {
160
+ id: TUI_COMMAND_IDS.apply,
161
+ title: "Sketchbook: preview and apply",
162
+ description: "Dry-run a command, review the plan, apply after confirmation",
163
+ group: "Sketchbook",
164
+ palette: true,
165
+ run: () => {
166
+ void showApplyFlow();
167
+ },
168
+ },
169
+ ],
170
+ }));
171
+ return { supported: true, commands: [...Object.values(TUI_COMMAND_IDS)], missing: [] };
172
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Shared catalog surfaces. Skills, slash commands and native subagents are
3
+ * generated from the same source the harness renders client projections from
4
+ * (`harness/templates/agent-catalog`); the bundled baseline in
5
+ * `src/generated/catalog-baseline.ts` is a build-time projection of that
6
+ * source, the same pattern as the CLI capabilities baseline manifest. Nothing
7
+ * here duplicates catalog copy by hand.
8
+ */
9
+ export interface CatalogBrief {
10
+ readonly name: string;
11
+ readonly description: string;
12
+ /** Space-separated tool list from the brief frontmatter, "" when unset. */
13
+ readonly tools: string;
14
+ readonly content: string;
15
+ readonly source: string;
16
+ }
17
+ export interface CatalogSkill {
18
+ readonly name: string;
19
+ readonly description: string;
20
+ readonly autoinvoke: boolean;
21
+ readonly content: string;
22
+ readonly source: string;
23
+ readonly briefs: readonly CatalogBrief[];
24
+ }
25
+ export interface CatalogCommand {
26
+ readonly name: string;
27
+ readonly description: string;
28
+ readonly argumentHint: string;
29
+ readonly content: string;
30
+ readonly source: string;
31
+ }
32
+ export interface CatalogBaseline {
33
+ readonly source: string;
34
+ readonly skills: readonly CatalogSkill[];
35
+ readonly commands: readonly CatalogCommand[];
36
+ }
37
+ export declare class CatalogValidationError extends Error {
38
+ }
39
+ /** Validates a catalog baseline, throwing `CatalogValidationError` on any bad entry. */
40
+ export declare function validateCatalog(baseline: CatalogBaseline): CatalogBaseline;
41
+ /**
42
+ * The validated bundled baseline. Thrown errors surface at plugin setup, so a
43
+ * stale or hand-broken generated file fails loudly instead of registering
44
+ * partial surfaces.
45
+ */
46
+ export declare function loadCatalogBaseline(): CatalogBaseline;
47
+ /**
48
+ * Renders a command body for a session: `<input>` placeholders (the shared
49
+ * catalog convention) become the arguments the person typed.
50
+ */
51
+ export declare function renderCommandBody(body: string, arguments_: string): string;
52
+ export declare const catalogSkillIDs: (baseline: CatalogBaseline) => string[];
@@ -0,0 +1,84 @@
1
+ import { CATALOG_BASELINE } from "../generated/catalog-baseline.js";
2
+ export class CatalogValidationError extends Error {
3
+ }
4
+ function assertEntryName(name, kind, source) {
5
+ if (!name || !/^[a-z][a-z0-9-]*$/.test(name)) {
6
+ throw new CatalogValidationError(`Invalid ${kind} name "${name}" from ${source}`);
7
+ }
8
+ }
9
+ function assertDescription(description, kind, source) {
10
+ if (!description || !description.trim()) {
11
+ throw new CatalogValidationError(`Missing description on ${kind} ${source}`);
12
+ }
13
+ }
14
+ function assertContent(content, kind, source) {
15
+ if (!content || !content.trim()) {
16
+ throw new CatalogValidationError(`Empty content for ${kind} ${source}`);
17
+ }
18
+ }
19
+ /** Validates a catalog baseline, throwing `CatalogValidationError` on any bad entry. */
20
+ export function validateCatalog(baseline) {
21
+ if (!baseline.source) {
22
+ throw new CatalogValidationError("Catalog baseline is missing its source path");
23
+ }
24
+ if (!Array.isArray(baseline.skills) || !Array.isArray(baseline.commands)) {
25
+ throw new CatalogValidationError("Catalog baseline must have skills and commands arrays");
26
+ }
27
+ const skillNames = new Set();
28
+ for (const skill of baseline.skills) {
29
+ assertEntryName(skill.name, "skill", skill.source);
30
+ assertDescription(skill.description, "skill", skill.source);
31
+ assertContent(skill.content, "skill", skill.source);
32
+ if (typeof skill.autoinvoke !== "boolean") {
33
+ throw new CatalogValidationError(`Skill ${skill.name} is missing a boolean autoinvoke flag`);
34
+ }
35
+ if (skillNames.has(skill.name)) {
36
+ throw new CatalogValidationError(`Duplicate skill name "${skill.name}"`);
37
+ }
38
+ skillNames.add(skill.name);
39
+ const briefNames = new Set();
40
+ for (const brief of skill.briefs) {
41
+ assertEntryName(brief.name, "agent brief", brief.source);
42
+ assertDescription(brief.description, "agent brief", brief.source);
43
+ assertContent(brief.content, "agent brief", brief.source);
44
+ if (briefNames.has(brief.name)) {
45
+ throw new CatalogValidationError(`Duplicate agent brief "${brief.name}" in skill ${skill.name}`);
46
+ }
47
+ briefNames.add(brief.name);
48
+ }
49
+ }
50
+ const commandNames = new Set();
51
+ for (const command of baseline.commands) {
52
+ assertEntryName(command.name, "command", command.source);
53
+ assertDescription(command.description, "command", command.source);
54
+ assertContent(command.content, "command", command.source);
55
+ if (commandNames.has(command.name)) {
56
+ throw new CatalogValidationError(`Duplicate command name "${command.name}"`);
57
+ }
58
+ commandNames.add(command.name);
59
+ }
60
+ if (baseline.skills.length === 0 || baseline.commands.length === 0) {
61
+ throw new CatalogValidationError("Catalog baseline must contain at least one skill and one command");
62
+ }
63
+ return baseline;
64
+ }
65
+ /**
66
+ * The validated bundled baseline. Thrown errors surface at plugin setup, so a
67
+ * stale or hand-broken generated file fails loudly instead of registering
68
+ * partial surfaces.
69
+ */
70
+ export function loadCatalogBaseline() {
71
+ return validateCatalog(CATALOG_BASELINE);
72
+ }
73
+ /**
74
+ * Renders a command body for a session: `<input>` placeholders (the shared
75
+ * catalog convention) become the arguments the person typed.
76
+ */
77
+ export function renderCommandBody(body, arguments_) {
78
+ const args = arguments_.trim();
79
+ if (!body.includes("<input>")) {
80
+ return args ? `${body}\n\n${args}` : body;
81
+ }
82
+ return body.replaceAll("<input>", args);
83
+ }
84
+ export const catalogSkillIDs = (baseline) => baseline.skills.map((skill) => skill.name);
@@ -0,0 +1,24 @@
1
+ export interface EnvelopeIssue {
2
+ file: string | null;
3
+ msg: string;
4
+ fix: string | null;
5
+ token?: string;
6
+ check?: string;
7
+ }
8
+ export interface Envelope {
9
+ ok: boolean;
10
+ command: string;
11
+ changed: string[];
12
+ warnings: (string | EnvelopeIssue)[];
13
+ errors: EnvelopeIssue[];
14
+ next: string | null;
15
+ data?: unknown;
16
+ }
17
+ export declare class CliError extends Error {
18
+ readonly command: string;
19
+ readonly exitCode: number | null;
20
+ readonly stderr: string;
21
+ readonly code = "SKETCHBOOK_CLI_ERROR";
22
+ constructor(command: string, exitCode: number | null, stderr: string, message: string);
23
+ }
24
+ export declare function parseEnvelope(text: string, command: string): Envelope;
@@ -0,0 +1,28 @@
1
+ export class CliError extends Error {
2
+ command;
3
+ exitCode;
4
+ stderr;
5
+ code = "SKETCHBOOK_CLI_ERROR";
6
+ constructor(command, exitCode, stderr, message) {
7
+ super(message);
8
+ this.command = command;
9
+ this.exitCode = exitCode;
10
+ this.stderr = stderr;
11
+ }
12
+ }
13
+ export function parseEnvelope(text, command) {
14
+ const trimmed = text.trim();
15
+ if (!trimmed) {
16
+ throw new CliError(command, null, "", "empty response from sketchbook CLI");
17
+ }
18
+ try {
19
+ const parsed = JSON.parse(trimmed);
20
+ if (typeof parsed.ok !== "boolean" || parsed.command !== command) {
21
+ throw new CliError(command, null, trimmed, "invalid envelope shape from sketchbook CLI");
22
+ }
23
+ return parsed;
24
+ }
25
+ catch (err) {
26
+ throw new CliError(command, null, trimmed, `failed to parse sketchbook CLI response: ${err instanceof Error ? err.message : String(err)}`);
27
+ }
28
+ }
@@ -0,0 +1,53 @@
1
+ export type CommandRisk = "read" | "write" | "delete" | "external-write" | "install" | "upgrade" | "privileged";
2
+ export interface ManifestOption {
3
+ type: "boolean" | "string";
4
+ description: string;
5
+ value?: string;
6
+ short?: string;
7
+ }
8
+ export interface ManifestArg {
9
+ name: string;
10
+ required: boolean;
11
+ variadic?: boolean;
12
+ description: string;
13
+ }
14
+ export interface ManifestSubcommand {
15
+ name: string;
16
+ usage: string;
17
+ summary: string;
18
+ mutates: boolean;
19
+ risk?: CommandRisk;
20
+ examples: string[];
21
+ }
22
+ export interface ManifestCommand {
23
+ name: string;
24
+ group: string;
25
+ summary: string;
26
+ usage: string;
27
+ args: ManifestArg[];
28
+ options: Record<string, ManifestOption>;
29
+ examples: string[];
30
+ mutates: boolean;
31
+ risk?: CommandRisk;
32
+ dryRun?: boolean;
33
+ interactiveOnly?: boolean;
34
+ project?: boolean;
35
+ subcommands?: ManifestSubcommand[];
36
+ }
37
+ export interface CapabilitiesManifest {
38
+ protocolVersion: string;
39
+ envelopeVersion: number;
40
+ engine: {
41
+ name: string;
42
+ version: string;
43
+ };
44
+ groups: Record<string, string>;
45
+ commands: ManifestCommand[];
46
+ }
47
+ export declare const AUTOMATION_PROTOCOL_VERSION = "1.0.0";
48
+ export declare const ENVELOPE_VERSION = 1;
49
+ export declare const COMMAND_RISKS: readonly CommandRisk[];
50
+ export declare class CompatibilityError extends Error {
51
+ readonly code = "SKETCHBOOK_INCOMPATIBLE_MANIFEST";
52
+ }
53
+ export declare function validateManifest(value: unknown): CapabilitiesManifest;