@draht/coding-agent 2026.10.4 → 2026.10.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/README.md +32 -6
- package/dist/bundle/chunks/anthropic.js +1 -1
- package/dist/bundle/chunks/{chunk-DPE4ALPU.js → chunk-2VAF4XJI.js} +1 -1
- package/dist/bundle/chunks/chunk-6APPDDHH.js +65 -0
- package/dist/bundle/chunks/{chunk-LDAOC5RB.js → chunk-JFDPOIUH.js} +1 -1
- package/dist/bundle/chunks/{chunk-COF5JT7R.js → chunk-KU5HAKZL.js} +1 -1
- package/dist/bundle/chunks/{chunk-Z2INEV2J.js → chunk-MIUVNYYW.js} +292 -153
- package/dist/bundle/chunks/{chunk-5VZWYVZB.js → chunk-NHTOADU6.js} +2 -2
- package/dist/bundle/chunks/{chunk-H6FT43VC.js → chunk-OWGSPJPZ.js} +4 -4
- package/dist/bundle/chunks/chunk-PGJAHC3R.js +107 -0
- package/dist/bundle/chunks/chunk-QVFELZW2.js +312 -0
- package/dist/bundle/chunks/{chunk-XKDTJ4YR.js → chunk-TJ3AW62W.js} +1 -1
- package/dist/bundle/chunks/{cli-SR5QBZH4.js → cli-U7Y4VNNI.js} +1 -1
- package/dist/bundle/chunks/execute-ZWB4PIQQ.js +18 -0
- package/dist/bundle/chunks/google-antigravity.js +1 -1
- package/dist/bundle/chunks/google-gemini-cli.js +1 -1
- package/dist/bundle/chunks/openai-chatgpt.js +1 -1
- package/dist/bundle/chunks/openai-codex.js +1 -1
- package/dist/bundle/chunks/openrouter.js +1 -1
- package/dist/bundle/chunks/radius.js +1 -1
- package/dist/bundle/chunks/runtime-363BOYEO.js +3 -0
- package/dist/bundle/chunks/{runtime-6YJPGSP7.js → runtime-PXJK4L7Y.js} +1 -1
- package/dist/bundle/chunks/{settings-manager-D2EG7WDO.js → settings-manager-GEOZJXFQ.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-BEJ4ZJ3D.js +2 -0
- package/dist/bundle/chunks/xai.js +1 -1
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/cli/args.js +3 -3
- package/dist/cli/args.js.map +1 -1
- package/dist/core/builtins/duet.d.ts +5 -2
- package/dist/core/builtins/duet.d.ts.map +1 -1
- package/dist/core/builtins/duet.js +65 -27
- package/dist/core/builtins/duet.js.map +1 -1
- package/dist/core/builtins/index.d.ts.map +1 -1
- package/dist/core/builtins/index.js +2 -0
- package/dist/core/builtins/index.js.map +1 -1
- package/dist/core/builtins/polyphase.d.ts +15 -0
- package/dist/core/builtins/polyphase.d.ts.map +1 -0
- package/dist/core/builtins/polyphase.js +196 -0
- package/dist/core/builtins/polyphase.js.map +1 -0
- package/dist/core/builtins/subagent.d.ts +44 -34
- package/dist/core/builtins/subagent.d.ts.map +1 -1
- package/dist/core/builtins/subagent.js +827 -560
- package/dist/core/builtins/subagent.js.map +1 -1
- package/dist/core/extensions/types.d.ts +17 -2
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/keybindings.d.ts +30 -0
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +24 -0
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/model-resolver.js +4 -4
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/multi-agent/permission-gate.d.ts.map +1 -1
- package/dist/core/multi-agent/permission-gate.js +4 -1
- package/dist/core/multi-agent/permission-gate.js.map +1 -1
- package/dist/core/polyphase/approval.d.ts +35 -0
- package/dist/core/polyphase/approval.d.ts.map +1 -0
- package/dist/core/polyphase/approval.js +184 -0
- package/dist/core/polyphase/approval.js.map +1 -0
- package/dist/core/polyphase/child-events.d.ts +107 -0
- package/dist/core/polyphase/child-events.d.ts.map +1 -0
- package/dist/core/polyphase/child-events.js +862 -0
- package/dist/core/polyphase/child-events.js.map +1 -0
- package/dist/core/polyphase/child-process.d.ts +65 -0
- package/dist/core/polyphase/child-process.d.ts.map +1 -0
- package/dist/core/polyphase/child-process.js +361 -0
- package/dist/core/polyphase/child-process.js.map +1 -0
- package/dist/core/polyphase/commands.d.ts +44 -0
- package/dist/core/polyphase/commands.d.ts.map +1 -0
- package/dist/core/polyphase/commands.js +244 -0
- package/dist/core/polyphase/commands.js.map +1 -0
- package/dist/core/polyphase/details.d.ts +40 -0
- package/dist/core/polyphase/details.d.ts.map +1 -0
- package/dist/core/polyphase/details.js +538 -0
- package/dist/core/polyphase/details.js.map +1 -0
- package/dist/core/polyphase/emitter.d.ts +20 -0
- package/dist/core/polyphase/emitter.d.ts.map +1 -0
- package/dist/core/polyphase/emitter.js +90 -0
- package/dist/core/polyphase/emitter.js.map +1 -0
- package/dist/core/polyphase/jsonl-reader.d.ts +31 -0
- package/dist/core/polyphase/jsonl-reader.d.ts.map +1 -0
- package/dist/core/polyphase/jsonl-reader.js +161 -0
- package/dist/core/polyphase/jsonl-reader.js.map +1 -0
- package/dist/core/polyphase/keyword.d.ts +27 -0
- package/dist/core/polyphase/keyword.d.ts.map +1 -0
- package/dist/core/polyphase/keyword.js +97 -0
- package/dist/core/polyphase/keyword.js.map +1 -0
- package/dist/core/polyphase/limiter.d.ts +38 -0
- package/dist/core/polyphase/limiter.d.ts.map +1 -0
- package/dist/core/polyphase/limiter.js +129 -0
- package/dist/core/polyphase/limiter.js.map +1 -0
- package/dist/core/polyphase/model-selection.d.ts +35 -0
- package/dist/core/polyphase/model-selection.d.ts.map +1 -0
- package/dist/core/polyphase/model-selection.js +72 -0
- package/dist/core/polyphase/model-selection.js.map +1 -0
- package/dist/core/polyphase/render/format.d.ts +52 -0
- package/dist/core/polyphase/render/format.d.ts.map +1 -0
- package/dist/core/polyphase/render/format.js +169 -0
- package/dist/core/polyphase/render/format.js.map +1 -0
- package/dist/core/polyphase/render/renderers.d.ts +63 -0
- package/dist/core/polyphase/render/renderers.d.ts.map +1 -0
- package/dist/core/polyphase/render/renderers.js +277 -0
- package/dist/core/polyphase/render/renderers.js.map +1 -0
- package/dist/core/polyphase/render/run-block.d.ts +45 -0
- package/dist/core/polyphase/render/run-block.d.ts.map +1 -0
- package/dist/core/polyphase/render/run-block.js +843 -0
- package/dist/core/polyphase/render/run-block.js.map +1 -0
- package/dist/core/polyphase/render/snapshot.d.ts +106 -0
- package/dist/core/polyphase/render/snapshot.d.ts.map +1 -0
- package/dist/core/polyphase/render/snapshot.js +292 -0
- package/dist/core/polyphase/render/snapshot.js.map +1 -0
- package/dist/core/polyphase/result-text.d.ts +41 -0
- package/dist/core/polyphase/result-text.d.ts.map +1 -0
- package/dist/core/polyphase/result-text.js +326 -0
- package/dist/core/polyphase/result-text.js.map +1 -0
- package/dist/core/polyphase/session.d.ts +33 -0
- package/dist/core/polyphase/session.d.ts.map +1 -0
- package/dist/core/polyphase/session.js +106 -0
- package/dist/core/polyphase/session.js.map +1 -0
- package/dist/core/polyphase/settings.d.ts +18 -0
- package/dist/core/polyphase/settings.d.ts.map +1 -0
- package/dist/core/polyphase/settings.js +93 -0
- package/dist/core/polyphase/settings.js.map +1 -0
- package/dist/core/polyphase/store.d.ts +197 -0
- package/dist/core/polyphase/store.d.ts.map +1 -0
- package/dist/core/polyphase/store.js +558 -0
- package/dist/core/polyphase/store.js.map +1 -0
- package/dist/core/polyphase/types.d.ts +371 -0
- package/dist/core/polyphase/types.d.ts.map +1 -0
- package/dist/core/polyphase/types.js +36 -0
- package/dist/core/polyphase/types.js.map +1 -0
- package/dist/core/polyphase/ui/controller.d.ts +28 -0
- package/dist/core/polyphase/ui/controller.d.ts.map +1 -0
- package/dist/core/polyphase/ui/controller.js +150 -0
- package/dist/core/polyphase/ui/controller.js.map +1 -0
- package/dist/core/polyphase/ui/dock.d.ts +27 -0
- package/dist/core/polyphase/ui/dock.d.ts.map +1 -0
- package/dist/core/polyphase/ui/dock.js +121 -0
- package/dist/core/polyphase/ui/dock.js.map +1 -0
- package/dist/core/polyphase/ui/inspector.d.ts +117 -0
- package/dist/core/polyphase/ui/inspector.d.ts.map +1 -0
- package/dist/core/polyphase/ui/inspector.js +1016 -0
- package/dist/core/polyphase/ui/inspector.js.map +1 -0
- package/dist/core/polyphase/ui/transcript-layout.d.ts +55 -0
- package/dist/core/polyphase/ui/transcript-layout.d.ts.map +1 -0
- package/dist/core/polyphase/ui/transcript-layout.js +210 -0
- package/dist/core/polyphase/ui/transcript-layout.js.map +1 -0
- package/dist/core/polyphase/update-pump.d.ts +18 -0
- package/dist/core/polyphase/update-pump.d.ts.map +1 -0
- package/dist/core/polyphase/update-pump.js +132 -0
- package/dist/core/polyphase/update-pump.js.map +1 -0
- package/dist/core/polyphase/workflow/agent-host.d.ts +26 -0
- package/dist/core/polyphase/workflow/agent-host.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/agent-host.js +187 -0
- package/dist/core/polyphase/workflow/agent-host.js.map +1 -0
- package/dist/core/polyphase/workflow/guidance.d.ts +19 -0
- package/dist/core/polyphase/workflow/guidance.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/guidance.js +119 -0
- package/dist/core/polyphase/workflow/guidance.js.map +1 -0
- package/dist/core/polyphase/workflow/launch.d.ts +41 -0
- package/dist/core/polyphase/workflow/launch.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/launch.js +173 -0
- package/dist/core/polyphase/workflow/launch.js.map +1 -0
- package/dist/core/polyphase/workflow/meta.d.ts +43 -0
- package/dist/core/polyphase/workflow/meta.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/meta.js +529 -0
- package/dist/core/polyphase/workflow/meta.js.map +1 -0
- package/dist/core/polyphase/workflow/prelude.d.ts +24 -0
- package/dist/core/polyphase/workflow/prelude.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/prelude.js +93 -0
- package/dist/core/polyphase/workflow/prelude.js.map +1 -0
- package/dist/core/polyphase/workflow/runtime.d.ts +79 -0
- package/dist/core/polyphase/workflow/runtime.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/runtime.js +217 -0
- package/dist/core/polyphase/workflow/runtime.js.map +1 -0
- package/dist/core/polyphase/workflow/runtime.lazy.d.ts +3 -0
- package/dist/core/polyphase/workflow/runtime.lazy.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/runtime.lazy.js +3 -0
- package/dist/core/polyphase/workflow/runtime.lazy.js.map +1 -0
- package/dist/core/polyphase/workflow/saved.d.ts +55 -0
- package/dist/core/polyphase/workflow/saved.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/saved.js +299 -0
- package/dist/core/polyphase/workflow/saved.js.map +1 -0
- package/dist/core/polyphase/workflow/structured-output.d.ts +22 -0
- package/dist/core/polyphase/workflow/structured-output.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/structured-output.js +66 -0
- package/dist/core/polyphase/workflow/structured-output.js.map +1 -0
- package/dist/core/polyphase/workflow/tool.d.ts +24 -0
- package/dist/core/polyphase/workflow/tool.d.ts.map +1 -0
- package/dist/core/polyphase/workflow/tool.js +139 -0
- package/dist/core/polyphase/workflow/tool.js.map +1 -0
- package/dist/core/sdk.d.ts +1 -1
- package/dist/core/sdk.js +1 -1
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/settings-manager.d.ts +27 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/socket-server/permission-relay.js +4 -0
- package/dist/core/socket-server/permission-relay.js.map +1 -1
- package/dist/core/trust-manager.d.ts +3 -2
- package/dist/core/trust-manager.d.ts.map +1 -1
- package/dist/core/trust-manager.js +5 -2
- package/dist/core/trust-manager.js.map +1 -1
- package/dist/experimental/micro/runtime.js +1 -1
- package/dist/experimental/micro/runtime.js.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.d.ts +7 -0
- package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.js +18 -0
- package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +11 -2
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +9 -0
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/prompts/commands/orchestrate.md +1 -1
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +7 -1
- package/dist/utils/shell.js.map +1 -1
- package/docs/docs.json +4 -0
- package/docs/duet.md +3 -3
- package/docs/environment-variables.md +11 -0
- package/docs/json.md +7 -0
- package/docs/keybindings.md +20 -0
- package/docs/polyphase.md +391 -0
- package/docs/rpc-commands.md +9 -9
- package/docs/settings.md +12 -0
- package/docs/virtual-models.md +3 -3
- package/examples/extensions/preset.ts +3 -3
- package/examples/extensions/subagent/README.md +1 -1
- package/examples/extensions/subagent/agents/planner.md +1 -1
- package/examples/extensions/subagent/agents/reviewer.md +1 -1
- package/examples/extensions/subagent/agents/scout.md +1 -1
- package/examples/extensions/subagent/agents/worker.md +1 -1
- package/examples/extensions/summarize.ts +3 -3
- package/examples/sdk/02-custom-model.ts +1 -1
- package/examples/sdk/12-full-control.ts +1 -1
- package/examples/sdk/README.md +1 -1
- package/package.json +10 -10
- package/prompts/commands/orchestrate.md +1 -1
- package/dist/bundle/chunks/chunk-CEJJ5XF2.js +0 -170
- package/dist/bundle/chunks/execute-VCYDHEYA.js +0 -328
- package/dist/bundle/chunks/virtual-modules-JTCGDL2Z.js +0 -2
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Discovery of saved workflow scripts: `<agentDir>/workflows/*.js` (user) and the nearest
|
|
3
|
+
* trusted `.draht/workflows/*.js` (project), mirroring `findProjectAgentsDir` in
|
|
4
|
+
* `builtins/subagent.ts`. See DESIGN.md §16.1.
|
|
5
|
+
*/
|
|
6
|
+
import * as fs from "node:fs";
|
|
7
|
+
import * as path from "node:path";
|
|
8
|
+
import { CONFIG_DIR_NAME } from "../../../config.js";
|
|
9
|
+
import { realPathStrict } from "../../../utils/canonical-path.js";
|
|
10
|
+
import { extractWorkflowMeta, WORKFLOW_NAME_PATTERN } from "./meta.js";
|
|
11
|
+
export const SAVED_WORKFLOW_MAX_BYTES = 262_144;
|
|
12
|
+
/**
|
|
13
|
+
* `lstatSync` first, never `statSync` outright: a fifo, socket or device reports its real type
|
|
14
|
+
* without being opened, so callers can refuse it before any `readSync` could block forever on it.
|
|
15
|
+
* A symlink is followed once (saved workflows may be symlinked in), then the same check applies to
|
|
16
|
+
* its target. Returns undefined for anything that isn't ultimately a regular file.
|
|
17
|
+
*/
|
|
18
|
+
function statRegularFile(filePath) {
|
|
19
|
+
let stats;
|
|
20
|
+
try {
|
|
21
|
+
stats = fs.lstatSync(filePath);
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
if (stats.isSymbolicLink()) {
|
|
27
|
+
try {
|
|
28
|
+
stats = fs.statSync(filePath);
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return undefined;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return stats.isFile() ? stats : undefined;
|
|
35
|
+
}
|
|
36
|
+
/** Reads up to `size` bytes from `fd`, stopping early at EOF. */
|
|
37
|
+
function readIntoBuffer(fd, size) {
|
|
38
|
+
const buffer = Buffer.allocUnsafe(Math.max(0, size));
|
|
39
|
+
let bytesRead = 0;
|
|
40
|
+
while (bytesRead < buffer.length) {
|
|
41
|
+
const chunk = fs.readSync(fd, buffer, bytesRead, buffer.length - bytesRead, null);
|
|
42
|
+
if (chunk === 0)
|
|
43
|
+
break;
|
|
44
|
+
bytesRead += chunk;
|
|
45
|
+
}
|
|
46
|
+
return { buffer, bytesRead };
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Opens with `O_NONBLOCK` (so a fifo with no writer returns immediately instead of blocking the
|
|
50
|
+
* event loop) and rejects anything that isn't a regular file by `fstat`ing the opened descriptor,
|
|
51
|
+
* which closes the TOCTOU window a separate `lstat`-then-`open` would leave between the two calls.
|
|
52
|
+
*
|
|
53
|
+
* `sizeHint` comes from a `statRegularFile` the caller already did, so the first read is sized for
|
|
54
|
+
* the common case (a small script) instead of always zero-filling a 256 KiB buffer. If the file
|
|
55
|
+
* grew past `sizeHint` since that stat, the first read fills exactly and a second read, sized to
|
|
56
|
+
* the real remaining budget, decides whether the file is genuinely over `SAVED_WORKFLOW_MAX_BYTES`
|
|
57
|
+
* or just grew by a few bytes — a `sizeHint`-sized probe alone would misreport the latter as too
|
|
58
|
+
* large.
|
|
59
|
+
*/
|
|
60
|
+
function readBoundedUtf8(filePath, sizeHint) {
|
|
61
|
+
const fd = fs.openSync(filePath, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK);
|
|
62
|
+
try {
|
|
63
|
+
if (!fs.fstatSync(fd).isFile())
|
|
64
|
+
return { kind: "not-regular" };
|
|
65
|
+
const hinted = Math.min(Math.max(sizeHint, 0), SAVED_WORKFLOW_MAX_BYTES);
|
|
66
|
+
const first = readIntoBuffer(fd, hinted + 1);
|
|
67
|
+
if (first.bytesRead <= hinted) {
|
|
68
|
+
return { kind: "ok", content: first.buffer.toString("utf-8", 0, first.bytesRead) };
|
|
69
|
+
}
|
|
70
|
+
if (hinted >= SAVED_WORKFLOW_MAX_BYTES)
|
|
71
|
+
return { kind: "too-large" };
|
|
72
|
+
const rest = readIntoBuffer(fd, SAVED_WORKFLOW_MAX_BYTES - hinted);
|
|
73
|
+
if (rest.bytesRead >= SAVED_WORKFLOW_MAX_BYTES - hinted)
|
|
74
|
+
return { kind: "too-large" };
|
|
75
|
+
const content = Buffer.concat([
|
|
76
|
+
first.buffer.subarray(0, first.bytesRead),
|
|
77
|
+
rest.buffer.subarray(0, rest.bytesRead),
|
|
78
|
+
]).toString("utf-8");
|
|
79
|
+
return { kind: "ok", content };
|
|
80
|
+
}
|
|
81
|
+
finally {
|
|
82
|
+
fs.closeSync(fd);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function metaToWorkflow(basename, filePath, source, extraction) {
|
|
86
|
+
if (!extraction.ok) {
|
|
87
|
+
return {
|
|
88
|
+
name: basename,
|
|
89
|
+
description: "",
|
|
90
|
+
phases: [],
|
|
91
|
+
path: filePath,
|
|
92
|
+
source,
|
|
93
|
+
valid: false,
|
|
94
|
+
error: `${extraction.error.message} (line ${extraction.error.line})`,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
const workflow = {
|
|
98
|
+
name: basename,
|
|
99
|
+
description: extraction.meta.description,
|
|
100
|
+
phases: extraction.meta.phases,
|
|
101
|
+
path: filePath,
|
|
102
|
+
source,
|
|
103
|
+
valid: true,
|
|
104
|
+
};
|
|
105
|
+
if (extraction.meta.whenToUse !== undefined)
|
|
106
|
+
workflow.whenToUse = extraction.meta.whenToUse;
|
|
107
|
+
return workflow;
|
|
108
|
+
}
|
|
109
|
+
function loadWorkflowsFromDir(dir, source) {
|
|
110
|
+
const workflows = [];
|
|
111
|
+
const diagnostics = [];
|
|
112
|
+
let entries;
|
|
113
|
+
try {
|
|
114
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
return { workflows, diagnostics };
|
|
118
|
+
}
|
|
119
|
+
for (const entry of entries) {
|
|
120
|
+
if (!entry.name.endsWith(".js"))
|
|
121
|
+
continue;
|
|
122
|
+
const filePath = path.join(dir, entry.name);
|
|
123
|
+
const stat = statRegularFile(filePath);
|
|
124
|
+
if (!stat)
|
|
125
|
+
continue;
|
|
126
|
+
if (stat.size > SAVED_WORKFLOW_MAX_BYTES) {
|
|
127
|
+
diagnostics.push({
|
|
128
|
+
path: filePath,
|
|
129
|
+
level: "warning",
|
|
130
|
+
message: `Saved workflow file "${entry.name}" was skipped: ${stat.size} bytes exceeds the ${SAVED_WORKFLOW_MAX_BYTES}-byte limit.`,
|
|
131
|
+
});
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
const basename = entry.name.slice(0, -3);
|
|
135
|
+
if (!WORKFLOW_NAME_PATTERN.test(basename)) {
|
|
136
|
+
diagnostics.push({
|
|
137
|
+
path: filePath,
|
|
138
|
+
level: "warning",
|
|
139
|
+
message: `Saved workflow file "${entry.name}" was skipped: its name must match ${WORKFLOW_NAME_PATTERN} (lowercase letters, digits and hyphens, starting with a letter, at most 48 characters).`,
|
|
140
|
+
});
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
let content;
|
|
144
|
+
try {
|
|
145
|
+
const read = readBoundedUtf8(filePath, stat.size);
|
|
146
|
+
if (read.kind === "not-regular") {
|
|
147
|
+
diagnostics.push({
|
|
148
|
+
path: filePath,
|
|
149
|
+
level: "warning",
|
|
150
|
+
message: `Saved workflow file "${entry.name}" was skipped: it is no longer a regular file.`,
|
|
151
|
+
});
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
if (read.kind === "too-large") {
|
|
155
|
+
diagnostics.push({
|
|
156
|
+
path: filePath,
|
|
157
|
+
level: "warning",
|
|
158
|
+
message: `Saved workflow file "${entry.name}" was skipped: it exceeds the ${SAVED_WORKFLOW_MAX_BYTES}-byte limit.`,
|
|
159
|
+
});
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
content = read.content;
|
|
163
|
+
}
|
|
164
|
+
catch (error) {
|
|
165
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
166
|
+
diagnostics.push({
|
|
167
|
+
path: filePath,
|
|
168
|
+
level: "warning",
|
|
169
|
+
message: `Saved workflow "${basename}" could not be read: ${message}`,
|
|
170
|
+
});
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
const extraction = extractWorkflowMeta(content);
|
|
174
|
+
if (!extraction.ok) {
|
|
175
|
+
diagnostics.push({
|
|
176
|
+
path: filePath,
|
|
177
|
+
level: "warning",
|
|
178
|
+
message: `Saved workflow "${basename}" has an invalid meta block: ${extraction.error.message} (line ${extraction.error.line}).`,
|
|
179
|
+
});
|
|
180
|
+
workflows.push(metaToWorkflow(basename, filePath, source, extraction));
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
if (extraction.meta.name !== basename) {
|
|
184
|
+
diagnostics.push({
|
|
185
|
+
path: filePath,
|
|
186
|
+
level: "info",
|
|
187
|
+
message: `Saved workflow file "${entry.name}" declares meta.name "${extraction.meta.name}"; using the file name "${basename}" instead.`,
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
workflows.push(metaToWorkflow(basename, filePath, source, extraction));
|
|
191
|
+
}
|
|
192
|
+
return { workflows, diagnostics };
|
|
193
|
+
}
|
|
194
|
+
/** Mirrors `findProjectAgentsDir` in `builtins/subagent.ts`: walk up from the real cwd for the nearest `.draht/workflows`. */
|
|
195
|
+
function findProjectWorkflowsDir(cwd) {
|
|
196
|
+
const realCwd = realPathStrict(cwd);
|
|
197
|
+
if (realCwd === undefined)
|
|
198
|
+
return null;
|
|
199
|
+
let dir = realCwd;
|
|
200
|
+
while (true) {
|
|
201
|
+
const candidate = path.join(dir, CONFIG_DIR_NAME, "workflows");
|
|
202
|
+
try {
|
|
203
|
+
if (fs.statSync(candidate).isDirectory())
|
|
204
|
+
return candidate;
|
|
205
|
+
}
|
|
206
|
+
catch { }
|
|
207
|
+
const parent = path.dirname(dir);
|
|
208
|
+
if (parent === dir)
|
|
209
|
+
return null;
|
|
210
|
+
dir = parent;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
export function discoverSavedWorkflows(options) {
|
|
214
|
+
const userDir = path.join(options.agentDir, "workflows");
|
|
215
|
+
const projectDir = options.projectTrusted ? findProjectWorkflowsDir(options.cwd) : null;
|
|
216
|
+
const userResult = loadWorkflowsFromDir(userDir, "user");
|
|
217
|
+
const projectResult = projectDir ? loadWorkflowsFromDir(projectDir, "project") : { workflows: [], diagnostics: [] };
|
|
218
|
+
const diagnostics = [...userResult.diagnostics, ...projectResult.diagnostics];
|
|
219
|
+
const byName = new Map();
|
|
220
|
+
for (const workflow of userResult.workflows)
|
|
221
|
+
byName.set(workflow.name, workflow);
|
|
222
|
+
for (const workflow of projectResult.workflows) {
|
|
223
|
+
const existing = byName.get(workflow.name);
|
|
224
|
+
if (existing && existing.source === "user") {
|
|
225
|
+
diagnostics.push({
|
|
226
|
+
path: workflow.path,
|
|
227
|
+
level: "info",
|
|
228
|
+
message: `Project workflow "${workflow.name}" overrides the user workflow at ${existing.path}.`,
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
byName.set(workflow.name, workflow);
|
|
232
|
+
}
|
|
233
|
+
const workflows = Array.from(byName.values()).sort((a, b) => a.name.localeCompare(b.name));
|
|
234
|
+
return { workflows, diagnostics };
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Looks up a single name directly in the project then user workflow directories, instead of
|
|
238
|
+
* discovering (opening, reading and meta-parsing) every file in both. Called on every workflow
|
|
239
|
+
* approval and again on every saved-workflow execution, so a directory with many saved workflows
|
|
240
|
+
* would otherwise redo that work twice per run.
|
|
241
|
+
*/
|
|
242
|
+
export function findSavedWorkflow(name, options) {
|
|
243
|
+
if (!WORKFLOW_NAME_PATTERN.test(name))
|
|
244
|
+
return undefined;
|
|
245
|
+
if (options.projectTrusted) {
|
|
246
|
+
const projectDir = findProjectWorkflowsDir(options.cwd);
|
|
247
|
+
if (projectDir) {
|
|
248
|
+
const found = loadSingleWorkflowFile(projectDir, name, "project");
|
|
249
|
+
if (found)
|
|
250
|
+
return found;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return loadSingleWorkflowFile(path.join(options.agentDir, "workflows"), name, "user");
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Never throws: a read error (e.g. `EACCES`) or a file that is no longer a regular file or too
|
|
257
|
+
* large is reported the same way discovery does, as "not found here", so `findSavedWorkflow`
|
|
258
|
+
* falls back to the next source instead of raising an error from an unrelated code path.
|
|
259
|
+
*/
|
|
260
|
+
function loadSingleWorkflowFile(dir, name, source) {
|
|
261
|
+
const filePath = path.join(dir, `${name}.js`);
|
|
262
|
+
const stat = statRegularFile(filePath);
|
|
263
|
+
if (!stat || stat.size > SAVED_WORKFLOW_MAX_BYTES)
|
|
264
|
+
return undefined;
|
|
265
|
+
try {
|
|
266
|
+
const read = readBoundedUtf8(filePath, stat.size);
|
|
267
|
+
if (read.kind !== "ok")
|
|
268
|
+
return undefined;
|
|
269
|
+
return metaToWorkflow(name, filePath, source, extractWorkflowMeta(read.content));
|
|
270
|
+
}
|
|
271
|
+
catch {
|
|
272
|
+
return undefined;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Throws when the file is no longer a regular file (e.g. replaced by a fifo since discovery),
|
|
277
|
+
* cannot be read, or has grown past {@link SAVED_WORKFLOW_MAX_BYTES} since discovery. The
|
|
278
|
+
* `statRegularFile` call below is only an early refusal and a size hint for `readBoundedUtf8`;
|
|
279
|
+
* the authoritative regular-file check happens on the opened fd inside `readBoundedUtf8` itself,
|
|
280
|
+
* so a swap between this stat and that open (e.g. into a fifo) still can't hang the read.
|
|
281
|
+
*/
|
|
282
|
+
export function readSavedWorkflowSource(workflow) {
|
|
283
|
+
const stat = statRegularFile(workflow.path);
|
|
284
|
+
if (!stat) {
|
|
285
|
+
throw new Error(`Saved workflow "${workflow.name}" is no longer a regular file.`);
|
|
286
|
+
}
|
|
287
|
+
if (stat.size > SAVED_WORKFLOW_MAX_BYTES) {
|
|
288
|
+
throw new Error(`Saved workflow "${workflow.name}" is too large (${stat.size} bytes, max ${SAVED_WORKFLOW_MAX_BYTES}).`);
|
|
289
|
+
}
|
|
290
|
+
const read = readBoundedUtf8(workflow.path, stat.size);
|
|
291
|
+
if (read.kind === "not-regular") {
|
|
292
|
+
throw new Error(`Saved workflow "${workflow.name}" is no longer a regular file.`);
|
|
293
|
+
}
|
|
294
|
+
if (read.kind === "too-large") {
|
|
295
|
+
throw new Error(`Saved workflow "${workflow.name}" is too large (max ${SAVED_WORKFLOW_MAX_BYTES} bytes).`);
|
|
296
|
+
}
|
|
297
|
+
return read.content;
|
|
298
|
+
}
|
|
299
|
+
//# sourceMappingURL=saved.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"saved.js","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/saved.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EAAE,cAAc,EAAE,MAAM,kCAAkC,CAAC;AAClE,OAAO,EAAE,mBAAmB,EAAuB,qBAAqB,EAA0B,MAAM,WAAW,CAAC;AAEpH,MAAM,CAAC,MAAM,wBAAwB,GAAG,OAAO,CAAC;AAsChD;;;;;GAKG;AACH,SAAS,eAAe,CAAC,QAAgB;IACxC,IAAI,KAAe,CAAC;IACpB,IAAI,CAAC;QACJ,KAAK,GAAG,EAAE,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;IAChC,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,SAAS,CAAC;IAClB,CAAC;IACD,IAAI,KAAK,CAAC,cAAc,EAAE,EAAE,CAAC;QAC5B,IAAI,CAAC;YACJ,KAAK,GAAG,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;QAC/B,CAAC;QAAC,MAAM,CAAC;YACR,OAAO,SAAS,CAAC;QAClB,CAAC;IACF,CAAC;IACD,OAAO,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AAC3C,CAAC;AAUD,iEAAiE;AACjE,SAAS,cAAc,CAAC,EAAU,EAAE,IAAY;IAC/C,MAAM,MAAM,GAAG,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,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C,CAAC;IACnF,CAAC;IACD,IAAI,IAAI,CAAC,IAAI,KAAK,WAAW,EAAE,CAAC;QAC/B,MAAM,IAAI,KAAK,CAAC,mBAAmB,QAAQ,CAAC,IAAI,uBAAuB,wBAAwB,UAAU,CAAC,CAAC;IAC5G,CAAC;IACD,OAAO,IAAI,CAAC,OAAO,CAAC;AACrB,CAAC","sourcesContent":["/**\n * Discovery of saved workflow scripts: `<agentDir>/workflows/*.js` (user) and the nearest\n * trusted `.draht/workflows/*.js` (project), mirroring `findProjectAgentsDir` in\n * `builtins/subagent.ts`. See DESIGN.md §16.1.\n */\n\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { CONFIG_DIR_NAME } from \"../../../config.ts\";\nimport { realPathStrict } from \"../../../utils/canonical-path.ts\";\nimport { extractWorkflowMeta, type MetaExtraction, WORKFLOW_NAME_PATTERN, type WorkflowPhaseMeta } from \"./meta.ts\";\n\nexport const SAVED_WORKFLOW_MAX_BYTES = 262_144;\n\nexport interface SavedWorkflow {\n\tname: string;\n\tdescription: string;\n\twhenToUse?: string;\n\tphases: WorkflowPhaseMeta[];\n\tpath: string;\n\tsource: \"project\" | \"user\";\n\tvalid: boolean;\n\terror?: string;\n}\n\nexport interface SavedWorkflowDiagnostic {\n\tpath: string;\n\tlevel: \"warning\" | \"info\";\n\tmessage: string;\n}\n\nexport interface SavedWorkflowSummary {\n\tname: string;\n\tdescription: string;\n\tsource: \"project\" | \"user\";\n\tvalid: boolean;\n\tcommand?: string;\n}\n\nexport interface SavedDiscoveryOptions {\n\tcwd: string;\n\tagentDir: string;\n\tprojectTrusted: boolean;\n}\n\nexport interface DirDiscovery {\n\tworkflows: SavedWorkflow[];\n\tdiagnostics: SavedWorkflowDiagnostic[];\n}\n\n/**\n * `lstatSync` first, never `statSync` outright: a fifo, socket or device reports its real type\n * without being opened, so callers can refuse it before any `readSync` could block forever on it.\n * A symlink is followed once (saved workflows may be symlinked in), then the same check applies to\n * its target. Returns undefined for anything that isn't ultimately a regular file.\n */\nfunction statRegularFile(filePath: string): fs.Stats | undefined {\n\tlet stats: fs.Stats;\n\ttry {\n\t\tstats = fs.lstatSync(filePath);\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (stats.isSymbolicLink()) {\n\t\ttry {\n\t\t\tstats = fs.statSync(filePath);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\treturn stats.isFile() ? stats : undefined;\n}\n\ntype BoundedReadResult =\n\t| { kind: \"ok\"; content: string }\n\t/** The opened fd is not a regular file: a fifo, socket or device swapped in since the\n\t * caller's own stat (TOCTOU). Caught here, on the fd itself, instead of only in a preceding\n\t * `statRegularFile` call, which would still leave a race window before the open. */\n\t| { kind: \"not-regular\" }\n\t| { kind: \"too-large\" };\n\n/** Reads up to `size` bytes from `fd`, stopping early at EOF. */\nfunction readIntoBuffer(fd: number, size: number): { buffer: Buffer; bytesRead: number } {\n\tconst buffer = Buffer.allocUnsafe(Math.max(0, size));\n\tlet bytesRead = 0;\n\twhile (bytesRead < buffer.length) {\n\t\tconst chunk = fs.readSync(fd, buffer, bytesRead, buffer.length - bytesRead, null);\n\t\tif (chunk === 0) break;\n\t\tbytesRead += chunk;\n\t}\n\treturn { buffer, bytesRead };\n}\n\n/**\n * Opens with `O_NONBLOCK` (so a fifo with no writer returns immediately instead of blocking the\n * event loop) and rejects anything that isn't a regular file by `fstat`ing the opened descriptor,\n * which closes the TOCTOU window a separate `lstat`-then-`open` would leave between the two calls.\n *\n * `sizeHint` comes from a `statRegularFile` the caller already did, so the first read is sized for\n * the common case (a small script) instead of always zero-filling a 256 KiB buffer. If the file\n * grew past `sizeHint` since that stat, the first read fills exactly and a second read, sized to\n * the real remaining budget, decides whether the file is genuinely over `SAVED_WORKFLOW_MAX_BYTES`\n * or just grew by a few bytes — a `sizeHint`-sized probe alone would misreport the latter as too\n * large.\n */\nfunction readBoundedUtf8(filePath: string, sizeHint: number): BoundedReadResult {\n\tconst fd = fs.openSync(filePath, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK);\n\ttry {\n\t\tif (!fs.fstatSync(fd).isFile()) return { kind: \"not-regular\" };\n\n\t\tconst hinted = Math.min(Math.max(sizeHint, 0), SAVED_WORKFLOW_MAX_BYTES);\n\t\tconst first = readIntoBuffer(fd, hinted + 1);\n\t\tif (first.bytesRead <= hinted) {\n\t\t\treturn { kind: \"ok\", content: first.buffer.toString(\"utf-8\", 0, first.bytesRead) };\n\t\t}\n\t\tif (hinted >= SAVED_WORKFLOW_MAX_BYTES) return { kind: \"too-large\" };\n\n\t\tconst rest = readIntoBuffer(fd, SAVED_WORKFLOW_MAX_BYTES - hinted);\n\t\tif (rest.bytesRead >= SAVED_WORKFLOW_MAX_BYTES - hinted) return { kind: \"too-large\" };\n\n\t\tconst content = Buffer.concat([\n\t\t\tfirst.buffer.subarray(0, first.bytesRead),\n\t\t\trest.buffer.subarray(0, rest.bytesRead),\n\t\t]).toString(\"utf-8\");\n\t\treturn { kind: \"ok\", content };\n\t} finally {\n\t\tfs.closeSync(fd);\n\t}\n}\n\nfunction metaToWorkflow(\n\tbasename: string,\n\tfilePath: string,\n\tsource: \"project\" | \"user\",\n\textraction: MetaExtraction,\n): SavedWorkflow {\n\tif (!extraction.ok) {\n\t\treturn {\n\t\t\tname: basename,\n\t\t\tdescription: \"\",\n\t\t\tphases: [],\n\t\t\tpath: filePath,\n\t\t\tsource,\n\t\t\tvalid: false,\n\t\t\terror: `${extraction.error.message} (line ${extraction.error.line})`,\n\t\t};\n\t}\n\tconst workflow: SavedWorkflow = {\n\t\tname: basename,\n\t\tdescription: extraction.meta.description,\n\t\tphases: extraction.meta.phases,\n\t\tpath: filePath,\n\t\tsource,\n\t\tvalid: true,\n\t};\n\tif (extraction.meta.whenToUse !== undefined) workflow.whenToUse = extraction.meta.whenToUse;\n\treturn workflow;\n}\n\nfunction loadWorkflowsFromDir(dir: string, source: \"project\" | \"user\"): DirDiscovery {\n\tconst workflows: SavedWorkflow[] = [];\n\tconst diagnostics: SavedWorkflowDiagnostic[] = [];\n\n\tlet entries: fs.Dirent[];\n\ttry {\n\t\tentries = fs.readdirSync(dir, { withFileTypes: true });\n\t} catch {\n\t\treturn { workflows, diagnostics };\n\t}\n\n\tfor (const entry of entries) {\n\t\tif (!entry.name.endsWith(\".js\")) continue;\n\t\tconst filePath = path.join(dir, entry.name);\n\n\t\tconst stat = statRegularFile(filePath);\n\t\tif (!stat) continue;\n\t\tif (stat.size > SAVED_WORKFLOW_MAX_BYTES) {\n\t\t\tdiagnostics.push({\n\t\t\t\tpath: filePath,\n\t\t\t\tlevel: \"warning\",\n\t\t\t\tmessage: `Saved workflow file \"${entry.name}\" was skipped: ${stat.size} bytes exceeds the ${SAVED_WORKFLOW_MAX_BYTES}-byte limit.`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst basename = entry.name.slice(0, -3);\n\t\tif (!WORKFLOW_NAME_PATTERN.test(basename)) {\n\t\t\tdiagnostics.push({\n\t\t\t\tpath: filePath,\n\t\t\t\tlevel: \"warning\",\n\t\t\t\tmessage: `Saved workflow file \"${entry.name}\" was skipped: its name must match ${WORKFLOW_NAME_PATTERN} (lowercase letters, digits and hyphens, starting with a letter, at most 48 characters).`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet content: string;\n\t\ttry {\n\t\t\tconst read = readBoundedUtf8(filePath, stat.size);\n\t\t\tif (read.kind === \"not-regular\") {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\tpath: filePath,\n\t\t\t\t\tlevel: \"warning\",\n\t\t\t\t\tmessage: `Saved workflow file \"${entry.name}\" was skipped: it is no longer a regular file.`,\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (read.kind === \"too-large\") {\n\t\t\t\tdiagnostics.push({\n\t\t\t\t\tpath: filePath,\n\t\t\t\t\tlevel: \"warning\",\n\t\t\t\t\tmessage: `Saved workflow file \"${entry.name}\" was skipped: it exceeds the ${SAVED_WORKFLOW_MAX_BYTES}-byte limit.`,\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcontent = read.content;\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tdiagnostics.push({\n\t\t\t\tpath: filePath,\n\t\t\t\tlevel: \"warning\",\n\t\t\t\tmessage: `Saved workflow \"${basename}\" could not be read: ${message}`,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst extraction = extractWorkflowMeta(content);\n\t\tif (!extraction.ok) {\n\t\t\tdiagnostics.push({\n\t\t\t\tpath: filePath,\n\t\t\t\tlevel: \"warning\",\n\t\t\t\tmessage: `Saved workflow \"${basename}\" has an invalid meta block: ${extraction.error.message} (line ${extraction.error.line}).`,\n\t\t\t});\n\t\t\tworkflows.push(metaToWorkflow(basename, filePath, source, extraction));\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (extraction.meta.name !== basename) {\n\t\t\tdiagnostics.push({\n\t\t\t\tpath: filePath,\n\t\t\t\tlevel: \"info\",\n\t\t\t\tmessage: `Saved workflow file \"${entry.name}\" declares meta.name \"${extraction.meta.name}\"; using the file name \"${basename}\" instead.`,\n\t\t\t});\n\t\t}\n\n\t\tworkflows.push(metaToWorkflow(basename, filePath, source, extraction));\n\t}\n\n\treturn { workflows, diagnostics };\n}\n\n/** Mirrors `findProjectAgentsDir` in `builtins/subagent.ts`: walk up from the real cwd for the nearest `.draht/workflows`. */\nfunction findProjectWorkflowsDir(cwd: string): string | null {\n\tconst realCwd = realPathStrict(cwd);\n\tif (realCwd === undefined) return null;\n\tlet dir = realCwd;\n\twhile (true) {\n\t\tconst candidate = path.join(dir, CONFIG_DIR_NAME, \"workflows\");\n\t\ttry {\n\t\t\tif (fs.statSync(candidate).isDirectory()) return candidate;\n\t\t} catch {}\n\t\tconst parent = path.dirname(dir);\n\t\tif (parent === dir) return null;\n\t\tdir = parent;\n\t}\n}\n\nexport function discoverSavedWorkflows(options: SavedDiscoveryOptions): DirDiscovery {\n\tconst userDir = path.join(options.agentDir, \"workflows\");\n\tconst projectDir = options.projectTrusted ? findProjectWorkflowsDir(options.cwd) : null;\n\n\tconst userResult = loadWorkflowsFromDir(userDir, \"user\");\n\tconst projectResult = projectDir ? loadWorkflowsFromDir(projectDir, \"project\") : { workflows: [], diagnostics: [] };\n\n\tconst diagnostics = [...userResult.diagnostics, ...projectResult.diagnostics];\n\tconst byName = new Map<string, SavedWorkflow>();\n\tfor (const workflow of userResult.workflows) byName.set(workflow.name, workflow);\n\tfor (const workflow of projectResult.workflows) {\n\t\tconst existing = byName.get(workflow.name);\n\t\tif (existing && existing.source === \"user\") {\n\t\t\tdiagnostics.push({\n\t\t\t\tpath: workflow.path,\n\t\t\t\tlevel: \"info\",\n\t\t\t\tmessage: `Project workflow \"${workflow.name}\" overrides the user workflow at ${existing.path}.`,\n\t\t\t});\n\t\t}\n\t\tbyName.set(workflow.name, workflow);\n\t}\n\n\tconst workflows = Array.from(byName.values()).sort((a, b) => a.name.localeCompare(b.name));\n\treturn { workflows, diagnostics };\n}\n\n/**\n * Looks up a single name directly in the project then user workflow directories, instead of\n * discovering (opening, reading and meta-parsing) every file in both. Called on every workflow\n * approval and again on every saved-workflow execution, so a directory with many saved workflows\n * would otherwise redo that work twice per run.\n */\nexport function findSavedWorkflow(name: string, options: SavedDiscoveryOptions): SavedWorkflow | undefined {\n\tif (!WORKFLOW_NAME_PATTERN.test(name)) return undefined;\n\n\tif (options.projectTrusted) {\n\t\tconst projectDir = findProjectWorkflowsDir(options.cwd);\n\t\tif (projectDir) {\n\t\t\tconst found = loadSingleWorkflowFile(projectDir, name, \"project\");\n\t\t\tif (found) return found;\n\t\t}\n\t}\n\treturn loadSingleWorkflowFile(path.join(options.agentDir, \"workflows\"), name, \"user\");\n}\n\n/**\n * Never throws: a read error (e.g. `EACCES`) or a file that is no longer a regular file or too\n * large is reported the same way discovery does, as \"not found here\", so `findSavedWorkflow`\n * falls back to the next source instead of raising an error from an unrelated code path.\n */\nfunction loadSingleWorkflowFile(dir: string, name: string, source: \"project\" | \"user\"): SavedWorkflow | undefined {\n\tconst filePath = path.join(dir, `${name}.js`);\n\tconst stat = statRegularFile(filePath);\n\tif (!stat || stat.size > SAVED_WORKFLOW_MAX_BYTES) return undefined;\n\ttry {\n\t\tconst read = readBoundedUtf8(filePath, stat.size);\n\t\tif (read.kind !== \"ok\") return undefined;\n\t\treturn metaToWorkflow(name, filePath, source, extractWorkflowMeta(read.content));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Throws when the file is no longer a regular file (e.g. replaced by a fifo since discovery),\n * cannot be read, or has grown past {@link SAVED_WORKFLOW_MAX_BYTES} since discovery. The\n * `statRegularFile` call below is only an early refusal and a size hint for `readBoundedUtf8`;\n * the authoritative regular-file check happens on the opened fd inside `readBoundedUtf8` itself,\n * so a swap between this stat and that open (e.g. into a fifo) still can't hang the read.\n */\nexport function readSavedWorkflowSource(workflow: SavedWorkflow): string {\n\tconst stat = statRegularFile(workflow.path);\n\tif (!stat) {\n\t\tthrow new Error(`Saved workflow \"${workflow.name}\" is no longer a regular file.`);\n\t}\n\tif (stat.size > SAVED_WORKFLOW_MAX_BYTES) {\n\t\tthrow new Error(\n\t\t\t`Saved workflow \"${workflow.name}\" is too large (${stat.size} bytes, max ${SAVED_WORKFLOW_MAX_BYTES}).`,\n\t\t);\n\t}\n\tconst read = readBoundedUtf8(workflow.path, stat.size);\n\tif (read.kind === \"not-regular\") {\n\t\tthrow new Error(`Saved workflow \"${workflow.name}\" is no longer a regular file.`);\n\t}\n\tif (read.kind === \"too-large\") {\n\t\tthrow new Error(`Saved workflow \"${workflow.name}\" is too large (max ${SAVED_WORKFLOW_MAX_BYTES} bytes).`);\n\t}\n\treturn read.content;\n}\n"]}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Child-side structured output (§14.4, D1/D3): the parent writes the prepared result schema to a
|
|
3
|
+
* temp file and sets `DRAHT_POLYPHASE_SCHEMA_FILE`; the child reads it once at extension-load time
|
|
4
|
+
* and, when present, registers `polyphase_result` so the agent can hand back a validated value.
|
|
5
|
+
*/
|
|
6
|
+
import type { JsonObject, JsonValue } from "@draht/ai";
|
|
7
|
+
import type { ExtensionAPI } from "../../extensions/types.ts";
|
|
8
|
+
export declare const STRUCTURED_OUTPUT_INSTRUCTION: string;
|
|
9
|
+
export interface PreparedResultSchema {
|
|
10
|
+
toolSchema: JsonObject;
|
|
11
|
+
unwrap(value: JsonValue): JsonValue;
|
|
12
|
+
}
|
|
13
|
+
/** Object schemas pass through unchanged; any other schema is wrapped as `{value: <schema>}` so the
|
|
14
|
+
* tool call always has an object shape, and unwrapped back to the bare value on the way out. */
|
|
15
|
+
export declare function prepareResultSchema(schema: JsonObject): PreparedResultSchema;
|
|
16
|
+
/**
|
|
17
|
+
* Registers `polyphase_result` when (and only when) this process was spawned with a schema file
|
|
18
|
+
* (`DRAHT_POLYPHASE_SCHEMA_FILE`): a no-op in every other process, including a child whose parent
|
|
19
|
+
* did not request structured output.
|
|
20
|
+
*/
|
|
21
|
+
export declare function registerChildResultTool(pi: ExtensionAPI): void;
|
|
22
|
+
//# sourceMappingURL=structured-output.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"structured-output.d.ts","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/structured-output.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEvD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAG9D,eAAO,MAAM,6BAA6B,QAGqC,CAAC;AAEhF,MAAM,WAAW,oBAAoB;IACpC,UAAU,EAAE,UAAU,CAAC;IACvB,MAAM,CAAC,KAAK,EAAE,SAAS,GAAG,SAAS,CAAC;CACpC;AAMD;gGACgG;AAChG,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,UAAU,GAAG,oBAAoB,CAY5E;AAeD;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,EAAE,EAAE,YAAY,GAAG,IAAI,CAe9D"}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Child-side structured output (§14.4, D1/D3): the parent writes the prepared result schema to a
|
|
3
|
+
* temp file and sets `DRAHT_POLYPHASE_SCHEMA_FILE`; the child reads it once at extension-load time
|
|
4
|
+
* and, when present, registers `polyphase_result` so the agent can hand back a validated value.
|
|
5
|
+
*/
|
|
6
|
+
import * as fs from "node:fs";
|
|
7
|
+
import { POLYPHASE_RESULT_TOOL_NAME, POLYPHASE_SCHEMA_FILE_ENV } from "../types.js";
|
|
8
|
+
export const STRUCTURED_OUTPUT_INSTRUCTION = "When you have finished, call the polyphase_result tool exactly once with your final answer as " +
|
|
9
|
+
"its arguments, matching its schema exactly. Call it as your last action: once it has run, your " +
|
|
10
|
+
"turn ends and nothing you say afterward is seen by the orchestrating script.";
|
|
11
|
+
function isObjectSchema(schema) {
|
|
12
|
+
return schema.type === "object";
|
|
13
|
+
}
|
|
14
|
+
/** Object schemas pass through unchanged; any other schema is wrapped as `{value: <schema>}` so the
|
|
15
|
+
* tool call always has an object shape, and unwrapped back to the bare value on the way out. */
|
|
16
|
+
export function prepareResultSchema(schema) {
|
|
17
|
+
if (isObjectSchema(schema)) {
|
|
18
|
+
return { toolSchema: schema, unwrap: (value) => value };
|
|
19
|
+
}
|
|
20
|
+
const toolSchema = { type: "object", properties: { value: schema }, required: ["value"] };
|
|
21
|
+
return {
|
|
22
|
+
toolSchema,
|
|
23
|
+
unwrap: (value) => {
|
|
24
|
+
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
25
|
+
return null;
|
|
26
|
+
return value.value ?? null;
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
/** Reads `DRAHT_POLYPHASE_SCHEMA_FILE` synchronously. Never throws: an unset or unreadable file is `undefined`. */
|
|
31
|
+
function readChildResultSchema(env = process.env) {
|
|
32
|
+
const file = env[POLYPHASE_SCHEMA_FILE_ENV];
|
|
33
|
+
if (!file)
|
|
34
|
+
return undefined;
|
|
35
|
+
try {
|
|
36
|
+
const parsed = JSON.parse(fs.readFileSync(file, "utf-8"));
|
|
37
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
|
|
38
|
+
return undefined;
|
|
39
|
+
return parsed;
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Registers `polyphase_result` when (and only when) this process was spawned with a schema file
|
|
47
|
+
* (`DRAHT_POLYPHASE_SCHEMA_FILE`): a no-op in every other process, including a child whose parent
|
|
48
|
+
* did not request structured output.
|
|
49
|
+
*/
|
|
50
|
+
export function registerChildResultTool(pi) {
|
|
51
|
+
const schema = readChildResultSchema();
|
|
52
|
+
if (!schema)
|
|
53
|
+
return;
|
|
54
|
+
pi.registerTool({
|
|
55
|
+
name: POLYPHASE_RESULT_TOOL_NAME,
|
|
56
|
+
label: "Polyphase Result",
|
|
57
|
+
description: "Records this agent's final structured result for the orchestrating workflow script. Call it exactly once, as the last thing you do.",
|
|
58
|
+
parameters: schema,
|
|
59
|
+
execute: async () => ({
|
|
60
|
+
content: [{ type: "text", text: "Result recorded." }],
|
|
61
|
+
details: {},
|
|
62
|
+
terminate: true,
|
|
63
|
+
}),
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
//# sourceMappingURL=structured-output.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"structured-output.js","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/structured-output.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAI9B,OAAO,EAAE,0BAA0B,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AAEpF,MAAM,CAAC,MA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F,OAAO,MAAoB,CAAC;IAC7B,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,SAAS,CAAC;IAClB,CAAC;AACF,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,uBAAuB,CAAC,EAAgB;IACvD,MAAM,MAAM,GAAG,qBAAqB,EAAE,CAAC;IACvC,IAAI,CAAC,MAAM;QAAE,OAAO;IACpB,EAAE,CAAC,YAAY,CAAC;QACf,IAAI,EAAE,0BAA0B;QAChC,KAAK,EAAE,kBAAkB;QACzB,WAAW,EACV,qIAAqI;QACtI,UAAU,EAAE,MAA4B;QACxC,OAAO,EAAE,KAAK,IAAI,EAAE,CAAC,CAAC;YACrB,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,kBAAkB,EAAE,CAAC;YACrD,OAAO,EAAE,EAAE;YACX,SAAS,EAAE,IAAI;SACf,CAAC;KACF,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Child-side structured output (§14.4, D1/D3): the parent writes the prepared result schema to a\n * temp file and sets `DRAHT_POLYPHASE_SCHEMA_FILE`; the child reads it once at extension-load time\n * and, when present, registers `polyphase_result` so the agent can hand back a validated value.\n */\n\nimport * as fs from \"node:fs\";\nimport type { JsonObject, JsonValue } from \"@draht/ai\";\nimport type { TSchema } from \"typebox\";\nimport type { ExtensionAPI } from \"../../extensions/types.ts\";\nimport { POLYPHASE_RESULT_TOOL_NAME, POLYPHASE_SCHEMA_FILE_ENV } from \"../types.ts\";\n\nexport const STRUCTURED_OUTPUT_INSTRUCTION =\n\t\"When you have finished, call the polyphase_result tool exactly once with your final answer as \" +\n\t\"its arguments, matching its schema exactly. Call it as your last action: once it has run, your \" +\n\t\"turn ends and nothing you say afterward is seen by the orchestrating script.\";\n\nexport interface PreparedResultSchema {\n\ttoolSchema: JsonObject;\n\tunwrap(value: JsonValue): JsonValue;\n}\n\nfunction isObjectSchema(schema: JsonObject): boolean {\n\treturn schema.type === \"object\";\n}\n\n/** Object schemas pass through unchanged; any other schema is wrapped as `{value: <schema>}` so the\n * tool call always has an object shape, and unwrapped back to the bare value on the way out. */\nexport function prepareResultSchema(schema: JsonObject): PreparedResultSchema {\n\tif (isObjectSchema(schema)) {\n\t\treturn { toolSchema: schema, unwrap: (value) => value };\n\t}\n\tconst toolSchema: JsonObject = { type: \"object\", properties: { value: schema }, required: [\"value\"] };\n\treturn {\n\t\ttoolSchema,\n\t\tunwrap: (value) => {\n\t\t\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return null;\n\t\t\treturn (value as JsonObject).value ?? null;\n\t\t},\n\t};\n}\n\n/** Reads `DRAHT_POLYPHASE_SCHEMA_FILE` synchronously. Never throws: an unset or unreadable file is `undefined`. */\nfunction readChildResultSchema(env: NodeJS.ProcessEnv = process.env): JsonObject | undefined {\n\tconst file = env[POLYPHASE_SCHEMA_FILE_ENV];\n\tif (!file) return undefined;\n\ttry {\n\t\tconst parsed = JSON.parse(fs.readFileSync(file, \"utf-8\"));\n\t\tif (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return undefined;\n\t\treturn parsed as JsonObject;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Registers `polyphase_result` when (and only when) this process was spawned with a schema file\n * (`DRAHT_POLYPHASE_SCHEMA_FILE`): a no-op in every other process, including a child whose parent\n * did not request structured output.\n */\nexport function registerChildResultTool(pi: ExtensionAPI): void {\n\tconst schema = readChildResultSchema();\n\tif (!schema) return;\n\tpi.registerTool({\n\t\tname: POLYPHASE_RESULT_TOOL_NAME,\n\t\tlabel: \"Polyphase Result\",\n\t\tdescription:\n\t\t\t\"Records this agent's final structured result for the orchestrating workflow script. Call it exactly once, as the last thing you do.\",\n\t\tparameters: schema as unknown as TSchema,\n\t\texecute: async () => ({\n\t\t\tcontent: [{ type: \"text\", text: \"Result recorded.\" }],\n\t\t\tdetails: {},\n\t\t\tterminate: true,\n\t\t}),\n\t});\n}\n"]}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `workflow` tool definition (§14.1): model-only, defaultActive false, registered lazily by
|
|
3
|
+
* `builtins/polyphase.ts` the first time the keyword or a resumed session needs it.
|
|
4
|
+
*/
|
|
5
|
+
import type { ExtensionContext, ToolDefinition } from "../../extensions/types.ts";
|
|
6
|
+
import { type PolyphaseRenderDeps, type PolyphaseRowState } from "../render/renderers.ts";
|
|
7
|
+
import type { PolyphaseSession } from "../session.ts";
|
|
8
|
+
import { type AgentRunner, type PolyphaseDetails } from "../types.ts";
|
|
9
|
+
declare const WorkflowParams: import("@sinclair/typebox").TObject<{
|
|
10
|
+
script: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TString>;
|
|
11
|
+
name: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TString>;
|
|
12
|
+
args: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TString>;
|
|
13
|
+
budgetTokens: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TInteger>;
|
|
14
|
+
}>;
|
|
15
|
+
/** Early errors (unknown name, invalid meta, wrong arguments) return before a run exists. */
|
|
16
|
+
type WorkflowToolDetails = PolyphaseDetails | Record<string, never>;
|
|
17
|
+
export interface WorkflowToolDeps {
|
|
18
|
+
getSession(ctx: ExtensionContext): PolyphaseSession;
|
|
19
|
+
runner?: AgentRunner;
|
|
20
|
+
renderDeps: PolyphaseRenderDeps;
|
|
21
|
+
}
|
|
22
|
+
export declare function createWorkflowToolDefinition(deps: WorkflowToolDeps): ToolDefinition<typeof WorkflowParams, WorkflowToolDetails, PolyphaseRowState>;
|
|
23
|
+
export {};
|
|
24
|
+
//# sourceMappingURL=tool.d.ts.map
|
|
@@ -0,0 +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;AAMrB,QAAA,MAAM,cAAc;;;;;EAoBlB,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+G/E"}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `workflow` tool definition (§14.1): model-only, defaultActive false, registered lazily by
|
|
3
|
+
* `builtins/polyphase.ts` the first time the keyword or a resumed session needs it.
|
|
4
|
+
*/
|
|
5
|
+
import { Type } from "@sinclair/typebox";
|
|
6
|
+
import { getAgentDir } from "../../../config.js";
|
|
7
|
+
import { createPartialUpdateEmitter } from "../emitter.js";
|
|
8
|
+
import { createWorkflowRenderers } from "../render/renderers.js";
|
|
9
|
+
import { currentPolyphaseDepth, WORKFLOW_TOOL_NAME, } from "../types.js";
|
|
10
|
+
import { WORKFLOW_PROMPT_GUIDELINES, WORKFLOW_PROMPT_SNIPPET, WORKFLOW_TOOL_DESCRIPTION } from "./guidance.js";
|
|
11
|
+
import { startWorkflowRun } from "./launch.js";
|
|
12
|
+
import { extractWorkflowMeta } from "./meta.js";
|
|
13
|
+
import { discoverSavedWorkflows, findSavedWorkflow, readSavedWorkflowSource } from "./saved.js";
|
|
14
|
+
const WorkflowParams = Type.Object({
|
|
15
|
+
script: Type.Optional(Type.String({
|
|
16
|
+
description: "Workflow script: `export const meta = {...}` first, then an async body using agent, parallel, pipeline, phase, log, args, budget",
|
|
17
|
+
})),
|
|
18
|
+
name: Type.Optional(Type.String({
|
|
19
|
+
description: "Run a saved workflow (.draht/workflows/<name>.js or <agentDir>/workflows/<name>.js) instead of an inline script",
|
|
20
|
+
})),
|
|
21
|
+
args: Type.Optional(Type.String({ description: "Input passed verbatim to the script as `args`" })),
|
|
22
|
+
budgetTokens: Type.Optional(Type.Integer({
|
|
23
|
+
minimum: 1000,
|
|
24
|
+
description: "Hard ceiling on billable tokens (input + output + cache writes) across all agents of this run",
|
|
25
|
+
})),
|
|
26
|
+
});
|
|
27
|
+
function errorResult(text) {
|
|
28
|
+
return { content: [{ type: "text", text }], details: {}, isError: true };
|
|
29
|
+
}
|
|
30
|
+
export function createWorkflowToolDefinition(deps) {
|
|
31
|
+
const renderers = createWorkflowRenderers(deps.renderDeps);
|
|
32
|
+
return {
|
|
33
|
+
name: WORKFLOW_TOOL_NAME,
|
|
34
|
+
label: "Workflow",
|
|
35
|
+
description: WORKFLOW_TOOL_DESCRIPTION,
|
|
36
|
+
promptSnippet: WORKFLOW_PROMPT_SNIPPET,
|
|
37
|
+
promptGuidelines: [...WORKFLOW_PROMPT_GUIDELINES],
|
|
38
|
+
parameters: WorkflowParams,
|
|
39
|
+
exposure: "model-only",
|
|
40
|
+
defaultActive: false,
|
|
41
|
+
renderCall: renderers.renderCall,
|
|
42
|
+
renderResult: renderers.renderResult,
|
|
43
|
+
async execute(toolCallId, params, signal, onUpdate, ctx) {
|
|
44
|
+
if ((params.script === undefined) === (params.name === undefined)) {
|
|
45
|
+
return errorResult("Exactly one of `script` or `name` must be given.");
|
|
46
|
+
}
|
|
47
|
+
if (currentPolyphaseDepth() >= 1) {
|
|
48
|
+
return errorResult("The workflow tool is not available to subagents.");
|
|
49
|
+
}
|
|
50
|
+
const session = deps.getSession(ctx);
|
|
51
|
+
const settings = session.settings();
|
|
52
|
+
let source;
|
|
53
|
+
let sourceInfo;
|
|
54
|
+
if (params.script !== undefined) {
|
|
55
|
+
source = params.script;
|
|
56
|
+
sourceInfo = { kind: "inline" };
|
|
57
|
+
}
|
|
58
|
+
else if (params.name !== undefined) {
|
|
59
|
+
const discovery = {
|
|
60
|
+
cwd: ctx.cwd,
|
|
61
|
+
agentDir: getAgentDir(),
|
|
62
|
+
projectTrusted: ctx.isProjectTrusted(),
|
|
63
|
+
};
|
|
64
|
+
const found = findSavedWorkflow(params.name, discovery);
|
|
65
|
+
if (!found) {
|
|
66
|
+
const names = discoverSavedWorkflows(discovery)
|
|
67
|
+
.workflows.map((workflow) => workflow.name)
|
|
68
|
+
.join(", ");
|
|
69
|
+
return errorResult(`Unknown saved workflow "${params.name}". Available: ${names || "(none)"}`);
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
source = readSavedWorkflowSource(found);
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
return errorResult(error instanceof Error ? error.message : String(error));
|
|
76
|
+
}
|
|
77
|
+
sourceInfo = { kind: found.source, path: found.path };
|
|
78
|
+
}
|
|
79
|
+
else {
|
|
80
|
+
return errorResult("Exactly one of `script` or `name` must be given.");
|
|
81
|
+
}
|
|
82
|
+
const extraction = extractWorkflowMeta(source);
|
|
83
|
+
if (!extraction.ok) {
|
|
84
|
+
return errorResult(`Workflow meta is invalid at line ${extraction.error.line}, column ${extraction.error.column}: ${extraction.error.message}`);
|
|
85
|
+
}
|
|
86
|
+
const handle = startWorkflowRun({
|
|
87
|
+
ctx,
|
|
88
|
+
session,
|
|
89
|
+
id: toolCallId,
|
|
90
|
+
origin: "tool",
|
|
91
|
+
parentSignal: signal,
|
|
92
|
+
meta: extraction.meta,
|
|
93
|
+
body: extraction.body,
|
|
94
|
+
args: params.args ?? "",
|
|
95
|
+
source: sourceInfo,
|
|
96
|
+
budgetTokens: params.budgetTokens ?? settings.defaultBudgetTokens,
|
|
97
|
+
runner: deps.runner,
|
|
98
|
+
});
|
|
99
|
+
// §13.1: unknown meta keys (e.g. a typo'd phase field) produce warnings instead of
|
|
100
|
+
// failing the run; without this they are silently discarded, with no sign anywhere that
|
|
101
|
+
// the key was ignored.
|
|
102
|
+
for (const warning of extraction.warnings)
|
|
103
|
+
handle.run.appendLog(warning, "warning");
|
|
104
|
+
let emitter;
|
|
105
|
+
try {
|
|
106
|
+
emitter = createPartialUpdateEmitter(handle.run, onUpdate, {
|
|
107
|
+
mode: ctx.mode,
|
|
108
|
+
liveUpdateMs: settings.liveUpdateMs,
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
// emitNow() runs synchronously inside the emitter's constructor (§10.7); if it throws,
|
|
113
|
+
// the run is already under way with no subscriber. Cancel it rather than leaving it to
|
|
114
|
+
// spend tokens unobserved, and still report its (failed) completion.
|
|
115
|
+
handle.run.cancel("run");
|
|
116
|
+
const completion = await handle.done;
|
|
117
|
+
return {
|
|
118
|
+
content: [{ type: "text", text: completion.text }],
|
|
119
|
+
details: completion.details,
|
|
120
|
+
usage: completion.usage,
|
|
121
|
+
isError: completion.isError,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
try {
|
|
125
|
+
const completion = await handle.done;
|
|
126
|
+
return {
|
|
127
|
+
content: [{ type: "text", text: completion.text }],
|
|
128
|
+
details: completion.details,
|
|
129
|
+
usage: completion.usage,
|
|
130
|
+
isError: completion.isError,
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
finally {
|
|
134
|
+
emitter.dispose();
|
|
135
|
+
}
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
//# sourceMappingURL=tool.js.map
|