@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.
- package/CHANGELOG.md +118 -0
- package/README.md +53 -0
- package/esm/src/code-mode/chain.d.ts +24 -1
- package/esm/src/code-mode/chain.d.ts.map +1 -1
- package/esm/src/code-mode/chain.js +219 -86
- package/esm/src/code-mode/errors.d.ts +80 -0
- package/esm/src/code-mode/errors.d.ts.map +1 -0
- package/esm/src/code-mode/errors.js +140 -0
- package/esm/src/code-mode/guest-worker.d.ts +11 -0
- package/esm/src/code-mode/guest-worker.d.ts.map +1 -0
- package/esm/src/code-mode/guest-worker.js +80 -0
- package/esm/src/code-mode/mod.d.ts +3 -1
- package/esm/src/code-mode/mod.d.ts.map +1 -1
- package/esm/src/code-mode/mod.js +2 -0
- package/esm/src/code-mode/sandbox-core.d.ts +61 -0
- package/esm/src/code-mode/sandbox-core.d.ts.map +1 -0
- package/esm/src/code-mode/sandbox-core.js +424 -0
- package/esm/src/code-mode/sandbox.d.ts +68 -7
- package/esm/src/code-mode/sandbox.d.ts.map +1 -1
- package/esm/src/code-mode/sandbox.js +182 -120
- package/esm/src/code-mode/tool.d.ts.map +1 -1
- package/esm/src/code-mode/tool.js +2 -0
- package/esm/src/code-mode/worker-host.d.ts +82 -0
- package/esm/src/code-mode/worker-host.d.ts.map +1 -0
- package/esm/src/code-mode/worker-host.js +364 -0
- package/esm/src/code-mode/worker-protocol.d.ts +44 -0
- package/esm/src/code-mode/worker-protocol.d.ts.map +1 -0
- package/esm/src/code-mode/worker-protocol.js +7 -0
- package/esm/src/host/renderer/css/panel-controls.d.ts.map +1 -1
- package/esm/src/host/renderer/css/panel-controls.js +5 -1
- package/esm/src/host/renderer/js/card-height.d.ts +11 -1
- package/esm/src/host/renderer/js/card-height.d.ts.map +1 -1
- package/esm/src/host/renderer/js/card-height.js +57 -10
- package/esm/src/host/renderer/js/event-bus.d.ts +11 -0
- package/esm/src/host/renderer/js/event-bus.d.ts.map +1 -1
- package/esm/src/host/renderer/js/event-bus.js +49 -8
- package/esm/src/host/renderer/js/intrinsic-layout.d.ts +26 -0
- package/esm/src/host/renderer/js/intrinsic-layout.d.ts.map +1 -0
- package/esm/src/host/renderer/js/intrinsic-layout.js +44 -0
- package/esm/src/host/renderer/panel-resizing.d.ts.map +1 -1
- package/esm/src/host/renderer/panel-resizing.js +8 -0
- package/esm/src/version.d.ts +1 -1
- package/esm/src/version.js +1 -1
- package/package.json +1 -1
- package/script/src/code-mode/chain.d.ts +24 -1
- package/script/src/code-mode/chain.d.ts.map +1 -1
- package/script/src/code-mode/chain.js +218 -85
- package/script/src/code-mode/errors.d.ts +80 -0
- package/script/src/code-mode/errors.d.ts.map +1 -0
- package/script/src/code-mode/errors.js +148 -0
- package/script/src/code-mode/guest-worker.d.ts +11 -0
- package/script/src/code-mode/guest-worker.d.ts.map +1 -0
- package/script/src/code-mode/guest-worker.js +105 -0
- package/script/src/code-mode/mod.d.ts +3 -1
- package/script/src/code-mode/mod.d.ts.map +1 -1
- package/script/src/code-mode/mod.js +9 -1
- package/script/src/code-mode/sandbox-core.d.ts +61 -0
- package/script/src/code-mode/sandbox-core.d.ts.map +1 -0
- package/script/src/code-mode/sandbox-core.js +430 -0
- package/script/src/code-mode/sandbox.d.ts +68 -7
- package/script/src/code-mode/sandbox.d.ts.map +1 -1
- package/script/src/code-mode/sandbox.js +190 -122
- package/script/src/code-mode/tool.d.ts.map +1 -1
- package/script/src/code-mode/tool.js +2 -0
- package/script/src/code-mode/worker-host.d.ts +82 -0
- package/script/src/code-mode/worker-host.d.ts.map +1 -0
- package/script/src/code-mode/worker-host.js +399 -0
- package/script/src/code-mode/worker-protocol.d.ts +44 -0
- package/script/src/code-mode/worker-protocol.d.ts.map +1 -0
- package/script/src/code-mode/worker-protocol.js +8 -0
- package/script/src/host/renderer/css/panel-controls.d.ts.map +1 -1
- package/script/src/host/renderer/css/panel-controls.js +5 -1
- package/script/src/host/renderer/js/card-height.d.ts +11 -1
- package/script/src/host/renderer/js/card-height.d.ts.map +1 -1
- package/script/src/host/renderer/js/card-height.js +57 -10
- package/script/src/host/renderer/js/event-bus.d.ts +11 -0
- package/script/src/host/renderer/js/event-bus.d.ts.map +1 -1
- package/script/src/host/renderer/js/event-bus.js +50 -8
- package/script/src/host/renderer/js/intrinsic-layout.d.ts +26 -0
- package/script/src/host/renderer/js/intrinsic-layout.d.ts.map +1 -0
- package/script/src/host/renderer/js/intrinsic-layout.js +48 -0
- package/script/src/host/renderer/panel-resizing.d.ts.map +1 -1
- package/script/src/host/renderer/panel-resizing.js +8 -0
- package/script/src/version.d.ts +1 -1
- package/script/src/version.js +1 -1
|
@@ -1,32 +1,53 @@
|
|
|
1
1
|
import { parseSnippetSyncRule, SNIPPET_SYNC_META_KEY, snippetPorts, snippetSyncKey, supportsSnippetSync, } from "./sync.js";
|
|
2
2
|
import { SNIPPET_PANELS_META_KEY } from "./board.js";
|
|
3
3
|
import { isSnippetName } from "./providers.js";
|
|
4
|
-
import {
|
|
4
|
+
import { CodeModeError, POSSIBLE_EFFECTS_RECOVERY, withPossibleEffects } from "./errors.js";
|
|
5
|
+
import { assertSandboxIsolation, encodeValue, resolveSandboxLimits, runProgram, } from "./sandbox.js";
|
|
5
6
|
const maxNativeSize = 4 * 1024 * 1024;
|
|
6
7
|
const maxNativeBytes = 6 * 1024 * 1024;
|
|
7
8
|
const maxSavedChains = 64;
|
|
8
|
-
const
|
|
9
|
+
const maxPanelTitle = 120;
|
|
9
10
|
function isRecord(value) {
|
|
10
11
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
11
12
|
}
|
|
12
13
|
const providerErrors = new Map([
|
|
13
|
-
["INVALID_INPUT",
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
["
|
|
14
|
+
["INVALID_INPUT", [
|
|
15
|
+
"the provider rejected the input",
|
|
16
|
+
"Check the input against the snippet's inputSchema from api.listSnippets",
|
|
17
|
+
]],
|
|
18
|
+
["ARTIFACT_UNAVAILABLE", [
|
|
19
|
+
"the input artifact is unavailable",
|
|
20
|
+
"Regenerate the artifact before retrying",
|
|
21
|
+
]],
|
|
22
|
+
["PROFILE_INVALID", [
|
|
23
|
+
"the configured provider profile is invalid or unavailable",
|
|
24
|
+
"Ask the operator to fix the provider profile; retrying will fail again",
|
|
25
|
+
]],
|
|
26
|
+
["UPSTREAM_ERROR", ["the upstream operation failed", "Retry once, then report the failure"]],
|
|
27
|
+
["TIMEOUT", ["the upstream operation timed out", "Retry once with a smaller input"]],
|
|
28
|
+
["UNAVAILABLE", ["the provider is unavailable", "Retry later"]],
|
|
18
29
|
]);
|
|
19
|
-
function providerError(result) {
|
|
30
|
+
function providerError(provider, snippet, result) {
|
|
20
31
|
const data = result.structuredContent;
|
|
21
32
|
const error = isRecord(data) ? data.error : undefined;
|
|
22
|
-
const code = isRecord(error) ? error.code : undefined;
|
|
23
|
-
|
|
24
|
-
|
|
33
|
+
const code = isRecord(error) && typeof error.code === "string" ? error.code : undefined;
|
|
34
|
+
const known = code ? providerErrors.get(code) : undefined;
|
|
35
|
+
const [detail, recovery] = known ??
|
|
36
|
+
["the provider reported an execution error", "Retry once, then report the failure"];
|
|
37
|
+
return new CodeModeError("PROVIDER_ERROR", `Snippet ${snippet}: ${detail}`, recovery, {
|
|
38
|
+
context: { provider, snippet, providerCode: known ? code : "UNKNOWN" },
|
|
39
|
+
});
|
|
25
40
|
}
|
|
26
41
|
function validateParams(input, shape) {
|
|
27
|
-
if (!isRecord(input))
|
|
28
|
-
throw new
|
|
29
|
-
|
|
42
|
+
if (!isRecord(input)) {
|
|
43
|
+
throw new CodeModeError("PARAMS_INVALID", "Supply params as a JSON object", "Pass an object");
|
|
44
|
+
}
|
|
45
|
+
try {
|
|
46
|
+
encodeValue(input, 8192);
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
throw new CodeModeError("PARAMS_INVALID", "params must be JSON of at most 8192 characters", "Pass fewer or smaller parameters", { context: { limit: 8192 } });
|
|
50
|
+
}
|
|
30
51
|
if (shape) {
|
|
31
52
|
const keys = Object.keys(input);
|
|
32
53
|
if (keys.length !== Object.keys(shape).length ||
|
|
@@ -35,11 +56,56 @@ function validateParams(input, shape) {
|
|
|
35
56
|
const kind = value === null ? "null" : Array.isArray(value) ? "array" : typeof value;
|
|
36
57
|
return !Object.hasOwn(shape, key) || shape[key] !== kind;
|
|
37
58
|
})) {
|
|
38
|
-
throw new
|
|
59
|
+
throw new CodeModeError("PARAMS_INVALID", "Replay parameters must match the saved key names and JSON types", "Pass the parameters listed by listSaved, with the same types");
|
|
39
60
|
}
|
|
40
61
|
}
|
|
41
62
|
return input;
|
|
42
63
|
}
|
|
64
|
+
/** Map a catalog failure to a coded error. Catalog messages are constant strings. */
|
|
65
|
+
function catalogError(error) {
|
|
66
|
+
if (error instanceof CodeModeError)
|
|
67
|
+
return error;
|
|
68
|
+
if (error instanceof TypeError || error instanceof RangeError || isCatalogError(error)) {
|
|
69
|
+
const catalogCode = isCatalogError(error) ? error.code : error.name;
|
|
70
|
+
return new CodeModeError("CATALOG_ERROR", error.message, "Call listSaved, then replay an existing name", { context: { catalogCode } });
|
|
71
|
+
}
|
|
72
|
+
return new CodeModeError("CATALOG_ERROR", "The saved chain catalog failed", "Retry once, then report the failure");
|
|
73
|
+
}
|
|
74
|
+
function isCatalogError(error) {
|
|
75
|
+
return error instanceof Error && error.name === "SnippetCatalogError" &&
|
|
76
|
+
typeof error.code === "string";
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Await a catalog operation. A failure while the caller's signal is aborted is the
|
|
80
|
+
* caller's cancellation and keeps its reason; any other failure, a store's own
|
|
81
|
+
* `AbortError` included, is a catalog failure.
|
|
82
|
+
*/
|
|
83
|
+
async function fromCatalog(work, signal) {
|
|
84
|
+
try {
|
|
85
|
+
return await work;
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
if (signal?.aborted)
|
|
89
|
+
throw signal.reason;
|
|
90
|
+
throw catalogError(error);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/** The store may have written the chain even though the write was not confirmed. */
|
|
94
|
+
function saveFailed() {
|
|
95
|
+
return new CodeModeError("SAVE_FAILED", "Failed to confirm that the chain was saved", "Call listSaved before saving again");
|
|
96
|
+
}
|
|
97
|
+
const SAVED_RECOVERY = "The chain was saved. Call listSaved before saving it again";
|
|
98
|
+
/**
|
|
99
|
+
* The cancellation exception: a DOMException named after the caller's reason, so
|
|
100
|
+
* a host can tell a cancelled task from a failed one. Its message carries the
|
|
101
|
+
* advice that structured fields cannot (a DOMException has no `effects`).
|
|
102
|
+
*/
|
|
103
|
+
function interrupted(reason, advice) {
|
|
104
|
+
const name = reason instanceof DOMException && reason.name === "TimeoutError"
|
|
105
|
+
? "TimeoutError"
|
|
106
|
+
: "AbortError";
|
|
107
|
+
return new DOMException(`[execute] INTERRUPTED: The chain was interrupted. Recovery: ${advice.join(". ")}.`, name);
|
|
108
|
+
}
|
|
43
109
|
function output(value, panels = [], saved, sync = []) {
|
|
44
110
|
const visible = {
|
|
45
111
|
value,
|
|
@@ -59,8 +125,23 @@ function output(value, panels = [], saved, sync = []) {
|
|
|
59
125
|
* Run JavaScript against host-configured snippet providers. Selected results stay
|
|
60
126
|
* out of guest memory except for their declared JSON value. Supplying a catalog
|
|
61
127
|
* enables named chains for calls with a trusted scope.
|
|
128
|
+
*
|
|
129
|
+
* Failures are {@link CodeModeError}s whose message reads
|
|
130
|
+
* `[execute] CODE: detail. Recovery: hint.`; a caller abort rejects with a
|
|
131
|
+
* DOMException. Once an upstream snippet call was dispatched, errors carry
|
|
132
|
+
* `effects: "possible"` and never repeat guest, provider or transport text.
|
|
133
|
+
*
|
|
134
|
+
* @example
|
|
135
|
+
* ```ts
|
|
136
|
+
* const execute = createSnippetChain(providers, catalog, { isolation: "worker" });
|
|
137
|
+
* const result = await execute({ code: "return 1;" }, { scope: "user-1" });
|
|
138
|
+
* ```
|
|
62
139
|
*/
|
|
63
|
-
export function createSnippetChain(providers, catalog) {
|
|
140
|
+
export function createSnippetChain(providers, catalog, options = {}) {
|
|
141
|
+
const isolation = options.isolation ?? "worker";
|
|
142
|
+
assertSandboxIsolation(isolation);
|
|
143
|
+
const limits = resolveSandboxLimits(options.limits);
|
|
144
|
+
const aliases = [...providers.keys()];
|
|
64
145
|
// Keep admission state only while saves overlap. Persistent catalogs are read again
|
|
65
146
|
// on the next save so a completed tenant leaves no resident quota state here.
|
|
66
147
|
const activeSaves = new Map();
|
|
@@ -70,15 +151,16 @@ export function createSnippetChain(providers, catalog) {
|
|
|
70
151
|
const exposedPorts = new Map();
|
|
71
152
|
const sync = new Map();
|
|
72
153
|
let totalBytes = 0;
|
|
73
|
-
const value = await runProgram(code, params, async (operation, args, signal) => {
|
|
154
|
+
const value = await runProgram(code, params, async (operation, args, signal, stopped) => {
|
|
74
155
|
signal.throwIfAborted();
|
|
75
156
|
const [first, second, input] = args;
|
|
76
157
|
if (operation === "panel") {
|
|
77
158
|
const panel = typeof first === "string" ? receipts.get(first) : undefined;
|
|
78
|
-
if (!panel || args.length > 2)
|
|
79
|
-
throw new
|
|
80
|
-
|
|
81
|
-
|
|
159
|
+
if (!panel || args.length > 2) {
|
|
160
|
+
throw new CodeModeError("PANEL_INVALID", "Select a receipt returned by api.runSnippet in this execution", "Pass receipt.id from this run");
|
|
161
|
+
}
|
|
162
|
+
if (second !== undefined && (typeof second !== "string" || second.length > maxPanelTitle)) {
|
|
163
|
+
throw new CodeModeError("PANEL_INVALID", `Panel titles may contain at most ${maxPanelTitle} characters`, "Shorten the title", { context: { maxTitleLength: maxPanelTitle } });
|
|
82
164
|
}
|
|
83
165
|
selected.set(panel.id, { ...panel, title: second ?? panel.title });
|
|
84
166
|
exposedPorts.set(panel.id, panel.events);
|
|
@@ -87,111 +169,141 @@ export function createSnippetChain(providers, catalog) {
|
|
|
87
169
|
if (operation === "sync") {
|
|
88
170
|
const rule = args.length === 1 ? parseSnippetSyncRule(first) : undefined;
|
|
89
171
|
if (!rule || !supportsSnippetSync(rule, exposedPorts)) {
|
|
90
|
-
|
|
91
|
-
"Sync requires distinct selected panel receipts and their declared event and action.";
|
|
92
|
-
throw new Error(status.diagnostic);
|
|
172
|
+
throw new 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");
|
|
93
173
|
}
|
|
94
|
-
|
|
95
|
-
sync.set(key, rule);
|
|
174
|
+
sync.set(snippetSyncKey(rule), rule);
|
|
96
175
|
return null;
|
|
97
176
|
}
|
|
98
177
|
const provider = typeof first === "string" ? providers.get(first) : undefined;
|
|
99
|
-
if (!provider)
|
|
100
|
-
throw new
|
|
178
|
+
if (!provider) {
|
|
179
|
+
throw new CodeModeError("PROVIDER_UNKNOWN", "No snippet provider is configured under this alias", "Use one of the configured provider aliases", { context: { available: aliases } });
|
|
180
|
+
}
|
|
181
|
+
const alias = first;
|
|
182
|
+
const callProvider = async (tool, args) => {
|
|
183
|
+
// Any provider call may have effects, and its text may echo into guest
|
|
184
|
+
// errors: redact from here on, not only after runSnippet.
|
|
185
|
+
// Reading `provider.names` may have held the event loop past the wall
|
|
186
|
+
// deadline: check the clock right before the provider can act.
|
|
187
|
+
if (stopped())
|
|
188
|
+
throw signal.reason;
|
|
189
|
+
status.dispatched = true;
|
|
190
|
+
try {
|
|
191
|
+
return await provider.call(tool, args, signal, context);
|
|
192
|
+
}
|
|
193
|
+
catch {
|
|
194
|
+
signal.throwIfAborted();
|
|
195
|
+
// Provider and transport errors, typed or not, may carry credentials or
|
|
196
|
+
// paths: keep only the fact.
|
|
197
|
+
throw new CodeModeError("PROVIDER_UNAVAILABLE", `The ${alias} provider could not complete the request`,
|
|
198
|
+
// The request was sent: the provider may have acted before the failure.
|
|
199
|
+
"Check whether the operation took effect before retrying; the failure may be transient", { context: { provider: alias } });
|
|
200
|
+
}
|
|
201
|
+
};
|
|
101
202
|
if (operation === "listSnippets" && args.length === 1) {
|
|
102
|
-
const catalog = await
|
|
203
|
+
const catalog = await callProvider("list_snippets", {});
|
|
103
204
|
signal.throwIfAborted();
|
|
104
205
|
const snippets = isRecord(catalog.structuredContent)
|
|
105
206
|
? catalog.structuredContent.snippets
|
|
106
207
|
: undefined;
|
|
107
208
|
if (catalog.isError || !Array.isArray(snippets)) {
|
|
108
|
-
throw new
|
|
209
|
+
throw new CodeModeError("PROVIDER_UNAVAILABLE", `The ${alias} provider could not list its snippets`, "Retry once; the failure may be transient", { context: { provider: alias } });
|
|
109
210
|
}
|
|
110
211
|
return snippets.filter((item) => isRecord(item) && typeof item.name === "string" && provider.names.includes(item.name)).map(({ name, description, inputSchema }) => ({ name, description, inputSchema }));
|
|
111
212
|
}
|
|
112
|
-
if (operation !== "runSnippet" || args.length !== 3 ||
|
|
113
|
-
|
|
114
|
-
throw new Error("Choose an approved named snippet and supply its input object.");
|
|
213
|
+
if (operation !== "runSnippet" || args.length !== 3 || !isRecord(input)) {
|
|
214
|
+
throw new CodeModeError("ARGUMENT_INVALID", "Call api.runSnippet(provider, name, input) with an input object, or api.listSnippets(provider)", "Pass exactly the documented arguments");
|
|
115
215
|
}
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
const result = await provider.call("run_snippet", { name: second, input }, signal, context);
|
|
119
|
-
signal.throwIfAborted();
|
|
120
|
-
if (result.isError) {
|
|
121
|
-
status.diagnostic = `Snippet ${second}: ${providerError(result)}`;
|
|
122
|
-
throw new Error(status.diagnostic);
|
|
216
|
+
if (typeof second !== "string" || !provider.names.includes(second)) {
|
|
217
|
+
throw new 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] } });
|
|
123
218
|
}
|
|
219
|
+
const result = await callProvider("run_snippet", { name: second, input });
|
|
220
|
+
signal.throwIfAborted();
|
|
221
|
+
if (result.isError)
|
|
222
|
+
throw providerError(alias, second, result);
|
|
124
223
|
if (!isRecord(result.structuredContent) || !Object.hasOwn(result.structuredContent, "value")) {
|
|
125
|
-
|
|
126
|
-
throw new Error(status.diagnostic);
|
|
224
|
+
throw new CodeModeError("PROVIDER_RESULT_INVALID", `Snippet ${second} returned an invalid result`, "Report the provider bug; retrying will fail again", { context: { provider: alias, snippet: second } });
|
|
127
225
|
}
|
|
128
226
|
const value = result.structuredContent.value;
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
227
|
+
const tooLarge = (limit) => new CodeModeError("RECEIPT_TOO_LARGE", `Snippet ${second} returned more than the board accepts`, "Select smaller results or fewer panels", { context: { provider: alias, snippet: second, limit } });
|
|
228
|
+
try {
|
|
229
|
+
encodeValue(value, limits.valueLength);
|
|
230
|
+
}
|
|
231
|
+
catch {
|
|
232
|
+
throw tooLarge(limits.valueLength);
|
|
133
233
|
}
|
|
234
|
+
let receiptSize;
|
|
235
|
+
try {
|
|
236
|
+
receiptSize = new TextEncoder().encode(encodeValue(result, maxNativeSize)).byteLength;
|
|
237
|
+
}
|
|
238
|
+
catch {
|
|
239
|
+
throw tooLarge(maxNativeSize);
|
|
240
|
+
}
|
|
241
|
+
totalBytes += receiptSize;
|
|
242
|
+
if (totalBytes > maxNativeBytes)
|
|
243
|
+
throw tooLarge(maxNativeBytes);
|
|
134
244
|
const id = crypto.randomUUID();
|
|
135
245
|
const events = snippetPorts(provider.events, second);
|
|
136
246
|
receipts.set(id, {
|
|
137
247
|
id,
|
|
138
|
-
provider:
|
|
248
|
+
provider: alias,
|
|
139
249
|
name: second,
|
|
140
250
|
title: second,
|
|
141
251
|
result,
|
|
142
252
|
...(events ? { events } : {}),
|
|
143
253
|
});
|
|
144
254
|
return { id, value };
|
|
145
|
-
}, context.signal);
|
|
255
|
+
}, context.signal, { isolation, limits });
|
|
146
256
|
return { value, panels: [...selected.values()], sync: [...sync.values()] };
|
|
147
257
|
}
|
|
148
258
|
async function call(input, context, status) {
|
|
149
259
|
const { signal, scope } = context;
|
|
150
260
|
signal?.throwIfAborted();
|
|
151
|
-
if (!isRecord(input))
|
|
152
|
-
throw new
|
|
261
|
+
if (!isRecord(input)) {
|
|
262
|
+
throw new CodeModeError("INVALID_INPUT", "Supply execute inputs as a JSON object", "Pass an object with code, replay or listSaved");
|
|
263
|
+
}
|
|
153
264
|
const has = (key) => Object.hasOwn(input, key);
|
|
154
265
|
const keysAllowed = (...keys) => Object.keys(input).every((key) => keys.includes(key));
|
|
155
266
|
if (has("code") && !has("saveAs") && keysAllowed("code", "params")) {
|
|
156
|
-
if (typeof input.code !== "string")
|
|
157
|
-
throw new
|
|
267
|
+
if (typeof input.code !== "string") {
|
|
268
|
+
throw new CodeModeError("INVALID_INPUT", "Supply code as a JavaScript function body", "Pass code as a string");
|
|
269
|
+
}
|
|
158
270
|
const result = await execute(input.code, validateParams(input.params === undefined ? {} : input.params), context, status);
|
|
159
271
|
signal?.throwIfAborted();
|
|
160
272
|
return output(result.value, result.panels, undefined, result.sync);
|
|
161
273
|
}
|
|
162
274
|
if (!catalog || typeof scope !== "string" || !scope.trim()) {
|
|
163
|
-
throw new
|
|
275
|
+
throw new CodeModeError("SAVED_CHAINS_UNAVAILABLE", "Saved chains require a configured catalog and a trusted scope", "Run the code directly, without saveAs, replay or listSaved");
|
|
164
276
|
}
|
|
165
277
|
if (input.listSaved === true && keysAllowed("listSaved")) {
|
|
166
|
-
const snippets = await catalog.list(scope);
|
|
278
|
+
const snippets = await fromCatalog(catalog.list(scope), signal);
|
|
167
279
|
signal?.throwIfAborted();
|
|
168
280
|
return output({ snippets });
|
|
169
281
|
}
|
|
170
282
|
if (isSnippetName(input.replay) && keysAllowed("replay", "params")) {
|
|
171
|
-
const result = await catalog.run(scope, input.replay, input.params === undefined ? {} : input.params, {
|
|
283
|
+
const result = await fromCatalog(catalog.run(scope, input.replay, input.params === undefined ? {} : input.params, {
|
|
172
284
|
validate: validateParams,
|
|
173
285
|
execute: (code, params) => execute(code, params, context, status),
|
|
174
|
-
});
|
|
286
|
+
}), signal);
|
|
175
287
|
signal?.throwIfAborted();
|
|
176
288
|
return output(result.value, result.panels, undefined, result.sync);
|
|
177
289
|
}
|
|
178
290
|
if (typeof input.code !== "string" || !has("saveAs") || !keysAllowed("code", "saveAs", "params")) {
|
|
179
|
-
throw new
|
|
291
|
+
throw new CodeModeError("INVALID_INPUT", "Supply code, replay, or listSaved", "Pass exactly one of code (optionally with saveAs and params), replay (with params) or listSaved");
|
|
180
292
|
}
|
|
181
293
|
const name = input.saveAs;
|
|
182
294
|
if (!isSnippetName(name)) {
|
|
183
|
-
throw new
|
|
295
|
+
throw new 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 } });
|
|
184
296
|
}
|
|
185
297
|
const params = validateParams(input.params === undefined ? {} : input.params);
|
|
186
298
|
const keys = Object.keys(params);
|
|
187
299
|
if (keys.length > 32 || keys.some((key) => new TextEncoder().encode(key).byteLength > 128)) {
|
|
188
|
-
throw new
|
|
300
|
+
throw new 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 } });
|
|
189
301
|
}
|
|
190
302
|
let usage = activeSaves.get(scope);
|
|
191
303
|
if (!usage) {
|
|
192
304
|
usage = {
|
|
193
305
|
users: 0,
|
|
194
|
-
stored: catalog.list(scope).then((entries) => new Set(entries.map((entry) => entry.name))),
|
|
306
|
+
stored: fromCatalog(catalog.list(scope)).then((entries) => new Set(entries.map((entry) => entry.name))),
|
|
195
307
|
saving: new Set(),
|
|
196
308
|
};
|
|
197
309
|
activeSaves.set(scope, usage);
|
|
@@ -199,13 +311,15 @@ export function createSnippetChain(providers, catalog) {
|
|
|
199
311
|
usage.users++;
|
|
200
312
|
let reserved = false;
|
|
201
313
|
try {
|
|
202
|
-
const savedNames = await usage.stored;
|
|
314
|
+
const savedNames = await fromCatalog(usage.stored, signal);
|
|
203
315
|
signal?.throwIfAborted();
|
|
204
|
-
if (usage.saving.has(name))
|
|
205
|
-
throw new
|
|
316
|
+
if (usage.saving.has(name)) {
|
|
317
|
+
throw new CodeModeError("SAVE_NAME_CONFLICT", "A save for this chain is already in progress", "Wait for it to finish, then call listSaved");
|
|
318
|
+
}
|
|
206
319
|
if (!savedNames.has(name)) {
|
|
207
|
-
if (savedNames.size >= maxSavedChains)
|
|
208
|
-
throw new
|
|
320
|
+
if (savedNames.size >= maxSavedChains) {
|
|
321
|
+
throw new CodeModeError("SAVE_CATALOG_FULL", "The saved chain catalog is full", "Reuse an existing name, or run the code without saveAs", { context: { max: maxSavedChains } });
|
|
322
|
+
}
|
|
209
323
|
savedNames.add(name);
|
|
210
324
|
reserved = true;
|
|
211
325
|
}
|
|
@@ -213,18 +327,24 @@ export function createSnippetChain(providers, catalog) {
|
|
|
213
327
|
usage.saving.add(name);
|
|
214
328
|
try {
|
|
215
329
|
if (!reserved) {
|
|
216
|
-
const previous = await catalog.inspect(scope, name);
|
|
217
|
-
if (previous.code !== input.code)
|
|
218
|
-
throw new
|
|
330
|
+
const previous = await fromCatalog(catalog.inspect(scope, name), signal);
|
|
331
|
+
if (previous.code !== input.code) {
|
|
332
|
+
throw new CodeModeError("SAVE_NAME_CONFLICT", "Snippet name already in use", "Pick another name, or replay the saved chain");
|
|
333
|
+
}
|
|
219
334
|
validateParams(params, previous.parameters);
|
|
220
335
|
}
|
|
221
336
|
signal?.throwIfAborted();
|
|
222
337
|
const result = await execute(input.code, params, context, status);
|
|
223
338
|
signal?.throwIfAborted();
|
|
224
|
-
status.saving = true;
|
|
225
339
|
const ref = catalog.recordSuccess(scope, input.code, params);
|
|
340
|
+
status.saving = true;
|
|
226
341
|
const saved = await catalog.save(scope, ref, name);
|
|
342
|
+
status.saved = true;
|
|
343
|
+
// The name stays counted: the chain exists even if the caller gave up meanwhile.
|
|
227
344
|
reserved = false;
|
|
345
|
+
// A confirmed write after the caller aborted is not a success the caller waited for.
|
|
346
|
+
if (signal?.aborted)
|
|
347
|
+
throw signal.reason;
|
|
228
348
|
return output(result.value, result.panels, saved.name, result.sync);
|
|
229
349
|
}
|
|
230
350
|
finally {
|
|
@@ -239,28 +359,41 @@ export function createSnippetChain(providers, catalog) {
|
|
|
239
359
|
}
|
|
240
360
|
}
|
|
241
361
|
return async (input, context = {}) => {
|
|
242
|
-
const status = { dispatched: false, saving: false };
|
|
362
|
+
const status = { dispatched: false, saving: false, saved: false };
|
|
243
363
|
try {
|
|
244
364
|
return await call(input, context, status);
|
|
245
365
|
}
|
|
246
366
|
catch (error) {
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
367
|
+
const signal = context.signal;
|
|
368
|
+
if (status.saving) {
|
|
369
|
+
// A catalog write was attempted: classify it before the exception type, since a
|
|
370
|
+
// store may fail with a DOMException (a lost acknowledgement). Say to look before
|
|
371
|
+
// retrying. Only a write the store confirmed is reported as saved.
|
|
372
|
+
if (status.saved && signal?.aborted) {
|
|
373
|
+
throw interrupted(signal.reason, [
|
|
374
|
+
SAVED_RECOVERY,
|
|
375
|
+
...(status.dispatched ? [POSSIBLE_EFFECTS_RECOVERY] : []),
|
|
376
|
+
]);
|
|
377
|
+
}
|
|
378
|
+
throw status.dispatched ? withPossibleEffects(saveFailed()) : saveFailed();
|
|
379
|
+
}
|
|
380
|
+
if (!status.dispatched) {
|
|
381
|
+
if (error instanceof CodeModeError || error instanceof DOMException)
|
|
382
|
+
throw error;
|
|
383
|
+
// The caller's own reason, whatever its type.
|
|
384
|
+
if (signal?.aborted)
|
|
385
|
+
throw signal.reason;
|
|
386
|
+
throw new CodeModeError("EXECUTION_FAILED", "The chain failed before calling any provider", "Retry once, then report the failure");
|
|
387
|
+
}
|
|
388
|
+
if (signal?.aborted)
|
|
389
|
+
throw interrupted(signal.reason, [POSSIBLE_EFFECTS_RECOVERY]);
|
|
390
|
+
if (error instanceof CodeModeError) {
|
|
391
|
+
// After a dispatch, guest text might echo upstream values: keep only the kind.
|
|
392
|
+
throw withPossibleEffects(error.code === "GUEST_ERROR"
|
|
393
|
+
? new CodeModeError("GUEST_ERROR", `The program threw ${error.context.name ?? "an exception"}`, error.recovery, { context: error.context })
|
|
394
|
+
: error);
|
|
255
395
|
}
|
|
256
|
-
|
|
257
|
-
// guest or storage exception may contain credentials, paths or native data.
|
|
258
|
-
const message = status.saving
|
|
259
|
-
? "Failed to confirm that the chain was saved."
|
|
260
|
-
: status.diagnostic && error instanceof Error && error.message === status.diagnostic
|
|
261
|
-
? status.diagnostic
|
|
262
|
-
: "Chain execution failed.";
|
|
263
|
-
throw new Error(`${message} ${afterDispatch}`);
|
|
396
|
+
throw withPossibleEffects(new CodeModeError("EXECUTION_FAILED", "The chain failed after calling a provider", "Report the failure"));
|
|
264
397
|
}
|
|
265
398
|
};
|
|
266
399
|
}
|
|
@@ -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"}
|