@draht/coding-agent 2026.10.4-3 → 2026.10.8-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 +13 -0
- package/README.md +32 -6
- package/dist/bundle/chunks/anthropic.js +1 -1
- package/dist/bundle/chunks/{chunk-JTLUBTZT.js → chunk-6QIFWMDF.js} +1 -1
- package/dist/bundle/chunks/{chunk-AFL4IDSI.js → chunk-AHGUOQPH.js} +2 -2
- package/dist/bundle/chunks/{chunk-VPYAVQLP.js → chunk-BOGY4QVF.js} +4 -4
- package/dist/bundle/chunks/chunk-GD2WVXWT.js +65 -0
- package/dist/bundle/chunks/{chunk-3HF756LN.js → chunk-KJJJSTND.js} +292 -153
- package/dist/bundle/chunks/chunk-PGJAHC3R.js +107 -0
- package/dist/bundle/chunks/chunk-QVFELZW2.js +312 -0
- package/dist/bundle/chunks/{chunk-V5HG6S2T.js → chunk-QVTLBSTH.js} +1 -1
- package/dist/bundle/chunks/{chunk-A4OX5CPR.js → chunk-U6LDZZGM.js} +1 -1
- package/dist/bundle/chunks/{chunk-XO3IECI5.js → chunk-VQOV5VFH.js} +1 -1
- package/dist/bundle/chunks/{cli-L74YA5GF.js → cli-O6OWCY7N.js} +1 -1
- package/dist/bundle/chunks/execute-4JU5WQXP.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-RYUR6LRB.js → runtime-FIGQHW75.js} +1 -1
- package/dist/bundle/chunks/runtime-TJ3EAMJK.js +3 -0
- package/dist/bundle/chunks/{settings-manager-CHEMMAGQ.js → settings-manager-HC5RR36T.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-UIGTRGHQ.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-SPZUYYP5.js +0 -170
- package/dist/bundle/chunks/execute-EMOVNTD6.js +0 -328
- package/dist/bundle/chunks/virtual-modules-OC56AAJ7.js +0 -2
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
export function createUpdatePump(options) {
|
|
2
|
+
return new UpdatePumpImpl(options);
|
|
3
|
+
}
|
|
4
|
+
const DEFAULT_INTERVAL_MS = 250;
|
|
5
|
+
const DEFAULT_HEARTBEAT_MS = 1000;
|
|
6
|
+
const DEFAULT_COARSE_DELAY_MS = 50;
|
|
7
|
+
function normalizeMs(value, fallback) {
|
|
8
|
+
return Number.isFinite(value) && value >= 1 ? Math.floor(value) : fallback;
|
|
9
|
+
}
|
|
10
|
+
class UpdatePumpImpl {
|
|
11
|
+
intervalMs;
|
|
12
|
+
heartbeatMs;
|
|
13
|
+
coarseDelayMs;
|
|
14
|
+
dirty = new Map();
|
|
15
|
+
heartbeats = new Set();
|
|
16
|
+
flushHandler;
|
|
17
|
+
flushTimer;
|
|
18
|
+
flushDeadline = 0;
|
|
19
|
+
heartbeatTimer;
|
|
20
|
+
disposed = false;
|
|
21
|
+
constructor(options) {
|
|
22
|
+
this.intervalMs = normalizeMs(options.intervalMs, DEFAULT_INTERVAL_MS);
|
|
23
|
+
this.heartbeatMs = normalizeMs(options.heartbeatMs ?? DEFAULT_HEARTBEAT_MS, DEFAULT_HEARTBEAT_MS);
|
|
24
|
+
this.coarseDelayMs = normalizeMs(options.coarseDelayMs ?? DEFAULT_COARSE_DELAY_MS, DEFAULT_COARSE_DELAY_MS);
|
|
25
|
+
}
|
|
26
|
+
get activeTimers() {
|
|
27
|
+
return (this.flushTimer ? 1 : 0) + (this.heartbeatTimer ? 1 : 0);
|
|
28
|
+
}
|
|
29
|
+
setIntervalMs(ms) {
|
|
30
|
+
if (this.disposed)
|
|
31
|
+
return;
|
|
32
|
+
this.intervalMs = normalizeMs(ms, this.intervalMs);
|
|
33
|
+
// A pending fine flush armed under the old (larger) interval would otherwise wait out its
|
|
34
|
+
// original deadline; ensureFlushTimer only ever moves the deadline earlier, so this is safe
|
|
35
|
+
// even when nothing is actually pending.
|
|
36
|
+
if (this.dirty.size > 0)
|
|
37
|
+
this.ensureFlushTimer(this.intervalMs);
|
|
38
|
+
}
|
|
39
|
+
setFlushHandler(handler) {
|
|
40
|
+
this.flushHandler = handler;
|
|
41
|
+
// runFlush holds dirty entries when no handler is installed; once one arrives, make sure
|
|
42
|
+
// those held changes still flush instead of waiting for the next unrelated schedule() call.
|
|
43
|
+
if (this.dirty.size > 0)
|
|
44
|
+
this.ensureFlushTimer(this.intervalMs);
|
|
45
|
+
}
|
|
46
|
+
schedule(runId, change) {
|
|
47
|
+
if (this.disposed)
|
|
48
|
+
return;
|
|
49
|
+
const coarse = change === "coarse";
|
|
50
|
+
this.dirty.set(runId, (this.dirty.get(runId) ?? false) || coarse);
|
|
51
|
+
const delayMs = coarse ? Math.min(this.coarseDelayMs, this.intervalMs) : this.intervalMs;
|
|
52
|
+
this.ensureFlushTimer(delayMs);
|
|
53
|
+
}
|
|
54
|
+
startHeartbeat(runId) {
|
|
55
|
+
if (this.disposed)
|
|
56
|
+
return;
|
|
57
|
+
this.heartbeats.add(runId);
|
|
58
|
+
this.ensureHeartbeatTimer();
|
|
59
|
+
}
|
|
60
|
+
stopHeartbeat(runId) {
|
|
61
|
+
this.heartbeats.delete(runId);
|
|
62
|
+
if (this.heartbeats.size === 0 && this.heartbeatTimer) {
|
|
63
|
+
clearInterval(this.heartbeatTimer);
|
|
64
|
+
this.heartbeatTimer = undefined;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
flushNow() {
|
|
68
|
+
if (this.disposed)
|
|
69
|
+
return;
|
|
70
|
+
if (this.flushTimer) {
|
|
71
|
+
clearTimeout(this.flushTimer);
|
|
72
|
+
this.flushTimer = undefined;
|
|
73
|
+
}
|
|
74
|
+
this.runFlush();
|
|
75
|
+
}
|
|
76
|
+
dispose() {
|
|
77
|
+
this.disposed = true;
|
|
78
|
+
if (this.flushTimer) {
|
|
79
|
+
clearTimeout(this.flushTimer);
|
|
80
|
+
this.flushTimer = undefined;
|
|
81
|
+
}
|
|
82
|
+
if (this.heartbeatTimer) {
|
|
83
|
+
clearInterval(this.heartbeatTimer);
|
|
84
|
+
this.heartbeatTimer = undefined;
|
|
85
|
+
}
|
|
86
|
+
this.dirty.clear();
|
|
87
|
+
this.heartbeats.clear();
|
|
88
|
+
this.flushHandler = undefined;
|
|
89
|
+
}
|
|
90
|
+
ensureFlushTimer(delayMs) {
|
|
91
|
+
const deadline = Date.now() + delayMs;
|
|
92
|
+
if (this.flushTimer) {
|
|
93
|
+
if (deadline >= this.flushDeadline)
|
|
94
|
+
return;
|
|
95
|
+
clearTimeout(this.flushTimer);
|
|
96
|
+
}
|
|
97
|
+
this.flushDeadline = deadline;
|
|
98
|
+
const timer = setTimeout(() => {
|
|
99
|
+
this.flushTimer = undefined;
|
|
100
|
+
this.runFlush();
|
|
101
|
+
}, delayMs);
|
|
102
|
+
timer.unref?.();
|
|
103
|
+
this.flushTimer = timer;
|
|
104
|
+
}
|
|
105
|
+
ensureHeartbeatTimer() {
|
|
106
|
+
if (this.heartbeatTimer)
|
|
107
|
+
return;
|
|
108
|
+
const timer = setInterval(() => {
|
|
109
|
+
for (const runId of this.heartbeats)
|
|
110
|
+
this.schedule(runId, "fine");
|
|
111
|
+
}, this.heartbeatMs);
|
|
112
|
+
timer.unref?.();
|
|
113
|
+
this.heartbeatTimer = timer;
|
|
114
|
+
}
|
|
115
|
+
runFlush() {
|
|
116
|
+
if (this.dirty.size === 0)
|
|
117
|
+
return;
|
|
118
|
+
// setFlushHandler can be called after schedule(): keep the dirty entries rather than
|
|
119
|
+
// discarding changes that arrived before a handler was installed.
|
|
120
|
+
if (!this.flushHandler)
|
|
121
|
+
return;
|
|
122
|
+
const dirty = new Map(this.dirty);
|
|
123
|
+
this.dirty.clear();
|
|
124
|
+
try {
|
|
125
|
+
this.flushHandler(dirty);
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
// A flush handler (tool-row/dock rendering) must not stall future flushes.
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
//# sourceMappingURL=update-pump.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"update-pump.js","sourceRoot":"","sources":["../../../src/core/polyphase/update-pump.ts"],"names":[],"mappings":"AAkBA,MAAM,UAAU,gBAAgB,CAAC,OAA0B;IAC1D,OAAO,IAAI,cAAc,CAAC,OAAO,CAAC,CAAC;AACpC,CAAC;AAED,MAAM,mBAAmB,GAAG,GAAG,CAAC;A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AU,CAAC,GAAG,EAAE;YAC7B,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;YAC5B,IAAI,CAAC,QAAQ,EAAE,CAAC;QACjB,CAAC,EAAE,OAAO,CAAC,CAAC;QACZ,KAAK,CAAC,KAAK,EAAE,EAAE,CAAC;QAChB,IAAI,CAAC,UAAU,GAAG,KAAK,CAAC;IACzB,CAAC;IAEO,oBAAoB;QAC3B,IAAI,IAAI,CAAC,cAAc;YAAE,OAAO;QAChC,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE;YAC9B,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,UAAU;gBAAE,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QACnE,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;QACrB,KAAK,CAAC,KAAK,EAAE,EAAE,CAAC;QAChB,IAAI,CAAC,cAAc,GAAG,KAAK,CAAC;IAC7B,CAAC;IAEO,QAAQ;QACf,IAAI,IAAI,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC;YAAE,OAAO;QAClC,qFAAqF;QACrF,kEAAkE;QAClE,IAAI,CAAC,IAAI,CAAC,YAAY;YAAE,OAAO;QAC/B,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAClC,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;QACnB,IAAI,CAAC;YACJ,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC;QAC1B,CAAC;QAAC,MAAM,CAAC;YACR,2EAA2E;QAC5E,CAAC;IACF,CAAC;CACD","sourcesContent":["export interface UpdatePump {\n\tschedule(runId: string, change: \"fine\" | \"coarse\"): void;\n\tsetIntervalMs(ms: number): void;\n\tsetFlushHandler(handler: (dirty: ReadonlyMap<string, boolean>) => void): void;\n\t/** Schedules a \"fine\" change for runId every heartbeatMs. */\n\tstartHeartbeat(runId: string): void;\n\tstopHeartbeat(runId: string): void;\n\tflushNow(): void;\n\tdispose(): void;\n\treadonly activeTimers: number;\n}\n\nexport interface UpdatePumpOptions {\n\tintervalMs: number;\n\theartbeatMs?: number;\n\tcoarseDelayMs?: number;\n}\n\nexport function createUpdatePump(options: UpdatePumpOptions): UpdatePump {\n\treturn new UpdatePumpImpl(options);\n}\n\nconst DEFAULT_INTERVAL_MS = 250;\nconst DEFAULT_HEARTBEAT_MS = 1000;\nconst DEFAULT_COARSE_DELAY_MS = 50;\n\nfunction normalizeMs(value: number, fallback: number): number {\n\treturn Number.isFinite(value) && value >= 1 ? Math.floor(value) : fallback;\n}\n\nclass UpdatePumpImpl implements UpdatePump {\n\tprivate intervalMs: number;\n\tprivate readonly heartbeatMs: number;\n\tprivate readonly coarseDelayMs: number;\n\tprivate readonly dirty = new Map<string, boolean>();\n\tprivate readonly heartbeats = new Set<string>();\n\tprivate flushHandler: ((dirty: ReadonlyMap<string, boolean>) => void) | undefined;\n\tprivate flushTimer: NodeJS.Timeout | undefined;\n\tprivate flushDeadline = 0;\n\tprivate heartbeatTimer: NodeJS.Timeout | undefined;\n\tprivate disposed = false;\n\n\tconstructor(options: UpdatePumpOptions) {\n\t\tthis.intervalMs = normalizeMs(options.intervalMs, DEFAULT_INTERVAL_MS);\n\t\tthis.heartbeatMs = normalizeMs(options.heartbeatMs ?? DEFAULT_HEARTBEAT_MS, DEFAULT_HEARTBEAT_MS);\n\t\tthis.coarseDelayMs = normalizeMs(options.coarseDelayMs ?? DEFAULT_COARSE_DELAY_MS, DEFAULT_COARSE_DELAY_MS);\n\t}\n\n\tget activeTimers(): number {\n\t\treturn (this.flushTimer ? 1 : 0) + (this.heartbeatTimer ? 1 : 0);\n\t}\n\n\tsetIntervalMs(ms: number): void {\n\t\tif (this.disposed) return;\n\t\tthis.intervalMs = normalizeMs(ms, this.intervalMs);\n\t\t// A pending fine flush armed under the old (larger) interval would otherwise wait out its\n\t\t// original deadline; ensureFlushTimer only ever moves the deadline earlier, so this is safe\n\t\t// even when nothing is actually pending.\n\t\tif (this.dirty.size > 0) this.ensureFlushTimer(this.intervalMs);\n\t}\n\n\tsetFlushHandler(handler: (dirty: ReadonlyMap<string, boolean>) => void): void {\n\t\tthis.flushHandler = handler;\n\t\t// runFlush holds dirty entries when no handler is installed; once one arrives, make sure\n\t\t// those held changes still flush instead of waiting for the next unrelated schedule() call.\n\t\tif (this.dirty.size > 0) this.ensureFlushTimer(this.intervalMs);\n\t}\n\n\tschedule(runId: string, change: \"fine\" | \"coarse\"): void {\n\t\tif (this.disposed) return;\n\t\tconst coarse = change === \"coarse\";\n\t\tthis.dirty.set(runId, (this.dirty.get(runId) ?? false) || coarse);\n\t\tconst delayMs = coarse ? Math.min(this.coarseDelayMs, this.intervalMs) : this.intervalMs;\n\t\tthis.ensureFlushTimer(delayMs);\n\t}\n\n\tstartHeartbeat(runId: string): void {\n\t\tif (this.disposed) return;\n\t\tthis.heartbeats.add(runId);\n\t\tthis.ensureHeartbeatTimer();\n\t}\n\n\tstopHeartbeat(runId: string): void {\n\t\tthis.heartbeats.delete(runId);\n\t\tif (this.heartbeats.size === 0 && this.heartbeatTimer) {\n\t\t\tclearInterval(this.heartbeatTimer);\n\t\t\tthis.heartbeatTimer = undefined;\n\t\t}\n\t}\n\n\tflushNow(): void {\n\t\tif (this.disposed) return;\n\t\tif (this.flushTimer) {\n\t\t\tclearTimeout(this.flushTimer);\n\t\t\tthis.flushTimer = undefined;\n\t\t}\n\t\tthis.runFlush();\n\t}\n\n\tdispose(): void {\n\t\tthis.disposed = true;\n\t\tif (this.flushTimer) {\n\t\t\tclearTimeout(this.flushTimer);\n\t\t\tthis.flushTimer = undefined;\n\t\t}\n\t\tif (this.heartbeatTimer) {\n\t\t\tclearInterval(this.heartbeatTimer);\n\t\t\tthis.heartbeatTimer = undefined;\n\t\t}\n\t\tthis.dirty.clear();\n\t\tthis.heartbeats.clear();\n\t\tthis.flushHandler = undefined;\n\t}\n\n\tprivate ensureFlushTimer(delayMs: number): void {\n\t\tconst deadline = Date.now() + delayMs;\n\t\tif (this.flushTimer) {\n\t\t\tif (deadline >= this.flushDeadline) return;\n\t\t\tclearTimeout(this.flushTimer);\n\t\t}\n\t\tthis.flushDeadline = deadline;\n\t\tconst timer = setTimeout(() => {\n\t\t\tthis.flushTimer = undefined;\n\t\t\tthis.runFlush();\n\t\t}, delayMs);\n\t\ttimer.unref?.();\n\t\tthis.flushTimer = timer;\n\t}\n\n\tprivate ensureHeartbeatTimer(): void {\n\t\tif (this.heartbeatTimer) return;\n\t\tconst timer = setInterval(() => {\n\t\t\tfor (const runId of this.heartbeats) this.schedule(runId, \"fine\");\n\t\t}, this.heartbeatMs);\n\t\ttimer.unref?.();\n\t\tthis.heartbeatTimer = timer;\n\t}\n\n\tprivate runFlush(): void {\n\t\tif (this.dirty.size === 0) return;\n\t\t// setFlushHandler can be called after schedule(): keep the dirty entries rather than\n\t\t// discarding changes that arrived before a handler was installed.\n\t\tif (!this.flushHandler) return;\n\t\tconst dirty = new Map(this.dirty);\n\t\tthis.dirty.clear();\n\t\ttry {\n\t\t\tthis.flushHandler(dirty);\n\t\t} catch {\n\t\t\t// A flush handler (tool-row/dock rendering) must not stall future flushes.\n\t\t}\n\t}\n}\n"]}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bridges a workflow script's `agent()`/`phase()`/`log()` calls to real subagent runs (§14.3): one
|
|
3
|
+
* `WorkflowHost` per run, created by `launch.ts` and handed to `runWorkflowScript`.
|
|
4
|
+
*/
|
|
5
|
+
import type { ExtensionContext } from "../../extensions/types.ts";
|
|
6
|
+
import type { PolyphaseSession } from "../session.ts";
|
|
7
|
+
import type { PolyphaseRun } from "../store.ts";
|
|
8
|
+
import { type AgentRunner } from "../types.ts";
|
|
9
|
+
import type { WorkflowMeta } from "./meta.ts";
|
|
10
|
+
import type { WorkflowHost } from "./runtime.ts";
|
|
11
|
+
export interface WorkflowAgentHostDeps {
|
|
12
|
+
ctx: ExtensionContext;
|
|
13
|
+
session: PolyphaseSession;
|
|
14
|
+
run: PolyphaseRun;
|
|
15
|
+
meta: WorkflowMeta;
|
|
16
|
+
mailbox: string;
|
|
17
|
+
runner?: AgentRunner;
|
|
18
|
+
}
|
|
19
|
+
export interface WorkflowAgentHost extends WorkflowHost {
|
|
20
|
+
/** Resolves once every `runSingleTask` started by this host has settled; bounded by the child
|
|
21
|
+
* kill grace period. Waiting on it after the script finishes (or throws) avoids returning while
|
|
22
|
+
* an agent orphaned by a sandbox abort is still being torn down (DESIGN.md §13.3 "Awaiting"). */
|
|
23
|
+
settled(): Promise<void>;
|
|
24
|
+
}
|
|
25
|
+
export declare function createWorkflowAgentHost(deps: WorkflowAgentHostDeps): WorkflowAgentHost;
|
|
26
|
+
//# sourceMappingURL=agent-host.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agent-host.d.ts","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/agent-host.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAElE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAEN,KAAK,WAAW,EAKhB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,KAAK,EAA4C,YAAY,EAAE,MAAM,cAAc,CAAC;AAG3F,MAAM,WAAW,qBAAqB;IACrC,GAAG,EAAE,gBAAgB,CAAC;IACtB,OAAO,EAAE,gBAAgB,CAAC;IAC1B,GAAG,EAAE,YAAY,CAAC;IAClB,IAAI,EAAE,YAAY,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AA4BD,MAAM,WAAW,iBAAkB,SAAQ,YAAY;IACtD;;qGAEiG;IACjG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACzB;AAED,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,qBAAqB,GAAG,iBAAiB,CA4KtF"}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bridges a workflow script's `agent()`/`phase()`/`log()` calls to real subagent runs (§14.3): one
|
|
3
|
+
* `WorkflowHost` per run, created by `launch.ts` and handed to `runWorkflowScript`.
|
|
4
|
+
*/
|
|
5
|
+
import { discoverAgents, runSingleTask } from "../../builtins/subagent.js";
|
|
6
|
+
import { ModelSelectionError, resolveChildModel } from "../model-selection.js";
|
|
7
|
+
import { currentPolyphaseDepth, POLYPHASE_RESULT_TOOL_NAME, } from "../types.js";
|
|
8
|
+
import { prepareResultSchema, STRUCTURED_OUTPUT_INSTRUCTION } from "./structured-output.js";
|
|
9
|
+
const DEFAULT_WORKFLOW_AGENT_CONFIG = {
|
|
10
|
+
name: "workflow-agent",
|
|
11
|
+
description: "polyphase workflow agent",
|
|
12
|
+
systemPrompt: "You are an agent in a polyphase workflow. Do the task; your final message is returned to the orchestrating script.",
|
|
13
|
+
source: "user",
|
|
14
|
+
};
|
|
15
|
+
/** First non-empty trimmed line of `stderr`, else `errorMessage`'s first non-empty trimmed line,
|
|
16
|
+
* else `exit code N`: a stderr that is blank or starts with a bare newline (or a leading runtime
|
|
17
|
+
* warning line) must not leave the failure log line with no detail at all. */
|
|
18
|
+
function failureDetail(stderr, errorMessage, exitCode) {
|
|
19
|
+
for (const candidate of [stderr, errorMessage ?? ""]) {
|
|
20
|
+
for (const line of candidate.split("\n")) {
|
|
21
|
+
const trimmed = line.trim();
|
|
22
|
+
if (trimmed)
|
|
23
|
+
return trimmed;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return `exit code ${exitCode}`;
|
|
27
|
+
}
|
|
28
|
+
/** `cancelReason "user"` reads as "you" in the log line; every other reason reads verbatim. */
|
|
29
|
+
function cancelReasonText(reason) {
|
|
30
|
+
return reason === "user" ? "you" : (reason ?? "run");
|
|
31
|
+
}
|
|
32
|
+
export function createWorkflowAgentHost(deps) {
|
|
33
|
+
let cachedAgents;
|
|
34
|
+
let budgetNoticeLogged = false;
|
|
35
|
+
const agentTypeCounts = new Map();
|
|
36
|
+
const usedLabels = new Set();
|
|
37
|
+
const inFlight = new Set();
|
|
38
|
+
function agentsByName() {
|
|
39
|
+
if (!cachedAgents) {
|
|
40
|
+
cachedAgents = new Map(discoverAgents(deps.ctx.cwd, "both", deps.ctx.isProjectTrusted()).map((agent) => [agent.name, agent]));
|
|
41
|
+
}
|
|
42
|
+
return cachedAgents;
|
|
43
|
+
}
|
|
44
|
+
/** Dedupe within this run: an explicit label keeps its text until it collides, appending `#2`,
|
|
45
|
+
* `#3`. A default label never collides by construction: its per-type counter advances past any
|
|
46
|
+
* slot already in `usedLabels` (including one taken by an explicit label of the same text). */
|
|
47
|
+
function nextLabel(explicit, agentTypeDisplay) {
|
|
48
|
+
const text = explicit?.trim();
|
|
49
|
+
if (!text) {
|
|
50
|
+
let n = agentTypeCounts.get(agentTypeDisplay) ?? 0;
|
|
51
|
+
let candidate;
|
|
52
|
+
do {
|
|
53
|
+
n++;
|
|
54
|
+
candidate = `${agentTypeDisplay}#${n}`;
|
|
55
|
+
} while (usedLabels.has(candidate));
|
|
56
|
+
agentTypeCounts.set(agentTypeDisplay, n);
|
|
57
|
+
usedLabels.add(candidate);
|
|
58
|
+
return candidate;
|
|
59
|
+
}
|
|
60
|
+
if (!usedLabels.has(text)) {
|
|
61
|
+
usedLabels.add(text);
|
|
62
|
+
return text;
|
|
63
|
+
}
|
|
64
|
+
let n = 2;
|
|
65
|
+
while (usedLabels.has(`${text}#${n}`))
|
|
66
|
+
n++;
|
|
67
|
+
const deduped = `${text}#${n}`;
|
|
68
|
+
usedLabels.add(deduped);
|
|
69
|
+
return deduped;
|
|
70
|
+
}
|
|
71
|
+
async function runAgent(request, signal) {
|
|
72
|
+
if (deps.run.budget.exhausted) {
|
|
73
|
+
if (!budgetNoticeLogged) {
|
|
74
|
+
budgetNoticeLogged = true;
|
|
75
|
+
deps.run.appendLog("budget exhausted; agent(...) returns null", "warning");
|
|
76
|
+
}
|
|
77
|
+
return { kind: "null", reason: "budget" };
|
|
78
|
+
}
|
|
79
|
+
let agentTypeDisplay;
|
|
80
|
+
let config;
|
|
81
|
+
if (request.agentType) {
|
|
82
|
+
const found = agentsByName().get(request.agentType);
|
|
83
|
+
if (!found) {
|
|
84
|
+
const available = [...agentsByName().keys()].sort().join(", ");
|
|
85
|
+
return {
|
|
86
|
+
kind: "error",
|
|
87
|
+
message: `unknown agentType "${request.agentType}"; available: ${available || "(none)"}`,
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
agentTypeDisplay = request.agentType;
|
|
91
|
+
config = found;
|
|
92
|
+
}
|
|
93
|
+
else {
|
|
94
|
+
agentTypeDisplay = "agent";
|
|
95
|
+
config = DEFAULT_WORKFLOW_AGENT_CONFIG;
|
|
96
|
+
}
|
|
97
|
+
// Side-effect-free lookup for the model step: declaring a phase permanently (and may log a
|
|
98
|
+
// one-time warning) must wait until every other validation has passed, so a rejected agent()
|
|
99
|
+
// call (bad agentType/model) never mutates the run as a side effect (DESIGN.md §14.3).
|
|
100
|
+
const declaredIndex = request.phase === undefined
|
|
101
|
+
? deps.run.currentPhase
|
|
102
|
+
: deps.run.phases.findIndex((phase) => phase.title === request.phase);
|
|
103
|
+
const phaseModel = declaredIndex !== undefined && declaredIndex >= 0 ? deps.meta.phases[declaredIndex]?.model : undefined;
|
|
104
|
+
let choice;
|
|
105
|
+
try {
|
|
106
|
+
choice = resolveChildModel({
|
|
107
|
+
override: request.model,
|
|
108
|
+
effort: request.effort,
|
|
109
|
+
phaseModel,
|
|
110
|
+
agentModel: config.model,
|
|
111
|
+
parentModel: deps.ctx.model,
|
|
112
|
+
parentThinking: deps.ctx.thinkingLevel,
|
|
113
|
+
available: deps.ctx.modelRegistry.getAvailable(),
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
if (error instanceof ModelSelectionError)
|
|
118
|
+
return { kind: "error", message: error.message };
|
|
119
|
+
throw error;
|
|
120
|
+
}
|
|
121
|
+
const schemaPrep = request.schema ? prepareResultSchema(request.schema) : undefined;
|
|
122
|
+
const label = nextLabel(request.label, agentTypeDisplay);
|
|
123
|
+
const phaseIndex = deps.run.resolvePhase(request.phase);
|
|
124
|
+
const live = deps.run.addAgent({
|
|
125
|
+
label,
|
|
126
|
+
agentType: agentTypeDisplay,
|
|
127
|
+
task: request.prompt,
|
|
128
|
+
phase: phaseIndex,
|
|
129
|
+
model: choice.info,
|
|
130
|
+
});
|
|
131
|
+
const combined = AbortSignal.any([signal, live.signal]);
|
|
132
|
+
signal.addEventListener("abort", () => live.cancel("run"), { once: true });
|
|
133
|
+
const depth = currentPolyphaseDepth();
|
|
134
|
+
const maxDepth = deps.session.settings().maxDepth;
|
|
135
|
+
const resultPromise = runSingleTask(deps.ctx.cwd, config, request.prompt, {
|
|
136
|
+
signal: combined,
|
|
137
|
+
worktree: request.isolation === "worktree",
|
|
138
|
+
runner: deps.runner,
|
|
139
|
+
resultMailbox: deps.mailbox,
|
|
140
|
+
limiter: deps.session.limiter,
|
|
141
|
+
run: live.createRunContext({
|
|
142
|
+
model: choice.modelArg,
|
|
143
|
+
thinking: choice.thinking,
|
|
144
|
+
modelInfo: choice.info,
|
|
145
|
+
fallbackToChildDefaultModel: choice.info.source === "inherited",
|
|
146
|
+
excludeTools: depth + 1 >= maxDepth ? ["subagent"] : [],
|
|
147
|
+
schema: schemaPrep?.toolSchema,
|
|
148
|
+
extraTools: schemaPrep ? [POLYPHASE_RESULT_TOOL_NAME] : undefined,
|
|
149
|
+
extraSystemPrompt: schemaPrep ? STRUCTURED_OUTPUT_INSTRUCTION : undefined,
|
|
150
|
+
}),
|
|
151
|
+
});
|
|
152
|
+
inFlight.add(resultPromise);
|
|
153
|
+
let result;
|
|
154
|
+
try {
|
|
155
|
+
result = await resultPromise;
|
|
156
|
+
}
|
|
157
|
+
finally {
|
|
158
|
+
inFlight.delete(resultPromise);
|
|
159
|
+
}
|
|
160
|
+
if (result.merge && !result.merge.success) {
|
|
161
|
+
deps.run.appendLog(`${label} merge-back failed; work is on branch ${result.merge.branch ?? "unknown"}`, "warning");
|
|
162
|
+
}
|
|
163
|
+
if (result.cancelled) {
|
|
164
|
+
deps.run.appendLog(`${label} skipped (cancelled by ${cancelReasonText(live.cancelReason)})`, "info");
|
|
165
|
+
return { kind: "null", reason: "cancelled" };
|
|
166
|
+
}
|
|
167
|
+
if (result.exitCode !== 0) {
|
|
168
|
+
const detail = failureDetail(result.stderr, live.state.errorMessage, result.exitCode);
|
|
169
|
+
deps.run.appendLog(`${label} failed: ${detail}`, "warning");
|
|
170
|
+
return { kind: "null", reason: "failed" };
|
|
171
|
+
}
|
|
172
|
+
if (request.schema && !result.structured) {
|
|
173
|
+
deps.run.appendLog(`${label} did not return structured output matching the schema`, "warning");
|
|
174
|
+
return { kind: "null", reason: "no-structured-output" };
|
|
175
|
+
}
|
|
176
|
+
const value = request.schema && schemaPrep && result.structured ? schemaPrep.unwrap(result.structured.value) : result.output;
|
|
177
|
+
return { kind: "value", value };
|
|
178
|
+
}
|
|
179
|
+
return {
|
|
180
|
+
runAgent,
|
|
181
|
+
onPhase: (title) => deps.run.enterPhase(title),
|
|
182
|
+
onLog: (text, level) => deps.run.appendLog(text, level),
|
|
183
|
+
spentTokens: () => deps.run.spentTokens(),
|
|
184
|
+
settled: () => Promise.allSettled([...inFlight]).then(() => undefined),
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
//# sourceMappingURL=agent-host.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agent-host.js","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/agent-host.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,cAAc,EAAE,aAA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AE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC;QAC3C,CAAC;QACD,IAAI,OAAO,CAAC,MAAM,IAAI,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC;YAC1C,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,GAAG,KAAK,uDAAuD,EAAE,SAAS,CAAC,CAAC;YAC/F,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,sBAAsB,EAAE,CAAC;QACzD,CAAC;QAED,MAAM,KAAK,GACV,OAAO,CAAC,MAAM,IAAI,UAAU,IAAI,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC;QAChH,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IACjC,CAAC;IAED,OAAO;QACN,QAAQ;QACR,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,KAAK,CAAC;QAC9C,KAAK,EAAE,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC;QACvD,WAAW,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,WAAW,EAAE;QACzC,OAAO,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC;KACtE,CAAC;AACH,CAAC","sourcesContent":["/**\n * Bridges a workflow script's `agent()`/`phase()`/`log()` calls to real subagent runs (§14.3): one\n * `WorkflowHost` per run, created by `launch.ts` and handed to `runWorkflowScript`.\n */\n\nimport { discoverAgents, runSingleTask } from \"../../builtins/subagent.ts\";\nimport type { ExtensionContext } from \"../../extensions/types.ts\";\nimport { type ChildModelChoice, ModelSelectionError, resolveChildModel } from \"../model-selection.ts\";\nimport type { PolyphaseSession } from \"../session.ts\";\nimport type { PolyphaseRun } from \"../store.ts\";\nimport {\n\ttype AgentConfig,\n\ttype AgentRunner,\n\ttype CancelReason,\n\tcurrentPolyphaseDepth,\n\tPOLYPHASE_RESULT_TOOL_NAME,\n\ttype RunResult,\n} from \"../types.ts\";\nimport type { WorkflowMeta } from \"./meta.ts\";\nimport type { WorkflowAgentReply, WorkflowAgentRequest, WorkflowHost } from \"./runtime.ts\";\nimport { prepareResultSchema, STRUCTURED_OUTPUT_INSTRUCTION } from \"./structured-output.ts\";\n\nexport interface WorkflowAgentHostDeps {\n\tctx: ExtensionContext;\n\tsession: PolyphaseSession;\n\trun: PolyphaseRun;\n\tmeta: WorkflowMeta;\n\tmailbox: string;\n\trunner?: AgentRunner;\n}\n\nconst DEFAULT_WORKFLOW_AGENT_CONFIG: AgentConfig = {\n\tname: \"workflow-agent\",\n\tdescription: \"polyphase workflow agent\",\n\tsystemPrompt:\n\t\t\"You are an agent in a polyphase workflow. Do the task; your final message is returned to the orchestrating script.\",\n\tsource: \"user\",\n};\n\n/** First non-empty trimmed line of `stderr`, else `errorMessage`'s first non-empty trimmed line,\n * else `exit code N`: a stderr that is blank or starts with a bare newline (or a leading runtime\n * warning line) must not leave the failure log line with no detail at all. */\nfunction failureDetail(stderr: string, errorMessage: string | undefined, exitCode: number): string {\n\tfor (const candidate of [stderr, errorMessage ?? \"\"]) {\n\t\tfor (const line of candidate.split(\"\\n\")) {\n\t\t\tconst trimmed = line.trim();\n\t\t\tif (trimmed) return trimmed;\n\t\t}\n\t}\n\treturn `exit code ${exitCode}`;\n}\n\n/** `cancelReason \"user\"` reads as \"you\" in the log line; every other reason reads verbatim. */\nfunction cancelReasonText(reason: CancelReason | undefined): string {\n\treturn reason === \"user\" ? \"you\" : (reason ?? \"run\");\n}\n\nexport interface WorkflowAgentHost extends WorkflowHost {\n\t/** Resolves once every `runSingleTask` started by this host has settled; bounded by the child\n\t * kill grace period. Waiting on it after the script finishes (or throws) avoids returning while\n\t * an agent orphaned by a sandbox abort is still being torn down (DESIGN.md §13.3 \"Awaiting\"). */\n\tsettled(): Promise<void>;\n}\n\nexport function createWorkflowAgentHost(deps: WorkflowAgentHostDeps): WorkflowAgentHost {\n\tlet cachedAgents: Map<string, AgentConfig> | undefined;\n\tlet budgetNoticeLogged = false;\n\tconst agentTypeCounts = new Map<string, number>();\n\tconst usedLabels = new Set<string>();\n\tconst inFlight = new Set<Promise<unknown>>();\n\n\tfunction agentsByName(): Map<string, AgentConfig> {\n\t\tif (!cachedAgents) {\n\t\t\tcachedAgents = new Map(\n\t\t\t\tdiscoverAgents(deps.ctx.cwd, \"both\", deps.ctx.isProjectTrusted()).map((agent) => [agent.name, agent]),\n\t\t\t);\n\t\t}\n\t\treturn cachedAgents;\n\t}\n\n\t/** Dedupe within this run: an explicit label keeps its text until it collides, appending `#2`,\n\t * `#3`. A default label never collides by construction: its per-type counter advances past any\n\t * slot already in `usedLabels` (including one taken by an explicit label of the same text). */\n\tfunction nextLabel(explicit: string | undefined, agentTypeDisplay: string): string {\n\t\tconst text = explicit?.trim();\n\t\tif (!text) {\n\t\t\tlet n = agentTypeCounts.get(agentTypeDisplay) ?? 0;\n\t\t\tlet candidate: string;\n\t\t\tdo {\n\t\t\t\tn++;\n\t\t\t\tcandidate = `${agentTypeDisplay}#${n}`;\n\t\t\t} while (usedLabels.has(candidate));\n\t\t\tagentTypeCounts.set(agentTypeDisplay, n);\n\t\t\tusedLabels.add(candidate);\n\t\t\treturn candidate;\n\t\t}\n\t\tif (!usedLabels.has(text)) {\n\t\t\tusedLabels.add(text);\n\t\t\treturn text;\n\t\t}\n\t\tlet n = 2;\n\t\twhile (usedLabels.has(`${text}#${n}`)) n++;\n\t\tconst deduped = `${text}#${n}`;\n\t\tusedLabels.add(deduped);\n\t\treturn deduped;\n\t}\n\n\tasync function runAgent(request: WorkflowAgentRequest, signal: AbortSignal): Promise<WorkflowAgentReply> {\n\t\tif (deps.run.budget.exhausted) {\n\t\t\tif (!budgetNoticeLogged) {\n\t\t\t\tbudgetNoticeLogged = true;\n\t\t\t\tdeps.run.appendLog(\"budget exhausted; agent(...) returns null\", \"warning\");\n\t\t\t}\n\t\t\treturn { kind: \"null\", reason: \"budget\" };\n\t\t}\n\n\t\tlet agentTypeDisplay: string;\n\t\tlet config: AgentConfig;\n\t\tif (request.agentType) {\n\t\t\tconst found = agentsByName().get(request.agentType);\n\t\t\tif (!found) {\n\t\t\t\tconst available = [...agentsByName().keys()].sort().join(\", \");\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"error\",\n\t\t\t\t\tmessage: `unknown agentType \"${request.agentType}\"; available: ${available || \"(none)\"}`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tagentTypeDisplay = request.agentType;\n\t\t\tconfig = found;\n\t\t} else {\n\t\t\tagentTypeDisplay = \"agent\";\n\t\t\tconfig = DEFAULT_WORKFLOW_AGENT_CONFIG;\n\t\t}\n\n\t\t// Side-effect-free lookup for the model step: declaring a phase permanently (and may log a\n\t\t// one-time warning) must wait until every other validation has passed, so a rejected agent()\n\t\t// call (bad agentType/model) never mutates the run as a side effect (DESIGN.md §14.3).\n\t\tconst declaredIndex =\n\t\t\trequest.phase === undefined\n\t\t\t\t? deps.run.currentPhase\n\t\t\t\t: deps.run.phases.findIndex((phase) => phase.title === request.phase);\n\t\tconst phaseModel =\n\t\t\tdeclaredIndex !== undefined && declaredIndex >= 0 ? deps.meta.phases[declaredIndex]?.model : undefined;\n\n\t\tlet choice: ChildModelChoice;\n\t\ttry {\n\t\t\tchoice = resolveChildModel({\n\t\t\t\toverride: request.model,\n\t\t\t\teffort: request.effort,\n\t\t\t\tphaseModel,\n\t\t\t\tagentModel: config.model,\n\t\t\t\tparentModel: deps.ctx.model,\n\t\t\t\tparentThinking: deps.ctx.thinkingLevel,\n\t\t\t\tavailable: deps.ctx.modelRegistry.getAvailable(),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof ModelSelectionError) return { kind: \"error\", message: error.message };\n\t\t\tthrow error;\n\t\t}\n\n\t\tconst schemaPrep = request.schema ? prepareResultSchema(request.schema) : undefined;\n\t\tconst label = nextLabel(request.label, agentTypeDisplay);\n\t\tconst phaseIndex = deps.run.resolvePhase(request.phase);\n\n\t\tconst live = deps.run.addAgent({\n\t\t\tlabel,\n\t\t\tagentType: agentTypeDisplay,\n\t\t\ttask: request.prompt,\n\t\t\tphase: phaseIndex,\n\t\t\tmodel: choice.info,\n\t\t});\n\n\t\tconst combined = AbortSignal.any([signal, live.signal]);\n\t\tsignal.addEventListener(\"abort\", () => live.cancel(\"run\"), { once: true });\n\n\t\tconst depth = currentPolyphaseDepth();\n\t\tconst maxDepth = deps.session.settings().maxDepth;\n\n\t\tconst resultPromise = runSingleTask(deps.ctx.cwd, config, request.prompt, {\n\t\t\tsignal: combined,\n\t\t\tworktree: request.isolation === \"worktree\",\n\t\t\trunner: deps.runner,\n\t\t\tresultMailbox: deps.mailbox,\n\t\t\tlimiter: deps.session.limiter,\n\t\t\trun: live.createRunContext({\n\t\t\t\tmodel: choice.modelArg,\n\t\t\t\tthinking: choice.thinking,\n\t\t\t\tmodelInfo: choice.info,\n\t\t\t\tfallbackToChildDefaultModel: choice.info.source === \"inherited\",\n\t\t\t\texcludeTools: depth + 1 >= maxDepth ? [\"subagent\"] : [],\n\t\t\t\tschema: schemaPrep?.toolSchema,\n\t\t\t\textraTools: schemaPrep ? [POLYPHASE_RESULT_TOOL_NAME] : undefined,\n\t\t\t\textraSystemPrompt: schemaPrep ? STRUCTURED_OUTPUT_INSTRUCTION : undefined,\n\t\t\t}),\n\t\t});\n\t\tinFlight.add(resultPromise);\n\t\tlet result: RunResult;\n\t\ttry {\n\t\t\tresult = await resultPromise;\n\t\t} finally {\n\t\t\tinFlight.delete(resultPromise);\n\t\t}\n\n\t\tif (result.merge && !result.merge.success) {\n\t\t\tdeps.run.appendLog(\n\t\t\t\t`${label} merge-back failed; work is on branch ${result.merge.branch ?? \"unknown\"}`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t}\n\n\t\tif (result.cancelled) {\n\t\t\tdeps.run.appendLog(`${label} skipped (cancelled by ${cancelReasonText(live.cancelReason)})`, \"info\");\n\t\t\treturn { kind: \"null\", reason: \"cancelled\" };\n\t\t}\n\t\tif (result.exitCode !== 0) {\n\t\t\tconst detail = failureDetail(result.stderr, live.state.errorMessage, result.exitCode);\n\t\t\tdeps.run.appendLog(`${label} failed: ${detail}`, \"warning\");\n\t\t\treturn { kind: \"null\", reason: \"failed\" };\n\t\t}\n\t\tif (request.schema && !result.structured) {\n\t\t\tdeps.run.appendLog(`${label} did not return structured output matching the schema`, \"warning\");\n\t\t\treturn { kind: \"null\", reason: \"no-structured-output\" };\n\t\t}\n\n\t\tconst value =\n\t\t\trequest.schema && schemaPrep && result.structured ? schemaPrep.unwrap(result.structured.value) : result.output;\n\t\treturn { kind: \"value\", value };\n\t}\n\n\treturn {\n\t\trunAgent,\n\t\tonPhase: (title) => deps.run.enterPhase(title),\n\t\tonLog: (text, level) => deps.run.appendLog(text, level),\n\t\tspentTokens: () => deps.run.spentTokens(),\n\t\tsettled: () => Promise.allSettled([...inFlight]).then(() => undefined),\n\t};\n}\n"]}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model-facing text for the `workflow` tool (§14.5): the tool description, prompt snippet and
|
|
3
|
+
* guidelines shown while the tool is active, and the longer authoring guide sent once when the
|
|
4
|
+
* keyword first enables it.
|
|
5
|
+
*/
|
|
6
|
+
export declare const WORKFLOW_TOOL_DESCRIPTION: string;
|
|
7
|
+
export declare const WORKFLOW_PROMPT_SNIPPET = "Run a multi-agent workflow script (phases, parallel agents, pipelines) with live oversight";
|
|
8
|
+
export declare const WORKFLOW_PROMPT_GUIDELINES: readonly string[];
|
|
9
|
+
export interface AuthoringGuideInput {
|
|
10
|
+
agentTypes: readonly string[];
|
|
11
|
+
savedNames: readonly string[];
|
|
12
|
+
limits: {
|
|
13
|
+
concurrency: number;
|
|
14
|
+
maxAgents: number;
|
|
15
|
+
maxItems: number;
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
export declare function buildAuthoringGuide(input: AuthoringGuideInput): string;
|
|
19
|
+
//# sourceMappingURL=guidance.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guidance.d.ts","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/guidance.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,eAAO,MAAM,yBAAyB,QAgB2C,CAAC;AAElF,eAAO,MAAM,uBAAuB,+FACyD,CAAC;AAE9F,eAAO,MAAM,0BAA0B,EAAE,SAAS,MAAM,EAKvD,CAAC;AAEF,MAAM,WAAW,mBAAmB;IACnC,UAAU,EAAE,SAAS,MAAM,EAAE,CAAC;IAC9B,UAAU,EAAE,SAAS,MAAM,EAAE,CAAC;IAC9B,MAAM,EAAE;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC;CACrE;AAED,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,mBAAmB,GAAG,MAAM,CA0FtE"}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model-facing text for the `workflow` tool (§14.5): the tool description, prompt snippet and
|
|
3
|
+
* guidelines shown while the tool is active, and the longer authoring guide sent once when the
|
|
4
|
+
* keyword first enables it.
|
|
5
|
+
*/
|
|
6
|
+
export const WORKFLOW_TOOL_DESCRIPTION = "Runs a workflow script that orchestrates one or more subagents through a multi-phase task, " +
|
|
7
|
+
"with live oversight in the TUI (a running-agents dock and an agent inspector).\n\n" +
|
|
8
|
+
"The script is plain JavaScript with no imports. It must start with `export const meta = " +
|
|
9
|
+
"{ name, description, phases: [{ title, detail?, model? }, ...] }` as a pure literal (no " +
|
|
10
|
+
"identifiers, calls, spreads, computed keys or template-literal interpolation), then an async body using:\n" +
|
|
11
|
+
" agent(prompt, opts) -> string | object | null\n" +
|
|
12
|
+
" parallel(thunks) -> array (barrier; a failed thunk becomes null)\n" +
|
|
13
|
+
" pipeline(items, ...stages) -> array (no barrier between stages)\n" +
|
|
14
|
+
" phase(title), log(...parts), args, budget\n\n" +
|
|
15
|
+
"agent() returns null when the agent failed, was cancelled, or produced no valid structured " +
|
|
16
|
+
"output. It throws for invalid options, an unknown agentType/model, an invalid effort, or the " +
|
|
17
|
+
"per-run agent cap. Reserved names (never redeclare): agent, parallel, pipeline, phase, log, " +
|
|
18
|
+
"args, budget, meta. Math.random, Date.now, Date() and new Date() throw; new Date(value) works. " +
|
|
19
|
+
"No workflow can start another workflow.\n\n" +
|
|
20
|
+
"Call this tool with either `script` (a new script) or `name` (a saved workflow). Set `args` " +
|
|
21
|
+
"for the script's input string and `budgetTokens` to cap total billable tokens.";
|
|
22
|
+
export const WORKFLOW_PROMPT_SNIPPET = "Run a multi-agent workflow script (phases, parallel agents, pipelines) with live oversight";
|
|
23
|
+
export const WORKFLOW_PROMPT_GUIDELINES = [
|
|
24
|
+
"Use the workflow tool for multi-phase tasks that benefit from several subagents running in parallel or in a pipeline, with live oversight in the TUI.",
|
|
25
|
+
"Write `export const meta = {...}` first, as a plain literal (no identifiers, calls, or template-literal interpolation), then an async body using agent, parallel, pipeline, phase, log, args and budget.",
|
|
26
|
+
"Each agent() call is a separate paid model session that cannot ask for permissions; give it a self-contained task and ask it to end with a STATUS line.",
|
|
27
|
+
"agent() returns null on failure, cancellation, or budget exhaustion; always check for null before using the result.",
|
|
28
|
+
];
|
|
29
|
+
export function buildAuthoringGuide(input) {
|
|
30
|
+
const agentTypesLine = input.agentTypes.length > 0 ? input.agentTypes.join(", ") : "(none discovered)";
|
|
31
|
+
const savedNamesLine = input.savedNames.length > 0 ? input.savedNames.join(", ") : "(none saved)";
|
|
32
|
+
return `# Writing a polyphase workflow
|
|
33
|
+
|
|
34
|
+
A workflow script is plain JavaScript. It runs in a sandbox with no imports and no filesystem or
|
|
35
|
+
network access of its own -- all real work happens inside the subagents it starts with agent().
|
|
36
|
+
|
|
37
|
+
## 1. The meta block comes first
|
|
38
|
+
|
|
39
|
+
\`\`\`js
|
|
40
|
+
export const meta = {
|
|
41
|
+
name: "review-pr", // ^[a-z][a-z0-9-]{0,47}$, used for /review-pr if you save it
|
|
42
|
+
description: "Review a change in parallel and synthesize findings", // 1-300 chars
|
|
43
|
+
whenToUse: "...", // optional, <= 300 chars
|
|
44
|
+
phases: [ // 1-20 entries
|
|
45
|
+
{ title: "Scan" },
|
|
46
|
+
{ title: "Review" },
|
|
47
|
+
{ title: "Synthesize", model: "anthropic/claude-opus-5-5" }, // optional per-phase model
|
|
48
|
+
],
|
|
49
|
+
};
|
|
50
|
+
\`\`\`
|
|
51
|
+
|
|
52
|
+
meta must be a pure literal: no identifiers, function calls, spreads, computed keys, template
|
|
53
|
+
interpolation (\${...}), or regex literals. Unknown keys are warnings, not errors.
|
|
54
|
+
|
|
55
|
+
## 2. The API
|
|
56
|
+
|
|
57
|
+
- \`agent(prompt, opts)\` starts one subagent and returns its final text, or the schema-validated
|
|
58
|
+
object when \`opts.schema\` is set. It returns \`null\` when the agent failed, was cancelled (by
|
|
59
|
+
the user or the token budget), the budget was already exhausted, or no valid structured output
|
|
60
|
+
was produced -- always check for null. It throws for invalid options, an unknown model/agentType,
|
|
61
|
+
an invalid effort, or hitting the per-run agent cap.
|
|
62
|
+
opts: { label, phase, schema, model, effort, isolation: "worktree", agentType }
|
|
63
|
+
- \`parallel(thunks)\` runs an array of zero-argument thunks (each should call agent()) and waits
|
|
64
|
+
for all of them (a barrier). A thunk that throws becomes null in the result array, with a
|
|
65
|
+
warning logged; parallel() itself never rejects.
|
|
66
|
+
- \`pipeline(items, ...stages)\` runs each item through the same stages in sequence, with no
|
|
67
|
+
barrier between stages: each stage \`(prev, item, index)\` receives the previous stage's result
|
|
68
|
+
(or the item itself, for the first stage). A throwing stage makes that item null and skips its
|
|
69
|
+
later stages for that item.
|
|
70
|
+
- \`phase(title)\` groups the agents started after it under that phase for the live view. Titles
|
|
71
|
+
not declared in meta.phases become dynamic phases, logged once.
|
|
72
|
+
- \`log(...parts)\` writes a narrator line visible in the dock and inspector.
|
|
73
|
+
- \`args\` is the verbatim string passed to this call (or to /<name>). \`meta\` is the frozen meta
|
|
74
|
+
object.
|
|
75
|
+
- \`budget\`: { total, spent(), remaining() }. spent() is this run's total billable tokens as of
|
|
76
|
+
the latest agent() reply.
|
|
77
|
+
|
|
78
|
+
## 3. Determinism and reserved names
|
|
79
|
+
|
|
80
|
+
Math.random, Date.now, Date() and new Date() all throw -- workflows must be deterministic.
|
|
81
|
+
new Date(value) still works. Never redeclare: agent, parallel, pipeline, phase, log, args, budget, meta.
|
|
82
|
+
|
|
83
|
+
## 4. Each agent is a separate paid session
|
|
84
|
+
|
|
85
|
+
Every agent() call spawns an independent subagent process. It cannot ask for permissions or see
|
|
86
|
+
anything outside its own prompt, so give it a self-contained task and ask it to end with a
|
|
87
|
+
STATUS: line you can look for in its output.
|
|
88
|
+
|
|
89
|
+
## 5. Limits
|
|
90
|
+
|
|
91
|
+
- Up to ${input.limits.concurrency} agents run at once in this session.
|
|
92
|
+
- Up to ${input.limits.maxAgents} agent() calls total in one workflow run.
|
|
93
|
+
- Up to ${input.limits.maxItems} items per parallel()/pipeline() call.
|
|
94
|
+
|
|
95
|
+
## 6. Available agent types
|
|
96
|
+
|
|
97
|
+
${agentTypesLine}
|
|
98
|
+
|
|
99
|
+
## 7. Saved workflows
|
|
100
|
+
|
|
101
|
+
${savedNamesLine}
|
|
102
|
+
|
|
103
|
+
## Example
|
|
104
|
+
|
|
105
|
+
\`\`\`js
|
|
106
|
+
export const meta = { name: "review-pr", description: "Review a change in parallel and synthesize findings",
|
|
107
|
+
phases: [{ title: "Scan" }, { title: "Review" }, { title: "Synthesize", model: "anthropic/claude-opus-5-5" }] };
|
|
108
|
+
phase("Scan");
|
|
109
|
+
const scan = await agent(\`List the areas touched by \${args}\`, { label: "scan",
|
|
110
|
+
schema: { type: "object", properties: { areas: { type: "array", items: { type: "string" } } }, required: ["areas"] } });
|
|
111
|
+
phase("Review");
|
|
112
|
+
const reviews = await parallel((scan?.areas ?? []).map((area) => () =>
|
|
113
|
+
agent(\`Review \${area} for \${args}. End with a STATUS line.\`, { label: \`review:\${area}\`, agentType: "reviewer" })));
|
|
114
|
+
phase("Synthesize");
|
|
115
|
+
return await agent(\`Synthesize these reviews:\\n\${reviews.filter(Boolean).join("\\n---\\n")}\`, { label: "synthesize" });
|
|
116
|
+
\`\`\`
|
|
117
|
+
`;
|
|
118
|
+
}
|
|
119
|
+
//# sourceMappingURL=guidance.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guidance.js","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/guidance.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,MAAM,CAAC,MAAM,yBAAyB,GACrC,6FAA6F;IAC7F,oFAAoF;IACpF,0FAA0F;IAC1F,0FAA0F;IAC1F,4GAA4G;IAC5G,mDAAmD;IACnD,sEAAsE;IACtE,qEAAqE;IACrE,iDAAiD;IACjD,6FAA6F;IAC7F,+FAA+F;IAC/F,8FAA8F;IAC9F,iGAAiG;IACjG,6CAA6C;IAC7C,8FAA8F;IAC9F,gFAAgF,CAAC;AAElF,MAAM,CAAC,MAAM,uBAAuB,GACnC,4FAA4F,CAAC;AAE9F,MAAM,CAAC,MAAM,0BAA0B,GAAsB;IAC5D,uJAAuJ;IACvJ,0MAA0M;IAC1M,yJAAyJ;IACzJ,qHAAqH;CACrH,CAAC;AAQF,MAAM,UAAU,mBAAmB,CAAC,KAA0B;IAC7D,MAAM,cAAc,GAAG,KAAK,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,mBAAmB,CAAC;IACvG,MAAM,cAAc,GAAG,KAAK,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC;IAElG,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA2DE,KAAK,CAAC,MAAM,CAAC,WAAW;UACxB,KAAK,CAAC,MAAM,CAAC,SAAS;UACtB,KAAK,CAAC,MAAM,CAAC,QAAQ;;;;EAI7B,cAAc;;;;EAId,cAAc;;;;;;;;;;;;;;;;CAgBf,CAAC;AACF,CAAC","sourcesContent":["/**\n * Model-facing text for the `workflow` tool (§14.5): the tool description, prompt snippet and\n * guidelines shown while the tool is active, and the longer authoring guide sent once when the\n * keyword first enables it.\n */\n\nexport const WORKFLOW_TOOL_DESCRIPTION =\n\t\"Runs a workflow script that orchestrates one or more subagents through a multi-phase task, \" +\n\t\"with live oversight in the TUI (a running-agents dock and an agent inspector).\\n\\n\" +\n\t\"The script is plain JavaScript with no imports. It must start with `export const meta = \" +\n\t\"{ name, description, phases: [{ title, detail?, model? }, ...] }` as a pure literal (no \" +\n\t\"identifiers, calls, spreads, computed keys or template-literal interpolation), then an async body using:\\n\" +\n\t\" agent(prompt, opts) -> string | object | null\\n\" +\n\t\" parallel(thunks) -> array (barrier; a failed thunk becomes null)\\n\" +\n\t\" pipeline(items, ...stages) -> array (no barrier between stages)\\n\" +\n\t\" phase(title), log(...parts), args, budget\\n\\n\" +\n\t\"agent() returns null when the agent failed, was cancelled, or produced no valid structured \" +\n\t\"output. It throws for invalid options, an unknown agentType/model, an invalid effort, or the \" +\n\t\"per-run agent cap. Reserved names (never redeclare): agent, parallel, pipeline, phase, log, \" +\n\t\"args, budget, meta. Math.random, Date.now, Date() and new Date() throw; new Date(value) works. \" +\n\t\"No workflow can start another workflow.\\n\\n\" +\n\t\"Call this tool with either `script` (a new script) or `name` (a saved workflow). Set `args` \" +\n\t\"for the script's input string and `budgetTokens` to cap total billable tokens.\";\n\nexport const WORKFLOW_PROMPT_SNIPPET =\n\t\"Run a multi-agent workflow script (phases, parallel agents, pipelines) with live oversight\";\n\nexport const WORKFLOW_PROMPT_GUIDELINES: readonly string[] = [\n\t\"Use the workflow tool for multi-phase tasks that benefit from several subagents running in parallel or in a pipeline, with live oversight in the TUI.\",\n\t\"Write `export const meta = {...}` first, as a plain literal (no identifiers, calls, or template-literal interpolation), then an async body using agent, parallel, pipeline, phase, log, args and budget.\",\n\t\"Each agent() call is a separate paid model session that cannot ask for permissions; give it a self-contained task and ask it to end with a STATUS line.\",\n\t\"agent() returns null on failure, cancellation, or budget exhaustion; always check for null before using the result.\",\n];\n\nexport interface AuthoringGuideInput {\n\tagentTypes: readonly string[];\n\tsavedNames: readonly string[];\n\tlimits: { concurrency: number; maxAgents: number; maxItems: number };\n}\n\nexport function buildAuthoringGuide(input: AuthoringGuideInput): string {\n\tconst agentTypesLine = input.agentTypes.length > 0 ? input.agentTypes.join(\", \") : \"(none discovered)\";\n\tconst savedNamesLine = input.savedNames.length > 0 ? input.savedNames.join(\", \") : \"(none saved)\";\n\n\treturn `# Writing a polyphase workflow\n\nA workflow script is plain JavaScript. It runs in a sandbox with no imports and no filesystem or\nnetwork access of its own -- all real work happens inside the subagents it starts with agent().\n\n## 1. The meta block comes first\n\n\\`\\`\\`js\nexport const meta = {\n name: \"review-pr\", // ^[a-z][a-z0-9-]{0,47}$, used for /review-pr if you save it\n description: \"Review a change in parallel and synthesize findings\", // 1-300 chars\n whenToUse: \"...\", // optional, <= 300 chars\n phases: [ // 1-20 entries\n { title: \"Scan\" },\n { title: \"Review\" },\n { title: \"Synthesize\", model: \"anthropic/claude-opus-5-5\" }, // optional per-phase model\n ],\n};\n\\`\\`\\`\n\nmeta must be a pure literal: no identifiers, function calls, spreads, computed keys, template\ninterpolation (\\${...}), or regex literals. Unknown keys are warnings, not errors.\n\n## 2. The API\n\n- \\`agent(prompt, opts)\\` starts one subagent and returns its final text, or the schema-validated\n object when \\`opts.schema\\` is set. It returns \\`null\\` when the agent failed, was cancelled (by\n the user or the token budget), the budget was already exhausted, or no valid structured output\n was produced -- always check for null. It throws for invalid options, an unknown model/agentType,\n an invalid effort, or hitting the per-run agent cap.\n opts: { label, phase, schema, model, effort, isolation: \"worktree\", agentType }\n- \\`parallel(thunks)\\` runs an array of zero-argument thunks (each should call agent()) and waits\n for all of them (a barrier). A thunk that throws becomes null in the result array, with a\n warning logged; parallel() itself never rejects.\n- \\`pipeline(items, ...stages)\\` runs each item through the same stages in sequence, with no\n barrier between stages: each stage \\`(prev, item, index)\\` receives the previous stage's result\n (or the item itself, for the first stage). A throwing stage makes that item null and skips its\n later stages for that item.\n- \\`phase(title)\\` groups the agents started after it under that phase for the live view. Titles\n not declared in meta.phases become dynamic phases, logged once.\n- \\`log(...parts)\\` writes a narrator line visible in the dock and inspector.\n- \\`args\\` is the verbatim string passed to this call (or to /<name>). \\`meta\\` is the frozen meta\n object.\n- \\`budget\\`: { total, spent(), remaining() }. spent() is this run's total billable tokens as of\n the latest agent() reply.\n\n## 3. Determinism and reserved names\n\nMath.random, Date.now, Date() and new Date() all throw -- workflows must be deterministic.\nnew Date(value) still works. Never redeclare: agent, parallel, pipeline, phase, log, args, budget, meta.\n\n## 4. Each agent is a separate paid session\n\nEvery agent() call spawns an independent subagent process. It cannot ask for permissions or see\nanything outside its own prompt, so give it a self-contained task and ask it to end with a\nSTATUS: line you can look for in its output.\n\n## 5. Limits\n\n- Up to ${input.limits.concurrency} agents run at once in this session.\n- Up to ${input.limits.maxAgents} agent() calls total in one workflow run.\n- Up to ${input.limits.maxItems} items per parallel()/pipeline() call.\n\n## 6. Available agent types\n\n${agentTypesLine}\n\n## 7. Saved workflows\n\n${savedNamesLine}\n\n## Example\n\n\\`\\`\\`js\nexport const meta = { name: \"review-pr\", description: \"Review a change in parallel and synthesize findings\",\n phases: [{ title: \"Scan\" }, { title: \"Review\" }, { title: \"Synthesize\", model: \"anthropic/claude-opus-5-5\" }] };\nphase(\"Scan\");\nconst scan = await agent(\\`List the areas touched by \\${args}\\`, { label: \"scan\",\n schema: { type: \"object\", properties: { areas: { type: \"array\", items: { type: \"string\" } } }, required: [\"areas\"] } });\nphase(\"Review\");\nconst reviews = await parallel((scan?.areas ?? []).map((area) => () =>\n agent(\\`Review \\${area} for \\${args}. End with a STATUS line.\\`, { label: \\`review:\\${area}\\`, agentType: \"reviewer\" })));\nphase(\"Synthesize\");\nreturn await agent(\\`Synthesize these reviews:\\\\n\\${reviews.filter(Boolean).join(\"\\\\n---\\\\n\")}\\`, { label: \"synthesize\" });\n\\`\\`\\`\n`;\n}\n"]}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Starts one workflow run (§14.2): creates the store run and mailbox synchronously, then runs the
|
|
3
|
+
* script asynchronously via the lazily-loaded runtime. `done` never rejects.
|
|
4
|
+
*/
|
|
5
|
+
import type { Usage } from "@draht/ai";
|
|
6
|
+
import type { ExtensionContext } from "../../extensions/types.ts";
|
|
7
|
+
import type { PolyphaseSession } from "../session.ts";
|
|
8
|
+
import type { PolyphaseRun } from "../store.ts";
|
|
9
|
+
import type { AgentRunner, PolyphaseDetails, RunOrigin, WorkflowSource } from "../types.ts";
|
|
10
|
+
import type { WorkflowMeta } from "./meta.ts";
|
|
11
|
+
import type { WorkflowOutcome } from "./runtime.ts";
|
|
12
|
+
export interface StartWorkflowRunOptions {
|
|
13
|
+
ctx: ExtensionContext;
|
|
14
|
+
session: PolyphaseSession;
|
|
15
|
+
id: string;
|
|
16
|
+
origin: RunOrigin;
|
|
17
|
+
parentSignal?: AbortSignal;
|
|
18
|
+
meta: WorkflowMeta;
|
|
19
|
+
body: string;
|
|
20
|
+
args: string;
|
|
21
|
+
source: {
|
|
22
|
+
kind: WorkflowSource;
|
|
23
|
+
path?: string;
|
|
24
|
+
};
|
|
25
|
+
budgetTokens: number | null;
|
|
26
|
+
runner?: AgentRunner;
|
|
27
|
+
}
|
|
28
|
+
export interface WorkflowRunCompletion {
|
|
29
|
+
outcome: WorkflowOutcome;
|
|
30
|
+
text: string;
|
|
31
|
+
details: PolyphaseDetails;
|
|
32
|
+
usage: Usage | undefined;
|
|
33
|
+
isError: boolean;
|
|
34
|
+
}
|
|
35
|
+
export interface WorkflowRunHandle {
|
|
36
|
+
readonly run: PolyphaseRun;
|
|
37
|
+
/** Never rejects. */
|
|
38
|
+
readonly done: Promise<WorkflowRunCompletion>;
|
|
39
|
+
}
|
|
40
|
+
export declare function startWorkflowRun(options: StartWorkflowRunOptions): WorkflowRunHandle;
|
|
41
|
+
//# sourceMappingURL=launch.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"launch.d.ts","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/launch.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAEvC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAGlE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,KAAK,EAAE,WAAW,EAAE,gBAAgB,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAE5F,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAE9C,OAAO,KAAK,EAAE,eAAe,EAAuB,MAAM,cAAc,CAAC;AAEzE,MAAM,WAAW,uBAAuB;IACvC,GAAG,EAAE,gBAAgB,CAAC;IACtB,OAAO,EAAE,gBAAgB,CAAC;IAC1B,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,SAAS,CAAC;IAClB,YAAY,CAAC,EAAE,W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