@draht/coding-agent 2026.10.16 → 2026.10.19-1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +39 -0
- package/README.md +1 -0
- package/dist/bundle/chunks/{anthropic-messages-GAKYXF65.js → anthropic-messages-E2P6C3P7.js} +1 -1
- package/dist/bundle/chunks/{azure-openai-responses-ZIXMK6JO.js → azure-openai-responses-JZMSTDIM.js} +1 -1
- package/dist/bundle/chunks/bedrock-converse-stream.js +20 -20
- package/dist/bundle/chunks/chunk-2JZLKNZ4.js +3 -0
- package/dist/bundle/chunks/{chunk-OWGSPJPZ.js → chunk-3DQNSI5W.js} +5 -5
- package/dist/bundle/chunks/{chunk-JFDPOIUH.js → chunk-4COXSQRQ.js} +1 -1
- package/dist/bundle/chunks/chunk-5QJFWTKA.js +4 -0
- package/dist/bundle/chunks/{chunk-TJ3AW62W.js → chunk-CQF6U56X.js} +1 -1
- package/dist/bundle/chunks/{chunk-RZKPFWMH.js → chunk-D3HO453P.js} +2 -2
- package/dist/bundle/chunks/{chunk-KVH4HR57.js → chunk-FHX2S5IG.js} +1 -1
- package/dist/bundle/chunks/chunk-GBFVS2SF.js +12 -0
- package/dist/bundle/chunks/{chunk-6APPDDHH.js → chunk-I2SOJ4JN.js} +3 -3
- package/dist/bundle/chunks/{chunk-BXSHCX3G.js → chunk-KY2BG6BC.js} +1 -1
- package/dist/bundle/chunks/chunk-LO6CVU2L.js +6 -0
- package/dist/bundle/chunks/{chunk-MIUVNYYW.js → chunk-QPCP4VHF.js} +123 -111
- package/dist/bundle/chunks/{chunk-KU5HAKZL.js → chunk-QVTLBSTH.js} +1 -1
- package/dist/bundle/chunks/{chunk-2VAF4XJI.js → chunk-U6LDZZGM.js} +10 -10
- package/dist/bundle/chunks/{chunk-D6TMD5Q2.js → chunk-UTRX2VHB.js} +8 -8
- package/dist/bundle/chunks/chunk-VXUJMEMO.js +2 -0
- package/dist/bundle/chunks/{chunk-NHTOADU6.js → chunk-X3YFUSCK.js} +1 -1
- package/dist/bundle/chunks/{cli-U7Y4VNNI.js → cli-VCHSHNKT.js} +1 -1
- package/dist/bundle/chunks/{execute-ZWB4PIQQ.js → execute-AGEWJLIO.js} +1 -1
- package/dist/bundle/chunks/{google-generative-ai-RPUPQ6PM.js → google-generative-ai-HPNDIAZD.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-EZES5QVQ.js → google-vertex-KPAWJ4SP.js} +1 -1
- package/dist/bundle/chunks/https-proxy-agent-WQIRL24U.js +13 -0
- package/dist/bundle/chunks/lib-ULKZYRGD.js +9 -0
- package/dist/bundle/chunks/{mistral-conversations-AOYGU43Y.js → mistral-conversations-FMSPWQ7A.js} +1 -1
- package/dist/bundle/chunks/{multipart-parser-AZP5BX2W.js → multipart-parser-HMCXZ4BD.js} +1 -1
- package/dist/bundle/chunks/{node-LQ52KV6B.js → node-4JNG6XQO.js} +1 -1
- package/dist/bundle/chunks/{node-C2JGH2OB.js → node-6IIDYB3K.js} +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-M2Y77JEQ.js → openai-codex-responses-TU7NGPXE.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-A4OKYOYV.js → openai-completions-GANCQQO5.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-6IXV53T3.js → openai-responses-ASDPAX3E.js} +1 -1
- package/dist/bundle/chunks/{openrouter-images-LYV4NKFM.js → openrouter-images-NROSQXMZ.js} +1 -1
- package/dist/bundle/chunks/{pi-messages-KKMEUT3Z.js → pi-messages-2QEJYOAO.js} +1 -1
- package/dist/bundle/chunks/{runtime-PXJK4L7Y.js → runtime-2B56SZM6.js} +1 -1
- package/dist/bundle/chunks/{runtime-363BOYEO.js → runtime-TJ3EAMJK.js} +1 -1
- package/dist/bundle/chunks/{settings-manager-GEOZJXFQ.js → settings-manager-HC5RR36T.js} +1 -1
- package/dist/bundle/chunks/src-KDGO7EGF.js +4 -0
- package/dist/bundle/chunks/{virtual-modules-BEJ4ZJ3D.js → virtual-modules-XT4MP2GI.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/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +4 -0
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/builtins/duet.d.ts +7 -1
- package/dist/core/builtins/duet.d.ts.map +1 -1
- package/dist/core/builtins/duet.js +83 -14
- package/dist/core/builtins/duet.js.map +1 -1
- package/dist/core/builtins/polyphase.d.ts.map +1 -1
- package/dist/core/builtins/polyphase.js +21 -2
- package/dist/core/builtins/polyphase.js.map +1 -1
- package/dist/core/builtins/subagent.d.ts +59 -2
- package/dist/core/builtins/subagent.d.ts.map +1 -1
- package/dist/core/builtins/subagent.js +258 -62
- package/dist/core/builtins/subagent.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +23 -0
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +2 -0
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +12 -0
- 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 +5 -0
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +4 -0
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/multi-agent/permission-gate.d.ts +18 -6
- package/dist/core/multi-agent/permission-gate.d.ts.map +1 -1
- package/dist/core/multi-agent/permission-gate.js +867 -59
- package/dist/core/multi-agent/permission-gate.js.map +1 -1
- package/dist/core/polyphase/approval.d.ts +6 -2
- package/dist/core/polyphase/approval.d.ts.map +1 -1
- package/dist/core/polyphase/approval.js +23 -35
- package/dist/core/polyphase/approval.js.map +1 -1
- package/dist/core/polyphase/child-events.js +1 -1
- package/dist/core/polyphase/child-events.js.map +1 -1
- package/dist/core/polyphase/child-process.d.ts.map +1 -1
- package/dist/core/polyphase/child-process.js +65 -7
- package/dist/core/polyphase/child-process.js.map +1 -1
- package/dist/core/polyphase/commands.d.ts.map +1 -1
- package/dist/core/polyphase/commands.js +46 -5
- package/dist/core/polyphase/commands.js.map +1 -1
- package/dist/core/polyphase/details.d.ts.map +1 -1
- package/dist/core/polyphase/details.js +5 -0
- package/dist/core/polyphase/details.js.map +1 -1
- package/dist/core/polyphase/permission-bridge.d.ts +128 -0
- package/dist/core/polyphase/permission-bridge.d.ts.map +1 -0
- package/dist/core/polyphase/permission-bridge.js +357 -0
- package/dist/core/polyphase/permission-bridge.js.map +1 -0
- package/dist/core/polyphase/render/run-block.d.ts.map +1 -1
- package/dist/core/polyphase/render/run-block.js +13 -4
- package/dist/core/polyphase/render/run-block.js.map +1 -1
- package/dist/core/polyphase/render/snapshot.d.ts +4 -0
- package/dist/core/polyphase/render/snapshot.d.ts.map +1 -1
- package/dist/core/polyphase/render/snapshot.js +4 -0
- package/dist/core/polyphase/render/snapshot.js.map +1 -1
- package/dist/core/polyphase/result-text.d.ts.map +1 -1
- package/dist/core/polyphase/result-text.js +23 -3
- package/dist/core/polyphase/result-text.js.map +1 -1
- package/dist/core/polyphase/session.d.ts +15 -1
- package/dist/core/polyphase/session.d.ts.map +1 -1
- package/dist/core/polyphase/session.js +36 -1
- package/dist/core/polyphase/session.js.map +1 -1
- package/dist/core/polyphase/settings.d.ts +1 -0
- package/dist/core/polyphase/settings.d.ts.map +1 -1
- package/dist/core/polyphase/settings.js +1 -1
- package/dist/core/polyphase/settings.js.map +1 -1
- package/dist/core/polyphase/store.d.ts +18 -0
- package/dist/core/polyphase/store.d.ts.map +1 -1
- package/dist/core/polyphase/store.js +38 -0
- package/dist/core/polyphase/store.js.map +1 -1
- package/dist/core/polyphase/types.d.ts +60 -3
- package/dist/core/polyphase/types.d.ts.map +1 -1
- package/dist/core/polyphase/types.js.map +1 -1
- package/dist/core/polyphase/ui/inspector.js +1 -1
- package/dist/core/polyphase/ui/inspector.js.map +1 -1
- package/dist/core/polyphase/workflow/agent-host.d.ts.map +1 -1
- package/dist/core/polyphase/workflow/agent-host.js +17 -3
- package/dist/core/polyphase/workflow/agent-host.js.map +1 -1
- package/dist/core/polyphase/workflow/guidance.d.ts.map +1 -1
- package/dist/core/polyphase/workflow/guidance.js +16 -5
- package/dist/core/polyphase/workflow/guidance.js.map +1 -1
- package/dist/core/polyphase/workflow/launch.d.ts +2 -1
- package/dist/core/polyphase/workflow/launch.d.ts.map +1 -1
- package/dist/core/polyphase/workflow/launch.js +22 -3
- package/dist/core/polyphase/workflow/launch.js.map +1 -1
- package/dist/core/polyphase/workflow/limits.d.ts +80 -0
- package/dist/core/polyphase/workflow/limits.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/limits.js +234 -0
- package/dist/core/polyphase/workflow/limits.js.map +1 -0
- package/dist/core/polyphase/workflow/runtime.d.ts +1 -1
- package/dist/core/polyphase/workflow/runtime.d.ts.map +1 -1
- package/dist/core/polyphase/workflow/runtime.js.map +1 -1
- package/dist/core/polyphase/workflow/tool.d.ts +1 -0
- package/dist/core/polyphase/workflow/tool.d.ts.map +1 -1
- package/dist/core/polyphase/workflow/tool.js +23 -2
- package/dist/core/polyphase/workflow/tool.js.map +1 -1
- package/dist/core/usage-totals.d.ts +5 -0
- package/dist/core/usage-totals.d.ts.map +1 -1
- package/dist/core/usage-totals.js +16 -0
- package/dist/core/usage-totals.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +4 -0
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +2 -0
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +3 -0
- package/dist/utils/shell.js.map +1 -1
- package/docs/duet.md +1 -1
- package/docs/environment-variables.md +3 -1
- package/docs/extensions.md +2 -1
- package/docs/keybindings.md +1 -0
- package/docs/polyphase.md +97 -33
- package/docs/settings.md +2 -2
- package/package.json +10 -10
- package/dist/bundle/chunks/chunk-6MSE6LZ3.js +0 -6
- package/dist/bundle/chunks/chunk-6ZJKIMU7.js +0 -2
- package/dist/bundle/chunks/chunk-736QBNUZ.js +0 -12
- package/dist/bundle/chunks/chunk-IWTUBX6V.js +0 -4
- package/dist/bundle/chunks/chunk-TIA2T6EO.js +0 -3
- package/dist/bundle/chunks/https-proxy-agent-O2PVUIOI.js +0 -13
- package/dist/bundle/chunks/lib-XOG5PI3Y.js +0 -9
- package/dist/bundle/chunks/src-TIBHS42X.js +0 -4
- /package/dist/bundle/chunks/{chunk-ZZD35WKM.js → chunk-FBU742QF.js} +0 -0
- /package/dist/bundle/chunks/{chunk-SVNWI7EV.js → chunk-XHCO4PPH.js} +0 -0
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Workflow token-budget and time-limit directives (D-B): a `+500k`/`+30min`-style token the user
|
|
3
|
+
* types in their own prompt, else a tool/command parameter, else config, else none. See
|
|
4
|
+
* docs/polyphase.md "Limits" for the full grammar and precedence.
|
|
5
|
+
*/
|
|
6
|
+
import { MAX_SET_TIMEOUT_MS } from "../settings.js";
|
|
7
|
+
/** Extra wall-clock time the hard sandbox deadline keeps past a resolved graceful time limit, so
|
|
8
|
+
* agents already in flight when the limit fires have a window to wind down before the sandbox
|
|
9
|
+
* itself is killed. */
|
|
10
|
+
export const TIME_LIMIT_BACKSTOP_MS = 60_000;
|
|
11
|
+
/** The longest time limit that still fits one `setTimeout` together with its backstop. Node turns
|
|
12
|
+
* any longer delay into 1ms, so an over-long limit would cancel every agent the moment it started;
|
|
13
|
+
* longer requests are capped here instead. */
|
|
14
|
+
export const MAX_TIME_LIMIT_MS = MAX_SET_TIMEOUT_MS - TIME_LIMIT_BACKSTOP_MS;
|
|
15
|
+
const MIN_DIRECTIVE_BUDGET_TOKENS = 1000;
|
|
16
|
+
/** A `+`-prefixed token standing alone as a word: `+` immediately followed by a digit (so `+abc`,
|
|
17
|
+
* `+-5` and a bare `+` never match), bounded by whitespace or the start/end of the string on both
|
|
18
|
+
* sides. One bounded character class per side, no nested quantifiers: linear in the input length. */
|
|
19
|
+
const DIRECTIVE_TOKEN_PATTERN = /(?<=^|\s)\+[0-9][0-9A-Za-z.]*(?=$|\s)/g;
|
|
20
|
+
/** A zero duration is no time limit at all, so it is not a time directive either (it would show as
|
|
21
|
+
* "time limit 0s" while the run ignored it); anything longer than {@link MAX_TIME_LIMIT_MS} is
|
|
22
|
+
* capped to it. */
|
|
23
|
+
function timeDirective(ms) {
|
|
24
|
+
if (!(ms > 0))
|
|
25
|
+
return undefined;
|
|
26
|
+
return { kind: "time", ms: Math.min(ms, MAX_TIME_LIMIT_MS) };
|
|
27
|
+
}
|
|
28
|
+
/** `rest` is the token's text after the leading `+` (e.g. "500k", "1.5M", "30min", "1h30min"). */
|
|
29
|
+
function classifyDirectiveBody(rest) {
|
|
30
|
+
const compoundHourMinute = /^(\d+)(?:h|hr)(\d+)min$/i.exec(rest);
|
|
31
|
+
if (compoundHourMinute) {
|
|
32
|
+
const hours = Number(compoundHourMinute[1]);
|
|
33
|
+
const minutes = Number(compoundHourMinute[2]);
|
|
34
|
+
return timeDirective((hours * 3600 + minutes * 60) * 1000);
|
|
35
|
+
}
|
|
36
|
+
// "m"/"M" alone is excluded here on purpose: a bare "m" suffix means "million tokens" (the
|
|
37
|
+
// budget grammar below), never "minutes" — only the full words "min"/"sec"/"hr" (or "s"/"h")
|
|
38
|
+
// are time units.
|
|
39
|
+
const simpleTime = /^(\d+)(h|hr|min|sec|s)$/i.exec(rest);
|
|
40
|
+
if (simpleTime) {
|
|
41
|
+
const amount = Number(simpleTime[1]);
|
|
42
|
+
const unit = simpleTime[2].toLowerCase();
|
|
43
|
+
const seconds = unit === "h" || unit === "hr" ? amount * 3600 : unit === "min" ? amount * 60 : amount;
|
|
44
|
+
return timeDirective(seconds * 1000);
|
|
45
|
+
}
|
|
46
|
+
const budget = /^(\d+(?:\.\d+)?)([kKmM])?$/.exec(rest);
|
|
47
|
+
if (budget) {
|
|
48
|
+
const amount = Number.parseFloat(budget[1]);
|
|
49
|
+
const suffix = budget[2]?.toLowerCase();
|
|
50
|
+
const multiplier = suffix === "k" ? 1_000 : suffix === "m" ? 1_000_000 : 1;
|
|
51
|
+
const tokens = Math.round(amount * multiplier);
|
|
52
|
+
if (Number.isSafeInteger(tokens) && tokens >= MIN_DIRECTIVE_BUDGET_TOKENS)
|
|
53
|
+
return { kind: "budget", tokens };
|
|
54
|
+
}
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
function findDirectives(text) {
|
|
58
|
+
const matches = [];
|
|
59
|
+
for (const match of text.matchAll(DIRECTIVE_TOKEN_PATTERN)) {
|
|
60
|
+
const classified = classifyDirectiveBody(match[0].slice(1));
|
|
61
|
+
if (classified && match.index !== undefined)
|
|
62
|
+
matches.push({ token: match[0], index: match.index, classified });
|
|
63
|
+
}
|
|
64
|
+
return matches;
|
|
65
|
+
}
|
|
66
|
+
/** The first `+500k`/`+1.5M`/`+200000`-style token (min 1000 tokens) and the first
|
|
67
|
+
* `+30min`/`+2h`/`+90s`/`+1h30min`-style token anywhere in `text`, each independent of the other. */
|
|
68
|
+
export function parsePromptDirectives(text) {
|
|
69
|
+
const result = { budgetTokens: null, timeLimitMs: null };
|
|
70
|
+
for (const match of findDirectives(text)) {
|
|
71
|
+
if (match.classified.kind === "budget" && result.budgetTokens === null)
|
|
72
|
+
result.budgetTokens = match.classified.tokens;
|
|
73
|
+
if (match.classified.kind === "time" && result.timeLimitMs === null)
|
|
74
|
+
result.timeLimitMs = match.classified.ms;
|
|
75
|
+
if (result.budgetTokens !== null && result.timeLimitMs !== null)
|
|
76
|
+
break;
|
|
77
|
+
}
|
|
78
|
+
return result;
|
|
79
|
+
}
|
|
80
|
+
/** Removes every recognized directive token from `text` (e.g. command args) by cutting out the
|
|
81
|
+
* matched positions, not by a substring replace: a glued, non-standalone occurrence (e.g. the
|
|
82
|
+
* `+500k` inside `v+500k`) was never matched by `findDirectives` and is left untouched, and a
|
|
83
|
+
* standalone token that happens to be a textual prefix of another standalone token (e.g. `+1000`
|
|
84
|
+
* inside `+10000`) only removes its own matched span. Collapses the whitespace immediately next to
|
|
85
|
+
* each removed span, not every run of whitespace in `text`. A `+`-token that didn't classify (too
|
|
86
|
+
* small, malformed unit) is left untouched — it was never a directive. */
|
|
87
|
+
export function stripPromptDirectives(text) {
|
|
88
|
+
const matches = findDirectives(text).sort((a, b) => b.index - a.index);
|
|
89
|
+
if (matches.length === 0)
|
|
90
|
+
return text;
|
|
91
|
+
let result = text;
|
|
92
|
+
for (const match of matches) {
|
|
93
|
+
const before = result.slice(0, match.index);
|
|
94
|
+
const after = result.slice(match.index + match.token.length);
|
|
95
|
+
const beforeTrimmed = before.replace(/[ \t]+$/, "");
|
|
96
|
+
const afterTrimmed = after.replace(/^[ \t]+/, "");
|
|
97
|
+
const hadAdjacentSpace = beforeTrimmed.length !== before.length || afterTrimmed.length !== after.length;
|
|
98
|
+
const joiner = beforeTrimmed.length === 0 || afterTrimmed.length === 0 ? "" : hadAdjacentSpace ? " " : "";
|
|
99
|
+
result = beforeTrimmed + joiner + afterTrimmed;
|
|
100
|
+
}
|
|
101
|
+
return result.trim();
|
|
102
|
+
}
|
|
103
|
+
/** Same grammar as the budget/time directive bodies, without the leading `+`: used for the
|
|
104
|
+
* `timeLimit` tool parameter. `undefined` when `text` is not a valid duration. */
|
|
105
|
+
export function parseDurationMs(text) {
|
|
106
|
+
const classified = classifyDirectiveBody(text);
|
|
107
|
+
return classified?.kind === "time" ? classified.ms : undefined;
|
|
108
|
+
}
|
|
109
|
+
function resolve(prompt, tool, config) {
|
|
110
|
+
if (prompt !== null && prompt !== undefined)
|
|
111
|
+
return { value: prompt, source: "prompt" };
|
|
112
|
+
if (tool !== null && tool !== undefined)
|
|
113
|
+
return { value: tool, source: "tool" };
|
|
114
|
+
if (config !== null)
|
|
115
|
+
return { value: config, source: "config" };
|
|
116
|
+
return { value: null, source: "none" };
|
|
117
|
+
}
|
|
118
|
+
/** A steer or follow-up typed while a turn runs (`streamingBehavior` set) only adds what it states:
|
|
119
|
+
* `update`'s limits over `base`'s, keeping `base`'s where `update` names none. A prompt that starts a
|
|
120
|
+
* turn replaces the directives instead (the caller decides which). */
|
|
121
|
+
export function mergePromptDirectives(base, update) {
|
|
122
|
+
return {
|
|
123
|
+
budgetTokens: update.budgetTokens ?? base?.budgetTokens ?? null,
|
|
124
|
+
timeLimitMs: update.timeLimitMs ?? base?.timeLimitMs ?? null,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
/** Same cap as a directive's, for a time limit from config, whose own clamp allows the full
|
|
128
|
+
* `setTimeout` range and leaves no room for the backstop. */
|
|
129
|
+
function capTimeLimit(ms) {
|
|
130
|
+
return typeof ms === "number" ? Math.min(ms, MAX_TIME_LIMIT_MS) : ms;
|
|
131
|
+
}
|
|
132
|
+
/** Precedence, independently for the token budget and the time limit: prompt directive, else tool
|
|
133
|
+
* parameter, else config, else none. */
|
|
134
|
+
export function resolveWorkflowLimits(options) {
|
|
135
|
+
return {
|
|
136
|
+
budgetTokens: resolve(options.prompt?.budgetTokens, options.tool?.budgetTokens, options.config.budgetTokens),
|
|
137
|
+
timeLimitMs: resolve(capTimeLimit(options.prompt?.timeLimitMs), capTimeLimit(options.tool?.timeLimitMs), capTimeLimit(options.config.timeLimitMs) ?? null),
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
/** The sandbox's own hard deadline: `timeLimitMs + 60s` when a time limit resolved, else disabled
|
|
141
|
+
* (0). There is no separate "config" hard-timeout concept anymore — `polyphase.workflowTimeoutMs`
|
|
142
|
+
* is itself one of the possible sources of the graceful time limit above. Never past what one
|
|
143
|
+
* `setTimeout` can wait. */
|
|
144
|
+
export function hardSandboxTimeoutMs(resolvedTimeLimitMs) {
|
|
145
|
+
return resolvedTimeLimitMs !== null ? Math.min(resolvedTimeLimitMs + TIME_LIMIT_BACKSTOP_MS, MAX_SET_TIMEOUT_MS) : 0;
|
|
146
|
+
}
|
|
147
|
+
function trimDecimal(value) {
|
|
148
|
+
return Number(value.toFixed(1)).toString();
|
|
149
|
+
}
|
|
150
|
+
function formatApproxTokens(tokens) {
|
|
151
|
+
if (tokens >= 1_000_000)
|
|
152
|
+
return `${trimDecimal(tokens / 1_000_000)}m`;
|
|
153
|
+
if (tokens >= 1_000) {
|
|
154
|
+
const kilos = trimDecimal(tokens / 1_000);
|
|
155
|
+
// toFixed(1) can round up to "1000.0", which would display as "1000k" instead of "1m".
|
|
156
|
+
if (Number(kilos) >= 1000)
|
|
157
|
+
return `${trimDecimal(tokens / 1_000_000)}m`;
|
|
158
|
+
return `${kilos}k`;
|
|
159
|
+
}
|
|
160
|
+
return `${tokens}`;
|
|
161
|
+
}
|
|
162
|
+
/** `1h30min`, `30min`, `90s` → `1min30s`: the one spelling of a limit's duration, wherever it
|
|
163
|
+
* is shown (approval, log lines, result text, tool row). */
|
|
164
|
+
export function formatLimitDuration(ms) {
|
|
165
|
+
const totalSeconds = Math.round(ms / 1000);
|
|
166
|
+
const hours = Math.floor(totalSeconds / 3600);
|
|
167
|
+
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
|
168
|
+
const seconds = totalSeconds % 60;
|
|
169
|
+
const parts = [];
|
|
170
|
+
if (hours > 0)
|
|
171
|
+
parts.push(`${hours}h`);
|
|
172
|
+
if (minutes > 0)
|
|
173
|
+
parts.push(`${minutes}min`);
|
|
174
|
+
if (seconds > 0 || parts.length === 0)
|
|
175
|
+
parts.push(`${seconds}s`);
|
|
176
|
+
return parts.join("");
|
|
177
|
+
}
|
|
178
|
+
function sourceText(source) {
|
|
179
|
+
switch (source) {
|
|
180
|
+
case "prompt":
|
|
181
|
+
return "from your prompt";
|
|
182
|
+
case "tool":
|
|
183
|
+
return "set by the model";
|
|
184
|
+
case "config":
|
|
185
|
+
return "from settings";
|
|
186
|
+
case "none":
|
|
187
|
+
return undefined;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
/** `budget 500k tokens (from your prompt)`, or `no token budget` when absent. */
|
|
191
|
+
export function formatBudgetLimitText(limit) {
|
|
192
|
+
if (limit.value === null)
|
|
193
|
+
return "no token budget";
|
|
194
|
+
const source = sourceText(limit.source);
|
|
195
|
+
return `budget ${formatApproxTokens(limit.value)} tokens${source ? ` (${source})` : ""}`;
|
|
196
|
+
}
|
|
197
|
+
/** `time limit 30min (from your prompt)`, or `no time limit` when absent. */
|
|
198
|
+
export function formatTimeLimitText(limit) {
|
|
199
|
+
if (limit.value === null)
|
|
200
|
+
return "no time limit";
|
|
201
|
+
const source = sourceText(limit.source);
|
|
202
|
+
return `time limit ${formatLimitDuration(limit.value)}${source ? ` (${source})` : ""}`;
|
|
203
|
+
}
|
|
204
|
+
const NO_LIMITS_DISCLAIMER = "no token budget and no time limit: runs until the workflow reaches its goal (add +500k or +30min to your prompt, or set polyphase.defaultBudgetTokens / polyphase.workflowTimeoutMs)";
|
|
205
|
+
const NO_BUDGET_DISCLAIMER = "no token budget (add +500k to your prompt, or set polyphase.defaultBudgetTokens)";
|
|
206
|
+
const NO_TIME_LIMIT_DISCLAIMER = "no time limit (add +30min to your prompt, or set polyphase.workflowTimeoutMs)";
|
|
207
|
+
/** The disclaimer shown (in the approval prompt, the start narrator line, and the final result
|
|
208
|
+
* text) when one or both limits are absent, naming only the missing one(s) and how to add them.
|
|
209
|
+
* "Runs until the workflow reaches its goal" is only said with neither limit: a time limit alone
|
|
210
|
+
* still ends the run. `undefined` when both are set. */
|
|
211
|
+
export function formatMissingLimitsDisclaimer(limits) {
|
|
212
|
+
const budgetMissing = limits.budgetTokens.value === null;
|
|
213
|
+
const timeMissing = limits.timeLimitMs.value === null;
|
|
214
|
+
if (budgetMissing && timeMissing)
|
|
215
|
+
return NO_LIMITS_DISCLAIMER;
|
|
216
|
+
if (budgetMissing)
|
|
217
|
+
return NO_BUDGET_DISCLAIMER;
|
|
218
|
+
if (timeMissing)
|
|
219
|
+
return NO_TIME_LIMIT_DISCLAIMER;
|
|
220
|
+
return undefined;
|
|
221
|
+
}
|
|
222
|
+
/** One line summarizing both limits, used identically by the approval prompt, the start narrator
|
|
223
|
+
* log line, and the final result text's `Limits:` line. Each limit is named exactly once: by its
|
|
224
|
+
* value and source when set, by its disclaimer when not. */
|
|
225
|
+
export function formatWorkflowLimitsLine(limits) {
|
|
226
|
+
const budgetMissing = limits.budgetTokens.value === null;
|
|
227
|
+
const timeMissing = limits.timeLimitMs.value === null;
|
|
228
|
+
if (budgetMissing && timeMissing)
|
|
229
|
+
return NO_LIMITS_DISCLAIMER;
|
|
230
|
+
const budget = budgetMissing ? NO_BUDGET_DISCLAIMER : formatBudgetLimitText(limits.budgetTokens);
|
|
231
|
+
const time = timeMissing ? NO_TIME_LIMIT_DISCLAIMER : formatTimeLimitText(limits.timeLimitMs);
|
|
232
|
+
return `${budget} · ${time}`;
|
|
233
|
+
}
|
|
234
|
+
//# sourceMappingURL=limits.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"limits.js","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/limits.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAGpD;;uBAEuB;AACvB,MAAM,CAAC,MAAM,sBAAsB,GAAG,MAAM,CAAC;AAE7C;;8CAE8C;AAC9C,MAAM,CAAC,MAAM,iBAAiB,GAAG,kBAAkB,GAAG,sBAAsB,CAAC;AAiB7E,MAAM,2BAA2B,GAAG,IAAI,CAAC;AAEzC;;qGAEqG;AACrG,MAAM,uBAAuB,GAAG,wCAAwC,CAAC;AAIzE;;mBAEmB;AACnB,SAAS,aAAa,CAAC,EAAU;IAChC,IAAI,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;QAAE,OAAO,SAAS,CAAC;IAChC,OAAO,EAAE,IA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O,oBAAoB,CAAC;IAC/C,IAAI,WAAW;QAAE,OAAO,wBAAwB,CAAC;IACjD,OAAO,SAAS,CAAC;AAClB,CAAC;AAED;;4DAE4D;AAC5D,MAAM,UAAU,wBAAwB,CAAC,MAA8B;IACtE,MAAM,aAAa,GAAG,MAAM,CAAC,YAAY,CAAC,KAAK,KAAK,IAAI,CAAC;IACzD,MAAM,WAAW,GAAG,MAAM,CAAC,WAAW,CAAC,KAAK,KAAK,IAAI,CAAC;IACtD,IAAI,aAAa,IAAI,WAAW;QAAE,OAAO,oBAAoB,CAAC;IAC9D,MAAM,MAAM,GAAG,aAAa,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,qBAAqB,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC;IACjG,MAAM,IAAI,GAAG,WAAW,CAAC,CAAC,CAAC,wBAAwB,CAAC,CAAC,CAAC,mBAAmB,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;IAC9F,OAAO,GAAG,MAAM,MAAM,IAAI,EAAE,CAAC;AAC9B,CAAC","sourcesContent":["/**\n * Workflow token-budget and time-limit directives (D-B): a `+500k`/`+30min`-style token the user\n * types in their own prompt, else a tool/command parameter, else config, else none. See\n * docs/polyphase.md \"Limits\" for the full grammar and precedence.\n */\n\nimport { MAX_SET_TIMEOUT_MS } from \"../settings.ts\";\nimport type { LimitSource } from \"../types.ts\";\n\n/** Extra wall-clock time the hard sandbox deadline keeps past a resolved graceful time limit, so\n * agents already in flight when the limit fires have a window to wind down before the sandbox\n * itself is killed. */\nexport const TIME_LIMIT_BACKSTOP_MS = 60_000;\n\n/** The longest time limit that still fits one `setTimeout` together with its backstop. Node turns\n * any longer delay into 1ms, so an over-long limit would cancel every agent the moment it started;\n * longer requests are capped here instead. */\nexport const MAX_TIME_LIMIT_MS = MAX_SET_TIMEOUT_MS - TIME_LIMIT_BACKSTOP_MS;\n\nexport interface ParsedDirectives {\n\tbudgetTokens: number | null;\n\ttimeLimitMs: number | null;\n}\n\nexport interface ResolvedLimit {\n\tvalue: number | null;\n\tsource: LimitSource;\n}\n\nexport interface ResolvedWorkflowLimits {\n\tbudgetTokens: ResolvedLimit;\n\ttimeLimitMs: ResolvedLimit;\n}\n\nconst MIN_DIRECTIVE_BUDGET_TOKENS = 1000;\n\n/** A `+`-prefixed token standing alone as a word: `+` immediately followed by a digit (so `+abc`,\n * `+-5` and a bare `+` never match), bounded by whitespace or the start/end of the string on both\n * sides. One bounded character class per side, no nested quantifiers: linear in the input length. */\nconst DIRECTIVE_TOKEN_PATTERN = /(?<=^|\\s)\\+[0-9][0-9A-Za-z.]*(?=$|\\s)/g;\n\ntype Classified = { kind: \"budget\"; tokens: number } | { kind: \"time\"; ms: number };\n\n/** A zero duration is no time limit at all, so it is not a time directive either (it would show as\n * \"time limit 0s\" while the run ignored it); anything longer than {@link MAX_TIME_LIMIT_MS} is\n * capped to it. */\nfunction timeDirective(ms: number): Classified | undefined {\n\tif (!(ms > 0)) return undefined;\n\treturn { kind: \"time\", ms: Math.min(ms, MAX_TIME_LIMIT_MS) };\n}\n\n/** `rest` is the token's text after the leading `+` (e.g. \"500k\", \"1.5M\", \"30min\", \"1h30min\"). */\nfunction classifyDirectiveBody(rest: string): Classified | undefined {\n\tconst compoundHourMinute = /^(\\d+)(?:h|hr)(\\d+)min$/i.exec(rest);\n\tif (compoundHourMinute) {\n\t\tconst hours = Number(compoundHourMinute[1]);\n\t\tconst minutes = Number(compoundHourMinute[2]);\n\t\treturn timeDirective((hours * 3600 + minutes * 60) * 1000);\n\t}\n\n\t// \"m\"/\"M\" alone is excluded here on purpose: a bare \"m\" suffix means \"million tokens\" (the\n\t// budget grammar below), never \"minutes\" — only the full words \"min\"/\"sec\"/\"hr\" (or \"s\"/\"h\")\n\t// are time units.\n\tconst simpleTime = /^(\\d+)(h|hr|min|sec|s)$/i.exec(rest);\n\tif (simpleTime) {\n\t\tconst amount = Number(simpleTime[1]);\n\t\tconst unit = simpleTime[2].toLowerCase();\n\t\tconst seconds = unit === \"h\" || unit === \"hr\" ? amount * 3600 : unit === \"min\" ? amount * 60 : amount;\n\t\treturn timeDirective(seconds * 1000);\n\t}\n\n\tconst budget = /^(\\d+(?:\\.\\d+)?)([kKmM])?$/.exec(rest);\n\tif (budget) {\n\t\tconst amount = Number.parseFloat(budget[1]);\n\t\tconst suffix = budget[2]?.toLowerCase();\n\t\tconst multiplier = suffix === \"k\" ? 1_000 : suffix === \"m\" ? 1_000_000 : 1;\n\t\tconst tokens = Math.round(amount * multiplier);\n\t\tif (Number.isSafeInteger(tokens) && tokens >= MIN_DIRECTIVE_BUDGET_TOKENS) return { kind: \"budget\", tokens };\n\t}\n\n\treturn undefined;\n}\n\ninterface DirectiveMatch {\n\ttoken: string;\n\tindex: number;\n\tclassified: Classified;\n}\n\nfunction findDirectives(text: string): DirectiveMatch[] {\n\tconst matches: DirectiveMatch[] = [];\n\tfor (const match of text.matchAll(DIRECTIVE_TOKEN_PATTERN)) {\n\t\tconst classified = classifyDirectiveBody(match[0].slice(1));\n\t\tif (classified && match.index !== undefined) matches.push({ token: match[0], index: match.index, classified });\n\t}\n\treturn matches;\n}\n\n/** The first `+500k`/`+1.5M`/`+200000`-style token (min 1000 tokens) and the first\n * `+30min`/`+2h`/`+90s`/`+1h30min`-style token anywhere in `text`, each independent of the other. */\nexport function parsePromptDirectives(text: string): ParsedDirectives {\n\tconst result: ParsedDirectives = { budgetTokens: null, timeLimitMs: null };\n\tfor (const match of findDirectives(text)) {\n\t\tif (match.classified.kind === \"budget\" && result.budgetTokens === null)\n\t\t\tresult.budgetTokens = match.classified.tokens;\n\t\tif (match.classified.kind === \"time\" && result.timeLimitMs === null) result.timeLimitMs = match.classified.ms;\n\t\tif (result.budgetTokens !== null && result.timeLimitMs !== null) break;\n\t}\n\treturn result;\n}\n\n/** Removes every recognized directive token from `text` (e.g. command args) by cutting out the\n * matched positions, not by a substring replace: a glued, non-standalone occurrence (e.g. the\n * `+500k` inside `v+500k`) was never matched by `findDirectives` and is left untouched, and a\n * standalone token that happens to be a textual prefix of another standalone token (e.g. `+1000`\n * inside `+10000`) only removes its own matched span. Collapses the whitespace immediately next to\n * each removed span, not every run of whitespace in `text`. A `+`-token that didn't classify (too\n * small, malformed unit) is left untouched — it was never a directive. */\nexport function stripPromptDirectives(text: string): string {\n\tconst matches = findDirectives(text).sort((a, b) => b.index - a.index);\n\tif (matches.length === 0) return text;\n\tlet result = text;\n\tfor (const match of matches) {\n\t\tconst before = result.slice(0, match.index);\n\t\tconst after = result.slice(match.index + match.token.length);\n\t\tconst beforeTrimmed = before.replace(/[ \\t]+$/, \"\");\n\t\tconst afterTrimmed = after.replace(/^[ \\t]+/, \"\");\n\t\tconst hadAdjacentSpace = beforeTrimmed.length !== before.length || afterTrimmed.length !== after.length;\n\t\tconst joiner = beforeTrimmed.length === 0 || afterTrimmed.length === 0 ? \"\" : hadAdjacentSpace ? \" \" : \"\";\n\t\tresult = beforeTrimmed + joiner + afterTrimmed;\n\t}\n\treturn result.trim();\n}\n\n/** Same grammar as the budget/time directive bodies, without the leading `+`: used for the\n * `timeLimit` tool parameter. `undefined` when `text` is not a valid duration. */\nexport function parseDurationMs(text: string): number | undefined {\n\tconst classified = classifyDirectiveBody(text);\n\treturn classified?.kind === \"time\" ? classified.ms : undefined;\n}\n\nfunction resolve(\n\tprompt: number | null | undefined,\n\ttool: number | null | undefined,\n\tconfig: number | null,\n): ResolvedLimit {\n\tif (prompt !== null && prompt !== undefined) return { value: prompt, source: \"prompt\" };\n\tif (tool !== null && tool !== undefined) return { value: tool, source: \"tool\" };\n\tif (config !== null) return { value: config, source: \"config\" };\n\treturn { value: null, source: \"none\" };\n}\n\n/** A steer or follow-up typed while a turn runs (`streamingBehavior` set) only adds what it states:\n * `update`'s limits over `base`'s, keeping `base`'s where `update` names none. A prompt that starts a\n * turn replaces the directives instead (the caller decides which). */\nexport function mergePromptDirectives(base: ParsedDirectives | undefined, update: ParsedDirectives): ParsedDirectives {\n\treturn {\n\t\tbudgetTokens: update.budgetTokens ?? base?.budgetTokens ?? null,\n\t\ttimeLimitMs: update.timeLimitMs ?? base?.timeLimitMs ?? null,\n\t};\n}\n\nexport interface ResolveWorkflowLimitsOptions {\n\tprompt?: ParsedDirectives;\n\ttool?: { budgetTokens?: number | null; timeLimitMs?: number | null };\n\tconfig: { budgetTokens: number | null; timeLimitMs: number | null };\n}\n\n/** Same cap as a directive's, for a time limit from config, whose own clamp allows the full\n * `setTimeout` range and leaves no room for the backstop. */\nfunction capTimeLimit(ms: number | null | undefined): number | null | undefined {\n\treturn typeof ms === \"number\" ? Math.min(ms, MAX_TIME_LIMIT_MS) : ms;\n}\n\n/** Precedence, independently for the token budget and the time limit: prompt directive, else tool\n * parameter, else config, else none. */\nexport function resolveWorkflowLimits(options: ResolveWorkflowLimitsOptions): ResolvedWorkflowLimits {\n\treturn {\n\t\tbudgetTokens: resolve(options.prompt?.budgetTokens, options.tool?.budgetTokens, options.config.budgetTokens),\n\t\ttimeLimitMs: resolve(\n\t\t\tcapTimeLimit(options.prompt?.timeLimitMs),\n\t\t\tcapTimeLimit(options.tool?.timeLimitMs),\n\t\t\tcapTimeLimit(options.config.timeLimitMs) ?? null,\n\t\t),\n\t};\n}\n\n/** The sandbox's own hard deadline: `timeLimitMs + 60s` when a time limit resolved, else disabled\n * (0). There is no separate \"config\" hard-timeout concept anymore — `polyphase.workflowTimeoutMs`\n * is itself one of the possible sources of the graceful time limit above. Never past what one\n * `setTimeout` can wait. */\nexport function hardSandboxTimeoutMs(resolvedTimeLimitMs: number | null): number {\n\treturn resolvedTimeLimitMs !== null ? Math.min(resolvedTimeLimitMs + TIME_LIMIT_BACKSTOP_MS, MAX_SET_TIMEOUT_MS) : 0;\n}\n\nfunction trimDecimal(value: number): string {\n\treturn Number(value.toFixed(1)).toString();\n}\n\nfunction formatApproxTokens(tokens: number): string {\n\tif (tokens >= 1_000_000) return `${trimDecimal(tokens / 1_000_000)}m`;\n\tif (tokens >= 1_000) {\n\t\tconst kilos = trimDecimal(tokens / 1_000);\n\t\t// toFixed(1) can round up to \"1000.0\", which would display as \"1000k\" instead of \"1m\".\n\t\tif (Number(kilos) >= 1000) return `${trimDecimal(tokens / 1_000_000)}m`;\n\t\treturn `${kilos}k`;\n\t}\n\treturn `${tokens}`;\n}\n\n/** `1h30min`, `30min`, `90s` → `1min30s`: the one spelling of a limit's duration, wherever it\n * is shown (approval, log lines, result text, tool row). */\nexport function formatLimitDuration(ms: number): string {\n\tconst totalSeconds = Math.round(ms / 1000);\n\tconst hours = Math.floor(totalSeconds / 3600);\n\tconst minutes = Math.floor((totalSeconds % 3600) / 60);\n\tconst seconds = totalSeconds % 60;\n\tconst parts: string[] = [];\n\tif (hours > 0) parts.push(`${hours}h`);\n\tif (minutes > 0) parts.push(`${minutes}min`);\n\tif (seconds > 0 || parts.length === 0) parts.push(`${seconds}s`);\n\treturn parts.join(\"\");\n}\n\nfunction sourceText(source: LimitSource): string | undefined {\n\tswitch (source) {\n\t\tcase \"prompt\":\n\t\t\treturn \"from your prompt\";\n\t\tcase \"tool\":\n\t\t\treturn \"set by the model\";\n\t\tcase \"config\":\n\t\t\treturn \"from settings\";\n\t\tcase \"none\":\n\t\t\treturn undefined;\n\t}\n}\n\n/** `budget 500k tokens (from your prompt)`, or `no token budget` when absent. */\nexport function formatBudgetLimitText(limit: ResolvedLimit): string {\n\tif (limit.value === null) return \"no token budget\";\n\tconst source = sourceText(limit.source);\n\treturn `budget ${formatApproxTokens(limit.value)} tokens${source ? ` (${source})` : \"\"}`;\n}\n\n/** `time limit 30min (from your prompt)`, or `no time limit` when absent. */\nexport function formatTimeLimitText(limit: ResolvedLimit): string {\n\tif (limit.value === null) return \"no time limit\";\n\tconst source = sourceText(limit.source);\n\treturn `time limit ${formatLimitDuration(limit.value)}${source ? ` (${source})` : \"\"}`;\n}\n\nconst NO_LIMITS_DISCLAIMER =\n\t\"no token budget and no time limit: runs until the workflow reaches its goal (add +500k or +30min to your prompt, or set polyphase.defaultBudgetTokens / polyphase.workflowTimeoutMs)\";\nconst NO_BUDGET_DISCLAIMER = \"no token budget (add +500k to your prompt, or set polyphase.defaultBudgetTokens)\";\nconst NO_TIME_LIMIT_DISCLAIMER = \"no time limit (add +30min to your prompt, or set polyphase.workflowTimeoutMs)\";\n\n/** The disclaimer shown (in the approval prompt, the start narrator line, and the final result\n * text) when one or both limits are absent, naming only the missing one(s) and how to add them.\n * \"Runs until the workflow reaches its goal\" is only said with neither limit: a time limit alone\n * still ends the run. `undefined` when both are set. */\nexport function formatMissingLimitsDisclaimer(limits: ResolvedWorkflowLimits): string | undefined {\n\tconst budgetMissing = limits.budgetTokens.value === null;\n\tconst timeMissing = limits.timeLimitMs.value === null;\n\tif (budgetMissing && timeMissing) return NO_LIMITS_DISCLAIMER;\n\tif (budgetMissing) return NO_BUDGET_DISCLAIMER;\n\tif (timeMissing) return NO_TIME_LIMIT_DISCLAIMER;\n\treturn undefined;\n}\n\n/** One line summarizing both limits, used identically by the approval prompt, the start narrator\n * log line, and the final result text's `Limits:` line. Each limit is named exactly once: by its\n * value and source when set, by its disclaimer when not. */\nexport function formatWorkflowLimitsLine(limits: ResolvedWorkflowLimits): string {\n\tconst budgetMissing = limits.budgetTokens.value === null;\n\tconst timeMissing = limits.timeLimitMs.value === null;\n\tif (budgetMissing && timeMissing) return NO_LIMITS_DISCLAIMER;\n\tconst budget = budgetMissing ? NO_BUDGET_DISCLAIMER : formatBudgetLimitText(limits.budgetTokens);\n\tconst time = timeMissing ? NO_TIME_LIMIT_DISCLAIMER : formatTimeLimitText(limits.timeLimitMs);\n\treturn `${budget} · ${time}`;\n}\n"]}
|
|
@@ -24,7 +24,7 @@ export type WorkflowAgentReply = {
|
|
|
24
24
|
value: JsonValue;
|
|
25
25
|
} | {
|
|
26
26
|
kind: "null";
|
|
27
|
-
reason: "failed" | "cancelled" | "budget" | "no-structured-output";
|
|
27
|
+
reason: "failed" | "cancelled" | "budget" | "time" | "no-structured-output";
|
|
28
28
|
message?: string;
|
|
29
29
|
} | {
|
|
30
30
|
kind: "error";
|
|
@@ -1 +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,MAAM,CAAA;CAAE,
|
|
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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CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;QAClE,CAAC;KACD,CAAC;IAEF,MAAM,OAAO,GAAG,IAAI,eAAe,CAAC;QACnC,OAAO,EAAE,CAAC,WAAW,EAAE,WAAW,EAAE,SAAS,CAAC;QAC9C,SAAS,EAAE,IAAI,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,iBAAiB;QACzE,gBAAgB,EAAE,IAAI,CAAC,gBAAgB,IAAI,0BAA0B;QACrE,cAAc,EAAE,IAAI,CAAC,cAAc,IAAI,wBAAwB;QAC/D,IAAI,EAAE,IAAI,CAAC,OAAO,EAAE,IAAI,IAAI,eAAe,CAAC,kBAAkB,EAAE,CAAC;QACjE,SAAS,EAAE,IAAI,CAAC,OAAO,EAAE,SAAS,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"]}
|
|
1
|
+
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/runtime.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAA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MAAM,CAAC,KAAK,CAAC,CAAC;YAC/D,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;QAClE,CAAC;KACD,CAAC;IAEF,MAAM,OAAO,GAAG,IAAI,eAAe,CAAC;QACnC,OAAO,EAAE,CAAC,WAAW,EAAE,WAAW,EAAE,SAAS,CAAC;QAC9C,SAAS,EAAE,IAAI,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,iBAAiB;QACzE,gBAAgB,EAAE,IAAI,CAAC,gBAAgB,IAAI,0BAA0B;QACrE,cAAc,EAAE,IAAI,CAAC,cAAc,IAAI,wBAAwB;QAC/D,IAAI,EAAE,IAAI,CAAC,OAAO,EAAE,IAAI,IAAI,eAAe,CAAC,kBAAkB,EAAE,CAAC;QACjE,SAAS,EAAE,IAAI,CAAC,OAAO,EAAE,SAAS,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\" | \"time\" | \"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"]}
|
|
@@ -11,6 +11,7 @@ declare const WorkflowParams: import("@sinclair/typebox").TObject<{
|
|
|
11
11
|
name: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TString>;
|
|
12
12
|
args: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TString>;
|
|
13
13
|
budgetTokens: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TInteger>;
|
|
14
|
+
timeLimit: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TString>;
|
|
14
15
|
}>;
|
|
15
16
|
/** Early errors (unknown name, invalid meta, wrong arguments) return before a run exists. */
|
|
16
17
|
type WorkflowToolDetails = PolyphaseDetails | Record<string, never>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool.d.ts","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/tool.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,KAAK,EAAmB,gBAAgB,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAEnG,OAAO,EAA2B,KAAK,mBAAmB,EAAE,KAAK,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AACnH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EACN,KAAK,WAAW,EAEhB,KAAK,gBAAgB,EAGrB,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"tool.d.ts","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/tool.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,KAAK,EAAmB,gBAAgB,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAEnG,OAAO,EAA2B,KAAK,mBAAmB,EAAE,KAAK,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AACnH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EACN,KAAK,WAAW,EAEhB,KAAK,gBAAgB,EAGrB,MAAM,aAAa,CAAC;AAOrB,QAAA,MAAM,cAAc;;;;;;EA8BlB,CAAC;AAEH,6FAA6F;AAC7F,KAAK,mBAAmB,GAAG,gBAAgB,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;AAEpE,MAAM,WAAW,gBAAgB;IAChC,UAAU,CAAC,GAAG,EAAE,gBAAgB,GAAG,gBAAgB,CAAC;IACpD,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,UAAU,EAAE,mBAAmB,CAAC;CAChC;AAMD,wBAAgB,4BAA4B,CAC3C,IAAI,EAAE,gBAAgB,GACpB,cAAc,CAAC,OAAO,cAAc,EAAE,mBAAmB,EAAE,iBAAiB,CAAC,CA+H/E"}
|
|
@@ -9,6 +9,7 @@ import { createWorkflowRenderers } from "../render/renderers.js";
|
|
|
9
9
|
import { currentPolyphaseDepth, WORKFLOW_TOOL_NAME, } from "../types.js";
|
|
10
10
|
import { WORKFLOW_PROMPT_GUIDELINES, WORKFLOW_PROMPT_SNIPPET, WORKFLOW_TOOL_DESCRIPTION } from "./guidance.js";
|
|
11
11
|
import { startWorkflowRun } from "./launch.js";
|
|
12
|
+
import { parseDurationMs, resolveWorkflowLimits } from "./limits.js";
|
|
12
13
|
import { extractWorkflowMeta } from "./meta.js";
|
|
13
14
|
import { discoverSavedWorkflows, findSavedWorkflow, readSavedWorkflowSource } from "./saved.js";
|
|
14
15
|
const WorkflowParams = Type.Object({
|
|
@@ -21,7 +22,13 @@ const WorkflowParams = Type.Object({
|
|
|
21
22
|
args: Type.Optional(Type.String({ description: "Input passed verbatim to the script as `args`" })),
|
|
22
23
|
budgetTokens: Type.Optional(Type.Integer({
|
|
23
24
|
minimum: 1000,
|
|
24
|
-
description: "Hard ceiling on billable tokens
|
|
25
|
+
description: "Hard ceiling on billable tokens across all agents of this run. Set this ONLY when the user stated a " +
|
|
26
|
+
'limit in words (e.g. "at most 300k tokens"); never invent one.',
|
|
27
|
+
})),
|
|
28
|
+
timeLimit: Type.Optional(Type.String({
|
|
29
|
+
description: 'Wall-clock time limit for this run, e.g. "30min", "2h", "1h30min". Set this ONLY when the user stated ' +
|
|
30
|
+
'a limit in words (e.g. "stop after 20 minutes"); never invent one. Past the limit, the run cancels ' +
|
|
31
|
+
"running/queued agents and finishes with partial results.",
|
|
25
32
|
})),
|
|
26
33
|
});
|
|
27
34
|
function errorResult(text) {
|
|
@@ -47,8 +54,22 @@ export function createWorkflowToolDefinition(deps) {
|
|
|
47
54
|
if (currentPolyphaseDepth() >= 1) {
|
|
48
55
|
return errorResult("The workflow tool is not available to subagents.");
|
|
49
56
|
}
|
|
57
|
+
if (params.timeLimit !== undefined && parseDurationMs(params.timeLimit) === undefined) {
|
|
58
|
+
return errorResult(`timeLimit "${params.timeLimit}" is not a valid duration. Use e.g. "30min", "2h", "90s", "1h30min".`);
|
|
59
|
+
}
|
|
50
60
|
const session = deps.getSession(ctx);
|
|
51
61
|
const settings = session.settings();
|
|
62
|
+
const limits = resolveWorkflowLimits({
|
|
63
|
+
prompt: session.pendingDirectives(),
|
|
64
|
+
tool: {
|
|
65
|
+
budgetTokens: params.budgetTokens,
|
|
66
|
+
timeLimitMs: params.timeLimit !== undefined ? parseDurationMs(params.timeLimit) : undefined,
|
|
67
|
+
},
|
|
68
|
+
config: {
|
|
69
|
+
budgetTokens: settings.defaultBudgetTokens,
|
|
70
|
+
timeLimitMs: settings.workflowTimeoutMs > 0 ? settings.workflowTimeoutMs : null,
|
|
71
|
+
},
|
|
72
|
+
});
|
|
52
73
|
let source;
|
|
53
74
|
let sourceInfo;
|
|
54
75
|
if (params.script !== undefined) {
|
|
@@ -93,7 +114,7 @@ export function createWorkflowToolDefinition(deps) {
|
|
|
93
114
|
body: extraction.body,
|
|
94
115
|
args: params.args ?? "",
|
|
95
116
|
source: sourceInfo,
|
|
96
|
-
|
|
117
|
+
limits,
|
|
97
118
|
runner: deps.runner,
|
|
98
119
|
});
|
|
99
120
|
// §13.1: unknown meta keys (e.g. a typo'd phase field) produce warnings instead of
|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AAE,UAAU,CAAC,OAAO;oBAC3B,KAAK,EAAE,UAAU,CAAC,KAAK;oBACvB,OAAO,EAAE,UAAU,CAAC,OAAO;iBAC3B,CAAC;YACH,CAAC;YACD,IAAI,CAAC;gBACJ,MAAM,UAAU,GAAG,MAAM,MAAM,CAAC,IAAI,CAAC;gBACrC,OAAO;oBACN,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,CAAC,IAAI,EAAE,CAAC;oBAClD,OAAO,EAAE,UAAU,CAAC,OAAO;oBAC3B,KAAK,EAAE,UAAU,CAAC,KAAK;oBACvB,OAAO,EAAE,UAAU,CAAC,OAAO;iBAC3B,CAAC;YACH,CAAC;oBAAS,CAAC;gBACV,OAAO,CAAC,OAAO,EAAE,CAAC;YACnB,CAAC;QACF,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["/**\n * The `workflow` tool definition (§14.1): model-only, defaultActive false, registered lazily by\n * `builtins/polyphase.ts` the first time the keyword or a resumed session needs it.\n */\n\nimport { Type } from \"@sinclair/typebox\";\nimport { getAgentDir } from \"../../../config.ts\";\nimport type { AgentToolResult, ExtensionContext, ToolDefinition } from \"../../extensions/types.ts\";\nimport { createPartialUpdateEmitter, type PartialUpdateEmitter } from \"../emitter.ts\";\nimport { createWorkflowRenderers, type PolyphaseRenderDeps, type PolyphaseRowState } from \"../render/renderers.ts\";\nimport type { PolyphaseSession } from \"../session.ts\";\nimport {\n\ttype AgentRunner,\n\tcurrentPolyphaseDepth,\n\ttype PolyphaseDetails,\n\tWORKFLOW_TOOL_NAME,\n\ttype WorkflowSource,\n} from \"../types.ts\";\nimport { WORKFLOW_PROMPT_GUIDELINES, WORKFLOW_PROMPT_SNIPPET, WORKFLOW_TOOL_DESCRIPTION } from \"./guidance.ts\";\nimport { startWorkflowRun } from \"./launch.ts\";\nimport { extractWorkflowMeta } from \"./meta.ts\";\nimport { discoverSavedWorkflows, findSavedWorkflow, readSavedWorkflowSource } from \"./saved.ts\";\n\nconst WorkflowParams = Type.Object({\n\tscript: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t\"Workflow script: `export const meta = {...}` first, then an async body using agent, parallel, pipeline, phase, log, args, budget\",\n\t\t}),\n\t),\n\tname: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t\"Run a saved workflow (.draht/workflows/<name>.js or <agentDir>/workflows/<name>.js) instead of an inline script\",\n\t\t}),\n\t),\n\targs: Type.Optional(Type.String({ description: \"Input passed verbatim to the script as `args`\" })),\n\tbudgetTokens: Type.Optional(\n\t\tType.Integer({\n\t\t\tminimum: 1000,\n\t\t\tdescription: \"Hard ceiling on billable tokens (input + output + cache writes) across all agents of this run\",\n\t\t}),\n\t),\n});\n\n/** Early errors (unknown name, invalid meta, wrong arguments) return before a run exists. */\ntype WorkflowToolDetails = PolyphaseDetails | Record<string, never>;\n\nexport interface WorkflowToolDeps {\n\tgetSession(ctx: ExtensionContext): PolyphaseSession;\n\trunner?: AgentRunner;\n\trenderDeps: PolyphaseRenderDeps;\n}\n\nfunction errorResult(text: string): AgentToolResult<WorkflowToolDetails> {\n\treturn { content: [{ type: \"text\", text }], details: {}, isError: true };\n}\n\nexport function createWorkflowToolDefinition(\n\tdeps: WorkflowToolDeps,\n): ToolDefinition<typeof WorkflowParams, WorkflowToolDetails, PolyphaseRowState> {\n\tconst renderers = createWorkflowRenderers(deps.renderDeps);\n\n\treturn {\n\t\tname: WORKFLOW_TOOL_NAME,\n\t\tlabel: \"Workflow\",\n\t\tdescription: WORKFLOW_TOOL_DESCRIPTION,\n\t\tpromptSnippet: WORKFLOW_PROMPT_SNIPPET,\n\t\tpromptGuidelines: [...WORKFLOW_PROMPT_GUIDELINES],\n\t\tparameters: WorkflowParams,\n\t\texposure: \"model-only\",\n\t\tdefaultActive: false,\n\t\trenderCall: renderers.renderCall,\n\t\trenderResult: renderers.renderResult,\n\n\t\tasync execute(toolCallId, params, signal, onUpdate, ctx) {\n\t\t\tif ((params.script === undefined) === (params.name === undefined)) {\n\t\t\t\treturn errorResult(\"Exactly one of `script` or `name` must be given.\");\n\t\t\t}\n\t\t\tif (currentPolyphaseDepth() >= 1) {\n\t\t\t\treturn errorResult(\"The workflow tool is not available to subagents.\");\n\t\t\t}\n\n\t\t\tconst session = deps.getSession(ctx);\n\t\t\tconst settings = session.settings();\n\n\t\t\tlet source: string;\n\t\t\tlet sourceInfo: { kind: WorkflowSource; path?: string };\n\t\t\tif (params.script !== undefined) {\n\t\t\t\tsource = params.script;\n\t\t\t\tsourceInfo = { kind: \"inline\" };\n\t\t\t} else if (params.name !== undefined) {\n\t\t\t\tconst discovery = {\n\t\t\t\t\tcwd: ctx.cwd,\n\t\t\t\t\tagentDir: getAgentDir(),\n\t\t\t\t\tprojectTrusted: ctx.isProjectTrusted(),\n\t\t\t\t};\n\t\t\t\tconst found = findSavedWorkflow(params.name, discovery);\n\t\t\t\tif (!found) {\n\t\t\t\t\tconst names = discoverSavedWorkflows(discovery)\n\t\t\t\t\t\t.workflows.map((workflow) => workflow.name)\n\t\t\t\t\t\t.join(\", \");\n\t\t\t\t\treturn errorResult(`Unknown saved workflow \"${params.name}\". Available: ${names || \"(none)\"}`);\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tsource = readSavedWorkflowSource(found);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn errorResult(error instanceof Error ? error.message : String(error));\n\t\t\t\t}\n\t\t\t\tsourceInfo = { kind: found.source, path: found.path };\n\t\t\t} else {\n\t\t\t\treturn errorResult(\"Exactly one of `script` or `name` must be given.\");\n\t\t\t}\n\n\t\t\tconst extraction = extractWorkflowMeta(source);\n\t\t\tif (!extraction.ok) {\n\t\t\t\treturn errorResult(\n\t\t\t\t\t`Workflow meta is invalid at line ${extraction.error.line}, column ${extraction.error.column}: ${extraction.error.message}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst handle = startWorkflowRun({\n\t\t\t\tctx,\n\t\t\t\tsession,\n\t\t\t\tid: toolCallId,\n\t\t\t\torigin: \"tool\",\n\t\t\t\tparentSignal: signal,\n\t\t\t\tmeta: extraction.meta,\n\t\t\t\tbody: extraction.body,\n\t\t\t\targs: params.args ?? \"\",\n\t\t\t\tsource: sourceInfo,\n\t\t\t\tbudgetTokens: params.budgetTokens ?? settings.defaultBudgetTokens,\n\t\t\t\trunner: deps.runner,\n\t\t\t});\n\t\t\t// §13.1: unknown meta keys (e.g. a typo'd phase field) produce warnings instead of\n\t\t\t// failing the run; without this they are silently discarded, with no sign anywhere that\n\t\t\t// the key was ignored.\n\t\t\tfor (const warning of extraction.warnings) handle.run.appendLog(warning, \"warning\");\n\n\t\t\tlet emitter: PartialUpdateEmitter;\n\t\t\ttry {\n\t\t\t\temitter = createPartialUpdateEmitter(handle.run, onUpdate, {\n\t\t\t\t\tmode: ctx.mode,\n\t\t\t\t\tliveUpdateMs: settings.liveUpdateMs,\n\t\t\t\t});\n\t\t\t} catch {\n\t\t\t\t// emitNow() runs synchronously inside the emitter's constructor (§10.7); if it throws,\n\t\t\t\t// the run is already under way with no subscriber. Cancel it rather than leaving it to\n\t\t\t\t// spend tokens unobserved, and still report its (failed) completion.\n\t\t\t\thandle.run.cancel(\"run\");\n\t\t\t\tconst completion = await handle.done;\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: completion.text }],\n\t\t\t\t\tdetails: completion.details,\n\t\t\t\t\tusage: completion.usage,\n\t\t\t\t\tisError: completion.isError,\n\t\t\t\t};\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst completion = await handle.done;\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: completion.text }],\n\t\t\t\t\tdetails: completion.details,\n\t\t\t\t\tusage: completion.usage,\n\t\t\t\t\tisError: completion.isError,\n\t\t\t\t};\n\t\t\t} finally {\n\t\t\t\temitter.dispose();\n\t\t\t}\n\t\t},\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"tool.js","sour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OAAO,CAAC,OAAO,EAAE,CAAC;YACnB,CAAC;QACF,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["/**\n * The `workflow` tool definition (§14.1): model-only, defaultActive false, registered lazily by\n * `builtins/polyphase.ts` the first time the keyword or a resumed session needs it.\n */\n\nimport { Type } from \"@sinclair/typebox\";\nimport { getAgentDir } from \"../../../config.ts\";\nimport type { AgentToolResult, ExtensionContext, ToolDefinition } from \"../../extensions/types.ts\";\nimport { createPartialUpdateEmitter, type PartialUpdateEmitter } from \"../emitter.ts\";\nimport { createWorkflowRenderers, type PolyphaseRenderDeps, type PolyphaseRowState } from \"../render/renderers.ts\";\nimport type { PolyphaseSession } from \"../session.ts\";\nimport {\n\ttype AgentRunner,\n\tcurrentPolyphaseDepth,\n\ttype PolyphaseDetails,\n\tWORKFLOW_TOOL_NAME,\n\ttype WorkflowSource,\n} from \"../types.ts\";\nimport { WORKFLOW_PROMPT_GUIDELINES, WORKFLOW_PROMPT_SNIPPET, WORKFLOW_TOOL_DESCRIPTION } from \"./guidance.ts\";\nimport { startWorkflowRun } from \"./launch.ts\";\nimport { parseDurationMs, resolveWorkflowLimits } from \"./limits.ts\";\nimport { extractWorkflowMeta } from \"./meta.ts\";\nimport { discoverSavedWorkflows, findSavedWorkflow, readSavedWorkflowSource } from \"./saved.ts\";\n\nconst WorkflowParams = Type.Object({\n\tscript: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t\"Workflow script: `export const meta = {...}` first, then an async body using agent, parallel, pipeline, phase, log, args, budget\",\n\t\t}),\n\t),\n\tname: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t\"Run a saved workflow (.draht/workflows/<name>.js or <agentDir>/workflows/<name>.js) instead of an inline script\",\n\t\t}),\n\t),\n\targs: Type.Optional(Type.String({ description: \"Input passed verbatim to the script as `args`\" })),\n\tbudgetTokens: Type.Optional(\n\t\tType.Integer({\n\t\t\tminimum: 1000,\n\t\t\tdescription:\n\t\t\t\t\"Hard ceiling on billable tokens across all agents of this run. Set this ONLY when the user stated a \" +\n\t\t\t\t'limit in words (e.g. \"at most 300k tokens\"); never invent one.',\n\t\t}),\n\t),\n\ttimeLimit: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t'Wall-clock time limit for this run, e.g. \"30min\", \"2h\", \"1h30min\". Set this ONLY when the user stated ' +\n\t\t\t\t'a limit in words (e.g. \"stop after 20 minutes\"); never invent one. Past the limit, the run cancels ' +\n\t\t\t\t\"running/queued agents and finishes with partial results.\",\n\t\t}),\n\t),\n});\n\n/** Early errors (unknown name, invalid meta, wrong arguments) return before a run exists. */\ntype WorkflowToolDetails = PolyphaseDetails | Record<string, never>;\n\nexport interface WorkflowToolDeps {\n\tgetSession(ctx: ExtensionContext): PolyphaseSession;\n\trunner?: AgentRunner;\n\trenderDeps: PolyphaseRenderDeps;\n}\n\nfunction errorResult(text: string): AgentToolResult<WorkflowToolDetails> {\n\treturn { content: [{ type: \"text\", text }], details: {}, isError: true };\n}\n\nexport function createWorkflowToolDefinition(\n\tdeps: WorkflowToolDeps,\n): ToolDefinition<typeof WorkflowParams, WorkflowToolDetails, PolyphaseRowState> {\n\tconst renderers = createWorkflowRenderers(deps.renderDeps);\n\n\treturn {\n\t\tname: WORKFLOW_TOOL_NAME,\n\t\tlabel: \"Workflow\",\n\t\tdescription: WORKFLOW_TOOL_DESCRIPTION,\n\t\tpromptSnippet: WORKFLOW_PROMPT_SNIPPET,\n\t\tpromptGuidelines: [...WORKFLOW_PROMPT_GUIDELINES],\n\t\tparameters: WorkflowParams,\n\t\texposure: \"model-only\",\n\t\tdefaultActive: false,\n\t\trenderCall: renderers.renderCall,\n\t\trenderResult: renderers.renderResult,\n\n\t\tasync execute(toolCallId, params, signal, onUpdate, ctx) {\n\t\t\tif ((params.script === undefined) === (params.name === undefined)) {\n\t\t\t\treturn errorResult(\"Exactly one of `script` or `name` must be given.\");\n\t\t\t}\n\t\t\tif (currentPolyphaseDepth() >= 1) {\n\t\t\t\treturn errorResult(\"The workflow tool is not available to subagents.\");\n\t\t\t}\n\t\t\tif (params.timeLimit !== undefined && parseDurationMs(params.timeLimit) === undefined) {\n\t\t\t\treturn errorResult(\n\t\t\t\t\t`timeLimit \"${params.timeLimit}\" is not a valid duration. Use e.g. \"30min\", \"2h\", \"90s\", \"1h30min\".`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst session = deps.getSession(ctx);\n\t\t\tconst settings = session.settings();\n\t\t\tconst limits = resolveWorkflowLimits({\n\t\t\t\tprompt: session.pendingDirectives(),\n\t\t\t\ttool: {\n\t\t\t\t\tbudgetTokens: params.budgetTokens,\n\t\t\t\t\ttimeLimitMs: params.timeLimit !== undefined ? parseDurationMs(params.timeLimit) : undefined,\n\t\t\t\t},\n\t\t\t\tconfig: {\n\t\t\t\t\tbudgetTokens: settings.defaultBudgetTokens,\n\t\t\t\t\ttimeLimitMs: settings.workflowTimeoutMs > 0 ? settings.workflowTimeoutMs : null,\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tlet source: string;\n\t\t\tlet sourceInfo: { kind: WorkflowSource; path?: string };\n\t\t\tif (params.script !== undefined) {\n\t\t\t\tsource = params.script;\n\t\t\t\tsourceInfo = { kind: \"inline\" };\n\t\t\t} else if (params.name !== undefined) {\n\t\t\t\tconst discovery = {\n\t\t\t\t\tcwd: ctx.cwd,\n\t\t\t\t\tagentDir: getAgentDir(),\n\t\t\t\t\tprojectTrusted: ctx.isProjectTrusted(),\n\t\t\t\t};\n\t\t\t\tconst found = findSavedWorkflow(params.name, discovery);\n\t\t\t\tif (!found) {\n\t\t\t\t\tconst names = discoverSavedWorkflows(discovery)\n\t\t\t\t\t\t.workflows.map((workflow) => workflow.name)\n\t\t\t\t\t\t.join(\", \");\n\t\t\t\t\treturn errorResult(`Unknown saved workflow \"${params.name}\". Available: ${names || \"(none)\"}`);\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tsource = readSavedWorkflowSource(found);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn errorResult(error instanceof Error ? error.message : String(error));\n\t\t\t\t}\n\t\t\t\tsourceInfo = { kind: found.source, path: found.path };\n\t\t\t} else {\n\t\t\t\treturn errorResult(\"Exactly one of `script` or `name` must be given.\");\n\t\t\t}\n\n\t\t\tconst extraction = extractWorkflowMeta(source);\n\t\t\tif (!extraction.ok) {\n\t\t\t\treturn errorResult(\n\t\t\t\t\t`Workflow meta is invalid at line ${extraction.error.line}, column ${extraction.error.column}: ${extraction.error.message}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst handle = startWorkflowRun({\n\t\t\t\tctx,\n\t\t\t\tsession,\n\t\t\t\tid: toolCallId,\n\t\t\t\torigin: \"tool\",\n\t\t\t\tparentSignal: signal,\n\t\t\t\tmeta: extraction.meta,\n\t\t\t\tbody: extraction.body,\n\t\t\t\targs: params.args ?? \"\",\n\t\t\t\tsource: sourceInfo,\n\t\t\t\tlimits,\n\t\t\t\trunner: deps.runner,\n\t\t\t});\n\t\t\t// §13.1: unknown meta keys (e.g. a typo'd phase field) produce warnings instead of\n\t\t\t// failing the run; without this they are silently discarded, with no sign anywhere that\n\t\t\t// the key was ignored.\n\t\t\tfor (const warning of extraction.warnings) handle.run.appendLog(warning, \"warning\");\n\n\t\t\tlet emitter: PartialUpdateEmitter;\n\t\t\ttry {\n\t\t\t\temitter = createPartialUpdateEmitter(handle.run, onUpdate, {\n\t\t\t\t\tmode: ctx.mode,\n\t\t\t\t\tliveUpdateMs: settings.liveUpdateMs,\n\t\t\t\t});\n\t\t\t} catch {\n\t\t\t\t// emitNow() runs synchronously inside the emitter's constructor (§10.7); if it throws,\n\t\t\t\t// the run is already under way with no subscriber. Cancel it rather than leaving it to\n\t\t\t\t// spend tokens unobserved, and still report its (failed) completion.\n\t\t\t\thandle.run.cancel(\"run\");\n\t\t\t\tconst completion = await handle.done;\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: completion.text }],\n\t\t\t\t\tdetails: completion.details,\n\t\t\t\t\tusage: completion.usage,\n\t\t\t\t\tisError: completion.isError,\n\t\t\t\t};\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst completion = await handle.done;\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: completion.text }],\n\t\t\t\t\tdetails: completion.details,\n\t\t\t\t\tusage: completion.usage,\n\t\t\t\t\tisError: completion.isError,\n\t\t\t\t};\n\t\t\t} finally {\n\t\t\t\temitter.dispose();\n\t\t\t}\n\t\t},\n\t};\n}\n"]}
|
|
@@ -7,6 +7,11 @@ export interface UsageTotals {
|
|
|
7
7
|
cacheWrite: number;
|
|
8
8
|
cost: number;
|
|
9
9
|
}
|
|
10
|
+
/** Finite-number guard for a `Usage` value from an untrusted source (e.g. a child process):
|
|
11
|
+
* `addUsageToTotals`/`combineUsage` add these fields with no validation of their own, so a
|
|
12
|
+
* malformed value (missing `cost`, a `NaN` field) corrupts every totals computation it touches
|
|
13
|
+
* from then on, including a persisted session's totals on every future resume. */
|
|
14
|
+
export declare function isValidUsage(value: unknown): value is Usage;
|
|
10
15
|
export declare function createUsageTotals(): UsageTotals;
|
|
11
16
|
export declare function addUsageToTotals(totals: UsageTotals, usage: Usage): void;
|
|
12
17
|
/** Sum of two usages, keeping the optional token splits when either side reports them. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"usage-totals.d.ts","sourceRoot":"","sources":["../../src/core/usage-totals.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAEzD,MAAM,WAAW,WAAW;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;CACb;AAED,wBAAgB,i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MAAM,EAAE,MAAM,CAAC;CACf;AAED,wFAAwF;AACxF,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,uBAAuB,EAAE,CAoCxF"}
|
|
@@ -1,3 +1,19 @@
|
|
|
1
|
+
/** Finite-number guard for a `Usage` value from an untrusted source (e.g. a child process):
|
|
2
|
+
* `addUsageToTotals`/`combineUsage` add these fields with no validation of their own, so a
|
|
3
|
+
* malformed value (missing `cost`, a `NaN` field) corrupts every totals computation it touches
|
|
4
|
+
* from then on, including a persisted session's totals on every future resume. */
|
|
5
|
+
export function isValidUsage(value) {
|
|
6
|
+
if (typeof value !== "object" || value === null)
|
|
7
|
+
return false;
|
|
8
|
+
const u = value;
|
|
9
|
+
if (![u.input, u.output, u.cacheRead, u.cacheWrite, u.totalTokens].every((n) => typeof n === "number" && Number.isFinite(n))) {
|
|
10
|
+
return false;
|
|
11
|
+
}
|
|
12
|
+
if (typeof u.cost !== "object" || u.cost === null)
|
|
13
|
+
return false;
|
|
14
|
+
const cost = u.cost;
|
|
15
|
+
return [cost.input, cost.output, cost.cacheRead, cost.cacheWrite, cost.total].every((n) => typeof n === "number" && Number.isFinite(n));
|
|
16
|
+
}
|
|
1
17
|
export function createUsageTotals() {
|
|
2
18
|
return {
|
|
3
19
|
input: 0,
|