@nathanstephenson/flow 0.1.10-beta.1 → 0.1.10-beta.3
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 +18 -0
- package/build/backend-worker-chunks/{chunk-CYE5L6Z5.mjs → chunk-LO7O6NAM.mjs} +9 -7
- package/build/backend-worker-chunks/{claude-UXZDJKZQ.mjs → claude-6L5KCQWJ.mjs} +99 -21
- package/build/backend-worker-chunks/{pi-UKRC4DDM.mjs → pi-QNU2YE4G.mjs} +45 -13
- package/build/backend-worker.mjs +48 -7
- package/dist/backend/claude/background-calls.js +7 -3
- package/dist/backend/claude/index.js +72 -10
- package/dist/backend/claude/subagents.js +30 -9
- package/dist/backend/fake/index.js +36 -6
- package/dist/backend/pi/index.js +34 -2
- package/dist/backend/pi/state.js +16 -1
- package/dist/backend/pi/subagents.js +7 -3
- package/dist/backend/worker/claude-state.js +22 -0
- package/dist/backend/worker/entry.js +25 -6
- package/dist/backend/worker/index.js +30 -5
- package/dist/backend/worker/protocol.js +1 -1
- package/dist/backend/worker/rpc.js +13 -0
- package/dist/backend/worker/sandbox-mcp.js +18 -7
- package/dist/backend/workflow-tools.js +9 -7
- package/dist/build-id +1 -1
- package/dist/cli/bootstrap.js +1 -1
- package/dist/client/reduce.js +29 -3
- package/dist/client/subagent-tree.js +49 -0
- package/dist/daemon/git.js +10 -7
- package/dist/daemon/host.js +226 -26
- package/dist/daemon/runtime.js +71 -3
- package/dist/daemon/server.js +3 -0
- package/dist/daemon/store.js +2 -0
- package/dist/daemon/workflow-builder-guidance.js +1 -1
- package/dist/daemon/workflow-builder.js +36 -11
- package/dist/daemon/workflow-environment.js +191 -0
- package/dist/daemon/workflow-execution-launch.js +77 -0
- package/dist/daemon/workflow-execution-resources.js +76 -0
- package/dist/daemon/workflow-execution-routes.js +9 -6
- package/dist/daemon/workflow-execution-values.js +128 -0
- package/dist/daemon/workflow-executions.js +382 -300
- package/dist/daemon/workflow-routes.js +39 -0
- package/dist/daemon/workflow-schedule-driver.js +247 -0
- package/dist/daemon/workflow-schedule-routes.js +137 -0
- package/dist/daemon/workflow-schedules.js +341 -0
- package/dist/isolation/sandbox.js +30 -14
- package/dist/isolation/shared-sandbox.js +3 -3
- package/dist/protocol/events.js +2 -0
- package/dist/protocol/workflow-schedules.js +1 -0
- package/dist/tui/render.js +7 -1
- package/dist/workflows/calls.js +53 -0
- package/dist/workflows/errors.js +2 -0
- package/dist/workflows/executors.js +1 -1
- package/dist/workflows/graph.js +78 -4
- package/dist/workflows/invocations.js +23 -0
- package/dist/workflows/owner.js +45 -0
- package/dist/workflows/records.js +124 -8
- package/dist/workflows/recovery.js +37 -1
- package/dist/workflows/schedule-errors.js +2 -0
- package/dist/workflows/schedule-store.js +385 -0
- package/dist/workflows/scheduler.js +351 -92
- package/dist/workflows/schedules.js +129 -0
- package/dist/workflows/schema.js +2 -0
- package/dist/workflows/store.js +110 -11
- package/package.json +2 -1
- package/web/dist/assets/index-BGu3YSP7.css +2 -0
- package/web/dist/assets/index-Miy2nveb.js +40 -0
- package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-Vf_fCXyE.js} +1 -1
- package/web/dist/assets/settings-workflows-DVKxJWQm.js +23 -0
- package/web/dist/assets/workflows-Dobqzjg-.js +146 -0
- package/web/dist/assets/workflows-pane-KB-Q76KZ.js +1 -0
- package/web/dist/index.html +4 -3
- package/web/dist/assets/index-DRfeO6GJ.js +0 -40
- package/web/dist/assets/index-DgQFpKbn.css +0 -2
- package/web/dist/assets/settings-workflows-H-6eCff3.js +0 -23
- package/web/dist/assets/workflow-editors-CsbVx4WJ.js +0 -139
- package/web/dist/assets/workflows-Bv0sj7d0.js +0 -7
- package/web/dist/assets/workflows-pane-DHm44w7P.js +0 -1
|
@@ -14,7 +14,9 @@ import { PendingPermissions } from "./permissions.js";
|
|
|
14
14
|
import { StreamedMessages } from "./streamed-message.js";
|
|
15
15
|
import { Subagents } from "./subagents.js";
|
|
16
16
|
import { BackgroundCalls } from "./background-calls.js";
|
|
17
|
-
import { prepareClaudeState } from "../worker/claude-state.js";
|
|
17
|
+
import { prepareClaudeState, projectKey } from "../worker/claude-state.js";
|
|
18
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
19
|
+
import { join } from "node:path";
|
|
18
20
|
import { AutoPermissionUnavailable } from "../permission-errors.js";
|
|
19
21
|
export { AutoPermissionUnavailable } from "../permission-errors.js";
|
|
20
22
|
/**
|
|
@@ -100,6 +102,10 @@ function attribution(producer) {
|
|
|
100
102
|
* something a transcript row can show. Falls back to the tool name so a client always has something
|
|
101
103
|
* to print, which is what the protocol promises.
|
|
102
104
|
*/
|
|
105
|
+
function promptOf(input) {
|
|
106
|
+
const prompt = input?.prompt;
|
|
107
|
+
return typeof prompt === "string" && prompt !== "" ? prompt : undefined;
|
|
108
|
+
}
|
|
103
109
|
export function briefOf(input) {
|
|
104
110
|
const fields = (input ?? {});
|
|
105
111
|
const name = typeof fields.subagent_type === "string" ? fields.subagent_type : SUBAGENT_TOOL;
|
|
@@ -158,7 +164,7 @@ const DEFAULT_ALLOWED_TOOLS = [
|
|
|
158
164
|
"Agent",
|
|
159
165
|
];
|
|
160
166
|
class ClaudeSession {
|
|
161
|
-
capabilities = { providers: ["anthropic"], models: [], compaction: true, autoCompaction: "startup", fork: true, subagents: true, enquiries: true, permissions: true };
|
|
167
|
+
capabilities = { providers: ["anthropic"], models: [], compaction: true, autoCompaction: "startup", fork: true, rewind: true, rewindFiles: true, subagents: true, enquiries: true, permissions: true };
|
|
162
168
|
inbox = new AsyncQueue();
|
|
163
169
|
emit;
|
|
164
170
|
stream;
|
|
@@ -189,6 +195,8 @@ class ClaudeSession {
|
|
|
189
195
|
subagents = new Subagents();
|
|
190
196
|
/** Tool calls announced this turn, and the ones the CLI is running past it (ADR 0021). */
|
|
191
197
|
calls = new BackgroundCalls();
|
|
198
|
+
/** Each Subagent's brief, reported from its `Agent` call, so the same text echoed into its stream is not reported twice. */
|
|
199
|
+
briefs = new Map();
|
|
192
200
|
enquiries = new PendingEnquiries();
|
|
193
201
|
permissions = new PendingPermissions();
|
|
194
202
|
/** Spawning call id for each parked ordinary-Subagent permission, through its terminal event. */
|
|
@@ -217,7 +225,7 @@ class ClaudeSession {
|
|
|
217
225
|
backendOptions;
|
|
218
226
|
workflowAutoCompaction;
|
|
219
227
|
claudeState;
|
|
220
|
-
constructor(options, backendOptions, claudeState) {
|
|
228
|
+
constructor(options, backendOptions, claudeState, resumeAt) {
|
|
221
229
|
this.claudeState = claudeState;
|
|
222
230
|
this.parentWorkflow = options.workflowBuilder ? workflowBuilderServer(options.workflowBuilder)
|
|
223
231
|
: workflowParentServer(options.tools === "none" ? undefined : options.workflow);
|
|
@@ -280,6 +288,8 @@ class ClaudeSession {
|
|
|
280
288
|
// while the model list is still in flight. Levels Claude does not have wait for the clamp.
|
|
281
289
|
...(startingEffort ? { effort: startingEffort } : {}),
|
|
282
290
|
...(options.resume ? { resume: options.resume } : {}),
|
|
291
|
+
...(resumeAt ? { resumeSessionAt: resumeAt } : {}),
|
|
292
|
+
...(builder || toolless ? {} : { enableFileCheckpointing: true }),
|
|
283
293
|
...(backendOptions.pathToClaudeCodeExecutable
|
|
284
294
|
? { pathToClaudeCodeExecutable: backendOptions.pathToClaudeCodeExecutable }
|
|
285
295
|
: {}),
|
|
@@ -406,7 +416,15 @@ class ClaudeSession {
|
|
|
406
416
|
resumeToken() {
|
|
407
417
|
return this.sdkSessionId || undefined;
|
|
408
418
|
}
|
|
409
|
-
async
|
|
419
|
+
async rewindFiles(messageId) {
|
|
420
|
+
const preview = await this.stream.rewindFiles(messageId, { dryRun: true });
|
|
421
|
+
if (!preview.canRewind)
|
|
422
|
+
throw new Error(preview.error ?? "No file checkpoint exists for this message");
|
|
423
|
+
const result = await this.stream.rewindFiles(messageId);
|
|
424
|
+
if (!result.canRewind)
|
|
425
|
+
throw new Error(result.error ?? "Files could not be rewound");
|
|
426
|
+
}
|
|
427
|
+
async prompt(text, attachments, messageId) {
|
|
410
428
|
if (this.disposed)
|
|
411
429
|
throw new Error("Backend Session disposed");
|
|
412
430
|
this.turnId = randomUUID();
|
|
@@ -416,6 +434,7 @@ class ClaudeSession {
|
|
|
416
434
|
message: { role: "user", content: userContent(text, attachments) },
|
|
417
435
|
parent_tool_use_id: null,
|
|
418
436
|
session_id: this.sdkSessionId,
|
|
437
|
+
...(messageId ? { uuid: messageId } : {}),
|
|
419
438
|
});
|
|
420
439
|
}
|
|
421
440
|
/**
|
|
@@ -693,6 +712,7 @@ class ClaudeSession {
|
|
|
693
712
|
// Detached Subagents die with the CLI process, so nothing will ever notify them closed. The
|
|
694
713
|
// Session Host records that from the transcript, the way it does a torn turn.
|
|
695
714
|
this.subagents.abandon();
|
|
715
|
+
this.briefs.clear();
|
|
696
716
|
// Background Calls are children of that process too, and go the same way for the same reason.
|
|
697
717
|
this.calls.abandon();
|
|
698
718
|
this.inbox.close();
|
|
@@ -827,13 +847,19 @@ class ClaudeSession {
|
|
|
827
847
|
if (block.name !== SUBAGENT_TOOL)
|
|
828
848
|
continue;
|
|
829
849
|
const brief = briefOf(block.input);
|
|
830
|
-
this.subagents.spawn(block.id, brief);
|
|
831
|
-
this.emit({ type: "subagent", subagentId: block.id, ...brief, state: "running" });
|
|
850
|
+
this.subagents.spawn(block.id, brief, producer);
|
|
851
|
+
this.emit({ type: "subagent", subagentId: block.id, ...brief, ...attribution(producer), state: "running" });
|
|
852
|
+
const prompt = promptOf(block.input);
|
|
853
|
+
if (prompt === undefined)
|
|
854
|
+
continue;
|
|
855
|
+
this.briefs.set(block.id, prompt);
|
|
856
|
+
this.emit({ type: "subagent_instruction", id: `${block.id}:brief`, text: prompt, producer: { subagentId: block.id } });
|
|
832
857
|
}
|
|
833
858
|
return;
|
|
834
859
|
}
|
|
835
860
|
case "user": {
|
|
836
861
|
const content = sdkMessage.message.content;
|
|
862
|
+
this.instructSubagent(sdkMessage);
|
|
837
863
|
if (typeof content === "string")
|
|
838
864
|
return;
|
|
839
865
|
for (const block of content) {
|
|
@@ -862,6 +888,7 @@ class ClaudeSession {
|
|
|
862
888
|
type: "subagent",
|
|
863
889
|
subagentId: block.tool_use_id,
|
|
864
890
|
...brief,
|
|
891
|
+
...attribution(this.subagents.parentOf(block.tool_use_id)),
|
|
865
892
|
state: isError ? "error" : "complete",
|
|
866
893
|
});
|
|
867
894
|
}
|
|
@@ -946,6 +973,7 @@ class ClaudeSession {
|
|
|
946
973
|
this.endTurn(reason);
|
|
947
974
|
}
|
|
948
975
|
closeSubagent(callId) {
|
|
976
|
+
this.briefs.delete(callId);
|
|
949
977
|
this.abandonPermissions("the Subagent stopped", (producer) => producer === callId);
|
|
950
978
|
this.permissions.clearRefusals((producer) => producer === callId);
|
|
951
979
|
const released = this.subagents.returned(callId);
|
|
@@ -1000,7 +1028,7 @@ class ClaudeSession {
|
|
|
1000
1028
|
return;
|
|
1001
1029
|
const brief = this.subagents.describe(callId);
|
|
1002
1030
|
if (brief !== undefined) {
|
|
1003
|
-
this.emit({ type: "subagent", subagentId: callId, ...brief, state: outcome });
|
|
1031
|
+
this.emit({ type: "subagent", subagentId: callId, ...brief, ...attribution(this.subagents.parentOf(callId)), state: outcome });
|
|
1004
1032
|
this.closeSubagent(callId);
|
|
1005
1033
|
return;
|
|
1006
1034
|
}
|
|
@@ -1027,6 +1055,23 @@ class ClaudeSession {
|
|
|
1027
1055
|
this.turnId = randomUUID();
|
|
1028
1056
|
this.emit({ type: "turn_started", turnId: this.turnId });
|
|
1029
1057
|
}
|
|
1058
|
+
/** Report text the spawning model sent into a Subagent. The Agent Session's own user text is the host's to record. */
|
|
1059
|
+
instructSubagent(sdkMessage) {
|
|
1060
|
+
const subagentId = producerOf(sdkMessage);
|
|
1061
|
+
if (subagentId === "")
|
|
1062
|
+
return;
|
|
1063
|
+
const content = sdkMessage.message.content;
|
|
1064
|
+
const text = typeof content === "string"
|
|
1065
|
+
? content
|
|
1066
|
+
: content.flatMap((block) => block.type === "text" ? [block.text] : []).join("\n");
|
|
1067
|
+
if (text === "")
|
|
1068
|
+
return;
|
|
1069
|
+
if (this.briefs.get(subagentId) === text) {
|
|
1070
|
+
this.briefs.delete(subagentId);
|
|
1071
|
+
return;
|
|
1072
|
+
}
|
|
1073
|
+
this.emit({ type: "subagent_instruction", id: sdkMessage.uuid ?? randomUUID(), text, producer: { subagentId } });
|
|
1074
|
+
}
|
|
1030
1075
|
endTurn(reason) {
|
|
1031
1076
|
const turnId = this.turnId;
|
|
1032
1077
|
/*
|
|
@@ -1041,8 +1086,8 @@ class ClaudeSession {
|
|
|
1041
1086
|
// Cleared whatever the outcome, so a held end cannot reach the turn after this one.
|
|
1042
1087
|
this.subagents.clear();
|
|
1043
1088
|
// Drops the calls this turn announced. Open Background Calls survive — one outlives the turn
|
|
1044
|
-
// that made it, which is the whole of ADR 0021.
|
|
1045
|
-
this.calls.clear();
|
|
1089
|
+
// that made it, which is the whole of ADR 0021 — and so do calls detached work announced.
|
|
1090
|
+
this.calls.clear((brief) => brief.producer !== undefined && !ended(brief.producer.subagentId));
|
|
1046
1091
|
this.enquiries.clear();
|
|
1047
1092
|
if (!turnId)
|
|
1048
1093
|
return;
|
|
@@ -1064,7 +1109,11 @@ export class ClaudeBackend {
|
|
|
1064
1109
|
const claudeState = prepareClaudeState(options.stateDir, process.env, options.scope, options.resume);
|
|
1065
1110
|
let session;
|
|
1066
1111
|
try {
|
|
1067
|
-
|
|
1112
|
+
const resumeAt = options.resume && options.resumeBefore ? resumePoint(claudeState.env, options.scope, options.resume, options.resumeBefore) : undefined;
|
|
1113
|
+
// A Rewind to the first message keeps nothing, so it starts a new conversation.
|
|
1114
|
+
const { resume: _discarded, ...fresh } = options;
|
|
1115
|
+
session = resumeAt === null ? new ClaudeSession(fresh, this.options, claudeState)
|
|
1116
|
+
: new ClaudeSession(options, this.options, claudeState, resumeAt);
|
|
1068
1117
|
}
|
|
1069
1118
|
catch (error) {
|
|
1070
1119
|
claudeState.cleanup();
|
|
@@ -1101,6 +1150,19 @@ export class ClaudeBackend {
|
|
|
1101
1150
|
}
|
|
1102
1151
|
}
|
|
1103
1152
|
}
|
|
1153
|
+
/** The chain entry just before user message `before`, or null when `before` starts the conversation. */
|
|
1154
|
+
function resumePoint(env, scope, resume, before) {
|
|
1155
|
+
const record = join(env.CLAUDE_CONFIG_DIR ?? "", "projects", projectKey(scope), `${resume}.jsonl`);
|
|
1156
|
+
const lines = existsSync(record) ? readFileSync(record, "utf8").split("\n") : [];
|
|
1157
|
+
for (const line of lines) {
|
|
1158
|
+
if (!line.includes(before))
|
|
1159
|
+
continue;
|
|
1160
|
+
const entry = JSON.parse(line);
|
|
1161
|
+
if (entry.uuid === before)
|
|
1162
|
+
return entry.parentUuid ?? null;
|
|
1163
|
+
}
|
|
1164
|
+
throw new Error("This message cannot be rewound: Claude has no record of it");
|
|
1165
|
+
}
|
|
1104
1166
|
/** Claude reports one Provider, and per-model effort: haiku carries no supportedEffortLevels. */
|
|
1105
1167
|
/**
|
|
1106
1168
|
* Which model id to announce for the one the SDK just named.
|
|
@@ -6,7 +6,8 @@
|
|
|
6
6
|
* subagent cannot be told apart from the one that ends the turn. (ADR 0016 records that CLI 2.1.247
|
|
7
7
|
* emits no such result in the first place — one per parent turn and no more — so the holding below
|
|
8
8
|
* is belt to the bookkeeping's braces. Kept because that is one version on the happy path, and says
|
|
9
|
-
* nothing about
|
|
9
|
+
* nothing about an interrupt or an error.) A nested Subagent holds the turn like any other, unless
|
|
10
|
+
* an ancestor is backgrounded: work started by backgrounded work is backgrounded too. Ending on the first would clear
|
|
10
11
|
* `turnInFlight` in the Session Host, and the Steering Queue would dispatch the next message into a
|
|
11
12
|
* turn that is still running — two messages in one turn, which reads as the agent ignoring the first.
|
|
12
13
|
*
|
|
@@ -31,8 +32,13 @@ export class Subagents {
|
|
|
31
32
|
*/
|
|
32
33
|
tasks = new Map();
|
|
33
34
|
held;
|
|
34
|
-
|
|
35
|
-
|
|
35
|
+
/** Record a Subagent. One spawned under detached work is detached from the start, and holds nothing. */
|
|
36
|
+
spawn(callId, brief, parent = "") {
|
|
37
|
+
(this.isDetached(parent) ? this.detached : this.open).set(callId, { brief, parent });
|
|
38
|
+
}
|
|
39
|
+
/** The Subagent that spawned this one, or `""` for one the Agent Session's own model spawned. */
|
|
40
|
+
parentOf(callId) {
|
|
41
|
+
return this.spawned(callId)?.parent ?? "";
|
|
36
42
|
}
|
|
37
43
|
/**
|
|
38
44
|
* What a still-open Subagent was called and asked to do, or undefined for a tool call that is
|
|
@@ -40,25 +46,37 @@ export class Subagents {
|
|
|
40
46
|
* a Subagent returns needs this back — the returning `tool_result` carries only an id.
|
|
41
47
|
*/
|
|
42
48
|
describe(callId) {
|
|
43
|
-
return this.
|
|
49
|
+
return this.spawned(callId)?.brief;
|
|
44
50
|
}
|
|
45
51
|
/**
|
|
46
52
|
* Record that a Subagent was backgrounded, so it stops holding the turn without ending.
|
|
47
53
|
*
|
|
48
54
|
* Answers the same question `returned` does — the turn end now free to fire — because a launch
|
|
49
55
|
* receipt releases a held end for exactly the reason a real one does: nothing else is waiting.
|
|
56
|
+
*
|
|
57
|
+
* Its open descendants are detached with it, since they now have a detached ancestor.
|
|
50
58
|
*/
|
|
51
59
|
background(callId) {
|
|
52
|
-
const
|
|
53
|
-
if (
|
|
60
|
+
const spawned = this.open.get(callId);
|
|
61
|
+
if (spawned === undefined)
|
|
54
62
|
return undefined;
|
|
55
63
|
this.open.delete(callId);
|
|
56
|
-
this.detached.set(callId,
|
|
64
|
+
this.detached.set(callId, spawned);
|
|
65
|
+
for (const [id, descendant] of this.open) {
|
|
66
|
+
if (!this.isDetached(id))
|
|
67
|
+
continue;
|
|
68
|
+
this.open.delete(id);
|
|
69
|
+
this.detached.set(id, descendant);
|
|
70
|
+
}
|
|
57
71
|
return this.release();
|
|
58
72
|
}
|
|
59
|
-
/** Whether this Subagent's work survives the parent turn ending. */
|
|
73
|
+
/** Whether this Subagent's work survives the parent turn ending: it or an ancestor is detached. */
|
|
60
74
|
isDetached(callId) {
|
|
61
|
-
|
|
75
|
+
for (let at = callId; at !== ""; at = this.spawned(at)?.parent ?? "") {
|
|
76
|
+
if (this.detached.has(at))
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
79
|
+
return false;
|
|
62
80
|
}
|
|
63
81
|
/** Remember which Subagent a task id belongs to. Ignores a task that is not one's. */
|
|
64
82
|
noteTask(taskId, callId) {
|
|
@@ -116,6 +134,9 @@ export class Subagents {
|
|
|
116
134
|
this.detached.clear();
|
|
117
135
|
this.tasks.clear();
|
|
118
136
|
}
|
|
137
|
+
spawned(callId) {
|
|
138
|
+
return this.open.get(callId) ?? this.detached.get(callId);
|
|
139
|
+
}
|
|
119
140
|
release() {
|
|
120
141
|
if (this.open.size > 0)
|
|
121
142
|
return undefined;
|
|
@@ -37,6 +37,11 @@ export class FakeSession {
|
|
|
37
37
|
/** Parallel to `prompts`, so a test can assert what reached the backend beside each text. */
|
|
38
38
|
promptedAttachments = [];
|
|
39
39
|
resumedFrom;
|
|
40
|
+
resumedBefore;
|
|
41
|
+
/** Parallel to `prompts`: the host's user message id for each. */
|
|
42
|
+
promptIds = [];
|
|
43
|
+
rewoundFiles = [];
|
|
44
|
+
rewindFiles;
|
|
40
45
|
/** What this session was told the Agent Session had already spent, for asserting a Revive. */
|
|
41
46
|
priorSpend;
|
|
42
47
|
/** What this session was told the machine already authorises, for asserting the read-at-create. */
|
|
@@ -150,6 +155,8 @@ export class FakeSession {
|
|
|
150
155
|
return true;
|
|
151
156
|
};
|
|
152
157
|
}
|
|
158
|
+
if (this.capabilities.rewindFiles)
|
|
159
|
+
this.rewindFiles = async (messageId) => { this.rewoundFiles.push(messageId); };
|
|
153
160
|
if (this.capabilities.compaction) {
|
|
154
161
|
// Opens and closes a turn, because a compaction is one: it spends money and holds the backend
|
|
155
162
|
// while it runs, and the Steering Queue only orders messages correctly if it is told so.
|
|
@@ -166,6 +173,7 @@ export class FakeSession {
|
|
|
166
173
|
this.emit = options.emit;
|
|
167
174
|
this.modelId = options.modelId ?? "fake-1";
|
|
168
175
|
this.resumedFrom = options.resume;
|
|
176
|
+
this.resumedBefore = options.resumeBefore;
|
|
169
177
|
this.priorSpend = options.priorSpend;
|
|
170
178
|
this.emit({ type: "model_changed", model: { id: this.modelId, provider: "fake" } });
|
|
171
179
|
if (options.effort)
|
|
@@ -174,8 +182,9 @@ export class FakeSession {
|
|
|
174
182
|
resumeToken() {
|
|
175
183
|
return "fake-resume";
|
|
176
184
|
}
|
|
177
|
-
async prompt(text, attachments) {
|
|
185
|
+
async prompt(text, attachments, messageId) {
|
|
178
186
|
this.prompts.push(text);
|
|
187
|
+
this.promptIds.push(messageId);
|
|
179
188
|
this.promptedAttachments.push(attachments ?? []);
|
|
180
189
|
this.turnId = randomUUID();
|
|
181
190
|
this.emit({ type: "turn_started", turnId: this.turnId });
|
|
@@ -314,12 +323,14 @@ export class FakeSession {
|
|
|
314
323
|
*
|
|
315
324
|
* `completeTurn` deliberately does not close an open Subagent: leaving one running is the
|
|
316
325
|
* torn-Subagent fixture, and the Session Host is what has to cope with it.
|
|
326
|
+
*
|
|
327
|
+
* `producer` names the Subagent spawning this one, for a nested Subagent.
|
|
317
328
|
*/
|
|
318
|
-
beginSubagent(name, description) {
|
|
329
|
+
beginSubagent(name, description, producer) {
|
|
319
330
|
const subagentId = randomUUID();
|
|
320
|
-
const subagent = new FakeSubagent(subagentId, name, description, this.emit);
|
|
331
|
+
const subagent = new FakeSubagent(subagentId, name, description, this.emit, producer);
|
|
321
332
|
this.subagents.push(subagent);
|
|
322
|
-
this.emit({ type: "tool_started", callId: subagentId, name: "Agent", input: { name, description } });
|
|
333
|
+
this.emit({ type: "tool_started", callId: subagentId, name: "Agent", input: { name, description }, ...(producer ? { producer } : {}) });
|
|
323
334
|
subagent.snapshot({ state: "running" });
|
|
324
335
|
return subagent;
|
|
325
336
|
}
|
|
@@ -381,16 +392,18 @@ export class FakeSubagent {
|
|
|
381
392
|
subagentId;
|
|
382
393
|
name;
|
|
383
394
|
description;
|
|
395
|
+
producer;
|
|
384
396
|
finished = false;
|
|
385
397
|
launched = false;
|
|
386
398
|
emit;
|
|
387
399
|
/** Bumped when a message finalises, so a partial and its finished half share one id. */
|
|
388
400
|
messageIndex = 0;
|
|
389
|
-
constructor(subagentId, name, description, emit) {
|
|
401
|
+
constructor(subagentId, name, description, emit, producer) {
|
|
390
402
|
this.subagentId = subagentId;
|
|
391
403
|
this.name = name;
|
|
392
404
|
this.description = description;
|
|
393
405
|
this.emit = emit;
|
|
406
|
+
this.producer = producer;
|
|
394
407
|
}
|
|
395
408
|
/**
|
|
396
409
|
* Attributed assistant text. The id is stable until the message finalises, because a partial and
|
|
@@ -408,6 +421,12 @@ export class FakeSubagent {
|
|
|
408
421
|
if (final)
|
|
409
422
|
this.messageIndex += 1;
|
|
410
423
|
}
|
|
424
|
+
/** Instructions from the model that spawned it. */
|
|
425
|
+
instruct(text) {
|
|
426
|
+
const id = randomUUID();
|
|
427
|
+
this.emit({ type: "subagent_instruction", id, text, producer: { subagentId: this.subagentId } });
|
|
428
|
+
return id;
|
|
429
|
+
}
|
|
411
430
|
/** An attributed tool call — the subagent's Read, not the parent's. */
|
|
412
431
|
useTool(name, input, result, isError = false) {
|
|
413
432
|
const callId = randomUUID();
|
|
@@ -440,6 +459,7 @@ export class FakeSubagent {
|
|
|
440
459
|
callId: this.subagentId,
|
|
441
460
|
result: `${this.name} launched in the background`,
|
|
442
461
|
isError: false,
|
|
462
|
+
...this.attribution(),
|
|
443
463
|
});
|
|
444
464
|
}
|
|
445
465
|
finish(reason = "complete") {
|
|
@@ -452,7 +472,7 @@ export class FakeSubagent {
|
|
|
452
472
|
// produces.
|
|
453
473
|
if (this.launched)
|
|
454
474
|
return;
|
|
455
|
-
this.emit({ type: "tool_ended", callId: this.subagentId, result: `${this.name} finished`, isError: reason === "error" });
|
|
475
|
+
this.emit({ type: "tool_ended", callId: this.subagentId, result: `${this.name} finished`, isError: reason === "error", ...this.attribution() });
|
|
456
476
|
}
|
|
457
477
|
/** @internal — used by FakeSession to emit the opening snapshot. */
|
|
458
478
|
snapshot(state) {
|
|
@@ -461,9 +481,13 @@ export class FakeSubagent {
|
|
|
461
481
|
subagentId: this.subagentId,
|
|
462
482
|
name: this.name,
|
|
463
483
|
...(this.description === undefined ? {} : { description: this.description }),
|
|
484
|
+
...this.attribution(),
|
|
464
485
|
...state,
|
|
465
486
|
});
|
|
466
487
|
}
|
|
488
|
+
attribution() {
|
|
489
|
+
return this.producer ? { producer: this.producer } : {};
|
|
490
|
+
}
|
|
467
491
|
}
|
|
468
492
|
export class FakeBackend {
|
|
469
493
|
name = "fake";
|
|
@@ -500,6 +524,12 @@ export class FakeBackend {
|
|
|
500
524
|
for (const resume of this.waiting.splice(0))
|
|
501
525
|
resume();
|
|
502
526
|
}
|
|
527
|
+
/** Every Fork copy asked of this backend. */
|
|
528
|
+
forks = [];
|
|
529
|
+
fork(from, to) {
|
|
530
|
+
this.forks.push({ from, to });
|
|
531
|
+
return from.resume;
|
|
532
|
+
}
|
|
503
533
|
get latest() {
|
|
504
534
|
const session = this.sessions.at(-1);
|
|
505
535
|
if (!session)
|
package/dist/backend/pi/index.js
CHANGED
|
@@ -3,6 +3,9 @@ import { piSessionTools } from "./session-tools.js";
|
|
|
3
3
|
import { piWorkflowBuilderTools } from "./workflow-builder.js";
|
|
4
4
|
import { piMcpTools } from "./mcp.js";
|
|
5
5
|
import { randomUUID } from "node:crypto";
|
|
6
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { USER_MESSAGE_MAP } from "./state.js";
|
|
6
9
|
import { createAgentSession, DefaultResourceLoader, getAgentDir, SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent";
|
|
7
10
|
import { PiWorkflowSubagent } from "./workflow-subagent.js";
|
|
8
11
|
import { piEffortLevels } from "./effort-capabilities.js";
|
|
@@ -60,6 +63,8 @@ export class PiSession {
|
|
|
60
63
|
effort;
|
|
61
64
|
messageSeq = 0;
|
|
62
65
|
currentMessageId;
|
|
66
|
+
/** Host user message ids sent but not yet seen as pi user messages, oldest first. */
|
|
67
|
+
unmappedMessageIds = [];
|
|
63
68
|
constructor(session, emit, sessionDir, support = {}) {
|
|
64
69
|
this.workflowBuilder = support.workflowBuilder ?? false;
|
|
65
70
|
this.mcp = support.mcp;
|
|
@@ -101,7 +106,9 @@ export class PiSession {
|
|
|
101
106
|
// pi persists through its own SessionManager; the directory we gave it is the resume handle.
|
|
102
107
|
return this.sessionDir;
|
|
103
108
|
}
|
|
104
|
-
async prompt(text, attachments) {
|
|
109
|
+
async prompt(text, attachments, messageId) {
|
|
110
|
+
if (messageId && this.sessionDir)
|
|
111
|
+
this.unmappedMessageIds.push(messageId);
|
|
105
112
|
this.turnId = `turn-${++this.messageSeq}`;
|
|
106
113
|
this.emit({ type: "turn_started", turnId: this.turnId });
|
|
107
114
|
await this.session.prompt(text, {
|
|
@@ -293,6 +300,15 @@ export class PiSession {
|
|
|
293
300
|
this.emit({ type: "turn_ended", turnId, reason });
|
|
294
301
|
this.scheduleCompletions();
|
|
295
302
|
}
|
|
303
|
+
/** pi appends the entry just after `message_end` reaches listeners, so look it up after that. */
|
|
304
|
+
mapUserMessage(messageId, message) {
|
|
305
|
+
queueMicrotask(() => {
|
|
306
|
+
const entry = this.session.sessionManager.getBranch().findLast((candidate) => candidate.type === "message" && candidate.message === message);
|
|
307
|
+
if (!entry || !this.sessionDir)
|
|
308
|
+
return;
|
|
309
|
+
writeFileSync(join(this.sessionDir, USER_MESSAGE_MAP), JSON.stringify({ ...readUserMessageMap(this.sessionDir), [messageId]: entry.id }), { mode: 0o600 });
|
|
310
|
+
});
|
|
311
|
+
}
|
|
296
312
|
translate(event) {
|
|
297
313
|
switch (event.type) {
|
|
298
314
|
case "agent_start":
|
|
@@ -308,6 +324,8 @@ export class PiSession {
|
|
|
308
324
|
case "message_end":
|
|
309
325
|
this.emitMessage(event.message, true);
|
|
310
326
|
this.currentMessageId = undefined;
|
|
327
|
+
if (event.message.role === "user" && this.unmappedMessageIds.length)
|
|
328
|
+
this.mapUserMessage(this.unmappedMessageIds.shift(), event.message);
|
|
311
329
|
return;
|
|
312
330
|
case "tool_execution_start":
|
|
313
331
|
this.emit({ type: "tool_started", callId: event.toolCallId, name: event.toolName, input: event.args });
|
|
@@ -484,6 +502,14 @@ export class PiBackend {
|
|
|
484
502
|
});
|
|
485
503
|
};
|
|
486
504
|
let { session, extensionsResult } = await start();
|
|
505
|
+
if (options.resumeBefore && sessionDir) {
|
|
506
|
+
const entryId = readUserMessageMap(sessionDir)[options.resumeBefore];
|
|
507
|
+
if (!entryId) {
|
|
508
|
+
session.dispose();
|
|
509
|
+
throw new Error("This message cannot be rewound: pi has no record of it");
|
|
510
|
+
}
|
|
511
|
+
await session.navigateTree(entryId);
|
|
512
|
+
}
|
|
487
513
|
const extensionError = options.compactionModelId && compactionExtensionError(extensionsResult.errors);
|
|
488
514
|
if (extensionError) {
|
|
489
515
|
session.dispose();
|
|
@@ -591,6 +617,7 @@ async function runSubagent(parent, scope, agentDir, work, id, input, signal, emi
|
|
|
591
617
|
signal.throwIfAborted();
|
|
592
618
|
await adapter.setEffort(effort);
|
|
593
619
|
signal.throwIfAborted();
|
|
620
|
+
emit({ type: "subagent_instruction", id: `${id}:brief`, text: input.prompt, producer });
|
|
594
621
|
await adapter.prompt(input.prompt);
|
|
595
622
|
if (reason !== "complete")
|
|
596
623
|
throw new Error(failure ?? `Subagent ${reason}`);
|
|
@@ -604,6 +631,10 @@ async function runSubagent(parent, scope, agentDir, work, id, input, signal, emi
|
|
|
604
631
|
await work.stopOwnedCalls(id);
|
|
605
632
|
}
|
|
606
633
|
}
|
|
634
|
+
function readUserMessageMap(sessionDir) {
|
|
635
|
+
const path = join(sessionDir, USER_MESSAGE_MAP);
|
|
636
|
+
return existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : {};
|
|
637
|
+
}
|
|
607
638
|
function capabilitiesOf(session, enquiries, subagents, permissions = true) {
|
|
608
639
|
// The SDK populates this auth-filtered snapshot before createAgentSession resolves. Every model is
|
|
609
640
|
// described directly: effort discovery is observational and must never switch the active model.
|
|
@@ -614,7 +645,8 @@ function capabilitiesOf(session, enquiries, subagents, permissions = true) {
|
|
|
614
645
|
models,
|
|
615
646
|
compaction: true,
|
|
616
647
|
autoCompaction: "model-change",
|
|
617
|
-
fork:
|
|
648
|
+
fork: true,
|
|
649
|
+
rewind: true,
|
|
618
650
|
subagents,
|
|
619
651
|
enquiries,
|
|
620
652
|
permissions,
|
package/dist/backend/pi/state.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { readdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
1
|
+
import { copyFileSync, existsSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
/** Point pi session files in `stateDir` from Scope `from` to Scope `to`. pi reopens a session only when its header `cwd` matches. */
|
|
4
4
|
export function relocatePiState(stateDir, from, to) {
|
|
@@ -16,3 +16,18 @@ export function relocatePiState(stateDir, from, to) {
|
|
|
16
16
|
renameSync(temporary, path);
|
|
17
17
|
}
|
|
18
18
|
}
|
|
19
|
+
export const USER_MESSAGE_MAP = "flow-user-messages.json";
|
|
20
|
+
/** Copy the most recent pi session file and its user message map for a Fork, bound to Scope `scope`. */
|
|
21
|
+
export function forkPiState(from, to, scope) {
|
|
22
|
+
const files = readdirSync(from, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".jsonl"));
|
|
23
|
+
const latest = files.map((entry) => entry.name).sort((a, b) => statSync(join(from, b)).mtimeMs - statSync(join(from, a)).mtimeMs)[0];
|
|
24
|
+
if (!latest)
|
|
25
|
+
throw new Error("No pi session to fork");
|
|
26
|
+
const content = readFileSync(join(from, latest), "utf8");
|
|
27
|
+
const end = content.indexOf("\n");
|
|
28
|
+
const header = JSON.parse(end < 0 ? content : content.slice(0, end));
|
|
29
|
+
writeFileSync(join(to, latest), JSON.stringify({ ...header, cwd: scope }) + (end < 0 ? "" : content.slice(end)), { mode: 0o600, flag: "wx" });
|
|
30
|
+
if (existsSync(join(from, USER_MESSAGE_MAP)))
|
|
31
|
+
copyFileSync(join(from, USER_MESSAGE_MAP), join(to, USER_MESSAGE_MAP));
|
|
32
|
+
return to;
|
|
33
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { defineTool } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import { Type } from "typebox";
|
|
3
3
|
import { EFFORT_ORDER } from "../effort.js";
|
|
4
|
+
import { callIdFor } from "./work.js";
|
|
4
5
|
export const SUBAGENT_TOOL = "subagent";
|
|
5
6
|
const parameters = Type.Object({
|
|
6
7
|
description: Type.String({ minLength: 1, description: "Short description of the delegated work" }),
|
|
@@ -10,14 +11,17 @@ const parameters = Type.Object({
|
|
|
10
11
|
effort: Type.Optional(Type.String({ enum: EFFORT_ORDER, description: "Defaults to the parent's Effort at launch" })),
|
|
11
12
|
run_in_background: Type.Optional(Type.Boolean({ description: "Defaults to true. Set false only when your next action requires the result." })),
|
|
12
13
|
});
|
|
13
|
-
export function subagentTool(work, run) {
|
|
14
|
+
export function subagentTool(work, run, producer) {
|
|
14
15
|
return defineTool({
|
|
15
16
|
name: SUBAGENT_TOOL,
|
|
16
17
|
label: "Subagent",
|
|
17
18
|
description: "Delegate work to a Subagent with its own Conversation Context. Subagents run in the background by default and report back automatically. Multiple Subagents may run concurrently. They cannot ask the human or create further Subagents.",
|
|
18
19
|
promptSnippet: "Delegate independent work to Subagents",
|
|
19
20
|
parameters,
|
|
20
|
-
execute: async (id, input, signal) =>
|
|
21
|
-
|
|
21
|
+
execute: async (id, input, signal) => {
|
|
22
|
+
const subagentId = callIdFor(id, producer);
|
|
23
|
+
return work.run({ type: "subagent", subagentId, name: input.name ?? "Subagent", description: input.description,
|
|
24
|
+
...(producer ? { producer } : {}) }, (childSignal) => run(subagentId, input, childSignal), input.run_in_background !== false, signal);
|
|
25
|
+
},
|
|
22
26
|
});
|
|
23
27
|
}
|
|
@@ -11,6 +11,15 @@ function ownedProjects(stateDir) {
|
|
|
11
11
|
}
|
|
12
12
|
return projects;
|
|
13
13
|
}
|
|
14
|
+
/** File checkpoints, kept beside the records so a Revive can still rewind files. */
|
|
15
|
+
function ownedFileHistory(stateDir) {
|
|
16
|
+
const history = join(realpathSync(stateDir), "claude-file-history");
|
|
17
|
+
if (!existsSync(history))
|
|
18
|
+
mkdirSync(history, { mode: 0o700 });
|
|
19
|
+
if (!lstatSync(history).isDirectory() || realpathSync(history) !== history)
|
|
20
|
+
throw new Error("Unsafe Claude file checkpoint directory");
|
|
21
|
+
return history;
|
|
22
|
+
}
|
|
14
23
|
/** Claude's Scope key, including the CLI's suffix for paths longer than 200 characters. */
|
|
15
24
|
export function projectKey(scope) {
|
|
16
25
|
const key = scope.replace(/[^a-zA-Z0-9]/g, "-");
|
|
@@ -34,6 +43,18 @@ export function relocateClaudeState(stateDir, from, to) {
|
|
|
34
43
|
throw new Error(`A Claude record for ${to} already exists`);
|
|
35
44
|
renameSync(source, destination);
|
|
36
45
|
}
|
|
46
|
+
/** Copy the record `from.resume` and its sidecars for a Fork. File checkpoints are not copied: they name `from.scope` paths. */
|
|
47
|
+
export function forkClaudeState(from, to) {
|
|
48
|
+
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(from.resume))
|
|
49
|
+
throw new Error("Invalid Claude resume ID");
|
|
50
|
+
const source = join(ownedProjects(from.stateDir), projectKey(from.scope));
|
|
51
|
+
const destination = join(ownedProjects(to.stateDir), projectKey(to.scope));
|
|
52
|
+
mkdirSync(destination, { recursive: true, mode: 0o700 });
|
|
53
|
+
copyRecord(join(source, `${from.resume}.jsonl`), join(destination, `${from.resume}.jsonl`));
|
|
54
|
+
if (existsSync(join(source, from.resume)))
|
|
55
|
+
copyRecord(join(source, from.resume), join(destination, from.resume));
|
|
56
|
+
return from.resume;
|
|
57
|
+
}
|
|
37
58
|
/** Copy only regular, unlinked records; never follow a link into other host state. */
|
|
38
59
|
function copyRecord(source, destination, from = source) {
|
|
39
60
|
const before = lstatSync(from);
|
|
@@ -174,6 +195,7 @@ export function prepareClaudeState(stateDir, inherited = process.env, scope = pr
|
|
|
174
195
|
const cleanup = () => rmSync(config, { recursive: true, force: true });
|
|
175
196
|
try {
|
|
176
197
|
symlinkSync(projects, join(config, "projects"), "dir");
|
|
198
|
+
symlinkSync(ownedFileHistory(stateDir), join(config, "file-history"), "dir");
|
|
177
199
|
for (const name of [".config.json", ".claude.json"]) {
|
|
178
200
|
const from = name === ".claude.json" && !existsSync(join(source, name)) ? join(home, name) : join(source, name);
|
|
179
201
|
if (existsSync(from) && statSync(from).isFile())
|