@nathanstephenson/flow 0.1.0
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/README.md +641 -0
- package/build/workflow-runtime.cjs +213964 -0
- package/dist/backend/claude/async-queue.js +44 -0
- package/dist/backend/claude/auto-compaction.js +10 -0
- package/dist/backend/claude/background-calls.js +116 -0
- package/dist/backend/claude/enquiries.js +162 -0
- package/dist/backend/claude/index.js +1138 -0
- package/dist/backend/claude/mcp.js +55 -0
- package/dist/backend/claude/permissions.js +106 -0
- package/dist/backend/claude/streamed-message.js +120 -0
- package/dist/backend/claude/subagents.js +128 -0
- package/dist/backend/claude/workflow-parent.js +12 -0
- package/dist/backend/claude/workflow-processes.js +95 -0
- package/dist/backend/claude/workflow-subagent.js +234 -0
- package/dist/backend/effort.js +30 -0
- package/dist/backend/fake/index.js +570 -0
- package/dist/backend/mcp.js +190 -0
- package/dist/backend/pi/auto-compaction.js +16 -0
- package/dist/backend/pi/background-calls.js +56 -0
- package/dist/backend/pi/enquiries.js +63 -0
- package/dist/backend/pi/index.js +597 -0
- package/dist/backend/pi/mcp.js +35 -0
- package/dist/backend/pi/subagents.js +23 -0
- package/dist/backend/pi/work.js +104 -0
- package/dist/backend/pi/workflow-parent.js +21 -0
- package/dist/backend/pi/workflow-subagent.js +199 -0
- package/dist/backend/registry.js +34 -0
- package/dist/backend/types.js +1 -0
- package/dist/backend/workflow-tools.js +25 -0
- package/dist/build-id +1 -0
- package/dist/cli/application.js +397 -0
- package/dist/cli/bootstrap.js +535 -0
- package/dist/cli/host-control.js +100 -0
- package/dist/cli/install-guard.js +270 -0
- package/dist/cli/install-process.js +52 -0
- package/dist/cli/main.js +12 -0
- package/dist/cli/update.js +128 -0
- package/dist/client/connection.js +183 -0
- package/dist/client/context-usage.js +66 -0
- package/dist/client/diff.js +36 -0
- package/dist/client/enquiry.js +105 -0
- package/dist/client/markdown.js +192 -0
- package/dist/client/model-choices.js +32 -0
- package/dist/client/permission.js +60 -0
- package/dist/client/project-name.js +19 -0
- package/dist/client/reduce.js +463 -0
- package/dist/client/relative-time.js +30 -0
- package/dist/client/scope-kind.js +28 -0
- package/dist/client/search.js +136 -0
- package/dist/client/session-label.js +9 -0
- package/dist/client/status.js +84 -0
- package/dist/client/tool-chains.js +52 -0
- package/dist/client/tool-summary.js +98 -0
- package/dist/daemon/auth.js +590 -0
- package/dist/daemon/config-store.js +183 -0
- package/dist/daemon/config.js +687 -0
- package/dist/daemon/credential-redaction.js +9 -0
- package/dist/daemon/git.js +312 -0
- package/dist/daemon/host-control-routes.js +29 -0
- package/dist/daemon/host.js +2343 -0
- package/dist/daemon/http.js +19 -0
- package/dist/daemon/log.js +44 -0
- package/dist/daemon/mcp-auth.js +164 -0
- package/dist/daemon/models.js +85 -0
- package/dist/daemon/ownership.js +104 -0
- package/dist/daemon/projects.js +317 -0
- package/dist/daemon/publish.js +289 -0
- package/dist/daemon/pull-request.js +198 -0
- package/dist/daemon/runtime.js +100 -0
- package/dist/daemon/secret-store.js +65 -0
- package/dist/daemon/server.js +827 -0
- package/dist/daemon/shell.js +220 -0
- package/dist/daemon/skills.js +104 -0
- package/dist/daemon/stack-metadata.js +24 -0
- package/dist/daemon/stack.js +743 -0
- package/dist/daemon/store.js +130 -0
- package/dist/daemon/summariser.js +476 -0
- package/dist/daemon/workflow-execution-routes.js +105 -0
- package/dist/daemon/workflow-executions.js +1018 -0
- package/dist/daemon/workflow-mcp.js +20 -0
- package/dist/daemon/workflow-routes.js +102 -0
- package/dist/protocol/attachments.js +59 -0
- package/dist/protocol/commands.js +1 -0
- package/dist/protocol/events.js +20 -0
- package/dist/protocol/fonts.js +26 -0
- package/dist/protocol/git.js +12 -0
- package/dist/protocol/mcp.js +51 -0
- package/dist/protocol/projects.js +21 -0
- package/dist/protocol/publish.js +1 -0
- package/dist/protocol/pull-request.js +1 -0
- package/dist/protocol/secrets.js +4 -0
- package/dist/protocol/settings.js +63 -0
- package/dist/protocol/shells.js +8 -0
- package/dist/protocol/skills.js +16 -0
- package/dist/protocol/stack.js +41 -0
- package/dist/protocol/workflow-executions.js +1 -0
- package/dist/protocol/workflows.js +1 -0
- package/dist/tui/app.js +518 -0
- package/dist/tui/keys.js +54 -0
- package/dist/tui/render.js +366 -0
- package/dist/web/assets.js +10 -0
- package/dist/web/embedded.js +12 -0
- package/dist/web/manifest.js +70 -0
- package/dist/workflows/decisions.js +65 -0
- package/dist/workflows/executors.js +132 -0
- package/dist/workflows/graph.js +276 -0
- package/dist/workflows/json-schema.js +49 -0
- package/dist/workflows/loops.js +102 -0
- package/dist/workflows/mcp.js +18 -0
- package/dist/workflows/records.js +111 -0
- package/dist/workflows/recovery.js +25 -0
- package/dist/workflows/runtime-asset.js +17 -0
- package/dist/workflows/runtime-libs.js +1 -0
- package/dist/workflows/runtime-settings.js +23 -0
- package/dist/workflows/runtime.js +343 -0
- package/dist/workflows/scheduler.js +573 -0
- package/dist/workflows/schema.js +161 -0
- package/dist/workflows/store.js +93 -0
- package/package.json +87 -0
- package/web/dist/assets/__vite-browser-external-2447137e-BvRk9kiK.js +0 -0
- package/web/dist/assets/ghostty-vt-DOMeXDrv.wasm +0 -0
- package/web/dist/assets/index-BC0gLS53.js +106 -0
- package/web/dist/assets/index-CCeZYKES.css +2 -0
- package/web/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
- package/web/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
- package/web/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
- package/web/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
- package/web/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
- package/web/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
- package/web/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
- package/web/dist/assets/rolldown-runtime-B0Z9INg1.js +1 -0
- package/web/dist/assets/select-6i3wxovH.js +1 -0
- package/web/dist/assets/settings-mcp-CcT0ADJR.js +1 -0
- package/web/dist/assets/settings-secrets-CK4uF7fd.js +1 -0
- package/web/dist/assets/settings-workflows-CrbZF-nM.js +23 -0
- package/web/dist/assets/switch-ftZleVB8.js +6 -0
- package/web/dist/assets/workflow-editors-naPqAmYO.js +65 -0
- package/web/dist/assets/workflows-D4T4Gy_7.css +1 -0
- package/web/dist/assets/workflows-hh6ioeEA.js +7 -0
- package/web/dist/assets/workflows-pane-Db-MHf7Z.js +1 -0
- package/web/dist/index.html +31 -0
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
+
import { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
|
|
3
|
+
const initializedStreams = new WeakSet();
|
|
4
|
+
export async function refreshClaudeMcp(stream, mcp, additional = {}) {
|
|
5
|
+
const servers = { ...claudeMcpServers(mcp), ...additional };
|
|
6
|
+
const deadline = Date.now() + 10_000;
|
|
7
|
+
while (!initializedStreams.has(stream)) {
|
|
8
|
+
const status = await stream.mcpServerStatus();
|
|
9
|
+
const selected = Object.keys(servers).map((name) => status.find((entry) => entry.name === name));
|
|
10
|
+
if (selected.every((entry) => entry && entry.status !== "pending")) {
|
|
11
|
+
initializedStreams.add(stream);
|
|
12
|
+
break;
|
|
13
|
+
}
|
|
14
|
+
if (Date.now() >= deadline)
|
|
15
|
+
throw new Error("MCP tools could not be registered");
|
|
16
|
+
await new Promise((resolve) => setTimeout(resolve, 25));
|
|
17
|
+
}
|
|
18
|
+
await stream.setMcpServers({});
|
|
19
|
+
const result = await stream.setMcpServers(servers);
|
|
20
|
+
while (!Object.keys(result.errors).length) {
|
|
21
|
+
const status = await stream.mcpServerStatus();
|
|
22
|
+
const selected = Object.keys(servers).map((name) => status.find((entry) => entry.name === name));
|
|
23
|
+
if (selected.every((entry) => entry?.status === "connected"))
|
|
24
|
+
return;
|
|
25
|
+
if (Date.now() >= deadline || selected.some((entry) => entry && entry.status !== "pending" && entry.status !== "connected"))
|
|
26
|
+
break;
|
|
27
|
+
await new Promise((resolve) => setTimeout(resolve, 25));
|
|
28
|
+
}
|
|
29
|
+
await stream.setMcpServers({});
|
|
30
|
+
throw new Error("MCP tools could not be registered");
|
|
31
|
+
}
|
|
32
|
+
export function claudeMcpServers(mcp) {
|
|
33
|
+
return Object.fromEntries((mcp?.connections ?? []).map((connection) => {
|
|
34
|
+
const instance = new McpServer({ name: connection.id, version: "1.0.0" });
|
|
35
|
+
instance.server.registerCapabilities({ tools: {} });
|
|
36
|
+
const tools = () => mcp.tools().filter((tool) => tool.connectionId === connection.id);
|
|
37
|
+
const localName = (name) => name.slice(`mcp__${connection.id}__`.length);
|
|
38
|
+
instance.server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
39
|
+
tools: tools().map((tool) => ({
|
|
40
|
+
...tool.definition,
|
|
41
|
+
name: localName(tool.name),
|
|
42
|
+
})),
|
|
43
|
+
}));
|
|
44
|
+
instance.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
|
|
45
|
+
const tool = tools().find((tool) => localName(tool.name) === request.params.name);
|
|
46
|
+
if (!tool)
|
|
47
|
+
throw new Error("MCP tool unavailable");
|
|
48
|
+
return await tool.call(request.params.arguments ?? {}, extra.signal);
|
|
49
|
+
});
|
|
50
|
+
return [
|
|
51
|
+
connection.id,
|
|
52
|
+
{ type: "sdk", name: connection.id, instance },
|
|
53
|
+
];
|
|
54
|
+
}));
|
|
55
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Permission Prompts open in one turn, the callbacks held for them, and what the human has
|
|
3
|
+
* already refused.
|
|
4
|
+
*
|
|
5
|
+
* A sibling of `PendingEnquiries`, and the rule is the same one: the Claude SDK does not continue
|
|
6
|
+
* until `canUseTool` settles, so **every path must settle it**. A rejected or dropped callback leaves
|
|
7
|
+
* the CLI with a `tool_use` it never resolved, the turn cannot end, and the Agent Session is pinned
|
|
8
|
+
* in `running` with no key that unpins it. A *denial* is a real `tool_result` and leaves the
|
|
9
|
+
* conversation complete, so a later Revive resumes onto a turn with nothing dangling.
|
|
10
|
+
*
|
|
11
|
+
* What it adds over its sibling is `refused`: an Enquiry is asked once, but a model that wanted a
|
|
12
|
+
* tool typically wants it several times in a turn, and asking again the moment someone said no is
|
|
13
|
+
* how a composer gets pinned on the same question while the model rephrases. So a no is remembered
|
|
14
|
+
* for the rest of the turn and answered silently — with the adapter's own neutral refusal rather
|
|
15
|
+
* than "the human declined", because the model is being unblocked, not corrected, and one told a
|
|
16
|
+
* person refused it will spend the turn negotiating.
|
|
17
|
+
*
|
|
18
|
+
* Turn-scoped and no wider. A no was about what was being attempted, not about the tool forever;
|
|
19
|
+
* `clear()` drops it at the end of the turn, and the Always decision is the only thing here that
|
|
20
|
+
* outlives one.
|
|
21
|
+
*
|
|
22
|
+
* Its own module rather than fields on ClaudeSession because that session cannot be constructed
|
|
23
|
+
* without spawning a Claude process, so none of this would be reachable from a test there.
|
|
24
|
+
*/
|
|
25
|
+
export class PendingPermissions {
|
|
26
|
+
open = new Map();
|
|
27
|
+
refused = new Set();
|
|
28
|
+
/** Park a callback against the call awaiting authorisation. `callId` is the SDK's `toolUseID`. */
|
|
29
|
+
hold(callId, tool, input, settle) {
|
|
30
|
+
this.open.set(callId, { tool, input, settle });
|
|
31
|
+
}
|
|
32
|
+
/** Which tool an open prompt is about, or undefined for one already settled. */
|
|
33
|
+
describe(callId) {
|
|
34
|
+
return this.open.get(callId)?.tool;
|
|
35
|
+
}
|
|
36
|
+
/** Whether this tool has already been refused in this turn, and so must not be asked about again. */
|
|
37
|
+
isRefused(tool) {
|
|
38
|
+
return this.refused.has(tool);
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Settle an open prompt with a human's decision.
|
|
42
|
+
*
|
|
43
|
+
* False when there was nothing open under this id, which is an ordinary race — a second click, or a
|
|
44
|
+
* decision made against a transcript older than the Backend Session serving it. The caller reports
|
|
45
|
+
* it as a refusal rather than an error, and nothing is persisted for it.
|
|
46
|
+
*/
|
|
47
|
+
decide(callId, decision) {
|
|
48
|
+
const pending = this.open.get(callId);
|
|
49
|
+
if (!pending)
|
|
50
|
+
return false;
|
|
51
|
+
this.open.delete(callId);
|
|
52
|
+
if (decision === "deny") {
|
|
53
|
+
this.refused.add(pending.tool);
|
|
54
|
+
pending.settle({ behavior: "deny", message: refusal(pending.tool) });
|
|
55
|
+
return true;
|
|
56
|
+
}
|
|
57
|
+
pending.settle({ behavior: "allow", updatedInput: pending.input });
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Settle an open prompt as unauthorised, denying the tool with something the model can act on.
|
|
62
|
+
* Answers with the tool it was about, so the caller can emit the terminal snapshot for it.
|
|
63
|
+
*/
|
|
64
|
+
abandon(callId, why) {
|
|
65
|
+
const pending = this.open.get(callId);
|
|
66
|
+
if (!pending)
|
|
67
|
+
return undefined;
|
|
68
|
+
this.open.delete(callId);
|
|
69
|
+
pending.settle({ behavior: "deny", message: abandonment(pending.tool, why) });
|
|
70
|
+
return pending.tool;
|
|
71
|
+
}
|
|
72
|
+
/** Abandon everything open, and say what was abandoned so each gets its terminal snapshot. */
|
|
73
|
+
abandonAll(why) {
|
|
74
|
+
return [...this.open.keys()].flatMap((callId) => {
|
|
75
|
+
const tool = this.abandon(callId, why);
|
|
76
|
+
return tool ? [{ callId, tool }] : [];
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Forget everything without settling anything, and forget what was refused.
|
|
81
|
+
*
|
|
82
|
+
* Beside `PendingEnquiries.clear()` and carrying its warning verbatim: this is **not** how a turn
|
|
83
|
+
* ends. Anything still open must be abandoned first, or its callback is dropped and the CLI waits
|
|
84
|
+
* forever. What makes it safe is that the callbacks are already gone — the process behind them is
|
|
85
|
+
* down, or the turn that held them is over.
|
|
86
|
+
*/
|
|
87
|
+
clear() {
|
|
88
|
+
this.open.clear();
|
|
89
|
+
this.refused.clear();
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* What the model is told when a human said no.
|
|
94
|
+
*
|
|
95
|
+
* Verbatim the adapter's own pre-existing refusal, and that is the point: the model learns the tool
|
|
96
|
+
* is not available and moves on, rather than learning a person is in the loop and spending the turn
|
|
97
|
+
* trying to persuade them. Which human decision produced it belongs in the transcript, where a
|
|
98
|
+
* reader can see it, and not in the model's context.
|
|
99
|
+
*/
|
|
100
|
+
function refusal(tool) {
|
|
101
|
+
return `${tool} is not enabled for this session. Continue without it.`;
|
|
102
|
+
}
|
|
103
|
+
/** What it is told when nobody was ever going to answer. Shaped after `denial` in ./enquiries.ts. */
|
|
104
|
+
function abandonment(tool, why) {
|
|
105
|
+
return `${tool} was not authorised: ${why}. Continue without it.`;
|
|
106
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
/**
|
|
3
|
+
* Reasoning and text share the SDK's content-block index space, so both live in one map with thinking
|
|
4
|
+
* offset above this — and every read of that map has to say which half it wants. Joining the whole
|
|
5
|
+
* map is what once appended a message's own reasoning to its visible text, which reads as the reply
|
|
6
|
+
* saying itself twice.
|
|
7
|
+
*/
|
|
8
|
+
const THINKING_KEY = 10_000;
|
|
9
|
+
export class StreamedMessage {
|
|
10
|
+
parts = new Map();
|
|
11
|
+
id;
|
|
12
|
+
/**
|
|
13
|
+
* Spread onto every event this emits. Held here rather than applied by the caller so a message
|
|
14
|
+
* cannot be emitted unattributed by a path that forgot: the producer is fixed for this message's
|
|
15
|
+
* whole life, which is exactly the lifetime of this object.
|
|
16
|
+
*/
|
|
17
|
+
attribution;
|
|
18
|
+
constructor(producer) {
|
|
19
|
+
this.attribution = producer === undefined ? {} : { producer };
|
|
20
|
+
}
|
|
21
|
+
/** `message_start`. The SDK does not always carry an id, so one is minted rather than left absent. */
|
|
22
|
+
start(id) {
|
|
23
|
+
this.parts.clear();
|
|
24
|
+
this.id = id ?? randomUUID();
|
|
25
|
+
}
|
|
26
|
+
text(index, delta) {
|
|
27
|
+
this.parts.set(index, (this.parts.get(index) ?? "") + delta);
|
|
28
|
+
return {
|
|
29
|
+
type: "message",
|
|
30
|
+
id: this.key(),
|
|
31
|
+
text: this.join((key) => key < THINKING_KEY),
|
|
32
|
+
final: false,
|
|
33
|
+
...this.attribution,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Joined across blocks rather than emitting only the one just written to: a message with more than
|
|
38
|
+
* one reasoning block would otherwise replace the Entry's text with whichever arrived last.
|
|
39
|
+
*/
|
|
40
|
+
thinking(index, delta) {
|
|
41
|
+
const key = index + THINKING_KEY;
|
|
42
|
+
this.parts.set(key, (this.parts.get(key) ?? "") + delta);
|
|
43
|
+
return { type: "thinking", id: `${this.key()}-thinking`, text: this.reasoning(), final: false, ...this.attribution };
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The finished message. `reportedId` is what the SDK called it, and it is used **only** when nothing
|
|
47
|
+
* streamed — otherwise the streamed id wins, because that is the Entry already on screen.
|
|
48
|
+
*
|
|
49
|
+
* Reasoning is finalised here too. It never used to be, so a thinking Entry kept `final: false` for
|
|
50
|
+
* the rest of the Agent Session's life: its caret blinked forever and ThinkingEntryView's clamp,
|
|
51
|
+
* gated on `final`, never engaged.
|
|
52
|
+
*/
|
|
53
|
+
finish(reportedId, content) {
|
|
54
|
+
const id = this.id ?? reportedId;
|
|
55
|
+
const streamed = this.reasoning();
|
|
56
|
+
this.parts.clear();
|
|
57
|
+
this.id = undefined;
|
|
58
|
+
const events = [];
|
|
59
|
+
const text = blocks(content, "text", (block) => block.text);
|
|
60
|
+
if (text)
|
|
61
|
+
events.push({ type: "message", id, text, final: true, ...this.attribution });
|
|
62
|
+
// The streamed text is the fallback for a message the SDK reports no thinking block back for.
|
|
63
|
+
const thinking = blocks(content, "thinking", (block) => block.thinking) || streamed;
|
|
64
|
+
if (thinking)
|
|
65
|
+
events.push({ type: "thinking", id: `${id}-thinking`, text: thinking, final: true, ...this.attribution });
|
|
66
|
+
return events;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* The id the stream is writing under, minted on first use. Deltas can arrive without a preceding
|
|
70
|
+
* `message_start`, and the constant placeholder that used to stand in for that case could never
|
|
71
|
+
* match the finished message's id — which is the same bug this class exists to prevent.
|
|
72
|
+
*/
|
|
73
|
+
key() {
|
|
74
|
+
this.id ??= randomUUID();
|
|
75
|
+
return this.id;
|
|
76
|
+
}
|
|
77
|
+
reasoning() {
|
|
78
|
+
return this.join((key) => key >= THINKING_KEY);
|
|
79
|
+
}
|
|
80
|
+
join(keep) {
|
|
81
|
+
return [...this.parts.entries()]
|
|
82
|
+
.filter(([key]) => keep(key))
|
|
83
|
+
.sort(([a], [b]) => a - b)
|
|
84
|
+
.map(([, value]) => value)
|
|
85
|
+
.join("");
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* One StreamedMessage per producer, so a Subagent's stream cannot disturb its parent's.
|
|
90
|
+
*
|
|
91
|
+
* A single StreamedMessage cannot serve two producers: `start()` clears `parts` and overwrites `id`,
|
|
92
|
+
* so a Subagent's `message_start` arriving mid-parent-message takes the id the parent's Entry is
|
|
93
|
+
* already on screen under, and the parent's accumulated text is discarded. That is the same stranded
|
|
94
|
+
* caret this module exists to prevent, reached by a second writer rather than by a changing id.
|
|
95
|
+
*
|
|
96
|
+
* Producers are keyed by the SDK's `parent_tool_use_id`, with `""` for the Agent Session's own model.
|
|
97
|
+
*/
|
|
98
|
+
export class StreamedMessages {
|
|
99
|
+
byProducer = new Map();
|
|
100
|
+
for(producer) {
|
|
101
|
+
const existing = this.byProducer.get(producer);
|
|
102
|
+
if (existing)
|
|
103
|
+
return existing;
|
|
104
|
+
const created = new StreamedMessage(producer === "" ? undefined : { subagentId: producer });
|
|
105
|
+
this.byProducer.set(producer, created);
|
|
106
|
+
return created;
|
|
107
|
+
}
|
|
108
|
+
/** Finishes this producer's message and forgets it, so a producer that never speaks again leaks nothing. */
|
|
109
|
+
finish(producer, reportedId, content) {
|
|
110
|
+
const events = this.for(producer).finish(reportedId, content);
|
|
111
|
+
this.byProducer.delete(producer);
|
|
112
|
+
return events;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
function blocks(content, type, read) {
|
|
116
|
+
return content
|
|
117
|
+
.filter((block) => block.type === type)
|
|
118
|
+
.map((block) => read(block) ?? "")
|
|
119
|
+
.join("");
|
|
120
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Subagents open in one turn, the turn end held back while any of them is, and the backgrounded
|
|
3
|
+
* ones that go on running past it.
|
|
4
|
+
*
|
|
5
|
+
* `SDKResultMessage` carries no `parent_tool_use_id` at SDK 0.3.247, so a `result` emitted for a
|
|
6
|
+
* subagent cannot be told apart from the one that ends the turn. (ADR 0016 records that CLI 2.1.247
|
|
7
|
+
* emits no such result in the first place — one per parent turn and no more — so the holding below
|
|
8
|
+
* is belt to the bookkeeping's braces. Kept because that is one version on the happy path, and says
|
|
9
|
+
* nothing about a nested Subagent, an interrupt, or an error.) Ending on the first would clear
|
|
10
|
+
* `turnInFlight` in the Session Host, and the Steering Queue would dispatch the next message into a
|
|
11
|
+
* turn that is still running — two messages in one turn, which reads as the agent ignoring the first.
|
|
12
|
+
*
|
|
13
|
+
* Its own module rather than three fields on ClaudeSession because that session cannot be constructed
|
|
14
|
+
* without spawning a Claude process, so none of this would be reachable from a test there — the same
|
|
15
|
+
* reason StreamedMessage lives apart.
|
|
16
|
+
*/
|
|
17
|
+
export class Subagents {
|
|
18
|
+
open = new Map();
|
|
19
|
+
/**
|
|
20
|
+
* The Subagents running detached, which are open without holding anything (ADR 0016).
|
|
21
|
+
*
|
|
22
|
+
* Apart from `open` rather than a flag on the brief because the two are asked different questions:
|
|
23
|
+
* `open` answers "may this turn end", and this answers "whose card is still running". Only the
|
|
24
|
+
* first is turn-scoped, which is why `clear` empties one and keeps the other.
|
|
25
|
+
*/
|
|
26
|
+
detached = new Map();
|
|
27
|
+
/**
|
|
28
|
+
* `task_id` to the `callId` that spawned it, for the `task_notification` that closes a detached
|
|
29
|
+
* Subagent — it is the only message carrying the task id alone, and ADR 0015 keeps `callId` the
|
|
30
|
+
* one id space.
|
|
31
|
+
*/
|
|
32
|
+
tasks = new Map();
|
|
33
|
+
held;
|
|
34
|
+
spawn(callId, brief) {
|
|
35
|
+
this.open.set(callId, brief);
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* What a still-open Subagent was called and asked to do, or undefined for a tool call that is
|
|
39
|
+
* not one. A snapshot carries the whole state including the name, so the terminal one emitted when
|
|
40
|
+
* a Subagent returns needs this back — the returning `tool_result` carries only an id.
|
|
41
|
+
*/
|
|
42
|
+
describe(callId) {
|
|
43
|
+
return this.open.get(callId) ?? this.detached.get(callId);
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Record that a Subagent was backgrounded, so it stops holding the turn without ending.
|
|
47
|
+
*
|
|
48
|
+
* Answers the same question `returned` does — the turn end now free to fire — because a launch
|
|
49
|
+
* receipt releases a held end for exactly the reason a real one does: nothing else is waiting.
|
|
50
|
+
*/
|
|
51
|
+
background(callId) {
|
|
52
|
+
const brief = this.open.get(callId);
|
|
53
|
+
if (brief === undefined)
|
|
54
|
+
return undefined;
|
|
55
|
+
this.open.delete(callId);
|
|
56
|
+
this.detached.set(callId, brief);
|
|
57
|
+
return this.release();
|
|
58
|
+
}
|
|
59
|
+
/** Remember which Subagent a task id belongs to. Ignores a task that is not one's. */
|
|
60
|
+
noteTask(taskId, callId) {
|
|
61
|
+
if (this.describe(callId) === undefined)
|
|
62
|
+
return;
|
|
63
|
+
this.tasks.set(taskId, callId);
|
|
64
|
+
}
|
|
65
|
+
/** The Subagent a `task_notification` is about, or undefined when the task is not a Subagent's. */
|
|
66
|
+
callIdOf(taskId) {
|
|
67
|
+
return this.tasks.get(taskId);
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Record that a Subagent returned. Answers with the turn end that was waiting on it, and only
|
|
71
|
+
* when it was the last one open — so a turn with three Subagents ends once, after the third.
|
|
72
|
+
*
|
|
73
|
+
* A detached one releases nothing: it gave up its hold when it was backgrounded, and the turn it
|
|
74
|
+
* was spawned in has long since ended.
|
|
75
|
+
*/
|
|
76
|
+
returned(callId) {
|
|
77
|
+
this.forgetTasks(callId);
|
|
78
|
+
if (this.detached.delete(callId))
|
|
79
|
+
return undefined;
|
|
80
|
+
if (!this.open.delete(callId))
|
|
81
|
+
return undefined;
|
|
82
|
+
return this.release();
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Offer a turn end. True when it was held because a Subagent is still open, false when the caller
|
|
86
|
+
* should end the turn now.
|
|
87
|
+
*/
|
|
88
|
+
hold(reason) {
|
|
89
|
+
if (this.open.size === 0)
|
|
90
|
+
return false;
|
|
91
|
+
this.held = reason;
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Forget this turn's bookkeeping, so a held end cannot reach the turn after this one.
|
|
96
|
+
*
|
|
97
|
+
* Detached Subagents and their task ids deliberately survive: one outlives the turn that spawned
|
|
98
|
+
* it (ADR 0016), and the snapshot closing it is emitted turns later from the brief kept here.
|
|
99
|
+
*/
|
|
100
|
+
clear() {
|
|
101
|
+
this.open.clear();
|
|
102
|
+
this.held = undefined;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Forget detached Subagents too, for a Backend Session being taken away.
|
|
106
|
+
*
|
|
107
|
+
* They die with the CLI process, so nothing will ever notify them closed — the Session Host
|
|
108
|
+
* records that as `aborted` from the transcript, the way it does a torn turn.
|
|
109
|
+
*/
|
|
110
|
+
abandon() {
|
|
111
|
+
this.clear();
|
|
112
|
+
this.detached.clear();
|
|
113
|
+
this.tasks.clear();
|
|
114
|
+
}
|
|
115
|
+
release() {
|
|
116
|
+
if (this.open.size > 0)
|
|
117
|
+
return undefined;
|
|
118
|
+
const held = this.held;
|
|
119
|
+
this.held = undefined;
|
|
120
|
+
return held;
|
|
121
|
+
}
|
|
122
|
+
forgetTasks(callId) {
|
|
123
|
+
for (const [taskId, owner] of this.tasks) {
|
|
124
|
+
if (owner === callId)
|
|
125
|
+
this.tasks.delete(taskId);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { createSdkMcpServer, tool } from '@anthropic-ai/claude-agent-sdk';
|
|
2
|
+
import { workflowInspectInput, workflowRecoverInput, workflowRelayInput, inspectDescription, recoverDescription, relayEnquiryDescription, relayPermissionDescription } from "../workflow-tools.js";
|
|
3
|
+
export function workflowParentServer(parent) {
|
|
4
|
+
if (!parent)
|
|
5
|
+
return {};
|
|
6
|
+
return { flow_workflow: createSdkMcpServer({ name: 'flow_workflow', tools: [
|
|
7
|
+
tool('workflow_inspect', inspectDescription, workflowInspectInput.shape, async (input) => ({ content: [{ type: 'text', text: JSON.stringify(await parent.inspect(input)) }] })),
|
|
8
|
+
tool('workflow_recover', recoverDescription, workflowRecoverInput.shape, async (input, extra) => ({ content: [{ type: 'text', text: JSON.stringify(await parent.recover(input, extra?.signal)) }] })),
|
|
9
|
+
tool('workflow_relay_enquiry', relayEnquiryDescription, workflowRelayInput.shape, async (input, extra) => ({ content: [{ type: 'text', text: JSON.stringify(await parent.relayEnquiry(input, extra?.signal)) }] })),
|
|
10
|
+
tool('workflow_relay_permission', relayPermissionDescription, workflowRelayInput.shape, async (input, extra) => ({ content: [{ type: 'text', text: JSON.stringify(await parent.relayPermission(input, extra?.signal)) }] })),
|
|
11
|
+
] }) };
|
|
12
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { createSdkMcpServer, tool } from "@anthropic-ai/claude-agent-sdk";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
export class WorkflowProcesses {
|
|
6
|
+
calls = new Map();
|
|
7
|
+
closed = false;
|
|
8
|
+
scope;
|
|
9
|
+
emit;
|
|
10
|
+
constructor(scope, emit) {
|
|
11
|
+
this.scope = scope;
|
|
12
|
+
this.emit = emit;
|
|
13
|
+
}
|
|
14
|
+
server = createSdkMcpServer({ name: "workflow", tools: [
|
|
15
|
+
tool("bash", "Run a shell command. Background calls are owned by this workflow step. Do not detach processes yourself.", { command: z.string(), run_in_background: z.boolean().optional(), call_id: z.string().optional() }, async (input) => {
|
|
16
|
+
const id = this.start(input.command, input.run_in_background === true, input.call_id);
|
|
17
|
+
if (!input.run_in_background)
|
|
18
|
+
await this.calls.get(id).done;
|
|
19
|
+
return this.result(id);
|
|
20
|
+
}),
|
|
21
|
+
tool("bash_output", "Read output and status of an owned shell call.", { call_id: z.string() }, async ({ call_id }) => this.result(call_id)),
|
|
22
|
+
tool("kill_shell", "Stop an owned shell call and wait for it to exit.", { call_id: z.string() }, async ({ call_id }) => {
|
|
23
|
+
const call = this.get(call_id);
|
|
24
|
+
this.stop(call);
|
|
25
|
+
await call.done;
|
|
26
|
+
return this.result(call_id);
|
|
27
|
+
}),
|
|
28
|
+
] });
|
|
29
|
+
start(command, background, id = randomUUID()) {
|
|
30
|
+
if (this.closed)
|
|
31
|
+
throw new Error("Workflow processes stopped");
|
|
32
|
+
if (process.platform === "win32")
|
|
33
|
+
throw new Error("Workflow shell tools require POSIX process groups");
|
|
34
|
+
if (this.calls.has(id))
|
|
35
|
+
throw new Error(`Duplicate workflow shell call: ${id}`);
|
|
36
|
+
const child = spawn("/bin/bash", ["-c", command], { cwd: this.scope, detached: true, stdio: ["ignore", "pipe", "pipe"] });
|
|
37
|
+
const call = { process: child, done: Promise.resolve(), output: "", exitCode: null, stopped: false };
|
|
38
|
+
this.calls.set(id, call);
|
|
39
|
+
if (background)
|
|
40
|
+
this.emit({ type: "background_call", callId: id, tool: "mcp__workflow__bash", state: "running" });
|
|
41
|
+
const append = (data) => {
|
|
42
|
+
call.output += data.toString();
|
|
43
|
+
};
|
|
44
|
+
child.stdout.setEncoding("utf8").on("data", append);
|
|
45
|
+
child.stderr.setEncoding("utf8").on("data", append);
|
|
46
|
+
child.on("error", (error) => append(error.message));
|
|
47
|
+
child.on("exit", () => this.killGroup(call));
|
|
48
|
+
call.done = new Promise((resolve) => child.once("close", (code) => {
|
|
49
|
+
call.exitCode = code;
|
|
50
|
+
if (background)
|
|
51
|
+
this.emit({ type: "background_call", callId: id, tool: "mcp__workflow__bash",
|
|
52
|
+
state: call.stopped ? "aborted" : code === 0 ? "complete" : "error" });
|
|
53
|
+
resolve();
|
|
54
|
+
}));
|
|
55
|
+
return id;
|
|
56
|
+
}
|
|
57
|
+
get(id) {
|
|
58
|
+
const call = this.calls.get(id);
|
|
59
|
+
if (!call)
|
|
60
|
+
throw new Error(`Unknown workflow shell call: ${id}`);
|
|
61
|
+
return call;
|
|
62
|
+
}
|
|
63
|
+
result(id) {
|
|
64
|
+
const call = this.get(id);
|
|
65
|
+
return { content: [{ type: "text", text: JSON.stringify({ call_id: id, output: call.output,
|
|
66
|
+
exitCode: call.exitCode, running: call.process.exitCode === null && call.process.signalCode === null }) }] };
|
|
67
|
+
}
|
|
68
|
+
killGroup(call) {
|
|
69
|
+
if (!call.process.pid)
|
|
70
|
+
return;
|
|
71
|
+
try {
|
|
72
|
+
process.kill(-call.process.pid, "SIGKILL");
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
if (error.code !== "ESRCH")
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
stop(call) {
|
|
80
|
+
call.stopped = true;
|
|
81
|
+
this.killGroup(call);
|
|
82
|
+
}
|
|
83
|
+
async drain() {
|
|
84
|
+
this.closed = true;
|
|
85
|
+
await Promise.all([...this.calls.values()].map((call) => call.done));
|
|
86
|
+
}
|
|
87
|
+
async dispose() {
|
|
88
|
+
this.closed = true;
|
|
89
|
+
for (const call of this.calls.values()) {
|
|
90
|
+
if (call.process.exitCode === null && call.process.signalCode === null)
|
|
91
|
+
this.stop(call);
|
|
92
|
+
}
|
|
93
|
+
await this.drain();
|
|
94
|
+
}
|
|
95
|
+
}
|