@draht/coding-agent 2026.10.4 → 2026.10.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/README.md +32 -6
- package/dist/bundle/chunks/anthropic.js +1 -1
- package/dist/bundle/chunks/{chunk-DPE4ALPU.js → chunk-2VAF4XJI.js} +1 -1
- package/dist/bundle/chunks/chunk-6APPDDHH.js +65 -0
- package/dist/bundle/chunks/{chunk-LDAOC5RB.js → chunk-JFDPOIUH.js} +1 -1
- package/dist/bundle/chunks/{chunk-COF5JT7R.js → chunk-KU5HAKZL.js} +1 -1
- package/dist/bundle/chunks/{chunk-Z2INEV2J.js → chunk-MIUVNYYW.js} +292 -153
- package/dist/bundle/chunks/{chunk-5VZWYVZB.js → chunk-NHTOADU6.js} +2 -2
- package/dist/bundle/chunks/{chunk-H6FT43VC.js → chunk-OWGSPJPZ.js} +4 -4
- package/dist/bundle/chunks/chunk-PGJAHC3R.js +107 -0
- package/dist/bundle/chunks/chunk-QVFELZW2.js +312 -0
- package/dist/bundle/chunks/{chunk-XKDTJ4YR.js → chunk-TJ3AW62W.js} +1 -1
- package/dist/bundle/chunks/{cli-SR5QBZH4.js → cli-U7Y4VNNI.js} +1 -1
- package/dist/bundle/chunks/execute-ZWB4PIQQ.js +18 -0
- package/dist/bundle/chunks/google-antigravity.js +1 -1
- package/dist/bundle/chunks/google-gemini-cli.js +1 -1
- package/dist/bundle/chunks/openai-chatgpt.js +1 -1
- package/dist/bundle/chunks/openai-codex.js +1 -1
- package/dist/bundle/chunks/openrouter.js +1 -1
- package/dist/bundle/chunks/radius.js +1 -1
- package/dist/bundle/chunks/runtime-363BOYEO.js +3 -0
- package/dist/bundle/chunks/{runtime-6YJPGSP7.js → runtime-PXJK4L7Y.js} +1 -1
- package/dist/bundle/chunks/{settings-manager-D2EG7WDO.js → settings-manager-GEOZJXFQ.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-BEJ4ZJ3D.js +2 -0
- package/dist/bundle/chunks/xai.js +1 -1
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/cli/args.js +3 -3
- package/dist/cli/args.js.map +1 -1
- package/dist/core/builtins/duet.d.ts +5 -2
- package/dist/core/builtins/duet.d.ts.map +1 -1
- package/dist/core/builtins/duet.js +65 -27
- package/dist/core/builtins/duet.js.map +1 -1
- package/dist/core/builtins/index.d.ts.map +1 -1
- package/dist/core/builtins/index.js +2 -0
- package/dist/core/builtins/index.js.map +1 -1
- package/dist/core/builtins/polyphase.d.ts +15 -0
- package/dist/core/builtins/polyphase.d.ts.map +1 -0
- package/dist/core/builtins/polyphase.js +196 -0
- package/dist/core/builtins/polyphase.js.map +1 -0
- package/dist/core/builtins/subagent.d.ts +44 -34
- package/dist/core/builtins/subagent.d.ts.map +1 -1
- package/dist/core/builtins/subagent.js +827 -560
- package/dist/core/builtins/subagent.js.map +1 -1
- package/dist/core/extensions/types.d.ts +17 -2
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/keybindings.d.ts +30 -0
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +24 -0
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/model-resolver.js +4 -4
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/multi-agent/permission-gate.d.ts.map +1 -1
- package/dist/core/multi-agent/permission-gate.js +4 -1
- package/dist/core/multi-agent/permission-gate.js.map +1 -1
- package/dist/core/polyphase/approval.d.ts +35 -0
- package/dist/core/polyphase/approval.d.ts.map +1 -0
- package/dist/core/polyphase/approval.js +184 -0
- package/dist/core/polyphase/approval.js.map +1 -0
- package/dist/core/polyphase/child-events.d.ts +107 -0
- package/dist/core/polyphase/child-events.d.ts.map +1 -0
- package/dist/core/polyphase/child-events.js +862 -0
- package/dist/core/polyphase/child-events.js.map +1 -0
- package/dist/core/polyphase/child-process.d.ts +65 -0
- package/dist/core/polyphase/child-process.d.ts.map +1 -0
- package/dist/core/polyphase/child-process.js +361 -0
- package/dist/core/polyphase/child-process.js.map +1 -0
- package/dist/core/polyphase/commands.d.ts +44 -0
- package/dist/core/polyphase/commands.d.ts.map +1 -0
- package/dist/core/polyphase/commands.js +244 -0
- package/dist/core/polyphase/commands.js.map +1 -0
- package/dist/core/polyphase/details.d.ts +40 -0
- package/dist/core/polyphase/details.d.ts.map +1 -0
- package/dist/core/polyphase/details.js +538 -0
- package/dist/core/polyphase/details.js.map +1 -0
- package/dist/core/polyphase/emitter.d.ts +20 -0
- package/dist/core/polyphase/emitter.d.ts.map +1 -0
- package/dist/core/polyphase/emitter.js +90 -0
- package/dist/core/polyphase/emitter.js.map +1 -0
- package/dist/core/polyphase/jsonl-reader.d.ts +31 -0
- package/dist/core/polyphase/jsonl-reader.d.ts.map +1 -0
- package/dist/core/polyphase/jsonl-reader.js +161 -0
- package/dist/core/polyphase/jsonl-reader.js.map +1 -0
- package/dist/core/polyphase/keyword.d.ts +27 -0
- package/dist/core/polyphase/keyword.d.ts.map +1 -0
- package/dist/core/polyphase/keyword.js +97 -0
- package/dist/core/polyphase/keyword.js.map +1 -0
- package/dist/core/polyphase/limiter.d.ts +38 -0
- package/dist/core/polyphase/limiter.d.ts.map +1 -0
- package/dist/core/polyphase/limiter.js +129 -0
- package/dist/core/polyphase/limiter.js.map +1 -0
- package/dist/core/polyphase/model-selection.d.ts +35 -0
- package/dist/core/polyphase/model-selection.d.ts.map +1 -0
- package/dist/core/polyphase/model-selection.js +72 -0
- package/dist/core/polyphase/model-selection.js.map +1 -0
- package/dist/core/polyphase/render/format.d.ts +52 -0
- package/dist/core/polyphase/render/format.d.ts.map +1 -0
- package/dist/core/polyphase/render/format.js +169 -0
- package/dist/core/polyphase/render/format.js.map +1 -0
- package/dist/core/polyphase/render/renderers.d.ts +63 -0
- package/dist/core/polyphase/render/renderers.d.ts.map +1 -0
- package/dist/core/polyphase/render/renderers.js +277 -0
- package/dist/core/polyphase/render/renderers.js.map +1 -0
- package/dist/core/polyphase/render/run-block.d.ts +45 -0
- package/dist/core/polyphase/render/run-block.d.ts.map +1 -0
- package/dist/core/polyphase/render/run-block.js +843 -0
- package/dist/core/polyphase/render/run-block.js.map +1 -0
- package/dist/core/polyphase/render/snapshot.d.ts +106 -0
- package/dist/core/polyphase/render/snapshot.d.ts.map +1 -0
- package/dist/core/polyphase/render/snapshot.js +292 -0
- package/dist/core/polyphase/render/snapshot.js.map +1 -0
- package/dist/core/polyphase/result-text.d.ts +41 -0
- package/dist/core/polyphase/result-text.d.ts.map +1 -0
- package/dist/core/polyphase/result-text.js +326 -0
- package/dist/core/polyphase/result-text.js.map +1 -0
- package/dist/core/polyphase/session.d.ts +33 -0
- package/dist/core/polyphase/session.d.ts.map +1 -0
- package/dist/core/polyphase/session.js +106 -0
- package/dist/core/polyphase/session.js.map +1 -0
- package/dist/core/polyphase/settings.d.ts +18 -0
- package/dist/core/polyphase/settings.d.ts.map +1 -0
- package/dist/core/polyphase/settings.js +93 -0
- package/dist/core/polyphase/settings.js.map +1 -0
- package/dist/core/polyphase/store.d.ts +197 -0
- package/dist/core/polyphase/store.d.ts.map +1 -0
- package/dist/core/polyphase/store.js +558 -0
- package/dist/core/polyphase/store.js.map +1 -0
- package/dist/core/polyphase/types.d.ts +371 -0
- package/dist/core/polyphase/types.d.ts.map +1 -0
- package/dist/core/polyphase/types.js +36 -0
- package/dist/core/polyphase/types.js.map +1 -0
- package/dist/core/polyphase/ui/controller.d.ts +28 -0
- package/dist/core/polyphase/ui/controller.d.ts.map +1 -0
- package/dist/core/polyphase/ui/controller.js +150 -0
- package/dist/core/polyphase/ui/controller.js.map +1 -0
- package/dist/core/polyphase/ui/dock.d.ts +27 -0
- package/dist/core/polyphase/ui/dock.d.ts.map +1 -0
- package/dist/core/polyphase/ui/dock.js +121 -0
- package/dist/core/polyphase/ui/dock.js.map +1 -0
- package/dist/core/polyphase/ui/inspector.d.ts +117 -0
- package/dist/core/polyphase/ui/inspector.d.ts.map +1 -0
- package/dist/core/polyphase/ui/inspector.js +1016 -0
- package/dist/core/polyphase/ui/inspector.js.map +1 -0
- package/dist/core/polyphase/ui/transcript-layout.d.ts +55 -0
- package/dist/core/polyphase/ui/transcript-layout.d.ts.map +1 -0
- package/dist/core/polyphase/ui/transcript-layout.js +210 -0
- package/dist/core/polyphase/ui/transcript-layout.js.map +1 -0
- package/dist/core/polyphase/update-pump.d.ts +18 -0
- package/dist/core/polyphase/update-pump.d.ts.map +1 -0
- package/dist/core/polyphase/update-pump.js +132 -0
- package/dist/core/polyphase/update-pump.js.map +1 -0
- package/dist/core/polyphase/workflow/agent-host.d.ts +26 -0
- package/dist/core/polyphase/workflow/agent-host.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/agent-host.js +187 -0
- package/dist/core/polyphase/workflow/agent-host.js.map +1 -0
- package/dist/core/polyphase/workflow/guidance.d.ts +19 -0
- package/dist/core/polyphase/workflow/guidance.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/guidance.js +119 -0
- package/dist/core/polyphase/workflow/guidance.js.map +1 -0
- package/dist/core/polyphase/workflow/launch.d.ts +41 -0
- package/dist/core/polyphase/workflow/launch.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/launch.js +173 -0
- package/dist/core/polyphase/workflow/launch.js.map +1 -0
- package/dist/core/polyphase/workflow/meta.d.ts +43 -0
- package/dist/core/polyphase/workflow/meta.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/meta.js +529 -0
- package/dist/core/polyphase/workflow/meta.js.map +1 -0
- package/dist/core/polyphase/workflow/prelude.d.ts +24 -0
- package/dist/core/polyphase/workflow/prelude.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/prelude.js +93 -0
- package/dist/core/polyphase/workflow/prelude.js.map +1 -0
- package/dist/core/polyphase/workflow/runtime.d.ts +79 -0
- package/dist/core/polyphase/workflow/runtime.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/runtime.js +217 -0
- package/dist/core/polyphase/workflow/runtime.js.map +1 -0
- package/dist/core/polyphase/workflow/runtime.lazy.d.ts +3 -0
- package/dist/core/polyphase/workflow/runtime.lazy.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/runtime.lazy.js +3 -0
- package/dist/core/polyphase/workflow/runtime.lazy.js.map +1 -0
- package/dist/core/polyphase/workflow/saved.d.ts +55 -0
- package/dist/core/polyphase/workflow/saved.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/saved.js +299 -0
- package/dist/core/polyphase/workflow/saved.js.map +1 -0
- package/dist/core/polyphase/workflow/structured-output.d.ts +22 -0
- package/dist/core/polyphase/workflow/structured-output.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/structured-output.js +66 -0
- package/dist/core/polyphase/workflow/structured-output.js.map +1 -0
- package/dist/core/polyphase/workflow/tool.d.ts +24 -0
- package/dist/core/polyphase/workflow/tool.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/tool.js +139 -0
- package/dist/core/polyphase/workflow/tool.js.map +1 -0
- package/dist/core/sdk.d.ts +1 -1
- package/dist/core/sdk.js +1 -1
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/settings-manager.d.ts +27 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/socket-server/permission-relay.js +4 -0
- package/dist/core/socket-server/permission-relay.js.map +1 -1
- package/dist/core/trust-manager.d.ts +3 -2
- package/dist/core/trust-manager.d.ts.map +1 -1
- package/dist/core/trust-manager.js +5 -2
- package/dist/core/trust-manager.js.map +1 -1
- package/dist/experimental/micro/runtime.js +1 -1
- package/dist/experimental/micro/runtime.js.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.d.ts +7 -0
- package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.js +18 -0
- package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +11 -2
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +9 -0
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/prompts/commands/orchestrate.md +1 -1
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +7 -1
- package/dist/utils/shell.js.map +1 -1
- package/docs/docs.json +4 -0
- package/docs/duet.md +3 -3
- package/docs/environment-variables.md +11 -0
- package/docs/json.md +7 -0
- package/docs/keybindings.md +20 -0
- package/docs/polyphase.md +391 -0
- package/docs/rpc-commands.md +9 -9
- package/docs/settings.md +12 -0
- package/docs/virtual-models.md +3 -3
- package/examples/extensions/preset.ts +3 -3
- package/examples/extensions/subagent/README.md +1 -1
- package/examples/extensions/subagent/agents/planner.md +1 -1
- package/examples/extensions/subagent/agents/reviewer.md +1 -1
- package/examples/extensions/subagent/agents/scout.md +1 -1
- package/examples/extensions/subagent/agents/worker.md +1 -1
- package/examples/extensions/summarize.ts +3 -3
- package/examples/sdk/02-custom-model.ts +1 -1
- package/examples/sdk/12-full-control.ts +1 -1
- package/examples/sdk/README.md +1 -1
- package/package.json +10 -10
- package/prompts/commands/orchestrate.md +1 -1
- package/dist/bundle/chunks/chunk-CEJJ5XF2.js +0 -170
- package/dist/bundle/chunks/execute-VCYDHEYA.js +0 -328
- package/dist/bundle/chunks/virtual-modules-JTCGDL2Z.js +0 -2
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Builds the single-line VM prelude injected before a workflow script's body (DESIGN.md §13.2).
|
|
3
|
+
*
|
|
4
|
+
* The prelude must stay one line because the sandbox evaluates `prelude + body` as a single
|
|
5
|
+
* `codemode.js` source, and the first line of `body` shares line 1 of that source with the
|
|
6
|
+
* prelude: any newline here would shift every reported script line and column.
|
|
7
|
+
*/
|
|
8
|
+
export const RESERVED_SCRIPT_NAMES = [
|
|
9
|
+
"agent",
|
|
10
|
+
"parallel",
|
|
11
|
+
"pipeline",
|
|
12
|
+
"phase",
|
|
13
|
+
"log",
|
|
14
|
+
"args",
|
|
15
|
+
"budget",
|
|
16
|
+
"meta",
|
|
17
|
+
];
|
|
18
|
+
/**
|
|
19
|
+
* Shared with runtime.ts's host-side guard on `agent()`'s `phase` field: both import this one
|
|
20
|
+
* constant, so there is nothing to keep in sync. Checking it here too (a deviation from
|
|
21
|
+
* DESIGN.md §13.2's verbatim `phase` statement) makes an overlong `phase(title)` throw at its own
|
|
22
|
+
* call site instead of silently poisoning every later `agent()` call with no reported source line.
|
|
23
|
+
*/
|
|
24
|
+
export const PHASE_MAX_CHARS = 80;
|
|
25
|
+
/**
|
|
26
|
+
* `JSON.stringify(Infinity)` and `JSON.stringify(NaN)` are both `"null"`, which would embed as
|
|
27
|
+
* `const __polyphaseMax = null;`; `thunks.length > null` is then true for any non-empty array, so
|
|
28
|
+
* every `parallel()`/`pipeline()` call would throw regardless of its actual size. A value below 1
|
|
29
|
+
* would make the cap tighter than any real call. Clamping here, at the embedding boundary, keeps
|
|
30
|
+
* `statements()` free of this defensive check.
|
|
31
|
+
*/
|
|
32
|
+
function normalizeMaxItemsPerCall(value) {
|
|
33
|
+
return Number.isFinite(value) ? Math.max(1, Math.floor(value)) : Number.MAX_SAFE_INTEGER;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* `JSON.stringify` never emits a raw newline, but it does emit `//` verbatim for any embedded
|
|
37
|
+
* string containing it (a URL, for instance), which would trip `buildWorkflowPrelude`'s
|
|
38
|
+
* single-line/no-comment assertion below. `\/` is a valid JS string escape, so swapping it in
|
|
39
|
+
* keeps the JSON valid while making `//` impossible to reconstruct from embedded data. U+2028 and
|
|
40
|
+
* U+2029 are valid unescaped in JS string literals but are line terminators for ASI purposes;
|
|
41
|
+
* escaping them keeps the prelude's line-counting invariant exact for any input.
|
|
42
|
+
*/
|
|
43
|
+
const LINE_SEPARATOR = String.fromCharCode(0x2028);
|
|
44
|
+
const PARAGRAPH_SEPARATOR = String.fromCharCode(0x2029);
|
|
45
|
+
function embed(value) {
|
|
46
|
+
return JSON.stringify(value)
|
|
47
|
+
.replace(/\//g, "\\/")
|
|
48
|
+
.split(LINE_SEPARATOR)
|
|
49
|
+
.join("\\u2028")
|
|
50
|
+
.split(PARAGRAPH_SEPARATOR)
|
|
51
|
+
.join("\\u2029");
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Beyond DESIGN.md §13.2's verbatim statement list, this also bans `performance.now` (the same
|
|
55
|
+
* determinism rationale as `Date.now`/`Math.random`, otherwise an uncovered escape hatch), pins
|
|
56
|
+
* `Date.prototype.constructor` to the banning proxy (so `x.constructor()` can't bypass the ban the
|
|
57
|
+
* way the determinism test exercises), and has `agent()` capture the call site with `new Error()`
|
|
58
|
+
* before awaiting, rewriting a `{ok:false}` reply's stack onto it so a thrown agent failure reports
|
|
59
|
+
* its script line instead of only the prelude's. Each is intentional; none is in §13.2.
|
|
60
|
+
*/
|
|
61
|
+
function statements(input) {
|
|
62
|
+
return [
|
|
63
|
+
`const meta = Object.freeze(${embed(input.meta)});`,
|
|
64
|
+
`const args = ${embed(input.args)};`,
|
|
65
|
+
"let __polyphasePhase = undefined; let __polyphaseSpent = 0;",
|
|
66
|
+
`const __polyphaseMax = ${embed(normalizeMaxItemsPerCall(input.maxItemsPerCall))}; const __polyphaseTotal = ${embed(input.budgetTokens)};`,
|
|
67
|
+
"const budget = Object.freeze({ total: __polyphaseTotal, spent: () => __polyphaseSpent, remaining: () => __polyphaseTotal === null ? Infinity : Math.max(0, __polyphaseTotal - __polyphaseSpent) });",
|
|
68
|
+
'const __polyphaseBan = (n) => () => { throw new Error(n + " is not available in workflow scripts: runs must be deterministic"); };',
|
|
69
|
+
'Object.defineProperty(Math, "random", { value: __polyphaseBan("Math.random"), writable: false, configurable: false });',
|
|
70
|
+
'if (typeof performance === "object" && performance !== null) { const __polyphaseDescs = Object.getOwnPropertyDescriptors(performance); __polyphaseDescs.now = { value: __polyphaseBan("performance.now"), writable: false, enumerable: true, configurable: false }; globalThis.performance = Object.create(Object.getPrototypeOf(performance), __polyphaseDescs); }',
|
|
71
|
+
"const __polyphaseDate = Date;",
|
|
72
|
+
'Object.defineProperty(__polyphaseDate, "now", { value: __polyphaseBan("Date.now"), writable: false, configurable: false });',
|
|
73
|
+
'const __polyphaseDateProxy = new Proxy(__polyphaseDate, { apply() { return __polyphaseBan("Date()")(); }, construct(t, a, nt) { if (a.length === 0) return __polyphaseBan("new Date()")(); return Reflect.construct(t, a, nt); } });',
|
|
74
|
+
'Object.defineProperty(__polyphaseDate.prototype, "constructor", { value: __polyphaseDateProxy, writable: false, configurable: false });',
|
|
75
|
+
"globalThis.Date = __polyphaseDateProxy;",
|
|
76
|
+
'const __polyphaseText = (p) => typeof p === "string" ? p : (() => { try { return JSON.stringify(p); } catch { return String(p); } })();',
|
|
77
|
+
'const log = (...parts) => { __polyphase.log(parts.map(__polyphaseText).join(" "), "info").catch(() => undefined); };',
|
|
78
|
+
'const __polyphaseWarn = (text) => { __polyphase.log(text, "warning").catch(() => undefined); };',
|
|
79
|
+
`const phase = (title) => { if (typeof title !== "string" || title.trim() === "" || title.length > ${PHASE_MAX_CHARS}) throw new TypeError("phase(title) needs a non-empty string of at most ${PHASE_MAX_CHARS} characters"); __polyphasePhase = title; __polyphase.phase(title).catch(() => undefined); };`,
|
|
80
|
+
'const agent = async (prompt, opts) => { if (typeof prompt !== "string" || prompt.length === 0) throw new TypeError("agent(prompt, opts) needs a non-empty prompt string"); if (opts !== undefined && (opts === null || typeof opts !== "object" || Array.isArray(opts))) throw new TypeError("agent(prompt, opts): opts must be an object"); const o = opts === undefined ? {} : opts; const __polyphaseSite = new Error(); const reply = await __polyphase.agent({ prompt, label: o.label, phase: o.phase !== undefined ? o.phase : __polyphasePhase, schema: o.schema, model: o.model, effort: o.effort, isolation: o.isolation, agentType: o.agentType }); __polyphaseSpent = reply.spent; if (!reply.ok) { const __polyphaseErr = new Error(reply.error); const __polyphaseStack = __polyphaseSite.stack; if (typeof __polyphaseStack === "string") { const __polyphaseNL = __polyphaseStack.indexOf("\\n"); __polyphaseErr.stack = "Error: " + reply.error + (__polyphaseNL === -1 ? "" : __polyphaseStack.slice(__polyphaseNL)); } throw __polyphaseErr; } return reply.value; };',
|
|
81
|
+
'const __polyphaseMessage = (e) => e && typeof e.message === "string" ? e.message : String(e);',
|
|
82
|
+
'const parallel = async (thunks) => { if (!Array.isArray(thunks)) throw new TypeError("parallel(thunks) needs an array of functions, e.g. items.map((x) => () => agent(...))"); if (thunks.length > __polyphaseMax) throw new RangeError("parallel() accepts at most " + __polyphaseMax + " items"); for (const t of thunks) if (typeof t !== "function") throw new TypeError("parallel(thunks): every item must be a function"); return Promise.all(thunks.map(async (t, i) => { try { return await t(); } catch (e) { __polyphaseWarn("parallel item " + i + " failed: " + __polyphaseMessage(e)); return null; } })); };',
|
|
83
|
+
'const pipeline = async (items, ...stages) => { if (!Array.isArray(items)) throw new TypeError("pipeline(items, ...stages) needs an array of items"); if (items.length > __polyphaseMax) throw new RangeError("pipeline() accepts at most " + __polyphaseMax + " items"); if (stages.length === 0 || stages.some((s) => typeof s !== "function")) throw new TypeError("pipeline(items, ...stages): stages must be functions (prev, item, index) => ..."); return Promise.all(items.map(async (item, index) => { let prev = item; for (let s = 0; s < stages.length; s++) { try { prev = await stages[s](prev, item, index); } catch (e) { __polyphaseWarn("pipeline item " + index + " failed in stage " + (s + 1) + ": " + __polyphaseMessage(e)); return null; } } return prev; })); };',
|
|
84
|
+
];
|
|
85
|
+
}
|
|
86
|
+
export function buildWorkflowPrelude(input) {
|
|
87
|
+
const prelude = statements(input).join(" ");
|
|
88
|
+
if (prelude.includes("\n") || prelude.includes("//")) {
|
|
89
|
+
throw new Error("buildWorkflowPrelude produced a multi-line prelude or a line comment; this is a bug");
|
|
90
|
+
}
|
|
91
|
+
return prelude;
|
|
92
|
+
}
|
|
93
|
+
//# sourceMappingURL=prelude.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prelude.js","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/prelude.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAIH,MAAM,CAAC,MAAM,qBAAqB,GAAsB;IACvD,OAAO;IACP,UAAU;IACV,UAAU;IACV,OAAO;IACP,KAAK;IACL,MAAM;IACN,QAAQ;IACR,MAAM;CACN,CAAC;AAEF;;;;;GAKG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,CAAC;AASlC;;;;;;GAMG;AACH,SAAS,wBAAwB,CAAC,KAAa;IAC9C,OAAO,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,gBAAgB,CAAC;AAC1F,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,cAAc,GAAG,MAAM,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC;AACnD,MAAM,mBAAmB,GAAG,MAAM,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC;AAExD,SAAS,KAAK,CAAC,KAAc;IAC5B,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC;SAC1B,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,KAAK,CAAC,cAAc,CAAC;SACrB,IAAI,CAAC,SAAS,CAAC;SACf,KAAK,CAAC,mBAAmB,CAAC;SAC1B,IAAI,CAAC,SAAS,CAAC,CAAC;AACnB,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,UAAU,CAAC,KAAmB;IACtC,OAAO;QACN,8BAA8B,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI;QACnD,gBAAgB,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG;QACpC,6DAA6D;QAC7D,0BAA0B,KAAK,CAAC,wBAAwB,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC,8BAA8B,KAAK,CAAC,KAAK,CAAC,YAAY,CAAC,GAAG;QAC1I,qMAAqM;QACrM,oIAAoI;QACpI,wHAAwH;QACxH,qWAAqW;QACrW,+BAA+B;QAC/B,6HAA6H;QAC7H,sOAAsO;QACtO,yIAAyI;QACzI,yCAAyC;QACzC,yIAAyI;QACzI,sHAAsH;QACtH,iGAAiG;QACjG,qGAAqG,eAAe,2EAA2E,eAAe,8FAA8F;QAC5S,yhCAAyhC;QACzhC,+FAA+F;QAC/F,4lBAA4lB;QAC5lB,0vBAA0vB;KAC1vB,CAAC;AACH,CAAC;AAED,MAAM,UAAU,oBAAoB,CAAC,KAAmB;IACvD,MAAM,OAAO,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC5C,IAAI,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;QACtD,MAAM,IAAI,KAAK,CAAC,qFAAqF,CAAC,CAAC;IACxG,CAAC;IACD,OAAO,OAAO,CAAC;AAChB,CAAC","sourcesContent":["/**\n * Builds the single-line VM prelude injected before a workflow script's body (DESIGN.md §13.2).\n *\n * The prelude must stay one line because the sandbox evaluates `prelude + body` as a single\n * `codemode.js` source, and the first line of `body` shares line 1 of that source with the\n * prelude: any newline here would shift every reported script line and column.\n */\n\nimport type { WorkflowMeta } from \"./meta.ts\";\n\nexport const RESERVED_SCRIPT_NAMES: readonly string[] = [\n\t\"agent\",\n\t\"parallel\",\n\t\"pipeline\",\n\t\"phase\",\n\t\"log\",\n\t\"args\",\n\t\"budget\",\n\t\"meta\",\n];\n\n/**\n * Shared with runtime.ts's host-side guard on `agent()`'s `phase` field: both import this one\n * constant, so there is nothing to keep in sync. Checking it here too (a deviation from\n * DESIGN.md §13.2's verbatim `phase` statement) makes an overlong `phase(title)` throw at its own\n * call site instead of silently poisoning every later `agent()` call with no reported source line.\n */\nexport const PHASE_MAX_CHARS = 80;\n\nexport interface PreludeInput {\n\tmeta: WorkflowMeta;\n\targs: string;\n\tbudgetTokens: number | null;\n\tmaxItemsPerCall: number;\n}\n\n/**\n * `JSON.stringify(Infinity)` and `JSON.stringify(NaN)` are both `\"null\"`, which would embed as\n * `const __polyphaseMax = null;`; `thunks.length > null` is then true for any non-empty array, so\n * every `parallel()`/`pipeline()` call would throw regardless of its actual size. A value below 1\n * would make the cap tighter than any real call. Clamping here, at the embedding boundary, keeps\n * `statements()` free of this defensive check.\n */\nfunction normalizeMaxItemsPerCall(value: number): number {\n\treturn Number.isFinite(value) ? Math.max(1, Math.floor(value)) : Number.MAX_SAFE_INTEGER;\n}\n\n/**\n * `JSON.stringify` never emits a raw newline, but it does emit `//` verbatim for any embedded\n * string containing it (a URL, for instance), which would trip `buildWorkflowPrelude`'s\n * single-line/no-comment assertion below. `\\/` is a valid JS string escape, so swapping it in\n * keeps the JSON valid while making `//` impossible to reconstruct from embedded data. U+2028 and\n * U+2029 are valid unescaped in JS string literals but are line terminators for ASI purposes;\n * escaping them keeps the prelude's line-counting invariant exact for any input.\n */\nconst LINE_SEPARATOR = String.fromCharCode(0x2028);\nconst PARAGRAPH_SEPARATOR = String.fromCharCode(0x2029);\n\nfunction embed(value: unknown): string {\n\treturn JSON.stringify(value)\n\t\t.replace(/\\//g, \"\\\\/\")\n\t\t.split(LINE_SEPARATOR)\n\t\t.join(\"\\\\u2028\")\n\t\t.split(PARAGRAPH_SEPARATOR)\n\t\t.join(\"\\\\u2029\");\n}\n\n/**\n * Beyond DESIGN.md §13.2's verbatim statement list, this also bans `performance.now` (the same\n * determinism rationale as `Date.now`/`Math.random`, otherwise an uncovered escape hatch), pins\n * `Date.prototype.constructor` to the banning proxy (so `x.constructor()` can't bypass the ban the\n * way the determinism test exercises), and has `agent()` capture the call site with `new Error()`\n * before awaiting, rewriting a `{ok:false}` reply's stack onto it so a thrown agent failure reports\n * its script line instead of only the prelude's. Each is intentional; none is in §13.2.\n */\nfunction statements(input: PreludeInput): string[] {\n\treturn [\n\t\t`const meta = Object.freeze(${embed(input.meta)});`,\n\t\t`const args = ${embed(input.args)};`,\n\t\t\"let __polyphasePhase = undefined; let __polyphaseSpent = 0;\",\n\t\t`const __polyphaseMax = ${embed(normalizeMaxItemsPerCall(input.maxItemsPerCall))}; const __polyphaseTotal = ${embed(input.budgetTokens)};`,\n\t\t\"const budget = Object.freeze({ total: __polyphaseTotal, spent: () => __polyphaseSpent, remaining: () => __polyphaseTotal === null ? Infinity : Math.max(0, __polyphaseTotal - __polyphaseSpent) });\",\n\t\t'const __polyphaseBan = (n) => () => { throw new Error(n + \" is not available in workflow scripts: runs must be deterministic\"); };',\n\t\t'Object.defineProperty(Math, \"random\", { value: __polyphaseBan(\"Math.random\"), writable: false, configurable: false });',\n\t\t'if (typeof performance === \"object\" && performance !== null) { const __polyphaseDescs = Object.getOwnPropertyDescriptors(performance); __polyphaseDescs.now = { value: __polyphaseBan(\"performance.now\"), writable: false, enumerable: true, configurable: false }; globalThis.performance = Object.create(Object.getPrototypeOf(performance), __polyphaseDescs); }',\n\t\t\"const __polyphaseDate = Date;\",\n\t\t'Object.defineProperty(__polyphaseDate, \"now\", { value: __polyphaseBan(\"Date.now\"), writable: false, configurable: false });',\n\t\t'const __polyphaseDateProxy = new Proxy(__polyphaseDate, { apply() { return __polyphaseBan(\"Date()\")(); }, construct(t, a, nt) { if (a.length === 0) return __polyphaseBan(\"new Date()\")(); return Reflect.construct(t, a, nt); } });',\n\t\t'Object.defineProperty(__polyphaseDate.prototype, \"constructor\", { value: __polyphaseDateProxy, writable: false, configurable: false });',\n\t\t\"globalThis.Date = __polyphaseDateProxy;\",\n\t\t'const __polyphaseText = (p) => typeof p === \"string\" ? p : (() => { try { return JSON.stringify(p); } catch { return String(p); } })();',\n\t\t'const log = (...parts) => { __polyphase.log(parts.map(__polyphaseText).join(\" \"), \"info\").catch(() => undefined); };',\n\t\t'const __polyphaseWarn = (text) => { __polyphase.log(text, \"warning\").catch(() => undefined); };',\n\t\t`const phase = (title) => { if (typeof title !== \"string\" || title.trim() === \"\" || title.length > ${PHASE_MAX_CHARS}) throw new TypeError(\"phase(title) needs a non-empty string of at most ${PHASE_MAX_CHARS} characters\"); __polyphasePhase = title; __polyphase.phase(title).catch(() => undefined); };`,\n\t\t'const agent = async (prompt, opts) => { if (typeof prompt !== \"string\" || prompt.length === 0) throw new TypeError(\"agent(prompt, opts) needs a non-empty prompt string\"); if (opts !== undefined && (opts === null || typeof opts !== \"object\" || Array.isArray(opts))) throw new TypeError(\"agent(prompt, opts): opts must be an object\"); const o = opts === undefined ? {} : opts; const __polyphaseSite = new Error(); const reply = await __polyphase.agent({ prompt, label: o.label, phase: o.phase !== undefined ? o.phase : __polyphasePhase, schema: o.schema, model: o.model, effort: o.effort, isolation: o.isolation, agentType: o.agentType }); __polyphaseSpent = reply.spent; if (!reply.ok) { const __polyphaseErr = new Error(reply.error); const __polyphaseStack = __polyphaseSite.stack; if (typeof __polyphaseStack === \"string\") { const __polyphaseNL = __polyphaseStack.indexOf(\"\\\\n\"); __polyphaseErr.stack = \"Error: \" + reply.error + (__polyphaseNL === -1 ? \"\" : __polyphaseStack.slice(__polyphaseNL)); } throw __polyphaseErr; } return reply.value; };',\n\t\t'const __polyphaseMessage = (e) => e && typeof e.message === \"string\" ? e.message : String(e);',\n\t\t'const parallel = async (thunks) => { if (!Array.isArray(thunks)) throw new TypeError(\"parallel(thunks) needs an array of functions, e.g. items.map((x) => () => agent(...))\"); if (thunks.length > __polyphaseMax) throw new RangeError(\"parallel() accepts at most \" + __polyphaseMax + \" items\"); for (const t of thunks) if (typeof t !== \"function\") throw new TypeError(\"parallel(thunks): every item must be a function\"); return Promise.all(thunks.map(async (t, i) => { try { return await t(); } catch (e) { __polyphaseWarn(\"parallel item \" + i + \" failed: \" + __polyphaseMessage(e)); return null; } })); };',\n\t\t'const pipeline = async (items, ...stages) => { if (!Array.isArray(items)) throw new TypeError(\"pipeline(items, ...stages) needs an array of items\"); if (items.length > __polyphaseMax) throw new RangeError(\"pipeline() accepts at most \" + __polyphaseMax + \" items\"); if (stages.length === 0 || stages.some((s) => typeof s !== \"function\")) throw new TypeError(\"pipeline(items, ...stages): stages must be functions (prev, item, index) => ...\"); return Promise.all(items.map(async (item, index) => { let prev = item; for (let s = 0; s < stages.length; s++) { try { prev = await stages[s](prev, item, index); } catch (e) { __polyphaseWarn(\"pipeline item \" + index + \" failed in stage \" + (s + 1) + \": \" + __polyphaseMessage(e)); return null; } } return prev; })); };',\n\t];\n}\n\nexport function buildWorkflowPrelude(input: PreludeInput): string {\n\tconst prelude = statements(input).join(\" \");\n\tif (prelude.includes(\"\\n\") || prelude.includes(\"//\")) {\n\t\tthrow new Error(\"buildWorkflowPrelude produced a multi-line prelude or a line comment; this is a bug\");\n\t}\n\treturn prelude;\n}\n"]}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runs a workflow script's prelude plus body in a `CodemodeSandbox` (DESIGN.md §13.4).
|
|
3
|
+
*
|
|
4
|
+
* The sandbox evaluates `(async (tools, console) => {<prelude><body>\n})` as `codemode.js`
|
|
5
|
+
* (packages/codemode/src/runtime/worker.ts). Since the prelude is one line, a script error on
|
|
6
|
+
* body line 1 is reported at `codemode.js:1:C` with `C` past the wrapper prefix and the prelude;
|
|
7
|
+
* errors on later body lines report their real line number unchanged.
|
|
8
|
+
*/
|
|
9
|
+
import type { JsonObject, JsonValue } from "@draht/ai";
|
|
10
|
+
import { type CodemodeErrorKind, type CodemodeWasmModule } from "@draht/codemode";
|
|
11
|
+
import type { WorkflowMeta } from "./meta.ts";
|
|
12
|
+
export interface WorkflowAgentRequest {
|
|
13
|
+
prompt: string;
|
|
14
|
+
label?: string;
|
|
15
|
+
phase?: string;
|
|
16
|
+
schema?: JsonObject;
|
|
17
|
+
model?: string;
|
|
18
|
+
effort?: string;
|
|
19
|
+
isolation?: "worktree";
|
|
20
|
+
agentType?: string;
|
|
21
|
+
}
|
|
22
|
+
export type WorkflowAgentReply = {
|
|
23
|
+
kind: "value";
|
|
24
|
+
value: JsonValue;
|
|
25
|
+
} | {
|
|
26
|
+
kind: "null";
|
|
27
|
+
reason: "failed" | "cancelled" | "budget" | "no-structured-output";
|
|
28
|
+
message?: string;
|
|
29
|
+
} | {
|
|
30
|
+
kind: "error";
|
|
31
|
+
message: string;
|
|
32
|
+
};
|
|
33
|
+
export interface WorkflowHost {
|
|
34
|
+
runAgent(request: WorkflowAgentRequest, signal: AbortSignal): Promise<WorkflowAgentReply>;
|
|
35
|
+
onPhase(title: string): number;
|
|
36
|
+
onLog(text: string, level: "info" | "warning"): void;
|
|
37
|
+
spentTokens(): number;
|
|
38
|
+
}
|
|
39
|
+
export interface WorkflowRunSpec {
|
|
40
|
+
meta: WorkflowMeta;
|
|
41
|
+
body: string;
|
|
42
|
+
args: string;
|
|
43
|
+
budgetTokens: number | null;
|
|
44
|
+
maxAgents: number;
|
|
45
|
+
maxItemsPerCall: number;
|
|
46
|
+
/** 0 or `Infinity` disables the deadline. */
|
|
47
|
+
timeoutMs: number;
|
|
48
|
+
/** Default 256 MiB. */
|
|
49
|
+
memoryLimitBytes?: number;
|
|
50
|
+
/** Default 1,000,000 (the result text keeps only the first/last 8000 console characters anyway). */
|
|
51
|
+
maxOutputChars?: number;
|
|
52
|
+
signal: AbortSignal;
|
|
53
|
+
host: WorkflowHost;
|
|
54
|
+
sandbox?: {
|
|
55
|
+
wasm?: CodemodeWasmModule | Promise<CodemodeWasmModule>;
|
|
56
|
+
workerUrl?: string | URL;
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
export interface WorkflowScriptError {
|
|
60
|
+
kind: CodemodeErrorKind;
|
|
61
|
+
message: string;
|
|
62
|
+
line?: number;
|
|
63
|
+
column?: number;
|
|
64
|
+
stack?: string;
|
|
65
|
+
hint?: string;
|
|
66
|
+
}
|
|
67
|
+
export type WorkflowOutcome = {
|
|
68
|
+
ok: true;
|
|
69
|
+
value: JsonValue | undefined;
|
|
70
|
+
consoleOutput: string[];
|
|
71
|
+
agentCalls: number;
|
|
72
|
+
} | {
|
|
73
|
+
ok: false;
|
|
74
|
+
error: WorkflowScriptError;
|
|
75
|
+
consoleOutput: string[];
|
|
76
|
+
agentCalls: number;
|
|
77
|
+
};
|
|
78
|
+
export declare function runWorkflowScript(spec: WorkflowRunSpec): Promise<WorkflowOutcome>;
|
|
79
|
+
//# sourceMappingURL=runtime.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/runtime.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACvD,OAAO,EAEN,KAAK,iBAAiB,EAItB,KAAK,kBAAkB,EAEvB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAG9C,MAAM,WAAW,oBAAoB;IACpC,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,UAAU,CAAC;IACpB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,UAAU,CAAC;IACvB,SAAS,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,MAAM,kBAAkB,GAC3B;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,KAAK,EAAE,SAAS,CAAA;CAAE,GACnC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,QAAQ,GAAG,WAAW,GAAG,QAAQ,GAAG,sBAAsB,CAAC;IAAC,OAAO,CAAC,EAAE,M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,MAAM,MAAM,eAAe,GACxB;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,KAAK,EAAE,SAAS,GAAG,SAAS,CAAC;IAAC,aAAa,EAAE,MAAM,EAAE,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,GACvF;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,KAAK,EAAE,mBAAmB,CAAC;IAAC,aAAa,EAAE,MAAM,EAAE,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,CAAC;AA2I1F,wBAAsB,iBAAiB,CAAC,IAAI,EAAE,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC,CAoFvF"}
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runs a workflow script's prelude plus body in a `CodemodeSandbox` (DESIGN.md §13.4).
|
|
3
|
+
*
|
|
4
|
+
* The sandbox evaluates `(async (tools, console) => {<prelude><body>\n})` as `codemode.js`
|
|
5
|
+
* (packages/codemode/src/runtime/worker.ts). Since the prelude is one line, a script error on
|
|
6
|
+
* body line 1 is reported at `codemode.js:1:C` with `C` past the wrapper prefix and the prelude;
|
|
7
|
+
* errors on later body lines report their real line number unchanged.
|
|
8
|
+
*/
|
|
9
|
+
import { CodemodeSandbox, loadQuickJSWasm, } from "@draht/codemode";
|
|
10
|
+
import { getCodemodeWorkerSpecifier, getQuickJSWasmPath } from "../../../config.js";
|
|
11
|
+
import { buildWorkflowPrelude, PHASE_MAX_CHARS } from "./prelude.js";
|
|
12
|
+
const DEFAULT_MEMORY_LIMIT_BYTES = 256 * 1024 * 1024;
|
|
13
|
+
/**
|
|
14
|
+
* `memoryLimitBytes` only bounds the QuickJS heap; nothing else stops a script from calling
|
|
15
|
+
* `console.log`/`text()`/`image()` in a loop and growing the host process's memory without bound
|
|
16
|
+
* (every output item is kept in `CodemodeResult.output` for the life of the run). The result text
|
|
17
|
+
* keeps only the first/last 8000 console characters (`result-text.ts`), so this cap is generous
|
|
18
|
+
* relative to what ever reaches the user.
|
|
19
|
+
*/
|
|
20
|
+
const DEFAULT_MAX_OUTPUT_CHARS = 1_000_000;
|
|
21
|
+
/** Prefix the worker wraps the full source in; see worker.ts:146. */
|
|
22
|
+
const WRAPPER_PREFIX_LENGTH = "(async (tools, console) => {".length;
|
|
23
|
+
/**
|
|
24
|
+
* Anchored to frame lines (` at ... (codemode.js:L:C)`, see sandbox.test.ts) rather than
|
|
25
|
+
* matching anywhere in the stack: the stack's first line is `Name: message`, and a script or
|
|
26
|
+
* agent-reply error message can itself contain text that looks like `codemode.js:L:C` (a host
|
|
27
|
+
* error string, or a user-thrown message), which would otherwise be mistaken for the real frame.
|
|
28
|
+
*/
|
|
29
|
+
const FRAME_PATTERN = /^[ \t]*at .*codemode\.js:(\d+):(\d+)/gm;
|
|
30
|
+
const REDECLARATION_PATTERN = /redefinition|redeclar|already been declared/i;
|
|
31
|
+
const REDECLARATION_HINT = "do not redeclare agent, parallel, pipeline, phase, log, args, budget or meta";
|
|
32
|
+
const PROMPT_MAX_CHARS = 200_000;
|
|
33
|
+
const LABEL_MAX_CHARS = 80;
|
|
34
|
+
const SCHEMA_MAX_JSON_CHARS = 65_536;
|
|
35
|
+
const MODEL_MAX_CHARS = 160;
|
|
36
|
+
const AGENT_TYPE_PATTERN = /^[\w.-]{1,64}$/;
|
|
37
|
+
function guardAgentRequest(raw) {
|
|
38
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
39
|
+
return { ok: false, error: "agent() request must be an object" };
|
|
40
|
+
}
|
|
41
|
+
const request = raw;
|
|
42
|
+
const prompt = request.prompt;
|
|
43
|
+
if (typeof prompt !== "string" || prompt.length < 1 || prompt.length > PROMPT_MAX_CHARS) {
|
|
44
|
+
return { ok: false, error: `agent(): prompt must be a string of 1 to ${PROMPT_MAX_CHARS} characters` };
|
|
45
|
+
}
|
|
46
|
+
const label = request.label;
|
|
47
|
+
if (label !== undefined && (typeof label !== "string" || label.length > LABEL_MAX_CHARS)) {
|
|
48
|
+
return { ok: false, error: `agent(): label must be a string of at most ${LABEL_MAX_CHARS} characters` };
|
|
49
|
+
}
|
|
50
|
+
const phase = request.phase;
|
|
51
|
+
if (phase !== undefined && (typeof phase !== "string" || phase.length > PHASE_MAX_CHARS)) {
|
|
52
|
+
return { ok: false, error: `agent(): phase must be a string of at most ${PHASE_MAX_CHARS} characters` };
|
|
53
|
+
}
|
|
54
|
+
const schema = request.schema;
|
|
55
|
+
if (schema !== undefined) {
|
|
56
|
+
if (typeof schema !== "object" || schema === null || Array.isArray(schema)) {
|
|
57
|
+
return { ok: false, error: "agent(): schema must be an object" };
|
|
58
|
+
}
|
|
59
|
+
let json;
|
|
60
|
+
try {
|
|
61
|
+
json = JSON.stringify(schema);
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return { ok: false, error: "agent(): schema must be JSON-serializable" };
|
|
65
|
+
}
|
|
66
|
+
if (json.length > SCHEMA_MAX_JSON_CHARS) {
|
|
67
|
+
return { ok: false, error: `agent(): schema must be at most ${SCHEMA_MAX_JSON_CHARS} JSON characters` };
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
const model = request.model;
|
|
71
|
+
if (model !== undefined && (typeof model !== "string" || model.length > MODEL_MAX_CHARS)) {
|
|
72
|
+
return { ok: false, error: `agent(): model must be a string of at most ${MODEL_MAX_CHARS} characters` };
|
|
73
|
+
}
|
|
74
|
+
const effort = request.effort;
|
|
75
|
+
if (effort !== undefined && typeof effort !== "string") {
|
|
76
|
+
return { ok: false, error: "agent(): effort must be a string" };
|
|
77
|
+
}
|
|
78
|
+
const isolation = request.isolation;
|
|
79
|
+
if (isolation !== undefined && isolation !== "worktree") {
|
|
80
|
+
return { ok: false, error: 'agent(): isolation must be "worktree"' };
|
|
81
|
+
}
|
|
82
|
+
const agentType = request.agentType;
|
|
83
|
+
if (agentType !== undefined && (typeof agentType !== "string" || !AGENT_TYPE_PATTERN.test(agentType))) {
|
|
84
|
+
return { ok: false, error: "agent(): agentType must match /^[\\w.-]{1,64}$/" };
|
|
85
|
+
}
|
|
86
|
+
return {
|
|
87
|
+
ok: true,
|
|
88
|
+
value: {
|
|
89
|
+
prompt,
|
|
90
|
+
label: label,
|
|
91
|
+
phase: phase,
|
|
92
|
+
schema: schema,
|
|
93
|
+
model: model,
|
|
94
|
+
effort: effort,
|
|
95
|
+
isolation: isolation,
|
|
96
|
+
agentType: agentType,
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
function mapAgentReply(reply, spent) {
|
|
101
|
+
if (reply.kind === "value")
|
|
102
|
+
return { ok: true, value: reply.value, spent };
|
|
103
|
+
if (reply.kind === "null")
|
|
104
|
+
return { ok: true, value: null, spent };
|
|
105
|
+
return { ok: false, error: reply.message ?? "agent failed", spent };
|
|
106
|
+
}
|
|
107
|
+
function extractLocation(stack, preludeLength) {
|
|
108
|
+
if (!stack)
|
|
109
|
+
return {};
|
|
110
|
+
const threshold = WRAPPER_PREFIX_LENGTH + preludeLength;
|
|
111
|
+
for (const match of stack.matchAll(FRAME_PATTERN)) {
|
|
112
|
+
const line = Number(match[1]);
|
|
113
|
+
const column = Number(match[2]);
|
|
114
|
+
if (line > 1 || column > threshold)
|
|
115
|
+
return { line, column: line === 1 ? column - threshold : column };
|
|
116
|
+
}
|
|
117
|
+
return {};
|
|
118
|
+
}
|
|
119
|
+
function toScriptError(error, preludeLength) {
|
|
120
|
+
if (error.kind !== "script") {
|
|
121
|
+
return { kind: error.kind, message: error.message, stack: error.stack };
|
|
122
|
+
}
|
|
123
|
+
const { line, column } = extractLocation(error.stack, preludeLength);
|
|
124
|
+
const hint = error.name === "SyntaxError" && REDECLARATION_PATTERN.test(error.message) ? REDECLARATION_HINT : undefined;
|
|
125
|
+
return { kind: "script", message: error.message, line, column, stack: error.stack, hint };
|
|
126
|
+
}
|
|
127
|
+
function toOutcome(result, preludeLength, agentCalls) {
|
|
128
|
+
const consoleOutput = result.output.filter((item) => item.type === "text").map((item) => item.text);
|
|
129
|
+
if (result.ok) {
|
|
130
|
+
return { ok: true, value: result.value, consoleOutput, agentCalls };
|
|
131
|
+
}
|
|
132
|
+
return { ok: false, error: toScriptError(result.error, preludeLength), consoleOutput, agentCalls };
|
|
133
|
+
}
|
|
134
|
+
export async function runWorkflowScript(spec) {
|
|
135
|
+
const prelude = buildWorkflowPrelude({
|
|
136
|
+
meta: spec.meta,
|
|
137
|
+
args: spec.args,
|
|
138
|
+
budgetTokens: spec.budgetTokens,
|
|
139
|
+
maxItemsPerCall: spec.maxItemsPerCall,
|
|
140
|
+
});
|
|
141
|
+
// A non-finite maxAgents (NaN from a malformed setting, Infinity) must not silently disable the
|
|
142
|
+
// cap for the wrong reason: `agentCalls >= NaN` is always false, same effect as "no cap" but by
|
|
143
|
+
// accident rather than by a documented "unlimited" value.
|
|
144
|
+
const maxAgents = Number.isFinite(spec.maxAgents)
|
|
145
|
+
? Math.max(0, Math.floor(spec.maxAgents))
|
|
146
|
+
: Number.MAX_SAFE_INTEGER;
|
|
147
|
+
// `agentCalls` counts agents actually dispatched to the host (DESIGN.md §13.4 "count accepted
|
|
148
|
+
// requests"); a request rejected by the cap never reaches `host.runAgent` and is not counted.
|
|
149
|
+
let agentCalls = 0;
|
|
150
|
+
const agentGlobal = {
|
|
151
|
+
name: "__polyphase.agent",
|
|
152
|
+
execute: async (rawArgs, { signal }) => {
|
|
153
|
+
const guarded = guardAgentRequest(rawArgs);
|
|
154
|
+
if (!guarded.ok) {
|
|
155
|
+
return { ok: false, error: guarded.error, spent: spec.host.spentTokens() };
|
|
156
|
+
}
|
|
157
|
+
if (agentCalls >= maxAgents) {
|
|
158
|
+
return {
|
|
159
|
+
ok: false,
|
|
160
|
+
error: `agent cap reached: a workflow may start at most ${maxAgents} agents (polyphase.maxAgentsPerRun)`,
|
|
161
|
+
spent: spec.host.spentTokens(),
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
agentCalls++;
|
|
165
|
+
let reply;
|
|
166
|
+
try {
|
|
167
|
+
reply = await spec.host.runAgent(guarded.value, signal);
|
|
168
|
+
}
|
|
169
|
+
catch (error) {
|
|
170
|
+
// A rejection must still flow through the normal `{ok:false}` reply path below, or
|
|
171
|
+
// the prelude's `agent()` never runs its call-site stack rewrite (its `if (!reply.ok)`
|
|
172
|
+
// branch is skipped entirely when `await __polyphase.agent(...)` itself throws) and
|
|
173
|
+
// `__polyphaseSpent` is never updated from this call.
|
|
174
|
+
reply = { kind: "error", message: error instanceof Error ? error.message : String(error) };
|
|
175
|
+
}
|
|
176
|
+
return mapAgentReply(reply, spec.host.spentTokens());
|
|
177
|
+
},
|
|
178
|
+
};
|
|
179
|
+
const phaseGlobal = {
|
|
180
|
+
name: "__polyphase.phase",
|
|
181
|
+
execute: (title) => {
|
|
182
|
+
if (typeof title !== "string" || title.trim() === "") {
|
|
183
|
+
throw new Error("phase(title) needs a non-empty string");
|
|
184
|
+
}
|
|
185
|
+
if (title.length > PHASE_MAX_CHARS) {
|
|
186
|
+
throw new Error(`phase(title) needs a non-empty string of at most ${PHASE_MAX_CHARS} characters`);
|
|
187
|
+
}
|
|
188
|
+
return spec.host.onPhase(title);
|
|
189
|
+
},
|
|
190
|
+
};
|
|
191
|
+
const logGlobal = {
|
|
192
|
+
name: "__polyphase.log",
|
|
193
|
+
spread: true,
|
|
194
|
+
execute: (rawArgs) => {
|
|
195
|
+
const args = Array.isArray(rawArgs) ? rawArgs : [];
|
|
196
|
+
const [first, second] = [args[0], args[1]];
|
|
197
|
+
const text = typeof first === "string" ? first : String(first);
|
|
198
|
+
spec.host.onLog(text, second === "warning" ? "warning" : "info");
|
|
199
|
+
},
|
|
200
|
+
};
|
|
201
|
+
const sandbox = new CodemodeSandbox({
|
|
202
|
+
globals: [agentGlobal, phaseGlobal, logGlobal],
|
|
203
|
+
timeoutMs: spec.timeoutMs > 0 ? spec.timeoutMs : Number.POSITIVE_INFINITY,
|
|
204
|
+
memoryLimitBytes: spec.memoryLimitBytes ?? DEFAULT_MEMORY_LIMIT_BYTES,
|
|
205
|
+
maxOutputChars: spec.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS,
|
|
206
|
+
wasm: spec.sandbox?.wasm ?? loadQuickJSWasm(getQuickJSWasmPath()),
|
|
207
|
+
workerUrl: spec.sandbox?.workerUrl ?? getCodemodeWorkerSpecifier(),
|
|
208
|
+
});
|
|
209
|
+
try {
|
|
210
|
+
const result = await sandbox.execute(prelude + spec.body, { signal: spec.signal });
|
|
211
|
+
return toOutcome(result, prelude.length, agentCalls);
|
|
212
|
+
}
|
|
213
|
+
finally {
|
|
214
|
+
await sandbox.close();
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
//# sourceMappingURL=runtime.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/runtime.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,EAIN,eAAe,EAGf,eAAe,GACf,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,0BAA0B,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAEpF,OAAO,EAAE,oBAAoB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAwDrE,MAAM,0BAA0B,GAAG,GAAG,GAAG,IAAI,GAAG,IAAI,CAAC;AACrD;;;;;;GAMG;AACH,MAAM,wBAAwB,GAAG,SAAS,CAAC;AAE3C,qEAAqE;AACrE,MAAM,qBAAqB,GAAG,8BAA8B,CAAC,MAAM,CAAC;AACpE;;;;;GAKG;AACH,MAAM,aAAa,GAAG,wCAAwC,CAAC;AAC/D,MAAM,qBAAqB,GAAG,8CAA8C,CAAC;AAC7E,MAAM,kBAAkB,GAAG,8EAA8E,CAAC;AAE1G,MAAM,gBAAgB,GAAG,OAAO,CAAC;AACjC,MAAM,eAAe,GAAG,EAAE,CAAC;AAC3B,MAAM,qBAAqB,GAAG,MAAM,CAAC;AACrC,MAAM,eAAe,GAAG,G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AS,IAAI,0BAA0B,EAAE;KAClE,CAAC,CAAC;IAEH,IAAI,CAAC;QACJ,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;QACnF,OAAO,SAAS,CAAC,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;IACtD,CAAC;YAAS,CAAC;QACV,MAAM,OAAO,CAAC,KAAK,EAAE,CAAC;IACvB,CAAC;AACF,CAAC","sourcesContent":["/**\n * Runs a workflow script's prelude plus body in a `CodemodeSandbox` (DESIGN.md §13.4).\n *\n * The sandbox evaluates `(async (tools, console) => {<prelude><body>\\n})` as `codemode.js`\n * (packages/codemode/src/runtime/worker.ts). Since the prelude is one line, a script error on\n * body line 1 is reported at `codemode.js:1:C` with `C` past the wrapper prefix and the prelude;\n * errors on later body lines report their real line number unchanged.\n */\n\nimport type { JsonObject, JsonValue } from \"@draht/ai\";\nimport {\n\ttype CodemodeError,\n\ttype CodemodeErrorKind,\n\ttype CodemodeResult,\n\tCodemodeSandbox,\n\ttype CodemodeTool,\n\ttype CodemodeWasmModule,\n\tloadQuickJSWasm,\n} from \"@draht/codemode\";\nimport { getCodemodeWorkerSpecifier, getQuickJSWasmPath } from \"../../../config.ts\";\nimport type { WorkflowMeta } from \"./meta.ts\";\nimport { buildWorkflowPrelude, PHASE_MAX_CHARS } from \"./prelude.ts\";\n\nexport interface WorkflowAgentRequest {\n\tprompt: string;\n\tlabel?: string;\n\tphase?: string;\n\tschema?: JsonObject;\n\tmodel?: string;\n\teffort?: string;\n\tisolation?: \"worktree\";\n\tagentType?: string;\n}\n\nexport type WorkflowAgentReply =\n\t| { kind: \"value\"; value: JsonValue }\n\t| { kind: \"null\"; reason: \"failed\" | \"cancelled\" | \"budget\" | \"no-structured-output\"; message?: string }\n\t| { kind: \"error\"; message: string };\n\nexport interface WorkflowHost {\n\trunAgent(request: WorkflowAgentRequest, signal: AbortSignal): Promise<WorkflowAgentReply>;\n\tonPhase(title: string): number;\n\tonLog(text: string, level: \"info\" | \"warning\"): void;\n\tspentTokens(): number;\n}\n\nexport interface WorkflowRunSpec {\n\tmeta: WorkflowMeta;\n\tbody: string;\n\targs: string;\n\tbudgetTokens: number | null;\n\tmaxAgents: number;\n\tmaxItemsPerCall: number;\n\t/** 0 or `Infinity` disables the deadline. */\n\ttimeoutMs: number;\n\t/** Default 256 MiB. */\n\tmemoryLimitBytes?: number;\n\t/** Default 1,000,000 (the result text keeps only the first/last 8000 console characters anyway). */\n\tmaxOutputChars?: number;\n\tsignal: AbortSignal;\n\thost: WorkflowHost;\n\tsandbox?: { wasm?: CodemodeWasmModule | Promise<CodemodeWasmModule>; workerUrl?: string | URL };\n}\n\nexport interface WorkflowScriptError {\n\tkind: CodemodeErrorKind;\n\tmessage: string;\n\tline?: number;\n\tcolumn?: number;\n\tstack?: string;\n\thint?: string;\n}\n\nexport type WorkflowOutcome =\n\t| { ok: true; value: JsonValue | undefined; consoleOutput: string[]; agentCalls: number }\n\t| { ok: false; error: WorkflowScriptError; consoleOutput: string[]; agentCalls: number };\n\nconst DEFAULT_MEMORY_LIMIT_BYTES = 256 * 1024 * 1024;\n/**\n * `memoryLimitBytes` only bounds the QuickJS heap; nothing else stops a script from calling\n * `console.log`/`text()`/`image()` in a loop and growing the host process's memory without bound\n * (every output item is kept in `CodemodeResult.output` for the life of the run). The result text\n * keeps only the first/last 8000 console characters (`result-text.ts`), so this cap is generous\n * relative to what ever reaches the user.\n */\nconst DEFAULT_MAX_OUTPUT_CHARS = 1_000_000;\n\n/** Prefix the worker wraps the full source in; see worker.ts:146. */\nconst WRAPPER_PREFIX_LENGTH = \"(async (tools, console) => {\".length;\n/**\n * Anchored to frame lines (` at ... (codemode.js:L:C)`, see sandbox.test.ts) rather than\n * matching anywhere in the stack: the stack's first line is `Name: message`, and a script or\n * agent-reply error message can itself contain text that looks like `codemode.js:L:C` (a host\n * error string, or a user-thrown message), which would otherwise be mistaken for the real frame.\n */\nconst FRAME_PATTERN = /^[ \\t]*at .*codemode\\.js:(\\d+):(\\d+)/gm;\nconst REDECLARATION_PATTERN = /redefinition|redeclar|already been declared/i;\nconst REDECLARATION_HINT = \"do not redeclare agent, parallel, pipeline, phase, log, args, budget or meta\";\n\nconst PROMPT_MAX_CHARS = 200_000;\nconst LABEL_MAX_CHARS = 80;\nconst SCHEMA_MAX_JSON_CHARS = 65_536;\nconst MODEL_MAX_CHARS = 160;\nconst AGENT_TYPE_PATTERN = /^[\\w.-]{1,64}$/;\n\ntype AgentGuardResult = { ok: true; value: WorkflowAgentRequest } | { ok: false; error: string };\n\nfunction guardAgentRequest(raw: unknown): AgentGuardResult {\n\tif (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n\t\treturn { ok: false, error: \"agent() request must be an object\" };\n\t}\n\tconst request = raw as Record<string, unknown>;\n\n\tconst prompt = request.prompt;\n\tif (typeof prompt !== \"string\" || prompt.length < 1 || prompt.length > PROMPT_MAX_CHARS) {\n\t\treturn { ok: false, error: `agent(): prompt must be a string of 1 to ${PROMPT_MAX_CHARS} characters` };\n\t}\n\n\tconst label = request.label;\n\tif (label !== undefined && (typeof label !== \"string\" || label.length > LABEL_MAX_CHARS)) {\n\t\treturn { ok: false, error: `agent(): label must be a string of at most ${LABEL_MAX_CHARS} characters` };\n\t}\n\n\tconst phase = request.phase;\n\tif (phase !== undefined && (typeof phase !== \"string\" || phase.length > PHASE_MAX_CHARS)) {\n\t\treturn { ok: false, error: `agent(): phase must be a string of at most ${PHASE_MAX_CHARS} characters` };\n\t}\n\n\tconst schema = request.schema;\n\tif (schema !== undefined) {\n\t\tif (typeof schema !== \"object\" || schema === null || Array.isArray(schema)) {\n\t\t\treturn { ok: false, error: \"agent(): schema must be an object\" };\n\t\t}\n\t\tlet json: string;\n\t\ttry {\n\t\t\tjson = JSON.stringify(schema);\n\t\t} catch {\n\t\t\treturn { ok: false, error: \"agent(): schema must be JSON-serializable\" };\n\t\t}\n\t\tif (json.length > SCHEMA_MAX_JSON_CHARS) {\n\t\t\treturn { ok: false, error: `agent(): schema must be at most ${SCHEMA_MAX_JSON_CHARS} JSON characters` };\n\t\t}\n\t}\n\n\tconst model = request.model;\n\tif (model !== undefined && (typeof model !== \"string\" || model.length > MODEL_MAX_CHARS)) {\n\t\treturn { ok: false, error: `agent(): model must be a string of at most ${MODEL_MAX_CHARS} characters` };\n\t}\n\n\tconst effort = request.effort;\n\tif (effort !== undefined && typeof effort !== \"string\") {\n\t\treturn { ok: false, error: \"agent(): effort must be a string\" };\n\t}\n\n\tconst isolation = request.isolation;\n\tif (isolation !== undefined && isolation !== \"worktree\") {\n\t\treturn { ok: false, error: 'agent(): isolation must be \"worktree\"' };\n\t}\n\n\tconst agentType = request.agentType;\n\tif (agentType !== undefined && (typeof agentType !== \"string\" || !AGENT_TYPE_PATTERN.test(agentType))) {\n\t\treturn { ok: false, error: \"agent(): agentType must match /^[\\\\w.-]{1,64}$/\" };\n\t}\n\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tprompt,\n\t\t\tlabel: label as string | undefined,\n\t\t\tphase: phase as string | undefined,\n\t\t\tschema: schema as JsonObject | undefined,\n\t\t\tmodel: model as string | undefined,\n\t\t\teffort: effort as string | undefined,\n\t\t\tisolation: isolation as \"worktree\" | undefined,\n\t\t\tagentType: agentType as string | undefined,\n\t\t},\n\t};\n}\n\nfunction mapAgentReply(reply: WorkflowAgentReply, spent: number): JsonValue {\n\tif (reply.kind === \"value\") return { ok: true, value: reply.value, spent };\n\tif (reply.kind === \"null\") return { ok: true, value: null, spent };\n\treturn { ok: false, error: reply.message ?? \"agent failed\", spent };\n}\n\nfunction extractLocation(stack: string | undefined, preludeLength: number): { line?: number; column?: number } {\n\tif (!stack) return {};\n\tconst threshold = WRAPPER_PREFIX_LENGTH + preludeLength;\n\tfor (const match of stack.matchAll(FRAME_PATTERN)) {\n\t\tconst line = Number(match[1]);\n\t\tconst column = Number(match[2]);\n\t\tif (line > 1 || column > threshold) return { line, column: line === 1 ? column - threshold : column };\n\t}\n\treturn {};\n}\n\nfunction toScriptError(error: CodemodeError, preludeLength: number): WorkflowScriptError {\n\tif (error.kind !== \"script\") {\n\t\treturn { kind: error.kind, message: error.message, stack: error.stack };\n\t}\n\tconst { line, column } = extractLocation(error.stack, preludeLength);\n\tconst hint =\n\t\terror.name === \"SyntaxError\" && REDECLARATION_PATTERN.test(error.message) ? REDECLARATION_HINT : undefined;\n\treturn { kind: \"script\", message: error.message, line, column, stack: error.stack, hint };\n}\n\nfunction toOutcome(result: CodemodeResult, preludeLength: number, agentCalls: number): WorkflowOutcome {\n\tconst consoleOutput = result.output.filter((item) => item.type === \"text\").map((item) => item.text);\n\tif (result.ok) {\n\t\treturn { ok: true, value: result.value as JsonValue | undefined, consoleOutput, agentCalls };\n\t}\n\treturn { ok: false, error: toScriptError(result.error, preludeLength), consoleOutput, agentCalls };\n}\n\nexport async function runWorkflowScript(spec: WorkflowRunSpec): Promise<WorkflowOutcome> {\n\tconst prelude = buildWorkflowPrelude({\n\t\tmeta: spec.meta,\n\t\targs: spec.args,\n\t\tbudgetTokens: spec.budgetTokens,\n\t\tmaxItemsPerCall: spec.maxItemsPerCall,\n\t});\n\n\t// A non-finite maxAgents (NaN from a malformed setting, Infinity) must not silently disable the\n\t// cap for the wrong reason: `agentCalls >= NaN` is always false, same effect as \"no cap\" but by\n\t// accident rather than by a documented \"unlimited\" value.\n\tconst maxAgents = Number.isFinite(spec.maxAgents)\n\t\t? Math.max(0, Math.floor(spec.maxAgents))\n\t\t: Number.MAX_SAFE_INTEGER;\n\n\t// `agentCalls` counts agents actually dispatched to the host (DESIGN.md §13.4 \"count accepted\n\t// requests\"); a request rejected by the cap never reaches `host.runAgent` and is not counted.\n\tlet agentCalls = 0;\n\tconst agentGlobal: CodemodeTool = {\n\t\tname: \"__polyphase.agent\",\n\t\texecute: async (rawArgs, { signal }) => {\n\t\t\tconst guarded = guardAgentRequest(rawArgs);\n\t\t\tif (!guarded.ok) {\n\t\t\t\treturn { ok: false, error: guarded.error, spent: spec.host.spentTokens() };\n\t\t\t}\n\t\t\tif (agentCalls >= maxAgents) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `agent cap reached: a workflow may start at most ${maxAgents} agents (polyphase.maxAgentsPerRun)`,\n\t\t\t\t\tspent: spec.host.spentTokens(),\n\t\t\t\t};\n\t\t\t}\n\t\t\tagentCalls++;\n\t\t\tlet reply: WorkflowAgentReply;\n\t\t\ttry {\n\t\t\t\treply = await spec.host.runAgent(guarded.value, signal);\n\t\t\t} catch (error) {\n\t\t\t\t// A rejection must still flow through the normal `{ok:false}` reply path below, or\n\t\t\t\t// the prelude's `agent()` never runs its call-site stack rewrite (its `if (!reply.ok)`\n\t\t\t\t// branch is skipped entirely when `await __polyphase.agent(...)` itself throws) and\n\t\t\t\t// `__polyphaseSpent` is never updated from this call.\n\t\t\t\treply = { kind: \"error\", message: error instanceof Error ? error.message : String(error) };\n\t\t\t}\n\t\t\treturn mapAgentReply(reply, spec.host.spentTokens());\n\t\t},\n\t};\n\tconst phaseGlobal: CodemodeTool = {\n\t\tname: \"__polyphase.phase\",\n\t\texecute: (title) => {\n\t\t\tif (typeof title !== \"string\" || title.trim() === \"\") {\n\t\t\t\tthrow new Error(\"phase(title) needs a non-empty string\");\n\t\t\t}\n\t\t\tif (title.length > PHASE_MAX_CHARS) {\n\t\t\t\tthrow new Error(`phase(title) needs a non-empty string of at most ${PHASE_MAX_CHARS} characters`);\n\t\t\t}\n\t\t\treturn spec.host.onPhase(title);\n\t\t},\n\t};\n\tconst logGlobal: CodemodeTool = {\n\t\tname: \"__polyphase.log\",\n\t\tspread: true,\n\t\texecute: (rawArgs) => {\n\t\t\tconst args = Array.isArray(rawArgs) ? rawArgs : [];\n\t\t\tconst [first, second]: [unknown, unknown] = [args[0], args[1]];\n\t\t\tconst text = typeof first === \"string\" ? first : String(first);\n\t\t\tspec.host.onLog(text, second === \"warning\" ? \"warning\" : \"info\");\n\t\t},\n\t};\n\n\tconst sandbox = new CodemodeSandbox({\n\t\tglobals: [agentGlobal, phaseGlobal, logGlobal],\n\t\ttimeoutMs: spec.timeoutMs > 0 ? spec.timeoutMs : Number.POSITIVE_INFINITY,\n\t\tmemoryLimitBytes: spec.memoryLimitBytes ?? DEFAULT_MEMORY_LIMIT_BYTES,\n\t\tmaxOutputChars: spec.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS,\n\t\twasm: spec.sandbox?.wasm ?? loadQuickJSWasm(getQuickJSWasmPath()),\n\t\tworkerUrl: spec.sandbox?.workerUrl ?? getCodemodeWorkerSpecifier(),\n\t});\n\n\ttry {\n\t\tconst result = await sandbox.execute(prelude + spec.body, { signal: spec.signal });\n\t\treturn toOutcome(result, prelude.length, agentCalls);\n\t} finally {\n\t\tawait sandbox.close();\n\t}\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime.lazy.d.ts","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/runtime.lazy.ts"],"names":[],"mappings":"AAAA,kFAAkF;AAClF,eAAO,MAAM,mBAAmB,8CAA+B,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime.lazy.js","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/runtime.lazy.ts"],"names":[],"mappings":"AAAA,kFAAkF;AAClF,MAAM,CAAC,MAAM,mBAAmB,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC","sourcesContent":["/** Loads the workflow script runtime on the first script run (see runtime.ts). */\nexport const loadWorkflowRuntime = () => import(\"./runtime.ts\");\n"]}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Discovery of saved workflow scripts: `<agentDir>/workflows/*.js` (user) and the nearest
|
|
3
|
+
* trusted `.draht/workflows/*.js` (project), mirroring `findProjectAgentsDir` in
|
|
4
|
+
* `builtins/subagent.ts`. See DESIGN.md §16.1.
|
|
5
|
+
*/
|
|
6
|
+
import { type WorkflowPhaseMeta } from "./meta.ts";
|
|
7
|
+
export declare const SAVED_WORKFLOW_MAX_BYTES = 262144;
|
|
8
|
+
export interface SavedWorkflow {
|
|
9
|
+
name: string;
|
|
10
|
+
description: string;
|
|
11
|
+
whenToUse?: string;
|
|
12
|
+
phases: WorkflowPhaseMeta[];
|
|
13
|
+
path: string;
|
|
14
|
+
source: "project" | "user";
|
|
15
|
+
valid: boolean;
|
|
16
|
+
error?: string;
|
|
17
|
+
}
|
|
18
|
+
export interface SavedWorkflowDiagnostic {
|
|
19
|
+
path: string;
|
|
20
|
+
level: "warning" | "info";
|
|
21
|
+
message: string;
|
|
22
|
+
}
|
|
23
|
+
export interface SavedWorkflowSummary {
|
|
24
|
+
name: string;
|
|
25
|
+
description: string;
|
|
26
|
+
source: "project" | "user";
|
|
27
|
+
valid: boolean;
|
|
28
|
+
command?: string;
|
|
29
|
+
}
|
|
30
|
+
export interface SavedDiscoveryOptions {
|
|
31
|
+
cwd: string;
|
|
32
|
+
agentDir: string;
|
|
33
|
+
projectTrusted: boolean;
|
|
34
|
+
}
|
|
35
|
+
export interface DirDiscovery {
|
|
36
|
+
workflows: SavedWorkflow[];
|
|
37
|
+
diagnostics: SavedWorkflowDiagnostic[];
|
|
38
|
+
}
|
|
39
|
+
export declare function discoverSavedWorkflows(options: SavedDiscoveryOptions): DirDiscovery;
|
|
40
|
+
/**
|
|
41
|
+
* Looks up a single name directly in the project then user workflow directories, instead of
|
|
42
|
+
* discovering (opening, reading and meta-parsing) every file in both. Called on every workflow
|
|
43
|
+
* approval and again on every saved-workflow execution, so a directory with many saved workflows
|
|
44
|
+
* would otherwise redo that work twice per run.
|
|
45
|
+
*/
|
|
46
|
+
export declare function findSavedWorkflow(name: string, options: SavedDiscoveryOptions): SavedWorkflow | undefined;
|
|
47
|
+
/**
|
|
48
|
+
* Throws when the file is no longer a regular file (e.g. replaced by a fifo since discovery),
|
|
49
|
+
* cannot be read, or has grown past {@link SAVED_WORKFLOW_MAX_BYTES} since discovery. The
|
|
50
|
+
* `statRegularFile` call below is only an early refusal and a size hint for `readBoundedUtf8`;
|
|
51
|
+
* the authoritative regular-file check happens on the opened fd inside `readBoundedUtf8` itself,
|
|
52
|
+
* so a swap between this stat and that open (e.g. into a fifo) still can't hang the read.
|
|
53
|
+
*/
|
|
54
|
+
export declare function readSavedWorkflowSource(workflow: SavedWorkflow): string;
|
|
55
|
+
//# sourceMappingURL=saved.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"saved.d.ts","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/saved.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAMH,OAAO,EAAmE,KAAK,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAEpH,eAAO,MAAM,wBAAwB,SAAU,CAAC;AAEhD,MAAM,WAAW,aAAa;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,iBAAiB,EAAE,CAAC;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,SAAS,GAAG,MAAM,CAAC;IAC3B,KAAK,EAAE,OAAO,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,uBAAuB;IACvC,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,SAAS,GAAG,MAAM,CAAC;IAC1B,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,oBAAoB;IACpC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,SAAS,GAAG,MAAM,CAAC;IAC3B,KAAK,EAAE,OAAO,CAAC;IACf,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB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