@cloudflare/codemode 0.3.8 → 0.4.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/LICENSE +21 -0
- package/README.md +251 -7
- package/dist/ai.d.ts +50 -7
- package/dist/ai.js +93 -5
- package/dist/ai.js.map +1 -1
- package/dist/base-B2amchZA.d.ts +239 -0
- package/dist/base-CHRR_a5j.js +156 -0
- package/dist/base-CHRR_a5j.js.map +1 -0
- package/dist/browser.d.ts +6 -6
- package/dist/browser.js +2 -2
- package/dist/browser.js.map +1 -1
- package/dist/{executor-BRm90XJT.d.ts → executor-BIs2dr7X.d.ts} +48 -10
- package/dist/index.d.ts +608 -8
- package/dist/index.js +1690 -17
- package/dist/index.js.map +1 -1
- package/dist/{json-schema-types-CVt4X9cw.js → json-schema-types-BGjW4KPy.js} +1 -1
- package/dist/{json-schema-types-CVt4X9cw.js.map → json-schema-types-BGjW4KPy.js.map} +1 -1
- package/dist/{json-schema-types-1OL3uao0.d.ts → json-schema-types-Cb2wClAd.d.ts} +1 -1
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +2 -2
- package/dist/mcp.js.map +1 -1
- package/dist/{resolve-DdyeEp3l.js → resolve-34dC47Il.js} +1 -1
- package/dist/{resolve-DdyeEp3l.js.map → resolve-34dC47Il.js.map} +1 -1
- package/dist/{resolve-DtfaKmms.d.ts → resolve-CBr_VoPl.d.ts} +4 -4
- package/dist/{run-code-5x8S5YWt.js → run-code-aKHcTgf9.js} +4 -4
- package/dist/run-code-aKHcTgf9.js.map +1 -0
- package/dist/{shared-TyFN6W7_.d.ts → shared-Ce-zCEBP.d.ts} +3 -3
- package/dist/{shared-xjl2irqK.js → shared-SMjV5yN4.js} +1 -1
- package/dist/{shared-xjl2irqK.js.map → shared-SMjV5yN4.js.map} +1 -1
- package/dist/tanstack-ai.d.ts +3 -3
- package/dist/tanstack-ai.js +4 -4
- package/dist/tanstack-ai.js.map +1 -1
- package/dist/vite.d.ts +7 -0
- package/dist/vite.js +122 -0
- package/dist/vite.js.map +1 -0
- package/package.json +19 -14
- package/dist/run-code-5x8S5YWt.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,14 +1,27 @@
|
|
|
1
|
-
import { a as sanitizeToolName, n as jsonSchemaToType, s as normalizeCode, t as generateTypesFromJsonSchema } from "./json-schema-types-
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
|
|
1
|
+
import { a as sanitizeToolName, n as jsonSchemaToType, s as normalizeCode, t as generateTypesFromJsonSchema } from "./json-schema-types-BGjW4KPy.js";
|
|
2
|
+
import { t as runCode } from "./run-code-aKHcTgf9.js";
|
|
3
|
+
import { r as resolveProvider } from "./resolve-34dC47Il.js";
|
|
4
|
+
import { t as CodemodeConnector } from "./base-CHRR_a5j.js";
|
|
5
|
+
import { DurableObject, RpcTarget } from "cloudflare:workers";
|
|
6
|
+
import { tool } from "ai";
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
//#region src/codec.ts
|
|
5
9
|
/**
|
|
6
|
-
*
|
|
10
|
+
* Host-side value codec.
|
|
7
11
|
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
12
|
+
* Two layers share the binary encoding (a tagged base64 envelope):
|
|
13
|
+
*
|
|
14
|
+
* - **Transport** (`stringifyForCodemode`/`parseForCodemode`): used for the
|
|
15
|
+
* host↔sandbox tool-call boundary. Must stay in lockstep with the sandbox's
|
|
16
|
+
* own codec (`SANDBOX_CODEC` in executor.ts).
|
|
17
|
+
* - **Storage** (`stringifyForStorage`/`parseForStorage`): used by the
|
|
18
|
+
* CodemodeRuntime facet to persist args/results in SQLite. Builds on the
|
|
19
|
+
* transport encoding and additionally round-trips `bigint` (which plain
|
|
20
|
+
* `JSON.stringify` rejects). The bigint tag is storage-only — it never
|
|
21
|
+
* crosses into the sandbox.
|
|
10
22
|
*/
|
|
11
23
|
const BINARY_TAG = "__codemode_binary_v1__";
|
|
24
|
+
const BIGINT_TAG = "__codemode_bigint_v1__";
|
|
12
25
|
function bytesToBase64(bytes) {
|
|
13
26
|
let binary = "";
|
|
14
27
|
const chunkSize = 32768;
|
|
@@ -40,11 +53,11 @@ function encodeCodemodeValue(value) {
|
|
|
40
53
|
return value;
|
|
41
54
|
}
|
|
42
55
|
function decodeCodemodeValue(value) {
|
|
43
|
-
if (!value || typeof value !== "object" || !(
|
|
56
|
+
if (!value || typeof value !== "object" || !("__codemode_binary_v1__" in value)) return value;
|
|
44
57
|
const encoded = value;
|
|
45
58
|
if (typeof encoded.data !== "string") return value;
|
|
46
59
|
const bytes = base64ToBytes(encoded.data);
|
|
47
|
-
if (encoded[
|
|
60
|
+
if (encoded["__codemode_binary_v1__"] === "ArrayBuffer") return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
|
|
48
61
|
return bytes;
|
|
49
62
|
}
|
|
50
63
|
function stringifyForCodemode(value) {
|
|
@@ -53,6 +66,39 @@ function stringifyForCodemode(value) {
|
|
|
53
66
|
function parseForCodemode(json) {
|
|
54
67
|
return JSON.parse(json, (_key, nested) => decodeCodemodeValue(nested));
|
|
55
68
|
}
|
|
69
|
+
/**
|
|
70
|
+
* Serialize a value for durable storage. Returns `undefined` when the value is
|
|
71
|
+
* `undefined` (callers store SQL NULL — distinguishing "no value" from a
|
|
72
|
+
* recorded `null`, which serializes to the string `"null"`).
|
|
73
|
+
*
|
|
74
|
+
* Throws on values JSON cannot represent even with the codec (e.g. cycles):
|
|
75
|
+
* a durable replay log cannot faithfully store such a value, and silently
|
|
76
|
+
* storing an approximation would corrupt replay.
|
|
77
|
+
*/
|
|
78
|
+
function stringifyForStorage(value) {
|
|
79
|
+
if (value === void 0) return void 0;
|
|
80
|
+
return JSON.stringify(value, (_key, nested) => {
|
|
81
|
+
if (typeof nested === "bigint") return { [BIGINT_TAG]: nested.toString() };
|
|
82
|
+
return encodeCodemodeValue(nested);
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
function parseForStorage(json) {
|
|
86
|
+
if (json === null) return void 0;
|
|
87
|
+
return JSON.parse(json, (_key, nested) => {
|
|
88
|
+
if (nested && typeof nested === "object" && BIGINT_TAG in nested && typeof nested[BIGINT_TAG] === "string") return BigInt(nested[BIGINT_TAG]);
|
|
89
|
+
return decodeCodemodeValue(nested);
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
//#endregion
|
|
93
|
+
//#region src/executor.ts
|
|
94
|
+
/**
|
|
95
|
+
* Executor interface and DynamicWorkerExecutor implementation.
|
|
96
|
+
*
|
|
97
|
+
* The Executor interface is the core abstraction — implement it to run
|
|
98
|
+
* LLM-generated code in any sandbox (Workers, QuickJS, Node VM, etc.).
|
|
99
|
+
*/
|
|
100
|
+
const CONNECTOR_CONTROL_KEY = "__codemode_control__";
|
|
101
|
+
const PAUSE_SENTINEL_LITERAL = "__CODEMODE_PAUSE__";
|
|
56
102
|
const SANDBOX_CODEC = String.raw`
|
|
57
103
|
const __CODEMODE_BINARY_TAG = "__codemode_binary_v1__";
|
|
58
104
|
function __bytesToBase64(bytes) {
|
|
@@ -141,14 +187,16 @@ var DynamicWorkerExecutor = class {
|
|
|
141
187
|
#timeout;
|
|
142
188
|
#globalOutbound;
|
|
143
189
|
#modules;
|
|
190
|
+
#bindings;
|
|
144
191
|
constructor(options) {
|
|
145
192
|
this.#loader = options.loader;
|
|
146
193
|
this.#timeout = options.timeout ?? 3e4;
|
|
147
194
|
this.#globalOutbound = options.globalOutbound ?? null;
|
|
148
195
|
const { "executor.js": _, ...safeModules } = options.modules ?? {};
|
|
149
196
|
this.#modules = safeModules;
|
|
197
|
+
this.#bindings = options.bindings ?? {};
|
|
150
198
|
}
|
|
151
|
-
async execute(code, providersOrFns) {
|
|
199
|
+
async execute(code, providersOrFns, options) {
|
|
152
200
|
let providers;
|
|
153
201
|
if (!Array.isArray(providersOrFns)) {
|
|
154
202
|
console.warn("[@cloudflare/codemode] Passing raw fns to executor.execute() is deprecated. Use ResolvedProvider[] instead. This will be removed in the next major version.");
|
|
@@ -161,6 +209,7 @@ var DynamicWorkerExecutor = class {
|
|
|
161
209
|
const timeoutMs = this.#timeout;
|
|
162
210
|
const RESERVED_NAMES = new Set([
|
|
163
211
|
"__dispatchers",
|
|
212
|
+
"__connectors",
|
|
164
213
|
"__logs",
|
|
165
214
|
"__CODEMODE_BINARY_TAG",
|
|
166
215
|
"__bytesToBase64",
|
|
@@ -168,7 +217,13 @@ var DynamicWorkerExecutor = class {
|
|
|
168
217
|
"__encodeCodemodeValue",
|
|
169
218
|
"__decodeCodemodeValue",
|
|
170
219
|
"__stringifyForCodemode",
|
|
171
|
-
"__parseForCodemode"
|
|
220
|
+
"__parseForCodemode",
|
|
221
|
+
"WorkerEntrypoint",
|
|
222
|
+
"CodeExecutor",
|
|
223
|
+
"Promise",
|
|
224
|
+
"setTimeout",
|
|
225
|
+
"Error",
|
|
226
|
+
"console"
|
|
172
227
|
]);
|
|
173
228
|
const VALID_IDENT = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
|
|
174
229
|
const seenNames = /* @__PURE__ */ new Set();
|
|
@@ -187,17 +242,39 @@ var DynamicWorkerExecutor = class {
|
|
|
187
242
|
};
|
|
188
243
|
seenNames.add(provider.name);
|
|
189
244
|
}
|
|
245
|
+
const connectors = options?.connectors ?? [];
|
|
246
|
+
const connectorNames = new Set(connectors.map((c) => c.name));
|
|
247
|
+
for (const connector of connectors) {
|
|
248
|
+
if (RESERVED_NAMES.has(connector.name)) return {
|
|
249
|
+
result: void 0,
|
|
250
|
+
error: `Connector name "${connector.name}" is reserved`
|
|
251
|
+
};
|
|
252
|
+
if (!VALID_IDENT.test(connector.name)) return {
|
|
253
|
+
result: void 0,
|
|
254
|
+
error: `Connector name "${connector.name}" is not a valid JavaScript identifier`
|
|
255
|
+
};
|
|
256
|
+
if (seenNames.has(connector.name)) return {
|
|
257
|
+
result: void 0,
|
|
258
|
+
error: `Duplicate name "${connector.name}" (connector clashes with provider)`
|
|
259
|
+
};
|
|
260
|
+
seenNames.add(connector.name);
|
|
261
|
+
}
|
|
262
|
+
const proxyInits = providers.filter((p) => !connectorNames.has(p.name)).map((p) => ` const ${p.name} = new Proxy({}, {\n get: (target, toolName) => {\n if (Object.prototype.hasOwnProperty.call(target, toolName)) return target[toolName];\n if (typeof toolName !== "string") return undefined;\n return async (...args) => {\n const resJson = await __dispatchers.${p.name}.call(String(toolName), __stringifyForCodemode(args));\n const data = __parseForCodemode(resJson);\n if (data.error) throw new Error(data.error);\n return data.result;\n };\n }\n });`);
|
|
263
|
+
const preludeInits = providers.filter((p) => !connectorNames.has(p.name) && p.prelude).map((p) => p.prelude);
|
|
264
|
+
const connectorProxyInits = connectors.map((c) => ` const ${c.name} = new Proxy({}, {\n get: (_, toolName) => {\n if (typeof toolName !== "string") return undefined;\n return async (...args) => {\n const __r = await __connectors.${c.name}.callTool(toolName, args[0]);\n if (__r && typeof __r === "object") {\n if (__r.${CONNECTOR_CONTROL_KEY} === "pause") throw new Error("${PAUSE_SENTINEL_LITERAL}");\n if (__r.${CONNECTOR_CONTROL_KEY} === "error") throw new Error(String(__r.message));\n }\n return __r;\n };\n }\n });`);
|
|
190
265
|
const executorModule = [
|
|
191
266
|
"import { WorkerEntrypoint } from \"cloudflare:workers\";",
|
|
192
267
|
"",
|
|
193
268
|
"export default class CodeExecutor extends WorkerEntrypoint {",
|
|
194
|
-
" async evaluate(__dispatchers = {}) {",
|
|
269
|
+
" async evaluate(__dispatchers = {}, __connectors = {}) {",
|
|
195
270
|
" const __logs = [];",
|
|
196
271
|
" console.log = (...a) => { __logs.push(a.map(String).join(\" \")); };",
|
|
197
272
|
" console.warn = (...a) => { __logs.push(\"[warn] \" + a.map(String).join(\" \")); };",
|
|
198
273
|
" console.error = (...a) => { __logs.push(\"[error] \" + a.map(String).join(\" \")); };",
|
|
199
274
|
SANDBOX_CODEC,
|
|
200
|
-
...
|
|
275
|
+
...proxyInits,
|
|
276
|
+
...connectorProxyInits,
|
|
277
|
+
...preludeInits,
|
|
201
278
|
"",
|
|
202
279
|
" try {",
|
|
203
280
|
" const result = await Promise.race([",
|
|
@@ -229,7 +306,11 @@ var DynamicWorkerExecutor = class {
|
|
|
229
306
|
}
|
|
230
307
|
dispatchers[provider.name] = new ToolDispatcher(sanitizedFns);
|
|
231
308
|
}
|
|
232
|
-
const
|
|
309
|
+
const connectorBindings = {};
|
|
310
|
+
for (const connector of connectors) connectorBindings[connector.name] = connector.binding;
|
|
311
|
+
const env = { ...this.#bindings };
|
|
312
|
+
const hasEnv = Object.keys(env).length > 0;
|
|
313
|
+
const response = await this.#loader.load({
|
|
233
314
|
compatibilityDate: "2025-06-01",
|
|
234
315
|
compatibilityFlags: ["nodejs_compat"],
|
|
235
316
|
mainModule: "executor.js",
|
|
@@ -237,8 +318,9 @@ var DynamicWorkerExecutor = class {
|
|
|
237
318
|
...this.#modules,
|
|
238
319
|
"executor.js": executorModule
|
|
239
320
|
},
|
|
240
|
-
globalOutbound: this.#globalOutbound
|
|
241
|
-
|
|
321
|
+
globalOutbound: this.#globalOutbound,
|
|
322
|
+
env: hasEnv ? env : void 0
|
|
323
|
+
}).getEntrypoint().evaluate(dispatchers, connectorBindings);
|
|
242
324
|
if (response.error) return {
|
|
243
325
|
result: void 0,
|
|
244
326
|
error: response.error,
|
|
@@ -251,6 +333,1597 @@ var DynamicWorkerExecutor = class {
|
|
|
251
333
|
}
|
|
252
334
|
};
|
|
253
335
|
//#endregion
|
|
254
|
-
|
|
336
|
+
//#region src/truncate.ts
|
|
337
|
+
/**
|
|
338
|
+
* Result truncation utilities.
|
|
339
|
+
*
|
|
340
|
+
* Tool and sandbox results can be large enough to blow a model's context
|
|
341
|
+
* window. These cap the serialized size of a value while leaving small,
|
|
342
|
+
* structured results intact so the model can still reason over them. They are
|
|
343
|
+
* the default building blocks for a `transformResult` hook (see
|
|
344
|
+
* `createCodemodeRuntime`).
|
|
345
|
+
*/
|
|
346
|
+
/** ~4 characters per token is a reasonable cross-model estimate. */
|
|
347
|
+
const CHARS_PER_TOKEN = 4;
|
|
348
|
+
const DEFAULT_MAX_TOKENS = 6e3;
|
|
349
|
+
const TRUNCATION_MARKER = "--- TRUNCATED ---";
|
|
350
|
+
function budget(options) {
|
|
351
|
+
const maxTokens = options?.maxTokens ?? DEFAULT_MAX_TOKENS;
|
|
352
|
+
return {
|
|
353
|
+
maxChars: options?.maxChars ?? maxTokens * CHARS_PER_TOKEN,
|
|
354
|
+
maxTokens
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Truncate a text response to a character budget, appending a marker that notes
|
|
359
|
+
* the original size so the model knows the output was clipped. Returns the
|
|
360
|
+
* input unchanged when it is within budget.
|
|
361
|
+
*/
|
|
362
|
+
function truncateResponse(text, options) {
|
|
363
|
+
const { maxChars, maxTokens } = budget(options);
|
|
364
|
+
if (text.length <= maxChars) return text;
|
|
365
|
+
const estimatedTokens = Math.ceil(text.length / CHARS_PER_TOKEN);
|
|
366
|
+
return text.slice(0, maxChars) + `\n\n${TRUNCATION_MARKER}\nResponse was ~${estimatedTokens.toLocaleString()} tokens (limit: ${maxTokens.toLocaleString()}). Narrow the request to reduce response size.`;
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* Truncate a structured result. Strings are truncated directly. Other values
|
|
370
|
+
* pass through unchanged when their JSON serialization is within budget; when
|
|
371
|
+
* oversized, the serialized form is truncated and returned as a string, so the
|
|
372
|
+
* model still gets a usable, bounded preview rather than a dropped result.
|
|
373
|
+
*
|
|
374
|
+
* Values that can't be serialized (cycles, bigint, `undefined`) are returned
|
|
375
|
+
* unchanged.
|
|
376
|
+
*/
|
|
377
|
+
function truncateResult(value, options) {
|
|
378
|
+
if (typeof value === "string") return truncateResponse(value, options);
|
|
379
|
+
let serialized;
|
|
380
|
+
try {
|
|
381
|
+
serialized = JSON.stringify(value, null, 2);
|
|
382
|
+
} catch {
|
|
383
|
+
return value;
|
|
384
|
+
}
|
|
385
|
+
if (serialized === void 0) return value;
|
|
386
|
+
const { maxChars } = budget(options);
|
|
387
|
+
if (serialized.length <= maxChars) return value;
|
|
388
|
+
return truncateResponse(serialized, options);
|
|
389
|
+
}
|
|
390
|
+
//#endregion
|
|
391
|
+
//#region src/runtime.ts
|
|
392
|
+
/**
|
|
393
|
+
* CodemodeRuntime — durable execution engine, implemented as a DurableObject
|
|
394
|
+
* facet of the agent.
|
|
395
|
+
*
|
|
396
|
+
* The Executor is a simple, stateless sandbox: it runs code once and dispatches
|
|
397
|
+
* tool calls back. The Runtime wraps an executor and makes execution durable via
|
|
398
|
+
* abort-and-replay:
|
|
399
|
+
*
|
|
400
|
+
* - Every tool call AND every `codemode.step(name, fn)` is recorded in a
|
|
401
|
+
* durable log (the replay spine).
|
|
402
|
+
* - Reads / steps execute and their result is recorded.
|
|
403
|
+
* - Actions requiring approval are recorded as pending, and the run aborts.
|
|
404
|
+
* - On `continue`, the same code re-runs. Calls already in the log are served
|
|
405
|
+
* from it (noop — reads/steps return recorded results, applied
|
|
406
|
+
* actions return theirs). The newly-approved action executes for real, then
|
|
407
|
+
* the run proceeds to the next pause or completion.
|
|
408
|
+
*
|
|
409
|
+
* `codemode.step(name, fn)` is the explicit side-effect boundary: any
|
|
410
|
+
* nondeterministic or side-effectful work wrapped in a step is recorded once
|
|
411
|
+
* and replayed thereafter, so replay correctness does not depend on the code
|
|
412
|
+
* being incidentally deterministic.
|
|
413
|
+
*
|
|
414
|
+
* ## Statelessness (concurrency + hibernation safety)
|
|
415
|
+
*
|
|
416
|
+
* The facet keeps **no per-run state in instance memory**. Every method that
|
|
417
|
+
* participates in a run is addressed by an explicit `executionId` and, where
|
|
418
|
+
* relevant, a `seq` allocated by the host (the proxy tool) — never an in-memory
|
|
419
|
+
* cursor. This means:
|
|
420
|
+
*
|
|
421
|
+
* - Two executions can run concurrently without clobbering each other (each
|
|
422
|
+
* run threads its own id + sequence; there is no shared "current cursor").
|
|
423
|
+
* - The facet may hibernate mid-run between tool calls without losing its
|
|
424
|
+
* place: the sequence lives on the host call stack and the log lives in
|
|
425
|
+
* durable storage.
|
|
426
|
+
*
|
|
427
|
+
* The only durable state is per-execution: the log, pending actions, result,
|
|
428
|
+
* snippets. The executor and connector stubs are transient — the proxy tool
|
|
429
|
+
* re-provides them on each message (they can't survive hibernation anyway).
|
|
430
|
+
*
|
|
431
|
+
* ## Storage layout
|
|
432
|
+
*
|
|
433
|
+
* The facet's own SQLite database (facets each get an isolated DB) holds three
|
|
434
|
+
* tables: `cm_executions` (one row per execution: code, status, final result),
|
|
435
|
+
* `cm_log` (one row per connector call / step — appends write one small row
|
|
436
|
+
* instead of rewriting the whole execution), and `cm_snippets`. Args/results
|
|
437
|
+
* are serialized with the storage codec (binary + bigint safe). Any single
|
|
438
|
+
* serialized value is capped at `MAX_DURABLE_VALUE_BYTES`: a durable log can't
|
|
439
|
+
* truncate values (replay would feed resumed code corrupted data), so an
|
|
440
|
+
* oversized value fails the run with a clear, model-actionable error instead.
|
|
441
|
+
*/
|
|
442
|
+
/** Connector name used for `codemode.step(name, fn)` log entries. */
|
|
443
|
+
const STEP_CONNECTOR = "__step";
|
|
444
|
+
/** Default number of terminal executions to retain per runtime. */
|
|
445
|
+
const DEFAULT_MAX_EXECUTIONS = 50;
|
|
446
|
+
/**
|
|
447
|
+
* Cap for any single serialized value stored in the durable log (args, a
|
|
448
|
+
* recorded result, the final result). SQLite rows in Durable Objects max out
|
|
449
|
+
* at ~2MB; 1MB leaves headroom for the rest of the row. Truncating stored
|
|
450
|
+
* values is never an option — replay would feed resumed code corrupted data —
|
|
451
|
+
* so a breach fails the run with a model-actionable error instead.
|
|
452
|
+
*/
|
|
453
|
+
const MAX_DURABLE_VALUE_BYTES = 1e6;
|
|
454
|
+
/** Default age after which a paused (awaiting-approval) run can be expired. */
|
|
455
|
+
const DEFAULT_PAUSED_TTL_MS = 1440 * 60 * 1e3;
|
|
456
|
+
/** Model-actionable error for a value too large to record durably. */
|
|
457
|
+
function tooLargeMessage(what, size) {
|
|
458
|
+
return `${what} is too large to record durably (${size} bytes > ${MAX_DURABLE_VALUE_BYTES} byte limit). Write large data to a file or workspace instead and pass/return a small reference (such as a path).`;
|
|
459
|
+
}
|
|
460
|
+
/** Pending actions (awaiting approval) of one execution. */
|
|
461
|
+
function pendingOf(state) {
|
|
462
|
+
return state.log.filter((e) => e.state === "pending").map((e) => ({
|
|
463
|
+
executionId: state.id,
|
|
464
|
+
seq: e.seq,
|
|
465
|
+
connector: e.connector,
|
|
466
|
+
method: e.method,
|
|
467
|
+
args: e.args
|
|
468
|
+
}));
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* Deterministic JSON of a value: object keys sorted recursively, BigInt tagged.
|
|
472
|
+
* Used to compare a replayed call's args against the recorded args. Best-effort
|
|
473
|
+
* — returns `undefined` if the value can't be serialized (e.g. a cycle), in
|
|
474
|
+
* which case the caller skips the args check rather than reporting a false
|
|
475
|
+
* divergence.
|
|
476
|
+
*/
|
|
477
|
+
function stableStringify(value) {
|
|
478
|
+
try {
|
|
479
|
+
return JSON.stringify(value, (_key, val) => {
|
|
480
|
+
if (typeof val === "bigint") return `__bigint__:${val.toString()}`;
|
|
481
|
+
if (val && typeof val === "object" && !Array.isArray(val)) {
|
|
482
|
+
const record = val;
|
|
483
|
+
const sorted = {};
|
|
484
|
+
for (const key of Object.keys(record).sort()) sorted[key] = record[key];
|
|
485
|
+
return sorted;
|
|
486
|
+
}
|
|
487
|
+
return val;
|
|
488
|
+
});
|
|
489
|
+
} catch {
|
|
490
|
+
return;
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
function rowToEntry(row) {
|
|
494
|
+
return {
|
|
495
|
+
seq: row.seq,
|
|
496
|
+
connector: row.connector,
|
|
497
|
+
method: row.method,
|
|
498
|
+
args: parseForStorage(row.args),
|
|
499
|
+
result: parseForStorage(row.result),
|
|
500
|
+
requiresApproval: row.requires_approval === 1,
|
|
501
|
+
ephemeral: row.ephemeral === 1 ? true : void 0,
|
|
502
|
+
state: row.state
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
function rowToSnippet(row) {
|
|
506
|
+
return {
|
|
507
|
+
name: row.name,
|
|
508
|
+
description: row.description,
|
|
509
|
+
code: row.code,
|
|
510
|
+
savedAt: row.saved_at,
|
|
511
|
+
inputSchema: parseForStorage(row.input_schema),
|
|
512
|
+
connectors: row.connectors ? JSON.parse(row.connectors) : void 0
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* Serialize a value for a durable column. `undefined` → SQL NULL; throws a
|
|
517
|
+
* model-actionable error when the value is too large or not serializable
|
|
518
|
+
* (e.g. cyclic) — the durable log can't store an approximation.
|
|
519
|
+
*/
|
|
520
|
+
function toStored(what, value) {
|
|
521
|
+
let stored;
|
|
522
|
+
try {
|
|
523
|
+
stored = stringifyForStorage(value);
|
|
524
|
+
} catch (err) {
|
|
525
|
+
throw new Error(`${what} could not be recorded durably (not serializable: ${err instanceof Error ? err.message : String(err)}). Only JSON-compatible values (plus binary and bigint) can cross a durable replay boundary.`);
|
|
526
|
+
}
|
|
527
|
+
if (stored === void 0) return null;
|
|
528
|
+
if (stored.length > 1e6) throw new Error(tooLargeMessage(what, stored.length));
|
|
529
|
+
return stored;
|
|
530
|
+
}
|
|
531
|
+
var CodemodeRuntime = class extends DurableObject {
|
|
532
|
+
constructor(ctx, env) {
|
|
533
|
+
super(ctx, env);
|
|
534
|
+
this.ctx.storage.sql.exec(`
|
|
535
|
+
CREATE TABLE IF NOT EXISTS cm_executions (
|
|
536
|
+
id TEXT PRIMARY KEY,
|
|
537
|
+
code TEXT NOT NULL,
|
|
538
|
+
status TEXT NOT NULL,
|
|
539
|
+
result TEXT,
|
|
540
|
+
error TEXT,
|
|
541
|
+
logs TEXT,
|
|
542
|
+
connectors TEXT,
|
|
543
|
+
created_at INTEGER NOT NULL,
|
|
544
|
+
updated_at INTEGER NOT NULL
|
|
545
|
+
);
|
|
546
|
+
CREATE INDEX IF NOT EXISTS cm_executions_status
|
|
547
|
+
ON cm_executions (status, created_at);
|
|
548
|
+
CREATE TABLE IF NOT EXISTS cm_log (
|
|
549
|
+
execution_id TEXT NOT NULL,
|
|
550
|
+
seq INTEGER NOT NULL,
|
|
551
|
+
connector TEXT NOT NULL,
|
|
552
|
+
method TEXT NOT NULL,
|
|
553
|
+
args TEXT,
|
|
554
|
+
result TEXT,
|
|
555
|
+
requires_approval INTEGER NOT NULL DEFAULT 0,
|
|
556
|
+
ephemeral INTEGER NOT NULL DEFAULT 0,
|
|
557
|
+
state TEXT NOT NULL,
|
|
558
|
+
PRIMARY KEY (execution_id, seq)
|
|
559
|
+
);
|
|
560
|
+
CREATE TABLE IF NOT EXISTS cm_snippets (
|
|
561
|
+
name TEXT PRIMARY KEY,
|
|
562
|
+
description TEXT NOT NULL,
|
|
563
|
+
code TEXT NOT NULL,
|
|
564
|
+
saved_at INTEGER NOT NULL,
|
|
565
|
+
input_schema TEXT,
|
|
566
|
+
connectors TEXT
|
|
567
|
+
);
|
|
568
|
+
`);
|
|
569
|
+
}
|
|
570
|
+
/**
|
|
571
|
+
* Begin a fresh execution. Returns the execution id. Prunes old terminal
|
|
572
|
+
* executions down to `maxExecutions` (newest kept). The connector names the
|
|
573
|
+
* runtime was created with are recorded on the execution so a later resume
|
|
574
|
+
* can verify they are still configured.
|
|
575
|
+
*/
|
|
576
|
+
async begin(code, options) {
|
|
577
|
+
if (code.length > 1e6) throw new Error(tooLargeMessage("The execution code", code.length));
|
|
578
|
+
const now = Date.now();
|
|
579
|
+
const id = `exec_${now.toString().padStart(16, "0")}_${crypto.randomUUID()}`;
|
|
580
|
+
this.ctx.storage.sql.exec(`INSERT INTO cm_executions
|
|
581
|
+
(id, code, status, connectors, created_at, updated_at)
|
|
582
|
+
VALUES (?, ?, 'running', ?, ?, ?)`, id, code, options?.connectors ? JSON.stringify(options.connectors) : null, now, now);
|
|
583
|
+
this.#pruneTerminal(options?.maxExecutions ?? 50, id);
|
|
584
|
+
return id;
|
|
585
|
+
}
|
|
586
|
+
/**
|
|
587
|
+
* Resume an execution for a replay run. Only a `paused` run can be resumed:
|
|
588
|
+
* reviving a terminal run (completed/error/rejected/rolled_back) would
|
|
589
|
+
* re-offer a rejected action for approval or re-apply rolled-back side
|
|
590
|
+
* effects, and restarting an already-`running` run would race. Returns `null`
|
|
591
|
+
* (no state change) when the run is missing or not paused — the caller turns
|
|
592
|
+
* that into a clear error.
|
|
593
|
+
*/
|
|
594
|
+
async resume(id) {
|
|
595
|
+
const row = this.#executionRow(id);
|
|
596
|
+
if (!row || row.status !== "paused") return null;
|
|
597
|
+
this.ctx.storage.sql.exec(`UPDATE cm_executions SET status = 'running', updated_at = ? WHERE id = ?`, Date.now(), id);
|
|
598
|
+
return this.#get(id);
|
|
599
|
+
}
|
|
600
|
+
/**
|
|
601
|
+
* Decide what to do with the next tool call or step. The host allocates and
|
|
602
|
+
* passes `seq` (not an in-memory cursor), so this is safe across hibernation
|
|
603
|
+
* and concurrent executions.
|
|
604
|
+
*
|
|
605
|
+
* If the execution is no longer "running" (already paused/terminal), every
|
|
606
|
+
* call gets a pause decision and nothing is recorded — so model code that
|
|
607
|
+
* swallows the pause sentinel can't drive further side effects.
|
|
608
|
+
*
|
|
609
|
+
* Replay: a log entry at `seq` must match connector + method + args
|
|
610
|
+
* (divergence is a hard error). Applied → replay its result (ephemeral
|
|
611
|
+
* entries re-execute instead). Pending → it was just approved, execute it.
|
|
612
|
+
* Executing (crashed mid-call) / reverted → treat as a fresh call.
|
|
613
|
+
*
|
|
614
|
+
* New call: step or read → execute (logged "executing" until recordResult).
|
|
615
|
+
* Approval-required → record pending, pause.
|
|
616
|
+
*/
|
|
617
|
+
async decide(executionId, seq, connector, method, args, requiresApproval, ephemeral = false) {
|
|
618
|
+
if (this.#requireRow(executionId).status !== "running") return {
|
|
619
|
+
kind: "pause",
|
|
620
|
+
seq
|
|
621
|
+
};
|
|
622
|
+
const existingRow = this.#logRow(executionId, seq);
|
|
623
|
+
const existing = existingRow ? rowToEntry(existingRow) : void 0;
|
|
624
|
+
if (existing) {
|
|
625
|
+
if (existing.connector !== connector || existing.method !== method) return this.#diverge(executionId, seq, `expected ${existing.connector}.${existing.method}, got ${connector}.${method}. Code must be deterministic up to tool calls and steps. Wrap nondeterministic work in codemode.step(name, fn).`);
|
|
626
|
+
const before = stableStringify(existing.args);
|
|
627
|
+
const after = stableStringify(args);
|
|
628
|
+
if (before !== void 0 && after !== void 0 && before !== after) return this.#diverge(executionId, seq, `${connector}.${method} was called with different arguments than the recorded run. Arguments must be deterministic across replays. Wrap nondeterministic inputs in codemode.step(name, fn).`);
|
|
629
|
+
if (existing.state === "applied") {
|
|
630
|
+
if (existing.ephemeral) return {
|
|
631
|
+
kind: "execute",
|
|
632
|
+
seq
|
|
633
|
+
};
|
|
634
|
+
return {
|
|
635
|
+
kind: "replay",
|
|
636
|
+
result: existing.result
|
|
637
|
+
};
|
|
638
|
+
}
|
|
639
|
+
if (existing.state === "pending") {
|
|
640
|
+
this.#setEntryState(executionId, seq, "executing");
|
|
641
|
+
this.#touch(executionId);
|
|
642
|
+
return {
|
|
643
|
+
kind: "execute",
|
|
644
|
+
seq
|
|
645
|
+
};
|
|
646
|
+
}
|
|
647
|
+
if (existing.state === "executing") return {
|
|
648
|
+
kind: "execute",
|
|
649
|
+
seq
|
|
650
|
+
};
|
|
651
|
+
}
|
|
652
|
+
let storedArgs;
|
|
653
|
+
try {
|
|
654
|
+
storedArgs = toStored(`Arguments to ${connector}.${method}`, args);
|
|
655
|
+
} catch (err) {
|
|
656
|
+
return this.#fail(executionId, seq, err instanceof Error ? err.message : String(err));
|
|
657
|
+
}
|
|
658
|
+
const state = requiresApproval ? "pending" : "executing";
|
|
659
|
+
this.ctx.storage.sql.exec(`INSERT OR REPLACE INTO cm_log
|
|
660
|
+
(execution_id, seq, connector, method, args, result,
|
|
661
|
+
requires_approval, ephemeral, state)
|
|
662
|
+
VALUES (?, ?, ?, ?, ?, NULL, ?, ?, ?)`, executionId, seq, connector, method, storedArgs, requiresApproval ? 1 : 0, ephemeral ? 1 : 0, state);
|
|
663
|
+
if (requiresApproval) {
|
|
664
|
+
this.ctx.storage.sql.exec(`UPDATE cm_executions SET status = 'paused', updated_at = ? WHERE id = ?`, Date.now(), executionId);
|
|
665
|
+
return {
|
|
666
|
+
kind: "pause",
|
|
667
|
+
seq
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
this.#touch(executionId);
|
|
671
|
+
return {
|
|
672
|
+
kind: "execute",
|
|
673
|
+
seq
|
|
674
|
+
};
|
|
675
|
+
}
|
|
676
|
+
/**
|
|
677
|
+
* Record the real result of an executed call or step. Ephemeral entries are
|
|
678
|
+
* marked applied but their result is never stored (they re-execute on
|
|
679
|
+
* replay).
|
|
680
|
+
*
|
|
681
|
+
* A non-ephemeral result that is too large / unserializable cannot live in
|
|
682
|
+
* the durable log (truncating it would corrupt replay), so the execution is
|
|
683
|
+
* marked failed with a model-actionable error — recorded on the execution
|
|
684
|
+
* rather than thrown, because a rejection across the facet RPC boundary
|
|
685
|
+
* would surface as an unhandled rejection on the host. The entry stays
|
|
686
|
+
* "executing" (its side effects already happened) and the run can make no
|
|
687
|
+
* further progress.
|
|
688
|
+
*/
|
|
689
|
+
async recordResult(executionId, seq, result) {
|
|
690
|
+
const row = this.#logRow(executionId, seq);
|
|
691
|
+
if (!row) throw new Error(`No log entry at step ${seq}`);
|
|
692
|
+
let stored;
|
|
693
|
+
try {
|
|
694
|
+
stored = row.ephemeral === 1 ? null : toStored(`The result of ${row.connector}.${row.method}`, result);
|
|
695
|
+
} catch (err) {
|
|
696
|
+
this.#fail(executionId, seq, err instanceof Error ? err.message : String(err));
|
|
697
|
+
return;
|
|
698
|
+
}
|
|
699
|
+
this.ctx.storage.sql.exec(`UPDATE cm_log SET result = ?, state = 'applied'
|
|
700
|
+
WHERE execution_id = ? AND seq = ?`, stored, executionId, seq);
|
|
701
|
+
this.#touch(executionId);
|
|
702
|
+
}
|
|
703
|
+
/**
|
|
704
|
+
* Mark the run completed with a final result. Replay never needs the final
|
|
705
|
+
* result (a resume re-derives it), so an oversized/unserializable result is
|
|
706
|
+
* replaced with a placeholder note in the audit trail rather than failing a
|
|
707
|
+
* run that genuinely completed.
|
|
708
|
+
*/
|
|
709
|
+
async complete(executionId, result, logs) {
|
|
710
|
+
this.#requireRow(executionId);
|
|
711
|
+
let storedResult;
|
|
712
|
+
try {
|
|
713
|
+
storedResult = toStored("The final result", result);
|
|
714
|
+
} catch (err) {
|
|
715
|
+
storedResult = stringifyForStorage(`[codemode: result omitted from the audit trail — ${err instanceof Error ? err.message : String(err)}]`);
|
|
716
|
+
}
|
|
717
|
+
this.ctx.storage.sql.exec(`UPDATE cm_executions
|
|
718
|
+
SET status = 'completed', result = ?, logs = ?, updated_at = ?
|
|
719
|
+
WHERE id = ?`, storedResult, this.#storedLogs(logs), Date.now(), executionId);
|
|
720
|
+
}
|
|
721
|
+
/** Mark the run errored. */
|
|
722
|
+
async fail(executionId, error, logs) {
|
|
723
|
+
this.#requireRow(executionId);
|
|
724
|
+
this.ctx.storage.sql.exec(`UPDATE cm_executions
|
|
725
|
+
SET status = 'error', error = ?, logs = ?, updated_at = ?
|
|
726
|
+
WHERE id = ?`, error.slice(0, MAX_DURABLE_VALUE_BYTES), this.#storedLogs(logs), Date.now(), executionId);
|
|
727
|
+
}
|
|
728
|
+
/**
|
|
729
|
+
* List pending actions awaiting approval. With an `executionId`, scopes to
|
|
730
|
+
* that run; without one, aggregates across every **paused** run (newest
|
|
731
|
+
* first) — so an approval UI sees every awaiting-approval run, not just
|
|
732
|
+
* whichever happened to be started/resumed last. (Defaulting to a single
|
|
733
|
+
* "current" run would drop pending actions when multiple runs are in flight.)
|
|
734
|
+
*
|
|
735
|
+
* Only **paused** runs are considered: a non-paused run can retain a stale
|
|
736
|
+
* "pending" log entry (e.g. a resume diverged before reaching it, ending the
|
|
737
|
+
* run as `error` while the later entry stays `pending`). Such an entry isn't
|
|
738
|
+
* actionable — approving it is a no-op — so it must not clutter the queue.
|
|
739
|
+
*/
|
|
740
|
+
async listPending(executionId) {
|
|
741
|
+
if (executionId) {
|
|
742
|
+
const state = await this.#get(executionId);
|
|
743
|
+
return state?.status === "paused" ? pendingOf(state) : [];
|
|
744
|
+
}
|
|
745
|
+
const paused = this.ctx.storage.sql.exec(`SELECT * FROM cm_executions WHERE status = 'paused'
|
|
746
|
+
ORDER BY created_at DESC, id DESC`).toArray();
|
|
747
|
+
const out = [];
|
|
748
|
+
for (const row of paused) out.push(...pendingOf(this.#assemble(row)));
|
|
749
|
+
return out;
|
|
750
|
+
}
|
|
751
|
+
/**
|
|
752
|
+
* Reject a pending action. Ends the execution with an error.
|
|
753
|
+
*
|
|
754
|
+
* Returns whether it actually terminated the run: `false` when the seq isn't
|
|
755
|
+
* pending (a stale/duplicate reject — e.g. the action was already handled by
|
|
756
|
+
* another tab), so the caller doesn't tear down a run that's still live.
|
|
757
|
+
*
|
|
758
|
+
* Rejection does NOT undo actions already applied earlier in the same run —
|
|
759
|
+
* call `rollback()` for that. See docs/codemode/approvals.md.
|
|
760
|
+
*/
|
|
761
|
+
async reject(seq, executionId) {
|
|
762
|
+
const entry = this.#logRow(executionId, seq);
|
|
763
|
+
if (entry?.state !== "pending") return false;
|
|
764
|
+
this.#setEntryState(executionId, seq, "reverted");
|
|
765
|
+
this.ctx.storage.sql.exec(`UPDATE cm_executions SET status = 'rejected', error = ?, updated_at = ?
|
|
766
|
+
WHERE id = ?`, `Action ${entry.connector}.${entry.method} rejected by user`, Date.now(), executionId);
|
|
767
|
+
return true;
|
|
768
|
+
}
|
|
769
|
+
/**
|
|
770
|
+
* Expire non-terminal runs whose last state change is older than
|
|
771
|
+
* `maxAgeMs`:
|
|
772
|
+
*
|
|
773
|
+
* - `paused` (awaiting approval) runs are marked **rejected**. A
|
|
774
|
+
* never-answered approval would otherwise live forever — paused runs are
|
|
775
|
+
* deliberately exempt from retention pruning.
|
|
776
|
+
* - `running` runs are marked **error**. A run only stays `running` with a
|
|
777
|
+
* stale `updated_at` when the host died mid-pass (every decide/record
|
|
778
|
+
* touches the row), and such a run can never be resumed — without expiry
|
|
779
|
+
* it would be unreclaimable and exempt from pruning forever.
|
|
780
|
+
*
|
|
781
|
+
* Returns the expired execution ids so the host can fire the connectors'
|
|
782
|
+
* `disposeExecution` for each. Each status flip is conditional on the
|
|
783
|
+
* status it observed, so an id is only returned (and disposed) when this
|
|
784
|
+
* call actually terminated the run.
|
|
785
|
+
*/
|
|
786
|
+
async expirePaused(maxAgeMs = DEFAULT_PAUSED_TTL_MS) {
|
|
787
|
+
const cutoff = Date.now() - maxAgeMs;
|
|
788
|
+
const rows = this.ctx.storage.sql.exec(`SELECT id, status FROM cm_executions
|
|
789
|
+
WHERE status IN ('paused', 'running') AND updated_at < ?`, cutoff).toArray();
|
|
790
|
+
const now = Date.now();
|
|
791
|
+
const expired = [];
|
|
792
|
+
for (const { id, status } of rows) {
|
|
793
|
+
if (this.ctx.storage.sql.exec(`UPDATE cm_executions SET status = ?, error = ?, updated_at = ?
|
|
794
|
+
WHERE id = ? AND status = ?`, status === "paused" ? "rejected" : "error", status === "paused" ? "Expired awaiting approval" : "Expired while running — the host never completed the pass", now, id, status).rowsWritten === 0) continue;
|
|
795
|
+
this.ctx.storage.sql.exec(`UPDATE cm_log SET state = 'reverted'
|
|
796
|
+
WHERE execution_id = ? AND state = 'pending'`, id);
|
|
797
|
+
expired.push(id);
|
|
798
|
+
}
|
|
799
|
+
return expired;
|
|
800
|
+
}
|
|
801
|
+
/**
|
|
802
|
+
* Return applied connector actions (not steps) in reverse order. Reads are
|
|
803
|
+
* included but are harmless — the host's revertAction no-ops when a tool has
|
|
804
|
+
* no `revert`, and only entries that actually reverted are marked.
|
|
805
|
+
*/
|
|
806
|
+
async actionsToRevert(executionId) {
|
|
807
|
+
return this.ctx.storage.sql.exec(`SELECT * FROM cm_log
|
|
808
|
+
WHERE execution_id = ? AND state = 'applied' AND connector != ?
|
|
809
|
+
ORDER BY seq DESC`, executionId, STEP_CONNECTOR).toArray().map(rowToEntry);
|
|
810
|
+
}
|
|
811
|
+
/** Mark an action reverted after the proxy tool has reverted it. */
|
|
812
|
+
async markReverted(seq, executionId) {
|
|
813
|
+
if (!this.#logRow(executionId, seq)) return;
|
|
814
|
+
this.#setEntryState(executionId, seq, "reverted");
|
|
815
|
+
this.#touch(executionId);
|
|
816
|
+
}
|
|
817
|
+
/**
|
|
818
|
+
* Mark a run as rolled back once the proxy tool has finished reverting its
|
|
819
|
+
* actions, so the execution status reflects the rollback (rather than staying
|
|
820
|
+
* "completed"/"error" with some entries quietly flipped to "reverted").
|
|
821
|
+
*/
|
|
822
|
+
async markRolledBack(executionId) {
|
|
823
|
+
this.ctx.storage.sql.exec(`UPDATE cm_executions SET status = 'rolled_back', updated_at = ?
|
|
824
|
+
WHERE id = ?`, Date.now(), executionId);
|
|
825
|
+
}
|
|
826
|
+
async getExecution(id) {
|
|
827
|
+
return this.#get(id);
|
|
828
|
+
}
|
|
829
|
+
/** List executions, newest first. Optionally cap the number returned. */
|
|
830
|
+
async listExecutions(limit) {
|
|
831
|
+
return this.ctx.storage.sql.exec(`SELECT * FROM cm_executions ORDER BY created_at DESC, id DESC
|
|
832
|
+
LIMIT ?`, typeof limit === "number" ? limit : -1).toArray().map((row) => this.#assemble(row));
|
|
833
|
+
}
|
|
834
|
+
/** Delete one execution. Returns whether it existed. */
|
|
835
|
+
async deleteExecution(id) {
|
|
836
|
+
const existed = this.#executionRow(id) !== null;
|
|
837
|
+
this.ctx.storage.sql.exec(`DELETE FROM cm_log WHERE execution_id = ?`, id);
|
|
838
|
+
this.ctx.storage.sql.exec(`DELETE FROM cm_executions WHERE id = ?`, id);
|
|
839
|
+
return existed;
|
|
840
|
+
}
|
|
841
|
+
/**
|
|
842
|
+
* Delete terminal (completed/error) executions, keeping the newest `keep`.
|
|
843
|
+
* Running/paused executions are never deleted. Returns the count removed.
|
|
844
|
+
*/
|
|
845
|
+
async pruneExecutions(keep = 50) {
|
|
846
|
+
return this.#pruneTerminal(keep);
|
|
847
|
+
}
|
|
848
|
+
/**
|
|
849
|
+
* Promote an execution's code to a saved, addressable snippet. This is the
|
|
850
|
+
* "save what ran" hook — the developer calls it (via runtime.saveSnippet)
|
|
851
|
+
* after a script proves useful, so the model can re-run it later with
|
|
852
|
+
* `codemode.run(name)`. The execution is named explicitly (its id comes from
|
|
853
|
+
* the tool's output or `listExecutions()`). The execution's recorded
|
|
854
|
+
* connector requirements carry over to the snippet so a later run can verify
|
|
855
|
+
* they are still configured.
|
|
856
|
+
*/
|
|
857
|
+
async saveSnippet(name, options) {
|
|
858
|
+
const row = this.#executionRow(options.executionId);
|
|
859
|
+
if (!row) throw new Error(`No execution "${options.executionId}" to save from`);
|
|
860
|
+
const snippet = {
|
|
861
|
+
name,
|
|
862
|
+
description: options.description ?? "",
|
|
863
|
+
code: row.code,
|
|
864
|
+
savedAt: Date.now(),
|
|
865
|
+
inputSchema: options.inputSchema,
|
|
866
|
+
connectors: row.connectors ? JSON.parse(row.connectors) : void 0
|
|
867
|
+
};
|
|
868
|
+
this.ctx.storage.sql.exec(`INSERT OR REPLACE INTO cm_snippets
|
|
869
|
+
(name, description, code, saved_at, input_schema, connectors)
|
|
870
|
+
VALUES (?, ?, ?, ?, ?, ?)`, snippet.name, snippet.description, snippet.code, snippet.savedAt, toStored("The snippet input schema", snippet.inputSchema), row.connectors);
|
|
871
|
+
return snippet;
|
|
872
|
+
}
|
|
873
|
+
async getSnippet(name) {
|
|
874
|
+
const rows = this.ctx.storage.sql.exec(`SELECT * FROM cm_snippets WHERE name = ?`, name).toArray();
|
|
875
|
+
return rows.length > 0 ? rowToSnippet(rows[0]) : null;
|
|
876
|
+
}
|
|
877
|
+
async listSnippets() {
|
|
878
|
+
return this.ctx.storage.sql.exec(`SELECT * FROM cm_snippets ORDER BY name`).toArray().map(rowToSnippet);
|
|
879
|
+
}
|
|
880
|
+
async deleteSnippet(name) {
|
|
881
|
+
const existed = this.ctx.storage.sql.exec(`SELECT 1 FROM cm_snippets WHERE name = ?`, name).toArray().length > 0;
|
|
882
|
+
this.ctx.storage.sql.exec(`DELETE FROM cm_snippets WHERE name = ?`, name);
|
|
883
|
+
return existed;
|
|
884
|
+
}
|
|
885
|
+
/**
|
|
886
|
+
* Record a replay divergence (or another in-run failure) as a terminal
|
|
887
|
+
* failure on the execution and tell the host to abort the sandbox. The host
|
|
888
|
+
* reads the failure from the execution record, so the message never travels
|
|
889
|
+
* back through the sandbox's error channel (which would flag it as an
|
|
890
|
+
* unhandled remote rejection).
|
|
891
|
+
*/
|
|
892
|
+
#diverge(executionId, seq, detail) {
|
|
893
|
+
return this.#fail(executionId, seq, `Codemode replay divergence at step ${seq}: ${detail}`);
|
|
894
|
+
}
|
|
895
|
+
#fail(executionId, seq, error) {
|
|
896
|
+
this.ctx.storage.sql.exec(`UPDATE cm_log SET state = 'error'
|
|
897
|
+
WHERE execution_id = ? AND seq = ? AND state IN ('executing', 'pending')`, executionId, seq);
|
|
898
|
+
this.ctx.storage.sql.exec(`UPDATE cm_executions SET status = 'error', error = ?, updated_at = ?
|
|
899
|
+
WHERE id = ?`, error.slice(0, MAX_DURABLE_VALUE_BYTES), Date.now(), executionId);
|
|
900
|
+
return {
|
|
901
|
+
kind: "pause",
|
|
902
|
+
seq
|
|
903
|
+
};
|
|
904
|
+
}
|
|
905
|
+
#pruneTerminal(keep, protectId) {
|
|
906
|
+
const rows = this.ctx.storage.sql.exec(`SELECT id FROM cm_executions
|
|
907
|
+
WHERE status IN ('completed', 'error', 'rejected', 'rolled_back')
|
|
908
|
+
AND id != ?
|
|
909
|
+
ORDER BY created_at DESC, id DESC`, protectId ?? "").toArray();
|
|
910
|
+
if (rows.length <= keep) return 0;
|
|
911
|
+
const toDelete = rows.slice(keep);
|
|
912
|
+
for (const { id } of toDelete) {
|
|
913
|
+
this.ctx.storage.sql.exec(`DELETE FROM cm_log WHERE execution_id = ?`, id);
|
|
914
|
+
this.ctx.storage.sql.exec(`DELETE FROM cm_executions WHERE id = ?`, id);
|
|
915
|
+
}
|
|
916
|
+
return toDelete.length;
|
|
917
|
+
}
|
|
918
|
+
/** Serialize console logs; an oversized log array is truncated with a note. */
|
|
919
|
+
#storedLogs(logs) {
|
|
920
|
+
if (!logs || logs.length === 0) return null;
|
|
921
|
+
let stored = JSON.stringify(logs);
|
|
922
|
+
let entries = logs;
|
|
923
|
+
while (stored.length > 1e6 && entries.length > 0) {
|
|
924
|
+
entries = ["[codemode: earlier console output dropped — too large to record]", ...entries.slice(Math.ceil(entries.length / 2))];
|
|
925
|
+
stored = JSON.stringify(entries);
|
|
926
|
+
}
|
|
927
|
+
return stored.length <= 1e6 ? stored : null;
|
|
928
|
+
}
|
|
929
|
+
#executionRow(id) {
|
|
930
|
+
const rows = this.ctx.storage.sql.exec(`SELECT * FROM cm_executions WHERE id = ?`, id).toArray();
|
|
931
|
+
return rows.length > 0 ? rows[0] : null;
|
|
932
|
+
}
|
|
933
|
+
#requireRow(id) {
|
|
934
|
+
const row = this.#executionRow(id);
|
|
935
|
+
if (!row) throw new Error(`No execution "${id}"`);
|
|
936
|
+
return row;
|
|
937
|
+
}
|
|
938
|
+
#logRow(executionId, seq) {
|
|
939
|
+
const rows = this.ctx.storage.sql.exec(`SELECT * FROM cm_log WHERE execution_id = ? AND seq = ?`, executionId, seq).toArray();
|
|
940
|
+
return rows.length > 0 ? rows[0] : null;
|
|
941
|
+
}
|
|
942
|
+
#setEntryState(executionId, seq, state) {
|
|
943
|
+
this.ctx.storage.sql.exec(`UPDATE cm_log SET state = ? WHERE execution_id = ? AND seq = ?`, state, executionId, seq);
|
|
944
|
+
}
|
|
945
|
+
#touch(executionId) {
|
|
946
|
+
this.ctx.storage.sql.exec(`UPDATE cm_executions SET updated_at = ? WHERE id = ?`, Date.now(), executionId);
|
|
947
|
+
}
|
|
948
|
+
#assemble(row) {
|
|
949
|
+
const entries = this.ctx.storage.sql.exec(`SELECT * FROM cm_log WHERE execution_id = ? ORDER BY seq`, row.id).toArray().map(rowToEntry);
|
|
950
|
+
const log = [];
|
|
951
|
+
for (const entry of entries) log[entry.seq] = entry;
|
|
952
|
+
return {
|
|
953
|
+
id: row.id,
|
|
954
|
+
code: row.code,
|
|
955
|
+
status: row.status,
|
|
956
|
+
log,
|
|
957
|
+
result: parseForStorage(row.result),
|
|
958
|
+
error: row.error ?? void 0,
|
|
959
|
+
logs: row.logs ? JSON.parse(row.logs) : void 0,
|
|
960
|
+
connectors: row.connectors ? JSON.parse(row.connectors) : void 0,
|
|
961
|
+
createdAt: row.created_at,
|
|
962
|
+
updatedAt: row.updated_at
|
|
963
|
+
};
|
|
964
|
+
}
|
|
965
|
+
async #get(id) {
|
|
966
|
+
const row = this.#executionRow(id);
|
|
967
|
+
return row ? this.#assemble(row) : null;
|
|
968
|
+
}
|
|
969
|
+
};
|
|
970
|
+
//#endregion
|
|
971
|
+
//#region src/connectors/mcp.ts
|
|
972
|
+
function unwrapMcpResult(result) {
|
|
973
|
+
if ("toolResult" in result) return result.toolResult;
|
|
974
|
+
if (result.isError) {
|
|
975
|
+
const msg = result.content?.filter((c) => c.type === "text").map((c) => "text" in c ? c.text : "").join("\n") || "Tool call failed";
|
|
976
|
+
throw new Error(msg);
|
|
977
|
+
}
|
|
978
|
+
if (result.structuredContent != null) return result.structuredContent;
|
|
979
|
+
if (!(result.content?.length > 0 && result.content.every((c) => c.type === "text"))) return result;
|
|
980
|
+
const text = result.content.map((c) => "text" in c ? c.text : "").join("\n");
|
|
981
|
+
try {
|
|
982
|
+
return JSON.parse(text);
|
|
983
|
+
} catch {
|
|
984
|
+
return text;
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
/**
|
|
988
|
+
* Connector backed by an MCP connection. Each MCP tool becomes one entry in
|
|
989
|
+
* the tools record, executing through `connection.client.callTool()`.
|
|
990
|
+
*
|
|
991
|
+
* Subclass and implement `createConnection()`. To mark a derived tool as
|
|
992
|
+
* requiring approval or to attach a revert, override the `tool(name, t)`
|
|
993
|
+
* decoration hook from the base class.
|
|
994
|
+
*/
|
|
995
|
+
var McpConnector = class extends CodemodeConnector {
|
|
996
|
+
toolName(tool) {
|
|
997
|
+
return sanitizeToolName(tool.name);
|
|
998
|
+
}
|
|
999
|
+
#connectionPromise;
|
|
1000
|
+
getConnection() {
|
|
1001
|
+
return this.#connectionPromise ??= Promise.resolve(this.createConnection());
|
|
1002
|
+
}
|
|
1003
|
+
async fetchTools() {
|
|
1004
|
+
const connection = await this.getConnection();
|
|
1005
|
+
if (connection.tools?.length) return connection.tools;
|
|
1006
|
+
if (connection.fetchTools) return connection.fetchTools();
|
|
1007
|
+
return [];
|
|
1008
|
+
}
|
|
1009
|
+
async describe() {
|
|
1010
|
+
const desc = await super.describe();
|
|
1011
|
+
const connection = await this.getConnection();
|
|
1012
|
+
if (connection.instructions) desc.instructions = [connection.instructions, desc.instructions].filter(Boolean).join("\n\n");
|
|
1013
|
+
return desc;
|
|
1014
|
+
}
|
|
1015
|
+
async tools() {
|
|
1016
|
+
const mcpTools = await this.fetchTools();
|
|
1017
|
+
const out = {};
|
|
1018
|
+
const sources = /* @__PURE__ */ new Map();
|
|
1019
|
+
for (const tool of mcpTools) {
|
|
1020
|
+
const name = this.toolName(tool);
|
|
1021
|
+
const existing = sources.get(name);
|
|
1022
|
+
if (existing !== void 0) throw new Error(`MCP tools "${existing}" and "${tool.name}" on ${this.name()} both map to "${name}". Override toolName() to disambiguate.`);
|
|
1023
|
+
sources.set(name, tool.name);
|
|
1024
|
+
out[name] = {
|
|
1025
|
+
description: tool.description,
|
|
1026
|
+
inputSchema: tool.inputSchema,
|
|
1027
|
+
outputSchema: tool.outputSchema,
|
|
1028
|
+
execute: async (args) => {
|
|
1029
|
+
return unwrapMcpResult(await (await this.getConnection()).client.callTool({
|
|
1030
|
+
name: tool.name,
|
|
1031
|
+
arguments: args
|
|
1032
|
+
}));
|
|
1033
|
+
}
|
|
1034
|
+
};
|
|
1035
|
+
}
|
|
1036
|
+
return out;
|
|
1037
|
+
}
|
|
1038
|
+
};
|
|
1039
|
+
//#endregion
|
|
1040
|
+
//#region src/connectors/openapi.ts
|
|
1041
|
+
const HTTP_METHODS = [
|
|
1042
|
+
"get",
|
|
1043
|
+
"put",
|
|
1044
|
+
"post",
|
|
1045
|
+
"delete",
|
|
1046
|
+
"patch",
|
|
1047
|
+
"options",
|
|
1048
|
+
"head"
|
|
1049
|
+
];
|
|
1050
|
+
/**
|
|
1051
|
+
* Connector backed by an OpenAPI spec.
|
|
1052
|
+
*
|
|
1053
|
+
* The base reads the spec **once, host-side** and derives one typed tool per
|
|
1054
|
+
* operation — so the model calls `api.get_repository({ owner, repo })` directly
|
|
1055
|
+
* (discoverable via `codemode.search` / `codemode.describe`, with input types)
|
|
1056
|
+
* instead of fetching the raw spec and hand-writing operation lookups on every
|
|
1057
|
+
* run. Deriving on the host costs zero prompt tokens.
|
|
1058
|
+
*
|
|
1059
|
+
* Override two methods:
|
|
1060
|
+
*
|
|
1061
|
+
* - `spec()` returns the OpenAPI document (used to derive operations)
|
|
1062
|
+
* - `request()` performs the authenticated HTTP call
|
|
1063
|
+
*
|
|
1064
|
+
* A low-level `request` tool is also exposed as an escape hatch for operations
|
|
1065
|
+
* the model can't reach through a derived tool.
|
|
1066
|
+
*
|
|
1067
|
+
* The per-operation tool's input is a single object: top-level keys are the
|
|
1068
|
+
* operation's path/query/header parameters, plus a `body` key when the
|
|
1069
|
+
* operation has a JSON request body. The derived tool substitutes path params,
|
|
1070
|
+
* then hands `request()` a clean `{ path, method, params, body, headers }`.
|
|
1071
|
+
*
|
|
1072
|
+
* (The sandbox-facing escape hatch is `request`, not `fetch`, because `fetch`
|
|
1073
|
+
* is reserved by `WorkerEntrypoint`.)
|
|
1074
|
+
*/
|
|
1075
|
+
var OpenApiConnector = class extends CodemodeConnector {
|
|
1076
|
+
/** Whether to also expose the raw `spec` document as a tool. Off by default. */
|
|
1077
|
+
exposeSpec() {
|
|
1078
|
+
return false;
|
|
1079
|
+
}
|
|
1080
|
+
async tools() {
|
|
1081
|
+
const operations = deriveOperations(await this.spec());
|
|
1082
|
+
const tools = {};
|
|
1083
|
+
if (this.exposeSpec()) tools.spec = {
|
|
1084
|
+
description: "Return the raw OpenAPI document.",
|
|
1085
|
+
inputSchema: {
|
|
1086
|
+
type: "object",
|
|
1087
|
+
properties: {}
|
|
1088
|
+
},
|
|
1089
|
+
execute: () => this.spec()
|
|
1090
|
+
};
|
|
1091
|
+
tools.request = {
|
|
1092
|
+
description: "Escape hatch: perform an authenticated request to a path (and optional method, params, body, headers). Prefer the per-operation tools.",
|
|
1093
|
+
inputSchema: {
|
|
1094
|
+
type: "object",
|
|
1095
|
+
properties: {
|
|
1096
|
+
path: { type: "string" },
|
|
1097
|
+
method: { type: "string" },
|
|
1098
|
+
params: {
|
|
1099
|
+
type: "object",
|
|
1100
|
+
additionalProperties: true
|
|
1101
|
+
},
|
|
1102
|
+
body: {},
|
|
1103
|
+
headers: {
|
|
1104
|
+
type: "object",
|
|
1105
|
+
additionalProperties: { type: "string" }
|
|
1106
|
+
}
|
|
1107
|
+
},
|
|
1108
|
+
required: ["path"]
|
|
1109
|
+
},
|
|
1110
|
+
execute: (args) => this.request(args)
|
|
1111
|
+
};
|
|
1112
|
+
for (const op of operations) tools[op.name] = {
|
|
1113
|
+
description: op.description,
|
|
1114
|
+
inputSchema: op.inputSchema,
|
|
1115
|
+
execute: (args) => this.request(toRequest(op, args))
|
|
1116
|
+
};
|
|
1117
|
+
return tools;
|
|
1118
|
+
}
|
|
1119
|
+
};
|
|
1120
|
+
const RESERVED_TOOL_NAMES = new Set(["request", "spec"]);
|
|
1121
|
+
const operationCache = /* @__PURE__ */ new WeakMap();
|
|
1122
|
+
function deriveOperations(spec) {
|
|
1123
|
+
if (!spec || typeof spec !== "object") return [];
|
|
1124
|
+
const cached = operationCache.get(spec);
|
|
1125
|
+
if (cached) return cached;
|
|
1126
|
+
const derived = buildOperations(spec);
|
|
1127
|
+
operationCache.set(spec, derived);
|
|
1128
|
+
return derived;
|
|
1129
|
+
}
|
|
1130
|
+
function buildOperations(doc) {
|
|
1131
|
+
const paths = doc.paths ?? {};
|
|
1132
|
+
const operations = [];
|
|
1133
|
+
const used = /* @__PURE__ */ new Set();
|
|
1134
|
+
for (const [path, item] of Object.entries(paths)) {
|
|
1135
|
+
if (!item || typeof item !== "object") continue;
|
|
1136
|
+
for (const method of HTTP_METHODS) {
|
|
1137
|
+
const operation = item[method];
|
|
1138
|
+
if (!operation || typeof operation !== "object") continue;
|
|
1139
|
+
const name = operationName(method, path, operation);
|
|
1140
|
+
if (!name) continue;
|
|
1141
|
+
if (RESERVED_TOOL_NAMES.has(name) || used.has(name)) {
|
|
1142
|
+
console.warn(`[OpenApiConnector] operation ${method.toUpperCase()} ${path} maps to tool name "${name}", which is ${RESERVED_TOOL_NAMES.has(name) ? "reserved" : "already used"} — skipping. Set a unique operationId to expose it.`);
|
|
1143
|
+
continue;
|
|
1144
|
+
}
|
|
1145
|
+
used.add(name);
|
|
1146
|
+
operations.push(buildOperation(doc, path, method, operation, name));
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
return operations;
|
|
1150
|
+
}
|
|
1151
|
+
function operationName(method, path, operation) {
|
|
1152
|
+
if (operation.operationId) return sanitizeToolName(operation.operationId);
|
|
1153
|
+
return sanitizeToolName(`${method}_${path}`);
|
|
1154
|
+
}
|
|
1155
|
+
function buildOperation(doc, path, method, operation, name) {
|
|
1156
|
+
const parameters = (operation.parameters ?? []).filter((p) => !!p && typeof p === "object" && !!p.name);
|
|
1157
|
+
const bodySchema = resolveRef(operation.requestBody?.content?.["application/json"]?.schema, doc);
|
|
1158
|
+
const bodyRequired = operation.requestBody?.required === true;
|
|
1159
|
+
const properties = {};
|
|
1160
|
+
const required = [];
|
|
1161
|
+
for (const param of parameters) {
|
|
1162
|
+
properties[param.name] = withDescription(resolveRef(param.schema, doc) ?? {}, param.description);
|
|
1163
|
+
if (param.required) required.push(param.name);
|
|
1164
|
+
}
|
|
1165
|
+
if (bodySchema !== void 0) {
|
|
1166
|
+
properties.body = bodySchema;
|
|
1167
|
+
if (bodyRequired) required.push("body");
|
|
1168
|
+
}
|
|
1169
|
+
const inputSchema = {
|
|
1170
|
+
type: "object",
|
|
1171
|
+
properties,
|
|
1172
|
+
...required.length ? { required } : {}
|
|
1173
|
+
};
|
|
1174
|
+
return {
|
|
1175
|
+
name,
|
|
1176
|
+
description: operation.summary || operation.description || `${method.toUpperCase()} ${path}`,
|
|
1177
|
+
inputSchema,
|
|
1178
|
+
path,
|
|
1179
|
+
method,
|
|
1180
|
+
parameters
|
|
1181
|
+
};
|
|
1182
|
+
}
|
|
1183
|
+
function toRequest(op, args) {
|
|
1184
|
+
const input = args && typeof args === "object" ? args : {};
|
|
1185
|
+
let resolvedPath = op.path;
|
|
1186
|
+
const query = {};
|
|
1187
|
+
const headers = {};
|
|
1188
|
+
for (const param of op.parameters) {
|
|
1189
|
+
const value = input[param.name];
|
|
1190
|
+
if (value === void 0) continue;
|
|
1191
|
+
if (param.in === "path") resolvedPath = resolvedPath.replace(`{${param.name}}`, encodeURIComponent(String(value)));
|
|
1192
|
+
else if (param.in === "query") query[param.name] = value;
|
|
1193
|
+
else if (param.in === "header") headers[param.name] = String(value);
|
|
1194
|
+
}
|
|
1195
|
+
return {
|
|
1196
|
+
path: resolvedPath,
|
|
1197
|
+
method: op.method.toUpperCase(),
|
|
1198
|
+
...Object.keys(query).length ? { params: query } : {},
|
|
1199
|
+
..."body" in input ? { body: input.body } : {},
|
|
1200
|
+
...Object.keys(headers).length ? { headers } : {}
|
|
1201
|
+
};
|
|
1202
|
+
}
|
|
1203
|
+
function withDescription(schema, description) {
|
|
1204
|
+
if (!description || typeof schema !== "object") return schema;
|
|
1205
|
+
return {
|
|
1206
|
+
...schema,
|
|
1207
|
+
description: schema.description ?? description
|
|
1208
|
+
};
|
|
1209
|
+
}
|
|
1210
|
+
/**
|
|
1211
|
+
* Inline local `#/...` `$ref`s so the generated input types are usable,
|
|
1212
|
+
* recursing through `properties`, `items`, `additionalProperties`, and the
|
|
1213
|
+
* `allOf`/`oneOf`/`anyOf` combinators. External refs and cycles degrade to an
|
|
1214
|
+
* open object rather than throwing.
|
|
1215
|
+
*/
|
|
1216
|
+
function resolveRef(schema, root, seen = /* @__PURE__ */ new Set()) {
|
|
1217
|
+
if (schema === void 0 || typeof schema === "boolean") return schema;
|
|
1218
|
+
if (typeof schema.$ref === "string") {
|
|
1219
|
+
const ref = schema.$ref;
|
|
1220
|
+
if (!ref.startsWith("#/") || seen.has(ref)) return { type: "object" };
|
|
1221
|
+
const target = pointer(root, ref.slice(2).split("/"));
|
|
1222
|
+
if (target === void 0) return { type: "object" };
|
|
1223
|
+
return resolveRef(target, root, new Set(seen).add(ref));
|
|
1224
|
+
}
|
|
1225
|
+
const out = { ...schema };
|
|
1226
|
+
if (schema.properties) {
|
|
1227
|
+
out.properties = {};
|
|
1228
|
+
for (const [key, value] of Object.entries(schema.properties)) out.properties[key] = resolveRef(value, root, seen) ?? {};
|
|
1229
|
+
}
|
|
1230
|
+
if (schema.items && !Array.isArray(schema.items)) out.items = resolveRef(schema.items, root, seen);
|
|
1231
|
+
if (schema.additionalProperties && typeof schema.additionalProperties === "object") out.additionalProperties = resolveRef(schema.additionalProperties, root, seen);
|
|
1232
|
+
for (const key of [
|
|
1233
|
+
"allOf",
|
|
1234
|
+
"oneOf",
|
|
1235
|
+
"anyOf"
|
|
1236
|
+
]) {
|
|
1237
|
+
const branch = schema[key];
|
|
1238
|
+
if (Array.isArray(branch)) out[key] = branch.map((s) => resolveRef(s, root, seen) ?? {});
|
|
1239
|
+
}
|
|
1240
|
+
return out;
|
|
1241
|
+
}
|
|
1242
|
+
function pointer(root, segments) {
|
|
1243
|
+
let current = root;
|
|
1244
|
+
for (const segment of segments) {
|
|
1245
|
+
const key = segment.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
1246
|
+
if (!current || typeof current !== "object") return void 0;
|
|
1247
|
+
current = current[key];
|
|
1248
|
+
}
|
|
1249
|
+
return current;
|
|
1250
|
+
}
|
|
1251
|
+
//#endregion
|
|
1252
|
+
//#region src/connectors/search.ts
|
|
1253
|
+
const SEARCH_RESULT_LIMIT = 50;
|
|
1254
|
+
const FIELD_WEIGHTS = {
|
|
1255
|
+
path: 12,
|
|
1256
|
+
connector: 8,
|
|
1257
|
+
method: 10,
|
|
1258
|
+
description: 5
|
|
1259
|
+
};
|
|
1260
|
+
function normalizeSearchText(value) {
|
|
1261
|
+
return value.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_./:-]+/g, " ").toLowerCase().trim();
|
|
1262
|
+
}
|
|
1263
|
+
function tokenize(value) {
|
|
1264
|
+
return normalizeSearchText(value).split(/[^a-z0-9]+/).map((t) => t.trim()).filter(Boolean);
|
|
1265
|
+
}
|
|
1266
|
+
function prepareField(value) {
|
|
1267
|
+
return {
|
|
1268
|
+
raw: normalizeSearchText(value ?? ""),
|
|
1269
|
+
tokens: tokenize(value ?? "")
|
|
1270
|
+
};
|
|
1271
|
+
}
|
|
1272
|
+
function scoreField(query, queryTokens, field, weight) {
|
|
1273
|
+
if (field.raw.length === 0) return {
|
|
1274
|
+
score: 0,
|
|
1275
|
+
matchedTokens: /* @__PURE__ */ new Set(),
|
|
1276
|
+
exactPhrase: false
|
|
1277
|
+
};
|
|
1278
|
+
let score = 0;
|
|
1279
|
+
const matchedTokens = /* @__PURE__ */ new Set();
|
|
1280
|
+
const exactPhrase = query.length > 0 && field.raw.includes(query);
|
|
1281
|
+
if (query.length > 0) {
|
|
1282
|
+
if (field.raw === query) score += weight * 14;
|
|
1283
|
+
else if (field.raw.startsWith(query)) score += weight * 9;
|
|
1284
|
+
else if (exactPhrase) score += weight * 6;
|
|
1285
|
+
}
|
|
1286
|
+
for (const token of queryTokens) if (field.tokens.includes(token)) {
|
|
1287
|
+
score += weight * 4;
|
|
1288
|
+
matchedTokens.add(token);
|
|
1289
|
+
} else if (field.tokens.some((c) => c.startsWith(token) || token.startsWith(c))) {
|
|
1290
|
+
score += weight * 2;
|
|
1291
|
+
matchedTokens.add(token);
|
|
1292
|
+
} else if (field.raw.includes(token)) {
|
|
1293
|
+
score += weight;
|
|
1294
|
+
matchedTokens.add(token);
|
|
1295
|
+
}
|
|
1296
|
+
return {
|
|
1297
|
+
score,
|
|
1298
|
+
matchedTokens,
|
|
1299
|
+
exactPhrase
|
|
1300
|
+
};
|
|
1301
|
+
}
|
|
1302
|
+
function scoreMatch(item, query) {
|
|
1303
|
+
const normalizedQuery = normalizeSearchText(query);
|
|
1304
|
+
const queryTokens = tokenize(query);
|
|
1305
|
+
if (normalizedQuery.length === 0 || queryTokens.length === 0) return null;
|
|
1306
|
+
const fields = [
|
|
1307
|
+
scoreField(normalizedQuery, queryTokens, prepareField(item.path), FIELD_WEIGHTS.path),
|
|
1308
|
+
scoreField(normalizedQuery, queryTokens, prepareField(item.connector), FIELD_WEIGHTS.connector),
|
|
1309
|
+
scoreField(normalizedQuery, queryTokens, prepareField(item.method), FIELD_WEIGHTS.method),
|
|
1310
|
+
scoreField(normalizedQuery, queryTokens, prepareField(item.description), FIELD_WEIGHTS.description)
|
|
1311
|
+
];
|
|
1312
|
+
const matchedTokens = /* @__PURE__ */ new Set();
|
|
1313
|
+
let score = 0;
|
|
1314
|
+
let exactPhrase = false;
|
|
1315
|
+
for (const field of fields) {
|
|
1316
|
+
score += field.score;
|
|
1317
|
+
exactPhrase ||= field.exactPhrase;
|
|
1318
|
+
for (const t of field.matchedTokens) matchedTokens.add(t);
|
|
1319
|
+
}
|
|
1320
|
+
if (matchedTokens.size === 0) return null;
|
|
1321
|
+
const coverage = matchedTokens.size / queryTokens.length;
|
|
1322
|
+
if (coverage < (queryTokens.length <= 2 ? 1 : .6) && !exactPhrase) return null;
|
|
1323
|
+
if (coverage === 1) score += 25;
|
|
1324
|
+
else score += Math.round(coverage * 10);
|
|
1325
|
+
const pathTokens = tokenize(item.path);
|
|
1326
|
+
const methodTokens = tokenize(item.method);
|
|
1327
|
+
if (pathTokens[0] === queryTokens[0] || methodTokens[0] === queryTokens[0]) score += 8;
|
|
1328
|
+
if (normalizeSearchText(item.path) === normalizedQuery || normalizeSearchText(item.method) === normalizedQuery) score += 20;
|
|
1329
|
+
return {
|
|
1330
|
+
path: item.path,
|
|
1331
|
+
connector: item.connector,
|
|
1332
|
+
method: item.method,
|
|
1333
|
+
description: item.description,
|
|
1334
|
+
kind: item.kind,
|
|
1335
|
+
score
|
|
1336
|
+
};
|
|
1337
|
+
}
|
|
1338
|
+
function searchConnectors(query, descriptions, snippets) {
|
|
1339
|
+
const items = [];
|
|
1340
|
+
for (const desc of descriptions) for (const [methodName, descriptor] of Object.entries(desc.descriptors)) items.push({
|
|
1341
|
+
path: `${desc.name}.${methodName}`,
|
|
1342
|
+
connector: desc.name,
|
|
1343
|
+
method: methodName,
|
|
1344
|
+
description: descriptor?.description,
|
|
1345
|
+
kind: "method"
|
|
1346
|
+
});
|
|
1347
|
+
if (snippets) for (const snippet of snippets) items.push({
|
|
1348
|
+
path: snippet.name,
|
|
1349
|
+
connector: "snippet",
|
|
1350
|
+
method: snippet.name,
|
|
1351
|
+
description: snippet.description,
|
|
1352
|
+
kind: "snippet"
|
|
1353
|
+
});
|
|
1354
|
+
const ranked = items.map((item) => scoreMatch(item, query)).filter((r) => r !== null).sort((a, b) => b.score - a.score || a.path.localeCompare(b.path));
|
|
1355
|
+
const total = ranked.length;
|
|
1356
|
+
return {
|
|
1357
|
+
results: ranked.slice(0, SEARCH_RESULT_LIMIT),
|
|
1358
|
+
total,
|
|
1359
|
+
truncated: total > SEARCH_RESULT_LIMIT
|
|
1360
|
+
};
|
|
1361
|
+
}
|
|
1362
|
+
//#endregion
|
|
1363
|
+
//#region src/connectors/describe.ts
|
|
1364
|
+
/**
|
|
1365
|
+
* Connector and snippet docs rendering — derives TypeScript documentation from
|
|
1366
|
+
* connector descriptors on demand. Also renders snippet source.
|
|
1367
|
+
*/
|
|
1368
|
+
function renderConnectorTypes(connectorName, instructions, descriptors) {
|
|
1369
|
+
return [instructions, generateTypesFromJsonSchema(descriptors).replace("declare const codemode", `declare const ${sanitizeToolName(connectorName)}`)].filter(Boolean).join("\n\n");
|
|
1370
|
+
}
|
|
1371
|
+
function renderMethodTypes(methodName, descriptors) {
|
|
1372
|
+
const descriptor = descriptors[methodName];
|
|
1373
|
+
if (!descriptor) return "";
|
|
1374
|
+
const generated = generateTypesFromJsonSchema({ [methodName]: descriptor });
|
|
1375
|
+
return generated.slice(0, generated.indexOf("declare const codemode")).trim();
|
|
1376
|
+
}
|
|
1377
|
+
function describeTarget(target, descriptions, snippets) {
|
|
1378
|
+
if (snippets) {
|
|
1379
|
+
const snippet = snippets.find((s) => s.name === target);
|
|
1380
|
+
if (snippet) {
|
|
1381
|
+
const parts = [snippet.description];
|
|
1382
|
+
parts.push(`\`\`\`ts\n${snippet.code}\n\`\`\``);
|
|
1383
|
+
return {
|
|
1384
|
+
path: snippet.name,
|
|
1385
|
+
description: snippet.description,
|
|
1386
|
+
types: parts.join("\n\n"),
|
|
1387
|
+
kind: "snippet"
|
|
1388
|
+
};
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
const [maybeConnector, maybeMethod] = target.includes(".") ? target.split(".", 2) : [target, void 0];
|
|
1392
|
+
const connector = descriptions.find((d) => d.name === maybeConnector);
|
|
1393
|
+
if (connector && !maybeMethod) return {
|
|
1394
|
+
path: connector.name,
|
|
1395
|
+
description: connector.instructions,
|
|
1396
|
+
types: renderConnectorTypes(connector.name, connector.instructions, connector.descriptors),
|
|
1397
|
+
kind: "connector"
|
|
1398
|
+
};
|
|
1399
|
+
const candidates = connector ? [connector] : descriptions;
|
|
1400
|
+
const methodName = maybeMethod ?? target;
|
|
1401
|
+
for (const candidate of candidates) if (candidate.descriptors[methodName]) return {
|
|
1402
|
+
path: `${candidate.name}.${methodName}`,
|
|
1403
|
+
description: candidate.descriptors[methodName]?.description,
|
|
1404
|
+
types: renderMethodTypes(methodName, candidate.descriptors),
|
|
1405
|
+
kind: "method"
|
|
1406
|
+
};
|
|
1407
|
+
return {
|
|
1408
|
+
path: target,
|
|
1409
|
+
description: void 0,
|
|
1410
|
+
types: `"${target}" not found.`,
|
|
1411
|
+
kind: "method"
|
|
1412
|
+
};
|
|
1413
|
+
}
|
|
1414
|
+
//#endregion
|
|
1415
|
+
//#region src/proxy-tool.ts
|
|
1416
|
+
/**
|
|
1417
|
+
* Model-facing proxy tool.
|
|
1418
|
+
*
|
|
1419
|
+
* One AI SDK tool with `{ code: string }`. Code runs in the Executor sandbox.
|
|
1420
|
+
* The CodemodeRuntime facet makes execution durable via abort-and-replay:
|
|
1421
|
+
* every tool call is logged; reads execute and record; approval-required
|
|
1422
|
+
* actions abort the run; `continue` replays the log and runs the approved action.
|
|
1423
|
+
*
|
|
1424
|
+
* Inside the sandbox:
|
|
1425
|
+
* - Connector SDKs as globals: `<connector>.<method>(...)`
|
|
1426
|
+
* - Platform SDK: `codemode.search/describe/step/run`
|
|
1427
|
+
*
|
|
1428
|
+
* ## Sequencing
|
|
1429
|
+
*
|
|
1430
|
+
* The host (this module) owns the replay cursor: a per-run counter allocates a
|
|
1431
|
+
* `seq` for every connector call and every `codemode.step` in the order they
|
|
1432
|
+
* happen, and threads `executionId` + `seq` to the facet. The facet keeps no
|
|
1433
|
+
* in-memory cursor, so runs are safe across hibernation and can run
|
|
1434
|
+
* concurrently without clobbering one another.
|
|
1435
|
+
*/
|
|
1436
|
+
const proxySchema = z.object({ code: z.string() });
|
|
1437
|
+
const STEP_PRELUDE = String.raw`
|
|
1438
|
+
codemode.step = async (name, fn) => {
|
|
1439
|
+
const decision = await codemode.__stepDecide(name);
|
|
1440
|
+
if (decision.kind === "replay") return decision.result;
|
|
1441
|
+
// Anything other than "execute" (i.e. a pause from divergence) aborts
|
|
1442
|
+
// the run; the reason is recorded on the execution.
|
|
1443
|
+
if (decision.kind !== "execute") throw new Error("${"__CODEMODE_PAUSE__"}");
|
|
1444
|
+
const value = await fn();
|
|
1445
|
+
await codemode.__stepRecord(decision.seq, value);
|
|
1446
|
+
return value;
|
|
1447
|
+
};`;
|
|
1448
|
+
const CONTROL_KEY = "__codemode_control__";
|
|
1449
|
+
function createCursor() {
|
|
1450
|
+
let n = 0;
|
|
1451
|
+
return { next: () => n++ };
|
|
1452
|
+
}
|
|
1453
|
+
var ConnectorCallTarget = class extends RpcTarget {
|
|
1454
|
+
#handle;
|
|
1455
|
+
constructor(handle) {
|
|
1456
|
+
super();
|
|
1457
|
+
this.#handle = handle;
|
|
1458
|
+
}
|
|
1459
|
+
callTool(method, args) {
|
|
1460
|
+
return this.#handle(method, args);
|
|
1461
|
+
}
|
|
1462
|
+
};
|
|
1463
|
+
async function loadSetup(connectors) {
|
|
1464
|
+
const connectorsByName = /* @__PURE__ */ new Map();
|
|
1465
|
+
const descriptions = [];
|
|
1466
|
+
const annotations = {};
|
|
1467
|
+
for (const connector of connectors) {
|
|
1468
|
+
const name = connector.name();
|
|
1469
|
+
const description = await connector.describe();
|
|
1470
|
+
connectorsByName.set(name, connector);
|
|
1471
|
+
descriptions.push(description);
|
|
1472
|
+
for (const [method, annotation] of Object.entries(description.annotations ?? {})) annotations[`${name}.${method}`] = annotation;
|
|
1473
|
+
}
|
|
1474
|
+
return {
|
|
1475
|
+
connectorsByName,
|
|
1476
|
+
descriptions,
|
|
1477
|
+
annotations
|
|
1478
|
+
};
|
|
1479
|
+
}
|
|
1480
|
+
/**
|
|
1481
|
+
* Notify every connector that an execution reached a terminal state so it can
|
|
1482
|
+
* dispose any per-execution resource (e.g. a browser session). Deliberately
|
|
1483
|
+
* *not* called on pause — a paused run may resume later. Hook rejections are
|
|
1484
|
+
* swallowed: teardown must never turn a finished run into a failure.
|
|
1485
|
+
*
|
|
1486
|
+
* Fires for every connector regardless of whether it took part in the run —
|
|
1487
|
+
* connectors that own no per-execution state default to a no-op.
|
|
1488
|
+
*/
|
|
1489
|
+
async function disposeConnectors(connectors, executionId, status) {
|
|
1490
|
+
await Promise.all([...connectors].map(async (connector) => {
|
|
1491
|
+
try {
|
|
1492
|
+
await connector.disposeExecution(executionId, status);
|
|
1493
|
+
} catch {}
|
|
1494
|
+
}));
|
|
1495
|
+
}
|
|
1496
|
+
/**
|
|
1497
|
+
* Notify every connector that an execution pass ended — including a pause,
|
|
1498
|
+
* where `disposeExecution` deliberately does not fire — so per-pass resources
|
|
1499
|
+
* (open sockets, leases) can be released. Rejections are swallowed for the
|
|
1500
|
+
* same reason as `disposeConnectors`.
|
|
1501
|
+
*/
|
|
1502
|
+
async function notifyPassEnd(connectors, executionId, status) {
|
|
1503
|
+
await Promise.all([...connectors].map(async (connector) => {
|
|
1504
|
+
try {
|
|
1505
|
+
await connector.onPassEnd(executionId, status);
|
|
1506
|
+
} catch {}
|
|
1507
|
+
}));
|
|
1508
|
+
}
|
|
1509
|
+
/**
|
|
1510
|
+
* Reject reserved and duplicate connector namespaces up front. Duplicates
|
|
1511
|
+
* would silently shadow each other in the sandbox (last one wins).
|
|
1512
|
+
*/
|
|
1513
|
+
function validateConnectorNames(connectors) {
|
|
1514
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1515
|
+
for (const connector of connectors) {
|
|
1516
|
+
const name = connector.name();
|
|
1517
|
+
if (name === "codemode") throw new Error("Connector name \"codemode\" is reserved for the codemode platform SDK.");
|
|
1518
|
+
if (seen.has(name)) throw new Error(`Duplicate connector name "${name}" — each connector needs a unique namespace (pass a distinct \`name\` option).`);
|
|
1519
|
+
seen.add(name);
|
|
1520
|
+
}
|
|
1521
|
+
}
|
|
1522
|
+
function buildConnectorBindings(setup, runtime, executionId, cursor) {
|
|
1523
|
+
return setup.descriptions.map((desc) => ({
|
|
1524
|
+
name: desc.name,
|
|
1525
|
+
binding: new ConnectorCallTarget(async (method, args) => {
|
|
1526
|
+
try {
|
|
1527
|
+
const seq = cursor.next();
|
|
1528
|
+
const annotation = setup.annotations[`${desc.name}.${method}`];
|
|
1529
|
+
const requiresApproval = annotation?.requiresApproval ?? false;
|
|
1530
|
+
const ephemeral = annotation?.replay === "reexecute";
|
|
1531
|
+
const decision = await runtime.decide(executionId, seq, desc.name, method, args, requiresApproval, ephemeral);
|
|
1532
|
+
if (decision.kind === "replay") return decision.result;
|
|
1533
|
+
if (decision.kind === "pause") return { [CONTROL_KEY]: "pause" };
|
|
1534
|
+
const connector = setup.connectorsByName.get(desc.name);
|
|
1535
|
+
if (!connector) throw new Error(`Unknown connector: ${desc.name}`);
|
|
1536
|
+
const result = await connector.executeTool(method, args, { executionId });
|
|
1537
|
+
await runtime.recordResult(executionId, decision.seq, result);
|
|
1538
|
+
return result;
|
|
1539
|
+
} catch (err) {
|
|
1540
|
+
console.error(`codemode: ${desc.name}.${method} failed (execution ${executionId})`, err);
|
|
1541
|
+
return {
|
|
1542
|
+
[CONTROL_KEY]: "error",
|
|
1543
|
+
message: err instanceof Error ? err.message : String(err)
|
|
1544
|
+
};
|
|
1545
|
+
}
|
|
1546
|
+
})
|
|
1547
|
+
}));
|
|
1548
|
+
}
|
|
1549
|
+
function createPlatformProvider(setup, bindings, runtime, executor, executionId, cursor) {
|
|
1550
|
+
const { descriptions } = setup;
|
|
1551
|
+
const provider = {
|
|
1552
|
+
name: "codemode",
|
|
1553
|
+
prelude: STEP_PRELUDE,
|
|
1554
|
+
fns: {
|
|
1555
|
+
search: async (query) => searchConnectors(String(query), descriptions, await runtime.listSnippets()),
|
|
1556
|
+
describe: async (target) => describeTarget(String(target), descriptions, await runtime.listSnippets()),
|
|
1557
|
+
run: async (...args) => {
|
|
1558
|
+
const snippet = await runtime.getSnippet(String(args[0]));
|
|
1559
|
+
if (!snippet) return { error: `Snippet "${args[0]}" not found.` };
|
|
1560
|
+
const missing = missingConnectors(snippet.connectors, new Set(setup.connectorsByName.keys()));
|
|
1561
|
+
if (missing.length > 0) return { error: `Snippet "${args[0]}" requires connector(s) ${missing.map((m) => `"${m}"`).join(", ")} that are not configured on this runtime.` };
|
|
1562
|
+
return (await runCode({
|
|
1563
|
+
code: `async () => {\n const snippet = (${normalizeCode(snippet.code)});\n return await snippet(${JSON.stringify(args[1])});\n}`,
|
|
1564
|
+
executor,
|
|
1565
|
+
providers: [provider],
|
|
1566
|
+
connectors: bindings
|
|
1567
|
+
})).result;
|
|
1568
|
+
},
|
|
1569
|
+
__stepDecide: async (name) => runtime.decide(executionId, cursor.next(), STEP_CONNECTOR, String(name), void 0, false),
|
|
1570
|
+
__stepRecord: async (seq, value) => {
|
|
1571
|
+
await runtime.recordResult(executionId, Number(seq), value);
|
|
1572
|
+
return true;
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
};
|
|
1576
|
+
return provider;
|
|
1577
|
+
}
|
|
1578
|
+
function buildDescription(connectors, customDescription, connectorHints) {
|
|
1579
|
+
if (customDescription) return customDescription;
|
|
1580
|
+
const namespaces = connectors.map((c) => {
|
|
1581
|
+
const name = c.name();
|
|
1582
|
+
const hint = connectorHints?.[name];
|
|
1583
|
+
return hint ? `- \`${name}\` — ${hint}` : `- \`${name}\``;
|
|
1584
|
+
}).join("\n");
|
|
1585
|
+
return [
|
|
1586
|
+
"Execute JavaScript in a sandbox with access to connector SDKs.",
|
|
1587
|
+
"",
|
|
1588
|
+
"## Workflow",
|
|
1589
|
+
"",
|
|
1590
|
+
"1. `const matches = await codemode.search(\"short intent phrase\");`",
|
|
1591
|
+
"2. `const docs = await codemode.describe(matches.results[0].path);`",
|
|
1592
|
+
"3. Call the method: `await <connector>.<method>(args);`",
|
|
1593
|
+
"",
|
|
1594
|
+
"## Rules",
|
|
1595
|
+
"",
|
|
1596
|
+
`- The ONLY globals are ${connectors.map((c) => `\`${c.name()}\``).join(", ")} and \`codemode\` (plus standard JavaScript). There is no \`host\`, \`fs\`, \`require\`, \`process\`, or Node.js API — all I/O goes through the connectors below.`,
|
|
1597
|
+
"- Never guess method names. If you have not used a connector in this conversation, run a discovery pass first: `codemode.search(query)` returns ranked matches across connector methods and saved snippets.",
|
|
1598
|
+
"- `codemode.describe(\"connector.method\")` returns TypeScript type declarations.",
|
|
1599
|
+
"- `codemode.step(name, fn)` wraps side-effectful or nondeterministic work (raw fetch, random, time) so it runs once and is replayed on resume. Use it for anything that isn't a connector call.",
|
|
1600
|
+
"- Some methods require approval. The run pauses until the user approves, then resumes automatically. Write code as if the call returns normally.",
|
|
1601
|
+
"- A result with `status: \"paused\"` means the run is awaiting human approval. Tell the user what is pending and wait — do NOT re-issue the code; the run resumes on its own once approved.",
|
|
1602
|
+
"- All code outside connector calls and `codemode.step` must be deterministic so resume can replay it.",
|
|
1603
|
+
"- Do not use `fetch` — use connector SDKs.",
|
|
1604
|
+
"",
|
|
1605
|
+
"## Snippets",
|
|
1606
|
+
"",
|
|
1607
|
+
"Snippets are saved scripts you can reuse.",
|
|
1608
|
+
"- `codemode.run(\"name\", input)` runs a saved snippet. Snippets appear in `codemode.search` results.",
|
|
1609
|
+
"- If a script may be saved as a snippet later, write it as `async (input) => { ... }` so it can take input.",
|
|
1610
|
+
"",
|
|
1611
|
+
"## Available connectors",
|
|
1612
|
+
"",
|
|
1613
|
+
namespaces
|
|
1614
|
+
].join("\n");
|
|
1615
|
+
}
|
|
1616
|
+
async function runPass(executionId, code, setup, runtime, executor, transformResult) {
|
|
1617
|
+
const cursor = createCursor();
|
|
1618
|
+
const bindings = buildConnectorBindings(setup, runtime, executionId, cursor);
|
|
1619
|
+
const platformProvider = createPlatformProvider(setup, bindings, runtime, executor, executionId, cursor);
|
|
1620
|
+
const connectors = [...setup.connectorsByName.values()];
|
|
1621
|
+
let ended = false;
|
|
1622
|
+
const endPass = async (status) => {
|
|
1623
|
+
ended = true;
|
|
1624
|
+
await notifyPassEnd(connectors, executionId, status);
|
|
1625
|
+
if (status !== "paused") await disposeConnectors(connectors, executionId, status);
|
|
1626
|
+
};
|
|
1627
|
+
try {
|
|
1628
|
+
let output;
|
|
1629
|
+
let threw;
|
|
1630
|
+
try {
|
|
1631
|
+
output = await runCode({
|
|
1632
|
+
code,
|
|
1633
|
+
executor,
|
|
1634
|
+
providers: [platformProvider],
|
|
1635
|
+
connectors: bindings
|
|
1636
|
+
});
|
|
1637
|
+
} catch (err) {
|
|
1638
|
+
threw = err;
|
|
1639
|
+
}
|
|
1640
|
+
const execution = await runtime.getExecution(executionId);
|
|
1641
|
+
if (execution?.status === "paused") {
|
|
1642
|
+
await endPass("paused");
|
|
1643
|
+
return {
|
|
1644
|
+
status: "paused",
|
|
1645
|
+
executionId,
|
|
1646
|
+
pending: await runtime.listPending(executionId)
|
|
1647
|
+
};
|
|
1648
|
+
}
|
|
1649
|
+
if (execution?.status === "error") {
|
|
1650
|
+
await endPass("error");
|
|
1651
|
+
return {
|
|
1652
|
+
status: "error",
|
|
1653
|
+
executionId,
|
|
1654
|
+
error: execution.error ?? "Codemode execution failed"
|
|
1655
|
+
};
|
|
1656
|
+
}
|
|
1657
|
+
if (threw) {
|
|
1658
|
+
const message = withGlobalsHint(threw instanceof Error ? threw.message : String(threw), setup);
|
|
1659
|
+
await runtime.fail(executionId, message);
|
|
1660
|
+
await endPass("error");
|
|
1661
|
+
return {
|
|
1662
|
+
status: "error",
|
|
1663
|
+
executionId,
|
|
1664
|
+
error: message
|
|
1665
|
+
};
|
|
1666
|
+
}
|
|
1667
|
+
const result = output?.result;
|
|
1668
|
+
await runtime.complete(executionId, result, output?.logs);
|
|
1669
|
+
await endPass("completed");
|
|
1670
|
+
return {
|
|
1671
|
+
status: "completed",
|
|
1672
|
+
executionId,
|
|
1673
|
+
result: await applyTransform(transformResult, result),
|
|
1674
|
+
logs: output?.logs
|
|
1675
|
+
};
|
|
1676
|
+
} finally {
|
|
1677
|
+
if (!ended) await endPass("error");
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
/**
|
|
1681
|
+
* A sandbox `ReferenceError` usually means the model invented a global (e.g.
|
|
1682
|
+
* `host.writeFile(...)`). Append the real globals so the retry is informed
|
|
1683
|
+
* instead of another guess.
|
|
1684
|
+
*/
|
|
1685
|
+
function withGlobalsHint(message, setup) {
|
|
1686
|
+
if (!/\bis not defined\b/.test(message)) return message;
|
|
1687
|
+
return `${message} (the only globals available in the sandbox are: ${[...setup.connectorsByName.keys(), "codemode"].join(", ")})`;
|
|
1688
|
+
}
|
|
1689
|
+
/**
|
|
1690
|
+
* Apply the result transform, defending against a buggy transform: the run has
|
|
1691
|
+
* already completed and its resources are disposed, so a throwing transform
|
|
1692
|
+
* must not turn a successful run into a thrown tool error. Fall back to the raw
|
|
1693
|
+
* result (and warn) instead.
|
|
1694
|
+
*/
|
|
1695
|
+
async function applyTransform(transformResult, result) {
|
|
1696
|
+
if (!transformResult) return result;
|
|
1697
|
+
try {
|
|
1698
|
+
return await transformResult(result);
|
|
1699
|
+
} catch (err) {
|
|
1700
|
+
console.warn("codemode: transformResult threw; returning the raw result.", err);
|
|
1701
|
+
return result;
|
|
1702
|
+
}
|
|
1703
|
+
}
|
|
1704
|
+
function createProxyTool(options) {
|
|
1705
|
+
const connectors = options.connectors;
|
|
1706
|
+
validateConnectorNames(connectors);
|
|
1707
|
+
const runtime = getRuntime(options.ctx, options.name);
|
|
1708
|
+
let setupPromise;
|
|
1709
|
+
function getSetup() {
|
|
1710
|
+
return setupPromise ??= loadSetup(connectors);
|
|
1711
|
+
}
|
|
1712
|
+
return tool({
|
|
1713
|
+
description: buildDescription(connectors, options.description, options.connectorHints),
|
|
1714
|
+
inputSchema: proxySchema,
|
|
1715
|
+
execute: async ({ code }) => {
|
|
1716
|
+
if (code.length > 1e6) return {
|
|
1717
|
+
status: "error",
|
|
1718
|
+
executionId: "",
|
|
1719
|
+
error: tooLargeMessage("The execution code", code.length)
|
|
1720
|
+
};
|
|
1721
|
+
const setup = await getSetup();
|
|
1722
|
+
return runPass(await runtime.begin(code, {
|
|
1723
|
+
maxExecutions: options.maxExecutions,
|
|
1724
|
+
connectors: connectors.map((c) => c.name())
|
|
1725
|
+
}), code, setup, runtime, options.executor, options.transformResult);
|
|
1726
|
+
}
|
|
1727
|
+
});
|
|
1728
|
+
}
|
|
1729
|
+
/** Default runtime name when none is given. */
|
|
1730
|
+
const DEFAULT_RUNTIME_NAME = "default";
|
|
1731
|
+
/**
|
|
1732
|
+
* The facet is keyed by an explicit runtime *name* (default `"default"`), not
|
|
1733
|
+
* by the connector set: a runtime keeps its executions and snippets when
|
|
1734
|
+
* connectors are added or removed. Staleness is handled as data instead —
|
|
1735
|
+
* every execution and snippet records the connector names it needs, and
|
|
1736
|
+
* resume/snippet-run verifies they are present, failing with a clear error
|
|
1737
|
+
* when one is missing.
|
|
1738
|
+
*/
|
|
1739
|
+
function runtimeFacetName(name = DEFAULT_RUNTIME_NAME) {
|
|
1740
|
+
if (!/^[a-zA-Z0-9_.-]+$/.test(name)) throw new Error(`Invalid codemode runtime name "${name}" — use letters, digits, "_", "-" or "."`);
|
|
1741
|
+
return `codemode:${name}`;
|
|
1742
|
+
}
|
|
1743
|
+
function getRuntime(ctx, name) {
|
|
1744
|
+
const facetCtx = ctx;
|
|
1745
|
+
const runtimeClass = facetCtx.exports?.CodemodeRuntime ?? CodemodeRuntime;
|
|
1746
|
+
return facetCtx.facets.get(runtimeFacetName(name), () => ({ class: runtimeClass }));
|
|
1747
|
+
}
|
|
1748
|
+
/** Internal: the runtime handle uses this to reach the facet. Not public API. */
|
|
1749
|
+
const getCodemodeRuntime = getRuntime;
|
|
1750
|
+
/** Connectors an execution/snippet recorded but the runtime no longer has. */
|
|
1751
|
+
function missingConnectors(required, available) {
|
|
1752
|
+
return (required ?? []).filter((name) => !available.has(name));
|
|
1753
|
+
}
|
|
1754
|
+
/**
|
|
1755
|
+
* Approve a pending action and continue the paused execution. Re-runs the
|
|
1756
|
+
* stored code; the runtime replays the log up to the approved action, runs it
|
|
1757
|
+
* for real, and proceeds to the next pause or completion.
|
|
1758
|
+
*/
|
|
1759
|
+
async function resumeCodemode(options) {
|
|
1760
|
+
const runtime = getRuntime(options.ctx, options.name);
|
|
1761
|
+
const setup = await loadSetup(options.connectors);
|
|
1762
|
+
const existing = await runtime.getExecution(options.executionId);
|
|
1763
|
+
if (existing) {
|
|
1764
|
+
const missing = missingConnectors(existing.connectors, new Set(setup.connectorsByName.keys()));
|
|
1765
|
+
if (missing.length > 0) return {
|
|
1766
|
+
status: "error",
|
|
1767
|
+
executionId: options.executionId,
|
|
1768
|
+
error: `Execution "${options.executionId}" requires connector(s) ${missing.map((m) => `"${m}"`).join(", ")} that are not configured on this runtime.`
|
|
1769
|
+
};
|
|
1770
|
+
}
|
|
1771
|
+
const execution = await runtime.resume(options.executionId);
|
|
1772
|
+
if (!execution) {
|
|
1773
|
+
const error = existing ? `Execution "${options.executionId}" is not paused (status: ${existing.status}); only a paused run can be approved.` : `No execution "${options.executionId}" to resume.`;
|
|
1774
|
+
return {
|
|
1775
|
+
status: "error",
|
|
1776
|
+
executionId: options.executionId,
|
|
1777
|
+
error
|
|
1778
|
+
};
|
|
1779
|
+
}
|
|
1780
|
+
return runPass(execution.id, execution.code, setup, runtime, options.executor, options.transformResult);
|
|
1781
|
+
}
|
|
1782
|
+
/**
|
|
1783
|
+
* Returns whether the reject actually terminated the run — `false` when the
|
|
1784
|
+
* seq was no longer pending (already approved, rejected elsewhere, or
|
|
1785
|
+
* expired). Callers MUST check this before reporting the run as rejected:
|
|
1786
|
+
* approve and reject can interleave across the facet RPC await, and a no-op
|
|
1787
|
+
* reject means the action may have executed.
|
|
1788
|
+
*/
|
|
1789
|
+
async function rejectCodemode(options) {
|
|
1790
|
+
const terminated = await getRuntime(options.ctx, options.name).reject(options.seq, options.executionId);
|
|
1791
|
+
if (terminated) await disposeConnectors(options.connectors, options.executionId, "rejected");
|
|
1792
|
+
return terminated;
|
|
1793
|
+
}
|
|
1794
|
+
async function pendingCodemode(options) {
|
|
1795
|
+
return getRuntime(options.ctx, options.name).listPending(options.executionId);
|
|
1796
|
+
}
|
|
1797
|
+
/**
|
|
1798
|
+
* Expire paused (awaiting-approval) executions idle past `maxAgeMs`, marking
|
|
1799
|
+
* them rejected and firing each connector's `disposeExecution` so
|
|
1800
|
+
* per-execution resources (e.g. browser sessions) are reclaimed. Paused runs
|
|
1801
|
+
* are deliberately exempt from retention pruning, so without this a
|
|
1802
|
+
* never-answered approval would live forever. Returns the expired ids.
|
|
1803
|
+
* Designed to be called from a recurring alarm/scheduled task.
|
|
1804
|
+
*/
|
|
1805
|
+
async function expireCodemode(options) {
|
|
1806
|
+
const expired = await getRuntime(options.ctx, options.name).expirePaused(options.maxAgeMs);
|
|
1807
|
+
for (const executionId of expired) await disposeConnectors(options.connectors, executionId, "rejected");
|
|
1808
|
+
return expired;
|
|
1809
|
+
}
|
|
1810
|
+
async function rollbackCodemode(options) {
|
|
1811
|
+
const runtime = getRuntime(options.ctx, options.name);
|
|
1812
|
+
const byName = new Map(options.connectors.map((c) => [c.name(), c]));
|
|
1813
|
+
const actions = await runtime.actionsToRevert(options.executionId);
|
|
1814
|
+
let reverted = 0;
|
|
1815
|
+
const failures = [];
|
|
1816
|
+
for (const action of actions) {
|
|
1817
|
+
const connector = byName.get(action.connector);
|
|
1818
|
+
if (!connector) continue;
|
|
1819
|
+
try {
|
|
1820
|
+
if (await connector.revertAction(action.method, action.args, action.result, { executionId: options.executionId })) {
|
|
1821
|
+
await runtime.markReverted(action.seq, options.executionId);
|
|
1822
|
+
reverted++;
|
|
1823
|
+
}
|
|
1824
|
+
} catch (err) {
|
|
1825
|
+
failures.push(`${action.connector}.${action.method}: ` + (err instanceof Error ? err.message : String(err)));
|
|
1826
|
+
}
|
|
1827
|
+
}
|
|
1828
|
+
if (reverted > 0) {
|
|
1829
|
+
await runtime.markRolledBack(options.executionId);
|
|
1830
|
+
await disposeConnectors(options.connectors, options.executionId, "rolled_back");
|
|
1831
|
+
}
|
|
1832
|
+
if (failures.length > 0) throw new Error(`Rollback reverted ${reverted} action(s) but ${failures.length} failed: ` + failures.join("; "));
|
|
1833
|
+
}
|
|
1834
|
+
//#endregion
|
|
1835
|
+
//#region src/runtime-handle.ts
|
|
1836
|
+
function createCodemodeRuntime(options) {
|
|
1837
|
+
return new DefaultCodemodeRuntimeHandle(options);
|
|
1838
|
+
}
|
|
1839
|
+
var DefaultCodemodeRuntimeHandle = class {
|
|
1840
|
+
#options;
|
|
1841
|
+
constructor(options) {
|
|
1842
|
+
validateConnectorNames(options.connectors);
|
|
1843
|
+
this.#options = options;
|
|
1844
|
+
}
|
|
1845
|
+
tool(options) {
|
|
1846
|
+
return createProxyTool({
|
|
1847
|
+
ctx: this.#options.ctx,
|
|
1848
|
+
executor: this.#options.executor,
|
|
1849
|
+
connectors: this.#options.connectors,
|
|
1850
|
+
name: this.#options.name,
|
|
1851
|
+
description: options?.description,
|
|
1852
|
+
connectorHints: options?.connectorHints,
|
|
1853
|
+
maxExecutions: this.#options.maxExecutions,
|
|
1854
|
+
transformResult: this.#options.transformResult
|
|
1855
|
+
});
|
|
1856
|
+
}
|
|
1857
|
+
approve(options) {
|
|
1858
|
+
return resumeCodemode({
|
|
1859
|
+
ctx: this.#options.ctx,
|
|
1860
|
+
executor: this.#options.executor,
|
|
1861
|
+
connectors: this.#options.connectors,
|
|
1862
|
+
name: this.#options.name,
|
|
1863
|
+
executionId: options.executionId,
|
|
1864
|
+
maxExecutions: this.#options.maxExecutions,
|
|
1865
|
+
transformResult: this.#options.transformResult
|
|
1866
|
+
});
|
|
1867
|
+
}
|
|
1868
|
+
reject(options) {
|
|
1869
|
+
return rejectCodemode({
|
|
1870
|
+
ctx: this.#options.ctx,
|
|
1871
|
+
connectors: this.#options.connectors,
|
|
1872
|
+
name: this.#options.name,
|
|
1873
|
+
seq: options.seq,
|
|
1874
|
+
executionId: options.executionId
|
|
1875
|
+
});
|
|
1876
|
+
}
|
|
1877
|
+
rollback(options) {
|
|
1878
|
+
return rollbackCodemode({
|
|
1879
|
+
ctx: this.#options.ctx,
|
|
1880
|
+
connectors: this.#options.connectors,
|
|
1881
|
+
name: this.#options.name,
|
|
1882
|
+
executionId: options.executionId
|
|
1883
|
+
});
|
|
1884
|
+
}
|
|
1885
|
+
pending(executionId) {
|
|
1886
|
+
return pendingCodemode({
|
|
1887
|
+
ctx: this.#options.ctx,
|
|
1888
|
+
name: this.#options.name,
|
|
1889
|
+
executionId
|
|
1890
|
+
});
|
|
1891
|
+
}
|
|
1892
|
+
expirePaused(options) {
|
|
1893
|
+
return expireCodemode({
|
|
1894
|
+
ctx: this.#options.ctx,
|
|
1895
|
+
connectors: this.#options.connectors,
|
|
1896
|
+
name: this.#options.name,
|
|
1897
|
+
maxAgeMs: options?.maxAgeMs
|
|
1898
|
+
});
|
|
1899
|
+
}
|
|
1900
|
+
executions(limit) {
|
|
1901
|
+
return this.#runtime().listExecutions(limit);
|
|
1902
|
+
}
|
|
1903
|
+
async deleteExecution(id) {
|
|
1904
|
+
const runtime = this.#runtime();
|
|
1905
|
+
const state = await runtime.getExecution(id);
|
|
1906
|
+
const deleted = await runtime.deleteExecution(id);
|
|
1907
|
+
if (deleted && (state?.status === "paused" || state?.status === "running")) await disposeConnectors(this.#options.connectors, id, "rejected");
|
|
1908
|
+
return deleted;
|
|
1909
|
+
}
|
|
1910
|
+
pruneExecutions(keep) {
|
|
1911
|
+
return this.#runtime().pruneExecutions(keep);
|
|
1912
|
+
}
|
|
1913
|
+
saveSnippet(name, options) {
|
|
1914
|
+
return this.#runtime().saveSnippet(name, options);
|
|
1915
|
+
}
|
|
1916
|
+
snippets() {
|
|
1917
|
+
return this.#runtime().listSnippets();
|
|
1918
|
+
}
|
|
1919
|
+
deleteSnippet(name) {
|
|
1920
|
+
return this.#runtime().deleteSnippet(name);
|
|
1921
|
+
}
|
|
1922
|
+
#runtime() {
|
|
1923
|
+
return getCodemodeRuntime(this.#options.ctx, this.#options.name);
|
|
1924
|
+
}
|
|
1925
|
+
};
|
|
1926
|
+
//#endregion
|
|
1927
|
+
export { CodemodeConnector, CodemodeRuntime, DEFAULT_MAX_EXECUTIONS, DEFAULT_PAUSED_TTL_MS, DynamicWorkerExecutor, MAX_DURABLE_VALUE_BYTES, McpConnector, OpenApiConnector, ToolDispatcher, createCodemodeRuntime, generateTypesFromJsonSchema, jsonSchemaToType, normalizeCode, resolveProvider, runCode, sanitizeToolName, truncateResponse, truncateResult };
|
|
255
1928
|
|
|
256
1929
|
//# sourceMappingURL=index.js.map
|