@mcpview/compose 0.13.1 → 0.14.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 (85) hide show
  1. package/CHANGELOG.md +118 -0
  2. package/README.md +53 -0
  3. package/esm/src/code-mode/chain.d.ts +24 -1
  4. package/esm/src/code-mode/chain.d.ts.map +1 -1
  5. package/esm/src/code-mode/chain.js +219 -86
  6. package/esm/src/code-mode/errors.d.ts +80 -0
  7. package/esm/src/code-mode/errors.d.ts.map +1 -0
  8. package/esm/src/code-mode/errors.js +140 -0
  9. package/esm/src/code-mode/guest-worker.d.ts +11 -0
  10. package/esm/src/code-mode/guest-worker.d.ts.map +1 -0
  11. package/esm/src/code-mode/guest-worker.js +80 -0
  12. package/esm/src/code-mode/mod.d.ts +3 -1
  13. package/esm/src/code-mode/mod.d.ts.map +1 -1
  14. package/esm/src/code-mode/mod.js +2 -0
  15. package/esm/src/code-mode/sandbox-core.d.ts +61 -0
  16. package/esm/src/code-mode/sandbox-core.d.ts.map +1 -0
  17. package/esm/src/code-mode/sandbox-core.js +424 -0
  18. package/esm/src/code-mode/sandbox.d.ts +68 -7
  19. package/esm/src/code-mode/sandbox.d.ts.map +1 -1
  20. package/esm/src/code-mode/sandbox.js +182 -120
  21. package/esm/src/code-mode/tool.d.ts.map +1 -1
  22. package/esm/src/code-mode/tool.js +2 -0
  23. package/esm/src/code-mode/worker-host.d.ts +82 -0
  24. package/esm/src/code-mode/worker-host.d.ts.map +1 -0
  25. package/esm/src/code-mode/worker-host.js +364 -0
  26. package/esm/src/code-mode/worker-protocol.d.ts +44 -0
  27. package/esm/src/code-mode/worker-protocol.d.ts.map +1 -0
  28. package/esm/src/code-mode/worker-protocol.js +7 -0
  29. package/esm/src/host/renderer/css/panel-controls.d.ts.map +1 -1
  30. package/esm/src/host/renderer/css/panel-controls.js +5 -1
  31. package/esm/src/host/renderer/js/card-height.d.ts +11 -1
  32. package/esm/src/host/renderer/js/card-height.d.ts.map +1 -1
  33. package/esm/src/host/renderer/js/card-height.js +57 -10
  34. package/esm/src/host/renderer/js/event-bus.d.ts +11 -0
  35. package/esm/src/host/renderer/js/event-bus.d.ts.map +1 -1
  36. package/esm/src/host/renderer/js/event-bus.js +49 -8
  37. package/esm/src/host/renderer/js/intrinsic-layout.d.ts +26 -0
  38. package/esm/src/host/renderer/js/intrinsic-layout.d.ts.map +1 -0
  39. package/esm/src/host/renderer/js/intrinsic-layout.js +44 -0
  40. package/esm/src/host/renderer/panel-resizing.d.ts.map +1 -1
  41. package/esm/src/host/renderer/panel-resizing.js +8 -0
  42. package/esm/src/version.d.ts +1 -1
  43. package/esm/src/version.js +1 -1
  44. package/package.json +1 -1
  45. package/script/src/code-mode/chain.d.ts +24 -1
  46. package/script/src/code-mode/chain.d.ts.map +1 -1
  47. package/script/src/code-mode/chain.js +218 -85
  48. package/script/src/code-mode/errors.d.ts +80 -0
  49. package/script/src/code-mode/errors.d.ts.map +1 -0
  50. package/script/src/code-mode/errors.js +148 -0
  51. package/script/src/code-mode/guest-worker.d.ts +11 -0
  52. package/script/src/code-mode/guest-worker.d.ts.map +1 -0
  53. package/script/src/code-mode/guest-worker.js +105 -0
  54. package/script/src/code-mode/mod.d.ts +3 -1
  55. package/script/src/code-mode/mod.d.ts.map +1 -1
  56. package/script/src/code-mode/mod.js +9 -1
  57. package/script/src/code-mode/sandbox-core.d.ts +61 -0
  58. package/script/src/code-mode/sandbox-core.d.ts.map +1 -0
  59. package/script/src/code-mode/sandbox-core.js +430 -0
  60. package/script/src/code-mode/sandbox.d.ts +68 -7
  61. package/script/src/code-mode/sandbox.d.ts.map +1 -1
  62. package/script/src/code-mode/sandbox.js +190 -122
  63. package/script/src/code-mode/tool.d.ts.map +1 -1
  64. package/script/src/code-mode/tool.js +2 -0
  65. package/script/src/code-mode/worker-host.d.ts +82 -0
  66. package/script/src/code-mode/worker-host.d.ts.map +1 -0
  67. package/script/src/code-mode/worker-host.js +399 -0
  68. package/script/src/code-mode/worker-protocol.d.ts +44 -0
  69. package/script/src/code-mode/worker-protocol.d.ts.map +1 -0
  70. package/script/src/code-mode/worker-protocol.js +8 -0
  71. package/script/src/host/renderer/css/panel-controls.d.ts.map +1 -1
  72. package/script/src/host/renderer/css/panel-controls.js +5 -1
  73. package/script/src/host/renderer/js/card-height.d.ts +11 -1
  74. package/script/src/host/renderer/js/card-height.d.ts.map +1 -1
  75. package/script/src/host/renderer/js/card-height.js +57 -10
  76. package/script/src/host/renderer/js/event-bus.d.ts +11 -0
  77. package/script/src/host/renderer/js/event-bus.d.ts.map +1 -1
  78. package/script/src/host/renderer/js/event-bus.js +50 -8
  79. package/script/src/host/renderer/js/intrinsic-layout.d.ts +26 -0
  80. package/script/src/host/renderer/js/intrinsic-layout.d.ts.map +1 -0
  81. package/script/src/host/renderer/js/intrinsic-layout.js +48 -0
  82. package/script/src/host/renderer/panel-resizing.d.ts.map +1 -1
  83. package/script/src/host/renderer/panel-resizing.js +8 -0
  84. package/script/src/version.d.ts +1 -1
  85. package/script/src/version.js +1 -1
@@ -4,32 +4,53 @@ exports.createSnippetChain = createSnippetChain;
4
4
  const sync_js_1 = require("./sync.js");
5
5
  const board_js_1 = require("./board.js");
6
6
  const providers_js_1 = require("./providers.js");
7
+ const errors_js_1 = require("./errors.js");
7
8
  const sandbox_js_1 = require("./sandbox.js");
8
9
  const maxNativeSize = 4 * 1024 * 1024;
9
10
  const maxNativeBytes = 6 * 1024 * 1024;
10
11
  const maxSavedChains = 64;
11
- const afterDispatch = "One or more upstream operations may have completed. Check their effects before replaying the chain.";
12
+ const maxPanelTitle = 120;
12
13
  function isRecord(value) {
13
14
  return value !== null && typeof value === "object" && !Array.isArray(value);
14
15
  }
15
16
  const providerErrors = new Map([
16
- ["INVALID_INPUT", "Check the snippet input against its declared schema."],
17
- ["ARTIFACT_UNAVAILABLE", "The input artifact is unavailable. Regenerate it before retrying."],
18
- ["PROFILE_INVALID", "The configured provider profile is invalid or unavailable."],
19
- ["UPSTREAM_ERROR", "The upstream operation failed."],
20
- ["TIMEOUT", "The upstream operation timed out."],
17
+ ["INVALID_INPUT", [
18
+ "the provider rejected the input",
19
+ "Check the input against the snippet's inputSchema from api.listSnippets",
20
+ ]],
21
+ ["ARTIFACT_UNAVAILABLE", [
22
+ "the input artifact is unavailable",
23
+ "Regenerate the artifact before retrying",
24
+ ]],
25
+ ["PROFILE_INVALID", [
26
+ "the configured provider profile is invalid or unavailable",
27
+ "Ask the operator to fix the provider profile; retrying will fail again",
28
+ ]],
29
+ ["UPSTREAM_ERROR", ["the upstream operation failed", "Retry once, then report the failure"]],
30
+ ["TIMEOUT", ["the upstream operation timed out", "Retry once with a smaller input"]],
31
+ ["UNAVAILABLE", ["the provider is unavailable", "Retry later"]],
21
32
  ]);
22
- function providerError(result) {
33
+ function providerError(provider, snippet, result) {
23
34
  const data = result.structuredContent;
24
35
  const error = isRecord(data) ? data.error : undefined;
25
- const code = isRecord(error) ? error.code : undefined;
26
- return (typeof code === "string" ? providerErrors.get(code) : undefined) ??
27
- "The provider reported an execution error.";
36
+ const code = isRecord(error) && typeof error.code === "string" ? error.code : undefined;
37
+ const known = code ? providerErrors.get(code) : undefined;
38
+ const [detail, recovery] = known ??
39
+ ["the provider reported an execution error", "Retry once, then report the failure"];
40
+ return new errors_js_1.CodeModeError("PROVIDER_ERROR", `Snippet ${snippet}: ${detail}`, recovery, {
41
+ context: { provider, snippet, providerCode: known ? code : "UNKNOWN" },
42
+ });
28
43
  }
29
44
  function validateParams(input, shape) {
30
- if (!isRecord(input))
31
- throw new Error("Supply params as a JSON object.");
32
- (0, sandbox_js_1.encodeValue)(input, 8192);
45
+ if (!isRecord(input)) {
46
+ throw new errors_js_1.CodeModeError("PARAMS_INVALID", "Supply params as a JSON object", "Pass an object");
47
+ }
48
+ try {
49
+ (0, sandbox_js_1.encodeValue)(input, 8192);
50
+ }
51
+ catch {
52
+ throw new errors_js_1.CodeModeError("PARAMS_INVALID", "params must be JSON of at most 8192 characters", "Pass fewer or smaller parameters", { context: { limit: 8192 } });
53
+ }
33
54
  if (shape) {
34
55
  const keys = Object.keys(input);
35
56
  if (keys.length !== Object.keys(shape).length ||
@@ -38,11 +59,56 @@ function validateParams(input, shape) {
38
59
  const kind = value === null ? "null" : Array.isArray(value) ? "array" : typeof value;
39
60
  return !Object.hasOwn(shape, key) || shape[key] !== kind;
40
61
  })) {
41
- throw new Error("Replay parameters must match the saved key names and JSON types.");
62
+ throw new errors_js_1.CodeModeError("PARAMS_INVALID", "Replay parameters must match the saved key names and JSON types", "Pass the parameters listed by listSaved, with the same types");
42
63
  }
43
64
  }
44
65
  return input;
45
66
  }
67
+ /** Map a catalog failure to a coded error. Catalog messages are constant strings. */
68
+ function catalogError(error) {
69
+ if (error instanceof errors_js_1.CodeModeError)
70
+ return error;
71
+ if (error instanceof TypeError || error instanceof RangeError || isCatalogError(error)) {
72
+ const catalogCode = isCatalogError(error) ? error.code : error.name;
73
+ return new errors_js_1.CodeModeError("CATALOG_ERROR", error.message, "Call listSaved, then replay an existing name", { context: { catalogCode } });
74
+ }
75
+ return new errors_js_1.CodeModeError("CATALOG_ERROR", "The saved chain catalog failed", "Retry once, then report the failure");
76
+ }
77
+ function isCatalogError(error) {
78
+ return error instanceof Error && error.name === "SnippetCatalogError" &&
79
+ typeof error.code === "string";
80
+ }
81
+ /**
82
+ * Await a catalog operation. A failure while the caller's signal is aborted is the
83
+ * caller's cancellation and keeps its reason; any other failure, a store's own
84
+ * `AbortError` included, is a catalog failure.
85
+ */
86
+ async function fromCatalog(work, signal) {
87
+ try {
88
+ return await work;
89
+ }
90
+ catch (error) {
91
+ if (signal?.aborted)
92
+ throw signal.reason;
93
+ throw catalogError(error);
94
+ }
95
+ }
96
+ /** The store may have written the chain even though the write was not confirmed. */
97
+ function saveFailed() {
98
+ return new errors_js_1.CodeModeError("SAVE_FAILED", "Failed to confirm that the chain was saved", "Call listSaved before saving again");
99
+ }
100
+ const SAVED_RECOVERY = "The chain was saved. Call listSaved before saving it again";
101
+ /**
102
+ * The cancellation exception: a DOMException named after the caller's reason, so
103
+ * a host can tell a cancelled task from a failed one. Its message carries the
104
+ * advice that structured fields cannot (a DOMException has no `effects`).
105
+ */
106
+ function interrupted(reason, advice) {
107
+ const name = reason instanceof DOMException && reason.name === "TimeoutError"
108
+ ? "TimeoutError"
109
+ : "AbortError";
110
+ return new DOMException(`[execute] INTERRUPTED: The chain was interrupted. Recovery: ${advice.join(". ")}.`, name);
111
+ }
46
112
  function output(value, panels = [], saved, sync = []) {
47
113
  const visible = {
48
114
  value,
@@ -62,8 +128,23 @@ function output(value, panels = [], saved, sync = []) {
62
128
  * Run JavaScript against host-configured snippet providers. Selected results stay
63
129
  * out of guest memory except for their declared JSON value. Supplying a catalog
64
130
  * enables named chains for calls with a trusted scope.
131
+ *
132
+ * Failures are {@link CodeModeError}s whose message reads
133
+ * `[execute] CODE: detail. Recovery: hint.`; a caller abort rejects with a
134
+ * DOMException. Once an upstream snippet call was dispatched, errors carry
135
+ * `effects: "possible"` and never repeat guest, provider or transport text.
136
+ *
137
+ * @example
138
+ * ```ts
139
+ * const execute = createSnippetChain(providers, catalog, { isolation: "worker" });
140
+ * const result = await execute({ code: "return 1;" }, { scope: "user-1" });
141
+ * ```
65
142
  */
66
- function createSnippetChain(providers, catalog) {
143
+ function createSnippetChain(providers, catalog, options = {}) {
144
+ const isolation = options.isolation ?? "worker";
145
+ (0, sandbox_js_1.assertSandboxIsolation)(isolation);
146
+ const limits = (0, sandbox_js_1.resolveSandboxLimits)(options.limits);
147
+ const aliases = [...providers.keys()];
67
148
  // Keep admission state only while saves overlap. Persistent catalogs are read again
68
149
  // on the next save so a completed tenant leaves no resident quota state here.
69
150
  const activeSaves = new Map();
@@ -73,15 +154,16 @@ function createSnippetChain(providers, catalog) {
73
154
  const exposedPorts = new Map();
74
155
  const sync = new Map();
75
156
  let totalBytes = 0;
76
- const value = await (0, sandbox_js_1.runProgram)(code, params, async (operation, args, signal) => {
157
+ const value = await (0, sandbox_js_1.runProgram)(code, params, async (operation, args, signal, stopped) => {
77
158
  signal.throwIfAborted();
78
159
  const [first, second, input] = args;
79
160
  if (operation === "panel") {
80
161
  const panel = typeof first === "string" ? receipts.get(first) : undefined;
81
- if (!panel || args.length > 2)
82
- throw new Error("Select a receipt from this execution.");
83
- if (second !== undefined && (typeof second !== "string" || second.length > 120)) {
84
- throw new Error("Panel titles may contain at most 120 characters.");
162
+ if (!panel || args.length > 2) {
163
+ throw new errors_js_1.CodeModeError("PANEL_INVALID", "Select a receipt returned by api.runSnippet in this execution", "Pass receipt.id from this run");
164
+ }
165
+ if (second !== undefined && (typeof second !== "string" || second.length > maxPanelTitle)) {
166
+ throw new errors_js_1.CodeModeError("PANEL_INVALID", `Panel titles may contain at most ${maxPanelTitle} characters`, "Shorten the title", { context: { maxTitleLength: maxPanelTitle } });
85
167
  }
86
168
  selected.set(panel.id, { ...panel, title: second ?? panel.title });
87
169
  exposedPorts.set(panel.id, panel.events);
@@ -90,111 +172,141 @@ function createSnippetChain(providers, catalog) {
90
172
  if (operation === "sync") {
91
173
  const rule = args.length === 1 ? (0, sync_js_1.parseSnippetSyncRule)(first) : undefined;
92
174
  if (!rule || !(0, sync_js_1.supportsSnippetSync)(rule, exposedPorts)) {
93
- status.diagnostic =
94
- "Sync requires distinct selected panel receipts and their declared event and action.";
95
- throw new Error(status.diagnostic);
175
+ throw new errors_js_1.CodeModeError("SYNC_INVALID", "Sync requires distinct selected panel receipts and their declared event and action", "Select both panels first, then use the source's declared event and the target's declared action");
96
176
  }
97
- const key = (0, sync_js_1.snippetSyncKey)(rule);
98
- sync.set(key, rule);
177
+ sync.set((0, sync_js_1.snippetSyncKey)(rule), rule);
99
178
  return null;
100
179
  }
101
180
  const provider = typeof first === "string" ? providers.get(first) : undefined;
102
- if (!provider)
103
- throw new Error("Unknown snippet provider.");
181
+ if (!provider) {
182
+ throw new errors_js_1.CodeModeError("PROVIDER_UNKNOWN", "No snippet provider is configured under this alias", "Use one of the configured provider aliases", { context: { available: aliases } });
183
+ }
184
+ const alias = first;
185
+ const callProvider = async (tool, args) => {
186
+ // Any provider call may have effects, and its text may echo into guest
187
+ // errors: redact from here on, not only after runSnippet.
188
+ // Reading `provider.names` may have held the event loop past the wall
189
+ // deadline: check the clock right before the provider can act.
190
+ if (stopped())
191
+ throw signal.reason;
192
+ status.dispatched = true;
193
+ try {
194
+ return await provider.call(tool, args, signal, context);
195
+ }
196
+ catch {
197
+ signal.throwIfAborted();
198
+ // Provider and transport errors, typed or not, may carry credentials or
199
+ // paths: keep only the fact.
200
+ throw new errors_js_1.CodeModeError("PROVIDER_UNAVAILABLE", `The ${alias} provider could not complete the request`,
201
+ // The request was sent: the provider may have acted before the failure.
202
+ "Check whether the operation took effect before retrying; the failure may be transient", { context: { provider: alias } });
203
+ }
204
+ };
104
205
  if (operation === "listSnippets" && args.length === 1) {
105
- const catalog = await provider.call("list_snippets", {}, signal, context);
206
+ const catalog = await callProvider("list_snippets", {});
106
207
  signal.throwIfAborted();
107
208
  const snippets = isRecord(catalog.structuredContent)
108
209
  ? catalog.structuredContent.snippets
109
210
  : undefined;
110
211
  if (catalog.isError || !Array.isArray(snippets)) {
111
- throw new Error("Provider snippet catalog is unavailable.");
212
+ throw new errors_js_1.CodeModeError("PROVIDER_UNAVAILABLE", `The ${alias} provider could not list its snippets`, "Retry once; the failure may be transient", { context: { provider: alias } });
112
213
  }
113
214
  return snippets.filter((item) => isRecord(item) && typeof item.name === "string" && provider.names.includes(item.name)).map(({ name, description, inputSchema }) => ({ name, description, inputSchema }));
114
215
  }
115
- if (operation !== "runSnippet" || args.length !== 3 || typeof second !== "string" ||
116
- !provider.names.includes(second) || !isRecord(input)) {
117
- throw new Error("Choose an approved named snippet and supply its input object.");
216
+ if (operation !== "runSnippet" || args.length !== 3 || !isRecord(input)) {
217
+ throw new errors_js_1.CodeModeError("ARGUMENT_INVALID", "Call api.runSnippet(provider, name, input) with an input object, or api.listSnippets(provider)", "Pass exactly the documented arguments");
118
218
  }
119
- status.dispatched = true;
120
- status.diagnostic = undefined;
121
- const result = await provider.call("run_snippet", { name: second, input }, signal, context);
122
- signal.throwIfAborted();
123
- if (result.isError) {
124
- status.diagnostic = `Snippet ${second}: ${providerError(result)}`;
125
- throw new Error(status.diagnostic);
219
+ if (typeof second !== "string" || !provider.names.includes(second)) {
220
+ throw new errors_js_1.CodeModeError("SNIPPET_NOT_APPROVED", "The requested snippet is not approved for this provider", "Call api.listSnippets(provider) and use one of its names", { context: { provider: alias, allowed: [...provider.names] } });
126
221
  }
222
+ const result = await callProvider("run_snippet", { name: second, input });
223
+ signal.throwIfAborted();
224
+ if (result.isError)
225
+ throw providerError(alias, second, result);
127
226
  if (!isRecord(result.structuredContent) || !Object.hasOwn(result.structuredContent, "value")) {
128
- status.diagnostic = `Snippet ${second} returned an invalid result.`;
129
- throw new Error(status.diagnostic);
227
+ throw new errors_js_1.CodeModeError("PROVIDER_RESULT_INVALID", `Snippet ${second} returned an invalid result`, "Report the provider bug; retrying will fail again", { context: { provider: alias, snippet: second } });
130
228
  }
131
229
  const value = result.structuredContent.value;
132
- (0, sandbox_js_1.encodeValue)(value);
133
- totalBytes += new TextEncoder().encode((0, sandbox_js_1.encodeValue)(result, maxNativeSize)).byteLength;
134
- if (totalBytes > maxNativeBytes) {
135
- throw new Error("Native snippet receipts exceed the board size limit.");
230
+ const tooLarge = (limit) => new errors_js_1.CodeModeError("RECEIPT_TOO_LARGE", `Snippet ${second} returned more than the board accepts`, "Select smaller results or fewer panels", { context: { provider: alias, snippet: second, limit } });
231
+ try {
232
+ (0, sandbox_js_1.encodeValue)(value, limits.valueLength);
233
+ }
234
+ catch {
235
+ throw tooLarge(limits.valueLength);
136
236
  }
237
+ let receiptSize;
238
+ try {
239
+ receiptSize = new TextEncoder().encode((0, sandbox_js_1.encodeValue)(result, maxNativeSize)).byteLength;
240
+ }
241
+ catch {
242
+ throw tooLarge(maxNativeSize);
243
+ }
244
+ totalBytes += receiptSize;
245
+ if (totalBytes > maxNativeBytes)
246
+ throw tooLarge(maxNativeBytes);
137
247
  const id = crypto.randomUUID();
138
248
  const events = (0, sync_js_1.snippetPorts)(provider.events, second);
139
249
  receipts.set(id, {
140
250
  id,
141
- provider: first,
251
+ provider: alias,
142
252
  name: second,
143
253
  title: second,
144
254
  result,
145
255
  ...(events ? { events } : {}),
146
256
  });
147
257
  return { id, value };
148
- }, context.signal);
258
+ }, context.signal, { isolation, limits });
149
259
  return { value, panels: [...selected.values()], sync: [...sync.values()] };
150
260
  }
151
261
  async function call(input, context, status) {
152
262
  const { signal, scope } = context;
153
263
  signal?.throwIfAborted();
154
- if (!isRecord(input))
155
- throw new Error("Supply execute inputs as a JSON object.");
264
+ if (!isRecord(input)) {
265
+ throw new errors_js_1.CodeModeError("INVALID_INPUT", "Supply execute inputs as a JSON object", "Pass an object with code, replay or listSaved");
266
+ }
156
267
  const has = (key) => Object.hasOwn(input, key);
157
268
  const keysAllowed = (...keys) => Object.keys(input).every((key) => keys.includes(key));
158
269
  if (has("code") && !has("saveAs") && keysAllowed("code", "params")) {
159
- if (typeof input.code !== "string")
160
- throw new Error("Supply a JavaScript function body.");
270
+ if (typeof input.code !== "string") {
271
+ throw new errors_js_1.CodeModeError("INVALID_INPUT", "Supply code as a JavaScript function body", "Pass code as a string");
272
+ }
161
273
  const result = await execute(input.code, validateParams(input.params === undefined ? {} : input.params), context, status);
162
274
  signal?.throwIfAborted();
163
275
  return output(result.value, result.panels, undefined, result.sync);
164
276
  }
165
277
  if (!catalog || typeof scope !== "string" || !scope.trim()) {
166
- throw new Error("Saved chains require a configured catalog and a trusted scope.");
278
+ throw new errors_js_1.CodeModeError("SAVED_CHAINS_UNAVAILABLE", "Saved chains require a configured catalog and a trusted scope", "Run the code directly, without saveAs, replay or listSaved");
167
279
  }
168
280
  if (input.listSaved === true && keysAllowed("listSaved")) {
169
- const snippets = await catalog.list(scope);
281
+ const snippets = await fromCatalog(catalog.list(scope), signal);
170
282
  signal?.throwIfAborted();
171
283
  return output({ snippets });
172
284
  }
173
285
  if ((0, providers_js_1.isSnippetName)(input.replay) && keysAllowed("replay", "params")) {
174
- const result = await catalog.run(scope, input.replay, input.params === undefined ? {} : input.params, {
286
+ const result = await fromCatalog(catalog.run(scope, input.replay, input.params === undefined ? {} : input.params, {
175
287
  validate: validateParams,
176
288
  execute: (code, params) => execute(code, params, context, status),
177
- });
289
+ }), signal);
178
290
  signal?.throwIfAborted();
179
291
  return output(result.value, result.panels, undefined, result.sync);
180
292
  }
181
293
  if (typeof input.code !== "string" || !has("saveAs") || !keysAllowed("code", "saveAs", "params")) {
182
- throw new Error("Supply code, replay, or listSaved.");
294
+ throw new errors_js_1.CodeModeError("INVALID_INPUT", "Supply code, replay, or listSaved", "Pass exactly one of code (optionally with saveAs and params), replay (with params) or listSaved");
183
295
  }
184
296
  const name = input.saveAs;
185
297
  if (!(0, providers_js_1.isSnippetName)(name)) {
186
- throw new Error("Supply a nonempty saved chain name of up to 256 UTF-8 bytes without surrounding whitespace.");
298
+ throw new errors_js_1.CodeModeError("SAVE_NAME_INVALID", "Supply a nonempty saved chain name of up to 256 UTF-8 bytes without surrounding whitespace", "Use a shorter, trimmed name", { context: { maxBytes: 256 } });
187
299
  }
188
300
  const params = validateParams(input.params === undefined ? {} : input.params);
189
301
  const keys = Object.keys(params);
190
302
  if (keys.length > 32 || keys.some((key) => new TextEncoder().encode(key).byteLength > 128)) {
191
- throw new Error("Saved chain parameter contract exceeds its size limit.");
303
+ throw new errors_js_1.CodeModeError("PARAMS_INVALID", "Saved chain parameter contract exceeds its size limit", "Use at most 32 parameters with names of up to 128 bytes", { context: { maxKeys: 32, maxKeyBytes: 128 } });
192
304
  }
193
305
  let usage = activeSaves.get(scope);
194
306
  if (!usage) {
195
307
  usage = {
196
308
  users: 0,
197
- stored: catalog.list(scope).then((entries) => new Set(entries.map((entry) => entry.name))),
309
+ stored: fromCatalog(catalog.list(scope)).then((entries) => new Set(entries.map((entry) => entry.name))),
198
310
  saving: new Set(),
199
311
  };
200
312
  activeSaves.set(scope, usage);
@@ -202,13 +314,15 @@ function createSnippetChain(providers, catalog) {
202
314
  usage.users++;
203
315
  let reserved = false;
204
316
  try {
205
- const savedNames = await usage.stored;
317
+ const savedNames = await fromCatalog(usage.stored, signal);
206
318
  signal?.throwIfAborted();
207
- if (usage.saving.has(name))
208
- throw new Error("A save for this chain is already in progress.");
319
+ if (usage.saving.has(name)) {
320
+ throw new errors_js_1.CodeModeError("SAVE_NAME_CONFLICT", "A save for this chain is already in progress", "Wait for it to finish, then call listSaved");
321
+ }
209
322
  if (!savedNames.has(name)) {
210
- if (savedNames.size >= maxSavedChains)
211
- throw new Error("The saved chain catalog is full.");
323
+ if (savedNames.size >= maxSavedChains) {
324
+ throw new errors_js_1.CodeModeError("SAVE_CATALOG_FULL", "The saved chain catalog is full", "Reuse an existing name, or run the code without saveAs", { context: { max: maxSavedChains } });
325
+ }
212
326
  savedNames.add(name);
213
327
  reserved = true;
214
328
  }
@@ -216,18 +330,24 @@ function createSnippetChain(providers, catalog) {
216
330
  usage.saving.add(name);
217
331
  try {
218
332
  if (!reserved) {
219
- const previous = await catalog.inspect(scope, name);
220
- if (previous.code !== input.code)
221
- throw new Error("Snippet name already in use.");
333
+ const previous = await fromCatalog(catalog.inspect(scope, name), signal);
334
+ if (previous.code !== input.code) {
335
+ throw new errors_js_1.CodeModeError("SAVE_NAME_CONFLICT", "Snippet name already in use", "Pick another name, or replay the saved chain");
336
+ }
222
337
  validateParams(params, previous.parameters);
223
338
  }
224
339
  signal?.throwIfAborted();
225
340
  const result = await execute(input.code, params, context, status);
226
341
  signal?.throwIfAborted();
227
- status.saving = true;
228
342
  const ref = catalog.recordSuccess(scope, input.code, params);
343
+ status.saving = true;
229
344
  const saved = await catalog.save(scope, ref, name);
345
+ status.saved = true;
346
+ // The name stays counted: the chain exists even if the caller gave up meanwhile.
230
347
  reserved = false;
348
+ // A confirmed write after the caller aborted is not a success the caller waited for.
349
+ if (signal?.aborted)
350
+ throw signal.reason;
231
351
  return output(result.value, result.panels, saved.name, result.sync);
232
352
  }
233
353
  finally {
@@ -242,28 +362,41 @@ function createSnippetChain(providers, catalog) {
242
362
  }
243
363
  }
244
364
  return async (input, context = {}) => {
245
- const status = { dispatched: false, saving: false };
365
+ const status = { dispatched: false, saving: false, saved: false };
246
366
  try {
247
367
  return await call(input, context, status);
248
368
  }
249
369
  catch (error) {
250
- if (!status.dispatched)
251
- throw error;
252
- if (context.signal?.aborted) {
253
- const reason = context.signal.reason;
254
- const name = reason instanceof DOMException && reason.name === "TimeoutError"
255
- ? "TimeoutError"
256
- : "AbortError";
257
- throw new DOMException(`Chain interrupted. ${afterDispatch}`, name);
370
+ const signal = context.signal;
371
+ if (status.saving) {
372
+ // A catalog write was attempted: classify it before the exception type, since a
373
+ // store may fail with a DOMException (a lost acknowledgement). Say to look before
374
+ // retrying. Only a write the store confirmed is reported as saved.
375
+ if (status.saved && signal?.aborted) {
376
+ throw interrupted(signal.reason, [
377
+ SAVED_RECOVERY,
378
+ ...(status.dispatched ? [errors_js_1.POSSIBLE_EFFECTS_RECOVERY] : []),
379
+ ]);
380
+ }
381
+ throw status.dispatched ? (0, errors_js_1.withPossibleEffects)(saveFailed()) : saveFailed();
382
+ }
383
+ if (!status.dispatched) {
384
+ if (error instanceof errors_js_1.CodeModeError || error instanceof DOMException)
385
+ throw error;
386
+ // The caller's own reason, whatever its type.
387
+ if (signal?.aborted)
388
+ throw signal.reason;
389
+ throw new errors_js_1.CodeModeError("EXECUTION_FAILED", "The chain failed before calling any provider", "Retry once, then report the failure");
390
+ }
391
+ if (signal?.aborted)
392
+ throw interrupted(signal.reason, [errors_js_1.POSSIBLE_EFFECTS_RECOVERY]);
393
+ if (error instanceof errors_js_1.CodeModeError) {
394
+ // After a dispatch, guest text might echo upstream values: keep only the kind.
395
+ throw (0, errors_js_1.withPossibleEffects)(error.code === "GUEST_ERROR"
396
+ ? new errors_js_1.CodeModeError("GUEST_ERROR", `The program threw ${error.context.name ?? "an exception"}`, error.recovery, { context: error.context })
397
+ : error);
258
398
  }
259
- // Preserve only diagnostics derived from known provider codes. A transport,
260
- // guest or storage exception may contain credentials, paths or native data.
261
- const message = status.saving
262
- ? "Failed to confirm that the chain was saved."
263
- : status.diagnostic && error instanceof Error && error.message === status.diagnostic
264
- ? status.diagnostic
265
- : "Chain execution failed.";
266
- throw new Error(`${message} ${afterDispatch}`);
399
+ throw (0, errors_js_1.withPossibleEffects)(new errors_js_1.CodeModeError("EXECUTION_FAILED", "The chain failed after calling a provider", "Report the failure"));
267
400
  }
268
401
  };
269
402
  }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Machine-readable failures of the Code Mode `execute` tool.
3
+ *
4
+ * An MCP host usually forwards only `error.message` to the model, so the message
5
+ * itself is the contract, in the format shared with other MCPView Code Mode
6
+ * servers:
7
+ *
8
+ * [execute] <CODE>: <detail>. Recovery: <recovery>.
9
+ *
10
+ * Guest programs see the same errors as `Error` objects that also carry
11
+ * `code`, `recovery` and `context`, so a program can branch on `e.code`.
12
+ *
13
+ * @module code-mode/errors
14
+ */
15
+ /** Every code the Code Mode tool can report. Codes are API: never rename one. */
16
+ export declare const CODE_MODE_ERROR_CODES: readonly ["INVALID_INPUT", "PARAMS_INVALID", "SAVED_CHAINS_UNAVAILABLE", "SAVE_NAME_INVALID", "SAVE_NAME_CONFLICT", "SAVE_CATALOG_FULL", "SAVE_FAILED", "CATALOG_ERROR", "GUEST_ERROR", "RESOURCE_LIMIT", "TIME_LIMIT", "RESULT_INVALID", "GUEST_STALLED", "UNAWAITED_OPERATION", "OPERATION_LIMIT", "ARGUMENT_INVALID", "OPERATION_FAILED", "SANDBOX_UNAVAILABLE", "SANDBOX_FAILED", "PROVIDER_UNKNOWN", "SNIPPET_NOT_APPROVED", "PROVIDER_UNAVAILABLE", "PROVIDER_ERROR", "PROVIDER_RESULT_INVALID", "RECEIPT_TOO_LARGE", "PANEL_INVALID", "SYNC_INVALID", "EXECUTION_FAILED", "INTERRUPTED"];
17
+ /** A Code Mode error code. */
18
+ export type CodeModeErrorCode = typeof CODE_MODE_ERROR_CODES[number];
19
+ /** Small, host-authored facts about a failure. Never guest or provider text. */
20
+ export type CodeModeErrorContext = Readonly<Record<string, string | number | boolean | readonly string[]>>;
21
+ /**
22
+ * `possible` when an upstream snippet call was already dispatched, so it may
23
+ * have changed something before the failure.
24
+ */
25
+ export type CodeModeErrorEffects = "none" | "possible";
26
+ /** The serializable fields of a {@link CodeModeError}. */
27
+ export interface CodeModeErrorFields {
28
+ readonly code: CodeModeErrorCode;
29
+ readonly detail: string;
30
+ readonly recovery: string;
31
+ readonly context: CodeModeErrorContext;
32
+ readonly effects: CodeModeErrorEffects;
33
+ }
34
+ /** Recovery suffix used once an upstream operation may have completed. */
35
+ export declare const POSSIBLE_EFFECTS_RECOVERY = "One or more upstream operations may have completed. Check their effects before replaying the chain";
36
+ /**
37
+ * Render `[execute] CODE: detail. Recovery: recovery.`
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * formatCodeModeError("TIME_LIMIT", "The program used its 2000 ms of CPU", "Split the work");
42
+ * // "[execute] TIME_LIMIT: The program used its 2000 ms of CPU. Recovery: Split the work."
43
+ * ```
44
+ */
45
+ export declare function formatCodeModeError(code: CodeModeErrorCode, detail: string, recovery: string): string;
46
+ /**
47
+ * A Code Mode failure with a stable code, a recovery hint and context.
48
+ *
49
+ * @example
50
+ * ```ts
51
+ * throw new CodeModeError("PROVIDER_UNKNOWN", "No provider is configured as cad", "Use one of the listed aliases", {
52
+ * context: { available: ["slicer"] },
53
+ * });
54
+ * ```
55
+ */
56
+ export declare class CodeModeError extends Error {
57
+ readonly name = "CodeModeError";
58
+ readonly code: CodeModeErrorCode;
59
+ /** What went wrong, without the code prefix or the recovery hint. */
60
+ readonly detail: string;
61
+ readonly recovery: string;
62
+ readonly context: CodeModeErrorContext;
63
+ readonly effects: CodeModeErrorEffects;
64
+ constructor(code: CodeModeErrorCode, detail: string, recovery: string, options?: {
65
+ context?: Record<string, unknown>;
66
+ effects?: CodeModeErrorEffects;
67
+ });
68
+ /** Plain fields, safe to post across a worker boundary. */
69
+ toJSON(): CodeModeErrorFields;
70
+ }
71
+ /** True for a {@link CodeModeError}. */
72
+ export declare function isCodeModeError(error: unknown): error is CodeModeError;
73
+ /**
74
+ * Rebuild an error from {@link CodeModeErrorFields}, for example after it
75
+ * crossed a worker boundary. Returns undefined for any other shape.
76
+ */
77
+ export declare function codeModeErrorFromFields(value: unknown): CodeModeError | undefined;
78
+ /** The same failure, reported once an upstream operation may have completed. */
79
+ export declare function withPossibleEffects(error: CodeModeError): CodeModeError;
80
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../src/src/code-mode/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,iFAAiF;AACjF,eAAO,MAAM,qBAAqB,ikBAkCxB,CAAC;AAEX,8BAA8B;AAC9B,MAAM,MAAM,iBAAiB,GAAG,OAAO,qBAAqB,CAAC,MAAM,CAAC,CAAC;AAErE,gFAAgF;AAChF,MAAM,MAAM,oBAAoB,GAAG,QAAQ,CACzC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,SAAS,MAAM,EAAE,CAAC,CAC9D,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,oBAAoB,GAAG,MAAM,GAAG,UAAU,CAAC;AAEvD,0DAA0D;AAC1D,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,IAAI,EAAE,iBAAiB,CAAC;IACjC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,OAAO,EAAE,oBAAoB,CAAC;IACvC,QAAQ,CAAC,OAAO,EAAE,oBAAoB,CAAC;CACxC;AAED,0EAA0E;AAC1E,eAAO,MAAM,yBAAyB,uGACgE,CAAC;AAOvG;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,iBAAiB,EACvB,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,GACf,MAAM,CAIR;AAED;;;;;;;;;GASG;AACH,qBAAa,aAAc,SAAQ,KAAK;IACtC,SAAkB,IAAI,mBAAmB;IACzC,QAAQ,CAAC,IAAI,EAAE,iBAAiB,CAAC;IACjC,qEAAqE;IACrE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,OAAO,EAAE,oBAAoB,CAAC;IACvC,QAAQ,CAAC,OAAO,EAAE,oBAAoB,CAAC;gBAGrC,IAAI,EAAE,iBAAiB,EACvB,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,EAChB,OAAO,GAAE;QAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAAC,OAAO,CAAC,EAAE,oBAAoB,CAAA;KAAO;IAUrF,2DAA2D;IAC3D,MAAM,IAAI,mBAAmB;CAS9B;AAUD,wCAAwC;AACxC,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,aAAa,CAEtE;AAID;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,OAAO,GAAG,aAAa,GAAG,SAAS,CAejF;AAED,gFAAgF;AAChF,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,aAAa,GAAG,aAAa,CAQvE"}