@nathanstephenson/flow 0.1.10-beta.1 → 0.1.10-beta.10
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 +52 -22
- package/build/backend-worker-chunks/{chunk-CYE5L6Z5.mjs → chunk-3KDHJA5P.mjs} +41 -10
- package/build/backend-worker-chunks/{chunk-UQDH2COY.mjs → chunk-K774KOGL.mjs} +2 -7
- package/build/backend-worker-chunks/chunk-LAEUXDNH.mjs +130 -0
- package/build/backend-worker-chunks/{chunk-MLOUI3ZM.mjs → chunk-NZZME2I3.mjs} +6 -1
- package/build/backend-worker-chunks/claude-JG2FXYBQ.mjs +35859 -0
- package/build/backend-worker-chunks/{pi-UKRC4DDM.mjs → pi-KJSP23AO.mjs} +2091 -92
- package/build/backend-worker.mjs +69 -122
- package/build/workflow-runtime.cjs +12 -12
- package/dist/backend/claude/background-calls.js +7 -3
- package/dist/backend/claude/import.js +415 -0
- package/dist/backend/claude/index.js +188 -25
- package/dist/backend/claude/subagents.js +41 -9
- package/dist/backend/claude/todo-list.js +114 -0
- package/dist/backend/claude/workflow-parent.js +1 -1
- package/dist/backend/diff-excerpt-instructions.js +8 -0
- package/dist/backend/fake/index.js +54 -6
- package/dist/backend/mcp.js +4 -1
- package/dist/backend/pi/agent-permissions.js +1 -1
- package/dist/backend/pi/cache-warming.js +8 -0
- package/dist/backend/pi/canonical-json.js +120 -0
- package/dist/backend/pi/compaction-model.js +3 -2
- package/dist/backend/pi/host-auth.js +258 -0
- package/dist/backend/pi/import.js +269 -0
- package/dist/backend/pi/index.js +118 -20
- package/dist/backend/pi/model-auth.js +159 -0
- package/dist/backend/pi/model-catalog.js +120 -0
- package/dist/backend/pi/model-config.js +5 -0
- package/dist/backend/pi/model-selection.js +32 -0
- package/dist/backend/pi/plan-limits.js +41 -0
- package/dist/backend/pi/state.js +19 -1
- package/dist/backend/pi/subagents.js +7 -3
- package/dist/backend/pi/todo-list.js +23 -0
- package/dist/backend/pi/work.js +9 -1
- package/dist/backend/pi/workflow-parent.js +1 -1
- package/dist/backend/pi/workflow-subagent.js +4 -3
- package/dist/backend/plan-limits.js +17 -0
- package/dist/backend/session-tools.js +1 -1
- package/dist/backend/worker/claude-state.js +48 -0
- package/dist/backend/worker/entry.js +42 -8
- package/dist/backend/worker/index.js +131 -15
- package/dist/backend/worker/launcher.js +11 -4
- package/dist/backend/worker/protocol.js +2 -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/application.js +48 -42
- package/dist/cli/bootstrap.js +2 -2
- package/dist/cli/host-control.js +1 -1
- package/dist/cli/install-guard.js +2 -2
- package/dist/cli/main.js +4 -4
- package/dist/cli/systemd-update.js +3 -3
- package/dist/cli/update.js +6 -6
- package/dist/cli/web-update.js +6 -6
- package/dist/client/connection.js +46 -0
- package/dist/client/context-usage.js +3 -4
- package/dist/client/diff.js +40 -0
- package/dist/client/enquiry.js +0 -6
- package/dist/client/markdown.js +3 -2
- package/dist/client/model-choices.js +1 -1
- package/dist/client/permission.js +1 -2
- package/dist/client/project-name.js +3 -1
- package/dist/client/reduce.js +77 -3
- package/dist/client/relative-time.js +1 -1
- package/dist/client/scope-kind.js +6 -3
- package/dist/client/search.js +1 -1
- package/dist/client/status.js +1 -1
- package/dist/client/subagent-tree.js +49 -0
- package/dist/client/tool-chains.js +1 -1
- package/dist/client/tool-summary.js +28 -18
- package/dist/daemon/changes.js +128 -0
- package/dist/daemon/commit.js +84 -0
- package/dist/daemon/config-store.js +8 -3
- package/dist/daemon/config.js +105 -4
- package/dist/daemon/diff-excerpts.js +52 -0
- package/dist/daemon/git-state.js +197 -0
- package/dist/daemon/git.js +53 -10
- package/dist/daemon/github-image.js +18 -0
- package/dist/daemon/github.js +54 -0
- package/dist/daemon/host-control-routes.js +1 -1
- package/dist/daemon/host.js +940 -119
- package/dist/daemon/http.js +4 -1
- package/dist/daemon/log.js +3 -0
- package/dist/daemon/mcp-auth.js +1 -1
- package/dist/daemon/models.js +2 -2
- package/dist/daemon/pi-model-cache.js +44 -0
- package/dist/daemon/pull-request.js +223 -138
- package/dist/daemon/push.js +43 -0
- package/dist/daemon/repository.js +123 -0
- package/dist/daemon/runtime.js +103 -22
- package/dist/daemon/secret-store.js +1 -1
- package/dist/daemon/server.js +111 -14
- package/dist/daemon/skills.js +24 -0
- package/dist/daemon/spend-ledger.js +118 -0
- package/dist/daemon/stack-metadata.js +12 -5
- package/dist/daemon/stack.js +162 -657
- package/dist/daemon/store.js +2 -0
- package/dist/daemon/summariser.js +30 -12
- package/dist/daemon/tour.js +56 -0
- package/dist/daemon/whisper.js +144 -0
- package/dist/daemon/workflow-authoring-scope-checks.js +1 -1
- package/dist/daemon/workflow-authoring-scope.js +1 -1
- package/dist/daemon/workflow-builder-files.js +2 -2
- package/dist/daemon/workflow-builder-guidance.js +1 -1
- package/dist/daemon/workflow-builder-routes.js +2 -2
- package/dist/daemon/workflow-builder.js +44 -17
- package/dist/daemon/workflow-environment.js +193 -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 +12 -9
- package/dist/daemon/workflow-execution-values.js +128 -0
- package/dist/daemon/workflow-executions.js +400 -311
- package/dist/daemon/workflow-mcp-authoring-routes.js +2 -2
- package/dist/daemon/workflow-mcp-authoring.js +4 -4
- package/dist/daemon/workflow-mcp.js +1 -1
- package/dist/daemon/workflow-routes.js +60 -2
- package/dist/daemon/workflow-schedule-driver.js +251 -0
- package/dist/daemon/workflow-schedule-routes.js +137 -0
- package/dist/daemon/workflow-schedules.js +342 -0
- package/dist/isolation/filesystem.js +6 -2
- package/dist/isolation/sandbox.js +61 -18
- package/dist/isolation/shared-sandbox.js +3 -3
- package/dist/isolation/toolchain-assets.js +1 -1
- package/dist/protocol/events.js +3 -0
- package/dist/protocol/plan-limits.js +1 -0
- package/dist/protocol/settings.js +1 -0
- package/dist/protocol/spend.js +2 -0
- package/dist/protocol/stack.js +12 -39
- package/dist/protocol/workflow-schedules.js +1 -0
- package/dist/workflows/calls.js +53 -0
- package/dist/workflows/errors.js +2 -0
- package/dist/workflows/executors.js +6 -5
- package/dist/workflows/graph.js +83 -9
- package/dist/workflows/invocations.js +23 -0
- package/dist/workflows/mcp.js +1 -1
- package/dist/workflows/owner.js +45 -0
- package/dist/workflows/records.js +127 -11
- package/dist/workflows/recovery.js +38 -2
- package/dist/workflows/runtime-settings.js +16 -16
- package/dist/workflows/runtime.js +2 -2
- package/dist/workflows/schedule-errors.js +2 -0
- package/dist/workflows/schedule-store.js +385 -0
- package/dist/workflows/scheduler.js +367 -96
- package/dist/workflows/schedules.js +130 -0
- package/dist/workflows/schema.js +3 -1
- package/dist/workflows/store.js +126 -13
- package/package.json +10 -6
- package/web/dist/assets/index-C76t-z4w.css +2 -0
- package/web/dist/assets/{index-DRfeO6GJ.js → index-WPfbYVQ4.js} +39 -23
- package/web/dist/assets/{switch-DIogWclb.js → select-C5Ly2OpB.js} +1 -1
- package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-BF-yqpeQ.js} +1 -1
- package/web/dist/assets/{settings-secrets-BIO_hXZ1.js → settings-secrets-WLarr2QP.js} +1 -1
- package/web/dist/assets/settings-workflows-DdcdRWFD.js +23 -0
- package/web/dist/assets/workflow-api-GjAmHc22.js +6 -0
- package/web/dist/assets/workflows-BhY3Uibo.js +149 -0
- package/web/dist/assets/workflows-pane-DElCcEpN.js +1 -0
- package/web/dist/index.html +6 -5
- package/build/backend-worker-chunks/claude-UXZDJKZQ.mjs +0 -30816
- package/dist/daemon/publish.js +0 -289
- package/dist/tui/app.js +0 -612
- package/dist/tui/keys.js +0 -90
- package/dist/tui/render.js +0 -411
- 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-api-BfExddae.js +0 -6
- 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
- /package/dist/protocol/{publish.js → imports.js} +0 -0
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
import { readdirSync, readFileSync } from "node:fs";
|
|
2
|
+
import { readdir, readFile } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { join, resolve } from "node:path";
|
|
5
|
+
import { writePiSession } from "./state.js";
|
|
6
|
+
/**
|
|
7
|
+
* Reading standalone pi sessions, for Import (ADR 0047).
|
|
8
|
+
*
|
|
9
|
+
* pi writes one JSONL file per session under `<agent dir>/sessions/<scope key>/`: a `session` header,
|
|
10
|
+
* then entries that form a tree through `parentId`. The tree is pi's own record of branching, so the
|
|
11
|
+
* transcript is the active branch only, the path from the last entry back to the root, which is the
|
|
12
|
+
* one a Revive continues. The file is read leniently, and never through pi's SessionManager, which
|
|
13
|
+
* creates directories and can rewrite what it opens.
|
|
14
|
+
*/
|
|
15
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
16
|
+
/** The longest title taken from a first prompt, matching the length a rail row can show. */
|
|
17
|
+
const TITLE_LENGTH = 80;
|
|
18
|
+
/** The longest notice taken from shell output or an extension's message. */
|
|
19
|
+
const NOTICE_LENGTH = 500;
|
|
20
|
+
/** Where pi keeps the sessions it started in `scope`, resolved the way pi resolves it. */
|
|
21
|
+
export function piSessionsDir(env, scope) {
|
|
22
|
+
const agentDir = resolve(env.PI_CODING_AGENT_DIR || join(env.HOME ?? homedir(), ".pi/agent"));
|
|
23
|
+
return join(agentDir, "sessions", `--${resolve(scope).replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`);
|
|
24
|
+
}
|
|
25
|
+
/** Every pi session recorded in `scope` with a prompt in it, newest first. Only prompts and titles are parsed. */
|
|
26
|
+
export async function listPiConversations(env, scope) {
|
|
27
|
+
const dir = piSessionsDir(env, scope);
|
|
28
|
+
let names;
|
|
29
|
+
try {
|
|
30
|
+
names = await readdir(dir);
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return [];
|
|
34
|
+
}
|
|
35
|
+
const conversations = [];
|
|
36
|
+
for (const name of names) {
|
|
37
|
+
if (!name.endsWith(".jsonl"))
|
|
38
|
+
continue;
|
|
39
|
+
let raw;
|
|
40
|
+
try {
|
|
41
|
+
raw = await readFile(join(dir, name), "utf8");
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
const header = headerOf(raw, scope);
|
|
47
|
+
if (!header)
|
|
48
|
+
continue;
|
|
49
|
+
const skimmed = translate(parse(raw, worthListing), header.startedAt, () => undefined);
|
|
50
|
+
const prompts = skimmed.events.filter(({ event }) => event.type === "turn_started").length;
|
|
51
|
+
if (prompts === 0)
|
|
52
|
+
continue;
|
|
53
|
+
conversations.push({
|
|
54
|
+
id: header.id,
|
|
55
|
+
title: skimmed.title,
|
|
56
|
+
startedAt: skimmed.startedAt,
|
|
57
|
+
updatedAt: lastTimestamp(raw) ?? skimmed.updatedAt,
|
|
58
|
+
prompts,
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
return conversations.sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
|
|
62
|
+
}
|
|
63
|
+
/** One pi session's active branch, translated into Agent Events. Throws when there is no such session. */
|
|
64
|
+
export function readPiConversation(env, scope, conversationId, storeImage) {
|
|
65
|
+
const { raw, startedAt } = findSession(env, scope, conversationId);
|
|
66
|
+
return translate(activeBranch(parse(raw)), startedAt, storeImage);
|
|
67
|
+
}
|
|
68
|
+
/** Copy one pi session file into `stateDir`, bound to `scope`. Returns `stateDir`, the pi resume token. */
|
|
69
|
+
export function copyPiConversation(env, stateDir, scope, conversationId) {
|
|
70
|
+
const { name, raw } = findSession(env, scope, conversationId);
|
|
71
|
+
writePiSession(join(stateDir, name), raw, scope);
|
|
72
|
+
return stateDir;
|
|
73
|
+
}
|
|
74
|
+
/** The file holding session `id`. The id is checked first because it arrives over the wire. */
|
|
75
|
+
function findSession(env, scope, id) {
|
|
76
|
+
if (!UUID.test(id))
|
|
77
|
+
throw new Error("Invalid pi session id");
|
|
78
|
+
const dir = piSessionsDir(env, scope);
|
|
79
|
+
let names;
|
|
80
|
+
try {
|
|
81
|
+
names = readdirSync(dir).filter((name) => name.endsWith(".jsonl"));
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
throw new Error("pi session not found");
|
|
85
|
+
}
|
|
86
|
+
names.sort((left, right) => Number(right.includes(id)) - Number(left.includes(id)));
|
|
87
|
+
for (const name of names) {
|
|
88
|
+
let raw;
|
|
89
|
+
try {
|
|
90
|
+
raw = readFileSync(join(dir, name), "utf8");
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
const header = headerOf(raw, scope);
|
|
96
|
+
if (header?.id === id)
|
|
97
|
+
return { name, raw, startedAt: header.startedAt };
|
|
98
|
+
}
|
|
99
|
+
throw new Error("pi session not found");
|
|
100
|
+
}
|
|
101
|
+
function headerOf(raw, scope) {
|
|
102
|
+
const end = raw.indexOf("\n");
|
|
103
|
+
const [header] = parse(end < 0 ? raw : raw.slice(0, end));
|
|
104
|
+
if (header?.type !== "session" || typeof header.id !== "string" || !UUID.test(header.id))
|
|
105
|
+
return undefined;
|
|
106
|
+
if (typeof header.cwd !== "string" || resolve(header.cwd) !== resolve(scope))
|
|
107
|
+
return undefined;
|
|
108
|
+
return { id: header.id, startedAt: header.timestamp ?? new Date().toISOString() };
|
|
109
|
+
}
|
|
110
|
+
/** pi writes compact JSON, so a human prompt and a session name are plain substrings. */
|
|
111
|
+
function worthListing(line) {
|
|
112
|
+
return line.includes('"role":"user"') || line.includes('"type":"session_info"');
|
|
113
|
+
}
|
|
114
|
+
function lastTimestamp(raw) {
|
|
115
|
+
const stamps = [...raw.slice(-65_536).matchAll(/"timestamp":"([^"]+)"/g)];
|
|
116
|
+
return stamps.at(-1)?.[1];
|
|
117
|
+
}
|
|
118
|
+
function parse(raw, keep = () => true) {
|
|
119
|
+
const entries = [];
|
|
120
|
+
for (const line of raw.split("\n")) {
|
|
121
|
+
if (!line.trim() || !keep(line))
|
|
122
|
+
continue;
|
|
123
|
+
try {
|
|
124
|
+
const entry = JSON.parse(line);
|
|
125
|
+
if (entry && typeof entry === "object")
|
|
126
|
+
entries.push(entry);
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return entries;
|
|
133
|
+
}
|
|
134
|
+
/** The path from the last entry back to the root, in order. A cycle in a damaged file ends the walk. */
|
|
135
|
+
function activeBranch(entries) {
|
|
136
|
+
const byId = new Map(entries.flatMap((entry) => entry.type !== "session" && entry.id ? [[entry.id, entry]] : []));
|
|
137
|
+
const branch = [];
|
|
138
|
+
let entry = entries.findLast((candidate) => candidate.type !== "session" && candidate.id);
|
|
139
|
+
while (entry) {
|
|
140
|
+
branch.push(entry);
|
|
141
|
+
byId.delete(entry.id);
|
|
142
|
+
entry = entry.parentId ? byId.get(entry.parentId) : undefined;
|
|
143
|
+
}
|
|
144
|
+
return branch.reverse();
|
|
145
|
+
}
|
|
146
|
+
function blocksOf(content) {
|
|
147
|
+
if (typeof content === "string")
|
|
148
|
+
return [{ type: "text", text: content }];
|
|
149
|
+
return Array.isArray(content) ? content.filter((block) => !!block && typeof block === "object") : [];
|
|
150
|
+
}
|
|
151
|
+
function textOf(content) {
|
|
152
|
+
return blocksOf(content).flatMap((block) => block.type === "text" && block.text ? [block.text] : []).join("\n");
|
|
153
|
+
}
|
|
154
|
+
function translate(entries, fallbackAt, storeImage) {
|
|
155
|
+
const events = [];
|
|
156
|
+
const openCalls = new Set();
|
|
157
|
+
let turnId;
|
|
158
|
+
let at = fallbackAt;
|
|
159
|
+
let startedAt;
|
|
160
|
+
let name;
|
|
161
|
+
let firstPrompt;
|
|
162
|
+
const push = (event) => events.push({ at, event });
|
|
163
|
+
const endTurn = (reason = "complete") => {
|
|
164
|
+
if (turnId === undefined)
|
|
165
|
+
return;
|
|
166
|
+
for (const callId of openCalls) {
|
|
167
|
+
push({ type: "tool_ended", callId, result: "No result was recorded.", isError: true });
|
|
168
|
+
}
|
|
169
|
+
openCalls.clear();
|
|
170
|
+
push({ type: "turn_ended", turnId, reason });
|
|
171
|
+
turnId = undefined;
|
|
172
|
+
};
|
|
173
|
+
const beginTurn = (id) => {
|
|
174
|
+
endTurn();
|
|
175
|
+
turnId = id;
|
|
176
|
+
push({ type: "turn_started", turnId: id });
|
|
177
|
+
};
|
|
178
|
+
for (const entry of entries) {
|
|
179
|
+
if (entry.type === "session_info") {
|
|
180
|
+
name = entry.name?.trim() || undefined;
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
if (!entry.id)
|
|
184
|
+
continue;
|
|
185
|
+
if (entry.timestamp) {
|
|
186
|
+
at = entry.timestamp;
|
|
187
|
+
startedAt ??= entry.timestamp;
|
|
188
|
+
}
|
|
189
|
+
const id = entry.id;
|
|
190
|
+
if (entry.type === "compaction") {
|
|
191
|
+
push({ type: "compacted", trigger: "auto", before: entry.tokensBefore ?? 0 });
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
if (entry.type === "custom_message") {
|
|
195
|
+
const text = textOf(entry.content).trim();
|
|
196
|
+
if (entry.display && text)
|
|
197
|
+
push({ type: "notice", level: "info", text: clip(text) });
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
const message = entry.message;
|
|
201
|
+
if (entry.type !== "message" || !message)
|
|
202
|
+
continue;
|
|
203
|
+
const blocks = blocksOf(message.content);
|
|
204
|
+
if (message.role === "user") {
|
|
205
|
+
const text = textOf(message.content);
|
|
206
|
+
const attachments = blocks.flatMap((block) => block.type === "image" && block.mimeType && block.data
|
|
207
|
+
? [storeImage(block.mimeType, block.data)].filter((stored) => stored !== undefined)
|
|
208
|
+
: []);
|
|
209
|
+
if (!text.trim() && attachments.length === 0)
|
|
210
|
+
continue;
|
|
211
|
+
firstPrompt ??= text;
|
|
212
|
+
beginTurn(id);
|
|
213
|
+
push({ type: "user_message", id, text, ...(attachments.length ? { attachments } : {}) });
|
|
214
|
+
}
|
|
215
|
+
else if (message.role === "assistant") {
|
|
216
|
+
if (turnId === undefined)
|
|
217
|
+
beginTurn(id);
|
|
218
|
+
for (const [index, block] of blocks.entries()) {
|
|
219
|
+
const blockId = `${id}:${index}`;
|
|
220
|
+
if (block.type === "text" && block.text?.trim()) {
|
|
221
|
+
push({ type: "message", id: blockId, text: block.text, final: true });
|
|
222
|
+
}
|
|
223
|
+
else if (block.type === "thinking" && !block.redacted && block.thinking?.trim()) {
|
|
224
|
+
push({ type: "thinking", id: blockId, text: block.thinking, final: true });
|
|
225
|
+
}
|
|
226
|
+
else if (block.type === "toolCall" && block.id && block.name) {
|
|
227
|
+
openCalls.add(block.id);
|
|
228
|
+
push({ type: "tool_started", callId: block.id, name: block.name, input: block.arguments ?? {} });
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
if (message.stopReason === "error" && message.errorMessage)
|
|
232
|
+
push({ type: "notice", level: "error", text: message.errorMessage });
|
|
233
|
+
if (message.stopReason === "aborted" || message.stopReason === "error")
|
|
234
|
+
endTurn(message.stopReason);
|
|
235
|
+
else if (message.stopReason === "stop" || message.stopReason === "length")
|
|
236
|
+
endTurn();
|
|
237
|
+
}
|
|
238
|
+
else if (message.role === "toolResult") {
|
|
239
|
+
if (!message.toolCallId || !openCalls.delete(message.toolCallId))
|
|
240
|
+
continue;
|
|
241
|
+
push({
|
|
242
|
+
type: "tool_ended",
|
|
243
|
+
callId: message.toolCallId,
|
|
244
|
+
result: { content: message.content, details: message.details },
|
|
245
|
+
isError: message.isError === true,
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
else if (message.role === "bashExecution" && message.command) {
|
|
249
|
+
push({ type: "notice", level: "info", text: clip(`! ${message.command}\n${message.output ?? ""}`.trim()) });
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
endTurn();
|
|
253
|
+
return {
|
|
254
|
+
title: name ?? titleFrom(firstPrompt) ?? "Imported pi session",
|
|
255
|
+
named: name !== undefined,
|
|
256
|
+
startedAt: startedAt ?? fallbackAt,
|
|
257
|
+
updatedAt: at,
|
|
258
|
+
events,
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
function clip(text) {
|
|
262
|
+
return text.length <= NOTICE_LENGTH ? text : `${text.slice(0, NOTICE_LENGTH - 1)}…`;
|
|
263
|
+
}
|
|
264
|
+
function titleFrom(prompt) {
|
|
265
|
+
const line = prompt?.split("\n").map((part) => part.trim()).find(Boolean);
|
|
266
|
+
if (!line)
|
|
267
|
+
return undefined;
|
|
268
|
+
return line.length <= TITLE_LENGTH ? line : `${line.slice(0, TITLE_LENGTH - 1)}…`;
|
|
269
|
+
}
|
package/dist/backend/pi/index.js
CHANGED
|
@@ -3,19 +3,30 @@ 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";
|
|
12
|
+
import { findPiModel, piModelUnavailable } from "./model-selection.js";
|
|
9
13
|
import { clampEffort } from "../effort.js";
|
|
10
14
|
import { piAutoCompaction } from "./auto-compaction.js";
|
|
15
|
+
import { createWorkerPiModelRuntime } from "./model-auth.js";
|
|
16
|
+
import { streamingCacheWarming } from "./cache-warming.js";
|
|
11
17
|
import { compactionExtensionError, compactionModelExtension } from "./compaction-model.js";
|
|
12
18
|
import { ASK_TOOL, PiEnquiries } from "./enquiries.js";
|
|
19
|
+
import { TODO_TOOL, piTodoTool } from "./todo-list.js";
|
|
13
20
|
import { backgroundTools } from "./background-calls.js";
|
|
14
21
|
import { SUBAGENT_TOOL, subagentTool } from "./subagents.js";
|
|
15
22
|
import { PiAgentPermissions } from "./agent-permissions.js";
|
|
23
|
+
import { fetchAnthropicPlanLimits, fetchCodexPlanLimits } from "./plan-limits.js";
|
|
16
24
|
import { PiWork, callIdFor, resultText, textResult } from "./work.js";
|
|
25
|
+
import { DIFF_EXCERPT_INSTRUCTIONS } from "../diff-excerpt-instructions.js";
|
|
17
26
|
export class PiSession {
|
|
18
27
|
capabilities;
|
|
28
|
+
spend;
|
|
29
|
+
counted;
|
|
19
30
|
answerEnquiry;
|
|
20
31
|
enquiries;
|
|
21
32
|
work;
|
|
@@ -31,7 +42,7 @@ export class PiSession {
|
|
|
31
42
|
this.unsubscribe();
|
|
32
43
|
current.dispose();
|
|
33
44
|
this.session = await this.recreate(current);
|
|
34
|
-
this.unsubscribe = this.
|
|
45
|
+
this.unsubscribe = this.bindSession();
|
|
35
46
|
}
|
|
36
47
|
standingAuthorisations;
|
|
37
48
|
agentPermissions;
|
|
@@ -60,6 +71,8 @@ export class PiSession {
|
|
|
60
71
|
effort;
|
|
61
72
|
messageSeq = 0;
|
|
62
73
|
currentMessageId;
|
|
74
|
+
/** Host user message ids sent but not yet seen as pi user messages, oldest first. */
|
|
75
|
+
unmappedMessageIds = [];
|
|
63
76
|
constructor(session, emit, sessionDir, support = {}) {
|
|
64
77
|
this.workflowBuilder = support.workflowBuilder ?? false;
|
|
65
78
|
this.mcp = support.mcp;
|
|
@@ -69,6 +82,8 @@ export class PiSession {
|
|
|
69
82
|
if (support.permissionProducer)
|
|
70
83
|
this.permissionProducer = support.permissionProducer;
|
|
71
84
|
this.session = session;
|
|
85
|
+
this.spend = support.priorSpend;
|
|
86
|
+
this.counted = statsOf(session);
|
|
72
87
|
this.applyAutoCompaction = support.autoCompaction;
|
|
73
88
|
this.workflowAutoCompaction = support.workflowAutoCompaction;
|
|
74
89
|
this.workflowCompactionModelId = support.workflowCompactionModelId;
|
|
@@ -83,7 +98,17 @@ export class PiSession {
|
|
|
83
98
|
if (enquiries)
|
|
84
99
|
this.answerEnquiry = async (askId, answers) => enquiries.answer(askId, answers);
|
|
85
100
|
this.capabilities = capabilitiesOf(session, support.enquiries !== undefined, support.subagents ?? false, !this.workflowBuilder);
|
|
86
|
-
this.unsubscribe =
|
|
101
|
+
this.unsubscribe = this.bindSession();
|
|
102
|
+
}
|
|
103
|
+
bindSession() {
|
|
104
|
+
const stream = this.session.agent?.streamFunction;
|
|
105
|
+
if (stream)
|
|
106
|
+
this.session.agent.streamFunction = (...args) => {
|
|
107
|
+
if (this.disposed)
|
|
108
|
+
throw new Error("Backend Session stopped");
|
|
109
|
+
return stream(...args);
|
|
110
|
+
};
|
|
111
|
+
return this.session.subscribe((event) => this.translate(event));
|
|
87
112
|
}
|
|
88
113
|
startWorkflowSubagent(options) {
|
|
89
114
|
if (this.disposed)
|
|
@@ -101,7 +126,11 @@ export class PiSession {
|
|
|
101
126
|
// pi persists through its own SessionManager; the directory we gave it is the resume handle.
|
|
102
127
|
return this.sessionDir;
|
|
103
128
|
}
|
|
104
|
-
async prompt(text, attachments) {
|
|
129
|
+
async prompt(text, attachments, messageId) {
|
|
130
|
+
if (this.disposed)
|
|
131
|
+
return;
|
|
132
|
+
if (messageId && this.sessionDir)
|
|
133
|
+
this.unmappedMessageIds.push(messageId);
|
|
105
134
|
this.turnId = `turn-${++this.messageSeq}`;
|
|
106
135
|
this.emit({ type: "turn_started", turnId: this.turnId });
|
|
107
136
|
await this.session.prompt(text, {
|
|
@@ -121,11 +150,9 @@ export class PiSession {
|
|
|
121
150
|
async setPermissionMode(mode) { this.agentPermissions?.setMode(mode); }
|
|
122
151
|
async setModel(modelId) {
|
|
123
152
|
const available = await this.session.modelRuntime.getAvailable();
|
|
124
|
-
const
|
|
125
|
-
const legacy = available.filter((candidate) => candidate.id === modelId);
|
|
126
|
-
const model = qualified ?? (legacy.length === 1 ? legacy[0] : undefined);
|
|
153
|
+
const model = findPiModel(available, modelId, true);
|
|
127
154
|
if (!model)
|
|
128
|
-
throw new Error(
|
|
155
|
+
throw new Error(piModelUnavailable(modelId));
|
|
129
156
|
await this.session.setModel(model);
|
|
130
157
|
this.applyAutoCompaction?.(this.session.model);
|
|
131
158
|
// Which levels are on offer follows the model, and pi may have clamped its own thinking level
|
|
@@ -206,6 +233,14 @@ export class PiSession {
|
|
|
206
233
|
})),
|
|
207
234
|
];
|
|
208
235
|
}
|
|
236
|
+
async planLimits() {
|
|
237
|
+
const read = async (provider, fetchLimits) => {
|
|
238
|
+
const token = (await this.session.modelRuntime.getAuth(provider).catch(() => undefined))?.auth.apiKey;
|
|
239
|
+
return token ? await fetchLimits(token).catch(() => undefined) : undefined;
|
|
240
|
+
};
|
|
241
|
+
const limits = await Promise.all([read("anthropic", fetchAnthropicPlanLimits), read("openai-codex", fetchCodexPlanLimits)]);
|
|
242
|
+
return limits.filter((limit) => limit !== undefined);
|
|
243
|
+
}
|
|
209
244
|
applyEffort(wanted) {
|
|
210
245
|
const level = clampEffort(wanted, availableEffort(this.session));
|
|
211
246
|
// Nothing to set on a model with no effort control. The request stays on file, so switching
|
|
@@ -293,6 +328,15 @@ export class PiSession {
|
|
|
293
328
|
this.emit({ type: "turn_ended", turnId, reason });
|
|
294
329
|
this.scheduleCompletions();
|
|
295
330
|
}
|
|
331
|
+
/** pi appends the entry just after `message_end` reaches listeners, so look it up after that. */
|
|
332
|
+
mapUserMessage(messageId, message) {
|
|
333
|
+
queueMicrotask(() => {
|
|
334
|
+
const entry = this.session.sessionManager.getBranch().findLast((candidate) => candidate.type === "message" && candidate.message === message);
|
|
335
|
+
if (!entry || !this.sessionDir)
|
|
336
|
+
return;
|
|
337
|
+
writeFileSync(join(this.sessionDir, USER_MESSAGE_MAP), JSON.stringify({ ...readUserMessageMap(this.sessionDir), [messageId]: entry.id }), { mode: 0o600 });
|
|
338
|
+
});
|
|
339
|
+
}
|
|
296
340
|
translate(event) {
|
|
297
341
|
switch (event.type) {
|
|
298
342
|
case "agent_start":
|
|
@@ -308,6 +352,8 @@ export class PiSession {
|
|
|
308
352
|
case "message_end":
|
|
309
353
|
this.emitMessage(event.message, true);
|
|
310
354
|
this.currentMessageId = undefined;
|
|
355
|
+
if (event.message.role === "user" && this.unmappedMessageIds.length)
|
|
356
|
+
this.mapUserMessage(this.unmappedMessageIds.shift(), event.message);
|
|
311
357
|
return;
|
|
312
358
|
case "tool_execution_start":
|
|
313
359
|
this.emit({ type: "tool_started", callId: event.toolCallId, name: event.toolName, input: event.args });
|
|
@@ -335,7 +381,7 @@ export class PiSession {
|
|
|
335
381
|
return;
|
|
336
382
|
}
|
|
337
383
|
case "agent_settled":
|
|
338
|
-
this.finishTurn(this.aborting ? "aborted" : this.turnReason);
|
|
384
|
+
this.finishTurn(event.aborted || this.aborting ? "aborted" : this.turnReason);
|
|
339
385
|
return;
|
|
340
386
|
case "auto_retry_start":
|
|
341
387
|
this.emit({
|
|
@@ -404,11 +450,26 @@ export class PiSession {
|
|
|
404
450
|
this.emit({ type: "thinking", id: `${id}-thinking`, text: thinking, final });
|
|
405
451
|
}
|
|
406
452
|
reportContextUsage() {
|
|
453
|
+
this.countSpend();
|
|
407
454
|
const usage = this.session.getContextUsage();
|
|
408
455
|
if (usage && typeof usage.tokens === "number") {
|
|
409
|
-
this.emit({ type: "context_usage", used: usage.tokens, window: usage.contextWindow });
|
|
456
|
+
this.emit({ type: "context_usage", used: usage.tokens, window: usage.contextWindow, ...(this.spend ? { spend: this.spend } : {}) });
|
|
410
457
|
}
|
|
411
458
|
}
|
|
459
|
+
countSpend() {
|
|
460
|
+
const now = statsOf(this.session);
|
|
461
|
+
const added = { tokens: now.tokens - this.counted.tokens, cached: now.cached - this.counted.cached, costUSD: now.costUSD - this.counted.costUSD };
|
|
462
|
+
this.counted = now;
|
|
463
|
+
if (added.tokens <= 0 && added.costUSD <= 0)
|
|
464
|
+
return;
|
|
465
|
+
const id = this.session.model ? describeModel(this.session.model).id : "unknown";
|
|
466
|
+
const spend = this.spend ?? { tokens: 0, cached: 0, costUSD: 0, models: [] };
|
|
467
|
+
const model = spend.models.find((item) => item.id === id) ?? { id, tokens: 0, cached: 0, costUSD: 0 };
|
|
468
|
+
this.spend = {
|
|
469
|
+
tokens: spend.tokens + added.tokens, cached: spend.cached + added.cached, costUSD: spend.costUSD + added.costUSD,
|
|
470
|
+
models: [...spend.models.filter((item) => item.id !== id), { id, tokens: model.tokens + added.tokens, cached: model.cached + added.cached, costUSD: model.costUSD + added.costUSD }],
|
|
471
|
+
};
|
|
472
|
+
}
|
|
412
473
|
}
|
|
413
474
|
export class PiBackend {
|
|
414
475
|
name = "pi";
|
|
@@ -418,10 +479,16 @@ export class PiBackend {
|
|
|
418
479
|
}
|
|
419
480
|
async create(options) {
|
|
420
481
|
const agentDir = getAgentDir();
|
|
482
|
+
const modelRuntime = options.piAuth
|
|
483
|
+
? await createWorkerPiModelRuntime(options.piAuth, join(agentDir, "models.json"), options.signal, {
|
|
484
|
+
...(options.stateDir ? { modelsStorePath: join(options.stateDir, 'models-store.json') } : {}),
|
|
485
|
+
discovery: options.refreshModels ? 'refresh' : 'automatic',
|
|
486
|
+
})
|
|
487
|
+
: undefined;
|
|
421
488
|
// Extensions are not loaded: they expect pi's own UI surface, and a background session that
|
|
422
489
|
// registers UI hooks has nowhere to render them.
|
|
423
490
|
const builder = options.workflowBuilder;
|
|
424
|
-
const settingsManager = builder ? SettingsManager.inMemory() : SettingsManager.create(options.scope, agentDir);
|
|
491
|
+
const settingsManager = builder ? SettingsManager.inMemory({ cacheWarming: "streaming" }) : SettingsManager.create(options.scope, agentDir);
|
|
425
492
|
const agentPermissions = builder || options.tools === "none" ? undefined : new PiAgentPermissions(options.permissionMode ?? "always", options.standingAuthorisations ?? [], options.emit);
|
|
426
493
|
const resourceLoader = new DefaultResourceLoader({
|
|
427
494
|
cwd: options.scope,
|
|
@@ -434,7 +501,9 @@ export class PiBackend {
|
|
|
434
501
|
appendSystemPromptOverride: () => [],
|
|
435
502
|
systemPromptOverride: () => builder.instructions,
|
|
436
503
|
} : {
|
|
504
|
+
appendSystemPromptOverride: (base) => [...base, DIFF_EXCERPT_INSTRUCTIONS],
|
|
437
505
|
extensionFactories: [
|
|
506
|
+
streamingCacheWarming(settingsManager),
|
|
438
507
|
...(agentPermissions ? [agentPermissions.extension()] : []),
|
|
439
508
|
...(options.compactionModelId ? [compactionModelExtension(options.compactionModelId, (text) => options.emit({ type: "notice", level: "error", text }))] : []),
|
|
440
509
|
],
|
|
@@ -452,8 +521,8 @@ export class PiBackend {
|
|
|
452
521
|
const defaults = settingsManager.getDefaultTools() ?? ["read", "bash", "edit", "write"];
|
|
453
522
|
const builderTools = builder ? piWorkflowBuilderTools(builder) : [];
|
|
454
523
|
const tools = builder ? builderTools.map(tool => tool.name) : options.tools === "none" ? [] : [...(this.options.tools ?? [
|
|
455
|
-
...defaults, ASK_TOOL, SUBAGENT_TOOL, ...(defaults.includes("bash") ? ["bash_output", "kill_shell"] : []),
|
|
456
|
-
])];
|
|
524
|
+
...defaults, ASK_TOOL, TODO_TOOL, SUBAGENT_TOOL, ...(defaults.includes("bash") ? ["bash_output", "kill_shell"] : []),
|
|
525
|
+
])].filter((name) => !readOnlyDeniedTools(options.readOnly).includes(name));
|
|
457
526
|
const mcp = builder || options.tools === "none" ? undefined : options.mcp;
|
|
458
527
|
const workflowTools = workflowParentTools(builder || options.tools === "none" ? undefined : options.workflow);
|
|
459
528
|
const sessionTools = piSessionTools(builder || options.tools === "none" ? undefined : options.sessionTools);
|
|
@@ -467,6 +536,7 @@ export class PiBackend {
|
|
|
467
536
|
...sessionTools,
|
|
468
537
|
...backgroundTools(options.scope, settingsManager, work).filter((tool) => enabled(tool.name)),
|
|
469
538
|
...(enquiries ? [enquiries.tool] : []),
|
|
539
|
+
...(enabled(TODO_TOOL) ? [piTodoTool(options.emit)] : []),
|
|
470
540
|
...(subagents ? [subagentTool(work, (id, input, signal) => runSubagent(session, options.scope, agentDir, work, id, input, signal, options.emit, mcp, options.compactionModelId, agentPermissions))] : []),
|
|
471
541
|
];
|
|
472
542
|
const start = (current) => {
|
|
@@ -476,6 +546,7 @@ export class PiBackend {
|
|
|
476
546
|
agentDir,
|
|
477
547
|
resourceLoader,
|
|
478
548
|
settingsManager,
|
|
549
|
+
...(modelRuntime ? { modelRuntime } : {}),
|
|
479
550
|
customTools: [...customTools, ...mcpTools],
|
|
480
551
|
tools: [...tools, ...mcpTools.map((tool) => tool.name)],
|
|
481
552
|
...(current ? { sessionManager: current.sessionManager, modelRuntime: current.modelRuntime, thinkingLevel: current.thinkingLevel, ...(current.model ? { model: current.model } : {}) }
|
|
@@ -484,16 +555,26 @@ export class PiBackend {
|
|
|
484
555
|
});
|
|
485
556
|
};
|
|
486
557
|
let { session, extensionsResult } = await start();
|
|
558
|
+
if (options.resumeBefore && sessionDir) {
|
|
559
|
+
const entryId = readUserMessageMap(sessionDir)[options.resumeBefore];
|
|
560
|
+
if (!entryId) {
|
|
561
|
+
session.dispose();
|
|
562
|
+
throw new Error("This message cannot be rewound: pi has no record of it");
|
|
563
|
+
}
|
|
564
|
+
await session.navigateTree(entryId);
|
|
565
|
+
}
|
|
487
566
|
const extensionError = options.compactionModelId && compactionExtensionError(extensionsResult.errors);
|
|
488
567
|
if (extensionError) {
|
|
489
568
|
session.dispose();
|
|
490
569
|
throw new Error(`Could not load the Pi compaction model hook: ${extensionError}`);
|
|
491
570
|
}
|
|
492
571
|
const autoCompaction = structuredClone(options.autoCompaction);
|
|
493
|
-
const piSession = new PiSession(session, options.emit, sessionDir, { workflowBuilder: !!builder, ...(mcp ? { mcp } : {}), work, subagents, standingAuthorisations: options.standingAuthorisations ?? [], ...(agentPermissions ? { agentPermissions } : {}), autoCompaction: piAutoCompaction(settingsManager, autoCompaction), ...(autoCompaction ? { workflowAutoCompaction: autoCompaction } : {}), ...(options.compactionModelId ? { workflowCompactionModelId: options.compactionModelId } : {}), ...(enquiries ? { enquiries } : {}), ...(mcp ? { recreate: async (current) => (session = (await start(current)).session) } : {}) });
|
|
494
|
-
|
|
572
|
+
const piSession = new PiSession(session, options.emit, sessionDir, { workflowBuilder: !!builder, ...(mcp ? { mcp } : {}), work, subagents, standingAuthorisations: options.standingAuthorisations ?? [], ...(agentPermissions ? { agentPermissions } : {}), ...(options.priorSpend ? { priorSpend: options.priorSpend } : {}), autoCompaction: piAutoCompaction(settingsManager, autoCompaction), ...(autoCompaction ? { workflowAutoCompaction: autoCompaction } : {}), ...(options.compactionModelId ? { workflowCompactionModelId: options.compactionModelId } : {}), ...(enquiries ? { enquiries } : {}), ...(mcp ? { recreate: async (current) => (session = (await start(current)).session) } : {}) });
|
|
573
|
+
const modelId = options.modelId ?? (settingsManager.getDefaultProvider() === "azure-openai-responses" && settingsManager.getDefaultModel()
|
|
574
|
+
? `azure-openai-responses/${settingsManager.getDefaultModel()}` : undefined);
|
|
575
|
+
if (modelId) {
|
|
495
576
|
try {
|
|
496
|
-
await piSession.setModel(
|
|
577
|
+
await piSession.setModel(modelId);
|
|
497
578
|
}
|
|
498
579
|
catch (error) {
|
|
499
580
|
await piSession.dispose();
|
|
@@ -528,21 +609,27 @@ export class PiBackend {
|
|
|
528
609
|
return piSession;
|
|
529
610
|
}
|
|
530
611
|
}
|
|
612
|
+
function readOnlyDeniedTools(readOnly) {
|
|
613
|
+
if (!readOnly)
|
|
614
|
+
return [];
|
|
615
|
+
return ["edit", "write", ...(readOnly === "tools" ? ["bash", "bash_output", "kill_shell", "powershell"] : [])];
|
|
616
|
+
}
|
|
531
617
|
async function runSubagent(parent, scope, agentDir, work, id, input, signal, emit, mcp, compactionModelId, agentPermissions) {
|
|
532
618
|
const available = parent.modelRuntime.getAvailableSnapshot();
|
|
533
|
-
const model = input.model ? available
|
|
619
|
+
const model = input.model ? findPiModel(available, input.model) : parent.model;
|
|
534
620
|
if (!model)
|
|
535
|
-
throw new Error(
|
|
621
|
+
throw new Error(`${piModelUnavailable(input.model ?? "(inherited)")} Available: ${available.map((model) => describeModel(model).id).join(", ")}`);
|
|
536
622
|
const effort = (input.effort ?? parent.thinkingLevel);
|
|
537
|
-
const tools = [...new Set([...parent.getActiveToolNames(), ...piMcpTools(mcp).map((tool) => tool.name)])].filter((name) => name !== ASK_TOOL && name !== SUBAGENT_TOOL && !name.startsWith("workflow_") && !name.startsWith("session_"));
|
|
623
|
+
const tools = [...new Set([...parent.getActiveToolNames(), ...piMcpTools(mcp).map((tool) => tool.name)])].filter((name) => name !== ASK_TOOL && name !== TODO_TOOL && name !== SUBAGENT_TOOL && !name.startsWith("workflow_") && !name.startsWith("session_"));
|
|
538
624
|
const settingsManager = SettingsManager.create(scope, agentDir);
|
|
539
625
|
const producer = { subagentId: id };
|
|
540
626
|
const resourceLoader = new DefaultResourceLoader({ cwd: scope, agentDir, settingsManager, noExtensions: true,
|
|
541
627
|
extensionFactories: [
|
|
628
|
+
streamingCacheWarming(settingsManager),
|
|
542
629
|
...(agentPermissions ? [agentPermissions.extension(producer)] : []),
|
|
543
630
|
...(compactionModelId ? [compactionModelExtension(compactionModelId, (text) => emit({ type: "notice", level: "error", text }))] : []),
|
|
544
631
|
],
|
|
545
|
-
appendSystemPrompt: ["You are a Subagent. Complete the delegated work and return the result. If human input is needed, return that request to the parent. You cannot ask the human or create further Subagents."] });
|
|
632
|
+
appendSystemPrompt: ["You are a Subagent. Complete the delegated work and return the result. If human input is needed, return that request to the parent. You cannot ask the human or create further Subagents.", DIFF_EXCERPT_INSTRUCTIONS] });
|
|
546
633
|
await resourceLoader.reload();
|
|
547
634
|
signal.throwIfAborted();
|
|
548
635
|
const { session: child, extensionsResult } = await createAgentSession({ cwd: scope, agentDir, model, modelRuntime: parent.modelRuntime,
|
|
@@ -590,7 +677,9 @@ async function runSubagent(parent, scope, agentDir, work, id, input, signal, emi
|
|
|
590
677
|
try {
|
|
591
678
|
signal.throwIfAborted();
|
|
592
679
|
await adapter.setEffort(effort);
|
|
680
|
+
work.refine(id, { model: describeModel(model).id, effort: child.thinkingLevel });
|
|
593
681
|
signal.throwIfAborted();
|
|
682
|
+
emit({ type: "subagent_instruction", id: `${id}:brief`, text: input.prompt, producer });
|
|
594
683
|
await adapter.prompt(input.prompt);
|
|
595
684
|
if (reason !== "complete")
|
|
596
685
|
throw new Error(failure ?? `Subagent ${reason}`);
|
|
@@ -604,6 +693,10 @@ async function runSubagent(parent, scope, agentDir, work, id, input, signal, emi
|
|
|
604
693
|
await work.stopOwnedCalls(id);
|
|
605
694
|
}
|
|
606
695
|
}
|
|
696
|
+
function readUserMessageMap(sessionDir) {
|
|
697
|
+
const path = join(sessionDir, USER_MESSAGE_MAP);
|
|
698
|
+
return existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : {};
|
|
699
|
+
}
|
|
607
700
|
function capabilitiesOf(session, enquiries, subagents, permissions = true) {
|
|
608
701
|
// The SDK populates this auth-filtered snapshot before createAgentSession resolves. Every model is
|
|
609
702
|
// described directly: effort discovery is observational and must never switch the active model.
|
|
@@ -614,7 +707,8 @@ function capabilitiesOf(session, enquiries, subagents, permissions = true) {
|
|
|
614
707
|
models,
|
|
615
708
|
compaction: true,
|
|
616
709
|
autoCompaction: "model-change",
|
|
617
|
-
fork:
|
|
710
|
+
fork: true,
|
|
711
|
+
rewind: true,
|
|
618
712
|
subagents,
|
|
619
713
|
enquiries,
|
|
620
714
|
permissions,
|
|
@@ -651,3 +745,7 @@ function joinBlocks(content, kind) {
|
|
|
651
745
|
function isString(value) {
|
|
652
746
|
return typeof value === "string";
|
|
653
747
|
}
|
|
748
|
+
function statsOf(session) {
|
|
749
|
+
const stats = session.getSessionStats();
|
|
750
|
+
return { tokens: stats.tokens.total, cached: stats.tokens.cacheRead, costUSD: stats.cost };
|
|
751
|
+
}
|