@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.
Files changed (141) hide show
  1. package/README.md +641 -0
  2. package/build/workflow-runtime.cjs +213964 -0
  3. package/dist/backend/claude/async-queue.js +44 -0
  4. package/dist/backend/claude/auto-compaction.js +10 -0
  5. package/dist/backend/claude/background-calls.js +116 -0
  6. package/dist/backend/claude/enquiries.js +162 -0
  7. package/dist/backend/claude/index.js +1138 -0
  8. package/dist/backend/claude/mcp.js +55 -0
  9. package/dist/backend/claude/permissions.js +106 -0
  10. package/dist/backend/claude/streamed-message.js +120 -0
  11. package/dist/backend/claude/subagents.js +128 -0
  12. package/dist/backend/claude/workflow-parent.js +12 -0
  13. package/dist/backend/claude/workflow-processes.js +95 -0
  14. package/dist/backend/claude/workflow-subagent.js +234 -0
  15. package/dist/backend/effort.js +30 -0
  16. package/dist/backend/fake/index.js +570 -0
  17. package/dist/backend/mcp.js +190 -0
  18. package/dist/backend/pi/auto-compaction.js +16 -0
  19. package/dist/backend/pi/background-calls.js +56 -0
  20. package/dist/backend/pi/enquiries.js +63 -0
  21. package/dist/backend/pi/index.js +597 -0
  22. package/dist/backend/pi/mcp.js +35 -0
  23. package/dist/backend/pi/subagents.js +23 -0
  24. package/dist/backend/pi/work.js +104 -0
  25. package/dist/backend/pi/workflow-parent.js +21 -0
  26. package/dist/backend/pi/workflow-subagent.js +199 -0
  27. package/dist/backend/registry.js +34 -0
  28. package/dist/backend/types.js +1 -0
  29. package/dist/backend/workflow-tools.js +25 -0
  30. package/dist/build-id +1 -0
  31. package/dist/cli/application.js +397 -0
  32. package/dist/cli/bootstrap.js +535 -0
  33. package/dist/cli/host-control.js +100 -0
  34. package/dist/cli/install-guard.js +270 -0
  35. package/dist/cli/install-process.js +52 -0
  36. package/dist/cli/main.js +12 -0
  37. package/dist/cli/update.js +128 -0
  38. package/dist/client/connection.js +183 -0
  39. package/dist/client/context-usage.js +66 -0
  40. package/dist/client/diff.js +36 -0
  41. package/dist/client/enquiry.js +105 -0
  42. package/dist/client/markdown.js +192 -0
  43. package/dist/client/model-choices.js +32 -0
  44. package/dist/client/permission.js +60 -0
  45. package/dist/client/project-name.js +19 -0
  46. package/dist/client/reduce.js +463 -0
  47. package/dist/client/relative-time.js +30 -0
  48. package/dist/client/scope-kind.js +28 -0
  49. package/dist/client/search.js +136 -0
  50. package/dist/client/session-label.js +9 -0
  51. package/dist/client/status.js +84 -0
  52. package/dist/client/tool-chains.js +52 -0
  53. package/dist/client/tool-summary.js +98 -0
  54. package/dist/daemon/auth.js +590 -0
  55. package/dist/daemon/config-store.js +183 -0
  56. package/dist/daemon/config.js +687 -0
  57. package/dist/daemon/credential-redaction.js +9 -0
  58. package/dist/daemon/git.js +312 -0
  59. package/dist/daemon/host-control-routes.js +29 -0
  60. package/dist/daemon/host.js +2343 -0
  61. package/dist/daemon/http.js +19 -0
  62. package/dist/daemon/log.js +44 -0
  63. package/dist/daemon/mcp-auth.js +164 -0
  64. package/dist/daemon/models.js +85 -0
  65. package/dist/daemon/ownership.js +104 -0
  66. package/dist/daemon/projects.js +317 -0
  67. package/dist/daemon/publish.js +289 -0
  68. package/dist/daemon/pull-request.js +198 -0
  69. package/dist/daemon/runtime.js +100 -0
  70. package/dist/daemon/secret-store.js +65 -0
  71. package/dist/daemon/server.js +827 -0
  72. package/dist/daemon/shell.js +220 -0
  73. package/dist/daemon/skills.js +104 -0
  74. package/dist/daemon/stack-metadata.js +24 -0
  75. package/dist/daemon/stack.js +743 -0
  76. package/dist/daemon/store.js +130 -0
  77. package/dist/daemon/summariser.js +476 -0
  78. package/dist/daemon/workflow-execution-routes.js +105 -0
  79. package/dist/daemon/workflow-executions.js +1018 -0
  80. package/dist/daemon/workflow-mcp.js +20 -0
  81. package/dist/daemon/workflow-routes.js +102 -0
  82. package/dist/protocol/attachments.js +59 -0
  83. package/dist/protocol/commands.js +1 -0
  84. package/dist/protocol/events.js +20 -0
  85. package/dist/protocol/fonts.js +26 -0
  86. package/dist/protocol/git.js +12 -0
  87. package/dist/protocol/mcp.js +51 -0
  88. package/dist/protocol/projects.js +21 -0
  89. package/dist/protocol/publish.js +1 -0
  90. package/dist/protocol/pull-request.js +1 -0
  91. package/dist/protocol/secrets.js +4 -0
  92. package/dist/protocol/settings.js +63 -0
  93. package/dist/protocol/shells.js +8 -0
  94. package/dist/protocol/skills.js +16 -0
  95. package/dist/protocol/stack.js +41 -0
  96. package/dist/protocol/workflow-executions.js +1 -0
  97. package/dist/protocol/workflows.js +1 -0
  98. package/dist/tui/app.js +518 -0
  99. package/dist/tui/keys.js +54 -0
  100. package/dist/tui/render.js +366 -0
  101. package/dist/web/assets.js +10 -0
  102. package/dist/web/embedded.js +12 -0
  103. package/dist/web/manifest.js +70 -0
  104. package/dist/workflows/decisions.js +65 -0
  105. package/dist/workflows/executors.js +132 -0
  106. package/dist/workflows/graph.js +276 -0
  107. package/dist/workflows/json-schema.js +49 -0
  108. package/dist/workflows/loops.js +102 -0
  109. package/dist/workflows/mcp.js +18 -0
  110. package/dist/workflows/records.js +111 -0
  111. package/dist/workflows/recovery.js +25 -0
  112. package/dist/workflows/runtime-asset.js +17 -0
  113. package/dist/workflows/runtime-libs.js +1 -0
  114. package/dist/workflows/runtime-settings.js +23 -0
  115. package/dist/workflows/runtime.js +343 -0
  116. package/dist/workflows/scheduler.js +573 -0
  117. package/dist/workflows/schema.js +161 -0
  118. package/dist/workflows/store.js +93 -0
  119. package/package.json +87 -0
  120. package/web/dist/assets/__vite-browser-external-2447137e-BvRk9kiK.js +0 -0
  121. package/web/dist/assets/ghostty-vt-DOMeXDrv.wasm +0 -0
  122. package/web/dist/assets/index-BC0gLS53.js +106 -0
  123. package/web/dist/assets/index-CCeZYKES.css +2 -0
  124. package/web/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  125. package/web/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  126. package/web/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  127. package/web/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  128. package/web/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  129. package/web/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  130. package/web/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  131. package/web/dist/assets/rolldown-runtime-B0Z9INg1.js +1 -0
  132. package/web/dist/assets/select-6i3wxovH.js +1 -0
  133. package/web/dist/assets/settings-mcp-CcT0ADJR.js +1 -0
  134. package/web/dist/assets/settings-secrets-CK4uF7fd.js +1 -0
  135. package/web/dist/assets/settings-workflows-CrbZF-nM.js +23 -0
  136. package/web/dist/assets/switch-ftZleVB8.js +6 -0
  137. package/web/dist/assets/workflow-editors-naPqAmYO.js +65 -0
  138. package/web/dist/assets/workflows-D4T4Gy_7.css +1 -0
  139. package/web/dist/assets/workflows-hh6ioeEA.js +7 -0
  140. package/web/dist/assets/workflows-pane-Db-MHf7Z.js +1 -0
  141. package/web/dist/index.html +31 -0
@@ -0,0 +1,597 @@
1
+ import { workflowParentTools } from "./workflow-parent.js";
2
+ import { piMcpTools } from "./mcp.js";
3
+ import { randomUUID } from "node:crypto";
4
+ import { createAgentSession, DefaultResourceLoader, getAgentDir, SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent";
5
+ import { PiWorkflowSubagent } from "./workflow-subagent.js";
6
+ import { clampEffort } from "../effort.js";
7
+ import { piAutoCompaction } from "./auto-compaction.js";
8
+ import { ASK_TOOL, PiEnquiries } from "./enquiries.js";
9
+ import { backgroundTools } from "./background-calls.js";
10
+ import { SUBAGENT_TOOL, subagentTool } from "./subagents.js";
11
+ import { PiWork, callIdFor, resultText, textResult } from "./work.js";
12
+ export class PiSession {
13
+ capabilities;
14
+ answerEnquiry;
15
+ enquiries;
16
+ work;
17
+ completions = [];
18
+ workflows = new Map();
19
+ mcp;
20
+ async refreshMcp() {
21
+ this.session.agent.state.tools = [...this.session.agent.state.tools.filter((tool) => !tool.name.startsWith("mcp__")), ...piMcpTools(this.mcp)];
22
+ }
23
+ standingAuthorisations;
24
+ disposed = false;
25
+ disposal;
26
+ turnReason = "complete";
27
+ session;
28
+ applyAutoCompaction;
29
+ workflowAutoCompaction;
30
+ emit;
31
+ unsubscribe;
32
+ sessionDir;
33
+ turnId;
34
+ /**
35
+ * The turn a *requested* compaction opened, kept apart from `turnId` because pi compacts on its
36
+ * own initiative too — and an automatic one runs inside a turn that is already open. Set only by
37
+ * `compact`, so `compaction_end` can tell whose turn it is ending, if anyone's.
38
+ */
39
+ compactionTurnId;
40
+ aborting = false;
41
+ /** What the human asked for, kept apart from what is in force so a clamp is never destructive. */
42
+ wantedEffort;
43
+ effort;
44
+ messageSeq = 0;
45
+ currentMessageId;
46
+ constructor(session, emit, sessionDir, support = {}) {
47
+ this.mcp = support.mcp;
48
+ this.standingAuthorisations = [...(support.standingAuthorisations ?? [])];
49
+ this.session = session;
50
+ this.applyAutoCompaction = support.autoCompaction;
51
+ this.workflowAutoCompaction = support.workflowAutoCompaction ?? {};
52
+ this.applyAutoCompaction?.(session.model);
53
+ this.emit = emit;
54
+ this.sessionDir = sessionDir;
55
+ this.enquiries = support.enquiries;
56
+ this.work = support.work;
57
+ const enquiries = support.enquiries;
58
+ if (enquiries)
59
+ this.answerEnquiry = async (askId, answers) => enquiries.answer(askId, answers);
60
+ this.capabilities = capabilitiesOf(session, support.enquiries !== undefined, support.subagents ?? false);
61
+ this.unsubscribe = session.subscribe((event) => this.translate(event));
62
+ }
63
+ startWorkflowSubagent(options) {
64
+ if (this.disposed)
65
+ throw new Error("Backend Session stopped");
66
+ if (this.workflows.has(options.id))
67
+ throw new Error(`Duplicate workflow Subagent: ${options.id}`);
68
+ const handle = new PiWorkflowSubagent(this.session, options, this.standingAuthorisations, this.mcp, this.workflowAutoCompaction);
69
+ this.workflows.set(options.id, handle);
70
+ void handle.done.finally(() => this.workflows.delete(options.id)).catch(() => { });
71
+ return handle;
72
+ }
73
+ resumeToken() {
74
+ // pi persists through its own SessionManager; the directory we gave it is the resume handle.
75
+ return this.sessionDir;
76
+ }
77
+ async prompt(text, attachments) {
78
+ this.turnId = `turn-${++this.messageSeq}`;
79
+ this.emit({ type: "turn_started", turnId: this.turnId });
80
+ await this.session.prompt(text, {
81
+ streamingBehavior: "steer",
82
+ // pi takes images beside the text rather than interleaved with it, so there is no ordering to
83
+ // choose here the way there is on Claude's content array.
84
+ ...(attachments?.length
85
+ ? { images: attachments.map((a) => ({ type: "image", data: a.data, mimeType: a.mediaType })) }
86
+ : {}),
87
+ });
88
+ }
89
+ async abort() {
90
+ this.aborting = this.turnId !== undefined;
91
+ await this.session.abort();
92
+ }
93
+ async setModel(modelId) {
94
+ const available = await this.session.modelRuntime.getAvailable();
95
+ const qualified = available.find((candidate) => describeModel(candidate).id === modelId);
96
+ const legacy = available.filter((candidate) => candidate.id === modelId);
97
+ const model = qualified ?? (legacy.length === 1 ? legacy[0] : undefined);
98
+ if (!model)
99
+ throw new Error(`Unknown model: ${modelId}`);
100
+ await this.session.setModel(model);
101
+ this.applyAutoCompaction?.(this.session.model);
102
+ // Which levels are on offer follows the model, and pi may have clamped its own thinking level
103
+ // on the way through, so both the list and the level in force are re-read here.
104
+ this.capabilities = capabilitiesOf(this.session, this.enquiries !== undefined, this.capabilities.subagents);
105
+ this.emit({ type: "model_changed", model: describeModel(model) });
106
+ this.emit({ type: "capabilities_changed", capabilities: this.capabilities });
107
+ this.reapplyEffort();
108
+ }
109
+ async setEffort(effort) {
110
+ this.wantedEffort = effort;
111
+ this.applyEffort(effort);
112
+ }
113
+ /**
114
+ * pi compacts first-class, so this is the whole implementation: it reports through
115
+ * `compaction_end`, which `translate` already turns into a `compacted`.
116
+ *
117
+ * Not awaited to completion on purpose. pi resolves this when the summary exists, which is a model
118
+ * call away, and the host's caller is an HTTP request that should not be held open for it — the
119
+ * events are how anyone finds out either way. A failure still reaches the transcript, because pi
120
+ * puts it on `compaction_end.errorMessage` rather than throwing.
121
+ *
122
+ * The turn is opened *here* rather than on `compaction_start`, because that event fires for pi's
123
+ * automatic compactions as well — and those happen inside a turn that is already open. Only the
124
+ * ones somebody asked for occupy a session of their own, and `compactionTurnId` is what tells the
125
+ * two apart when the end arrives.
126
+ */
127
+ async compact(instructions) {
128
+ const turnId = `compaction-${++this.messageSeq}`;
129
+ this.compactionTurnId = turnId;
130
+ this.emit({ type: "turn_started", turnId });
131
+ // A rejection here would never reach `compaction_end`, and a turn left open pins the session in
132
+ // `running` forever — refusing every later send and every later compaction.
133
+ void this.session.compact(instructions).catch((error) => {
134
+ if (this.compactionTurnId !== turnId)
135
+ return;
136
+ this.emit({
137
+ type: "notice",
138
+ level: "error",
139
+ text: error instanceof Error ? error.message : String(error),
140
+ });
141
+ this.endCompactionTurn("error");
142
+ });
143
+ }
144
+ /** Ends the turn a requested compaction opened, and does nothing for one pi started itself. */
145
+ endCompactionTurn(reason) {
146
+ const turnId = this.compactionTurnId;
147
+ if (!turnId)
148
+ return;
149
+ this.compactionTurnId = undefined;
150
+ this.emit({ type: "turn_ended", turnId, reason });
151
+ this.scheduleCompletions();
152
+ }
153
+ /**
154
+ * pi splits what Claude calls a Skill in two: a `Skill` is a capability the model may invoke, and a
155
+ * `PromptTemplate` is a named prompt a human triggers. Both are offered here, because from the
156
+ * composer they are the same act — type a name, get a prompt — and only the second has an
157
+ * `argumentHint` to carry.
158
+ *
159
+ * Reloaded first, for the reason the Claude adapter rescans: a human who has just written one
160
+ * opens the menu expecting to find it.
161
+ */
162
+ async skills() {
163
+ await this.session.resourceLoader.reload();
164
+ const { skills } = this.session.resourceLoader.getSkills();
165
+ const { prompts } = this.session.resourceLoader.getPrompts();
166
+ return [
167
+ ...skills.map((skill) => ({ name: skill.name, description: skill.description })),
168
+ ...prompts.map((prompt) => ({
169
+ name: prompt.name,
170
+ description: prompt.description,
171
+ ...(prompt.argumentHint ? { argumentHint: prompt.argumentHint } : {}),
172
+ })),
173
+ ];
174
+ }
175
+ applyEffort(wanted) {
176
+ const level = clampEffort(wanted, availableEffort(this.session));
177
+ // Nothing to set on a model with no effort control. The request stays on file, so switching
178
+ // back to a model that has one restores it.
179
+ if (!level) {
180
+ this.effort = undefined;
181
+ return;
182
+ }
183
+ // Safe: the level came out of pi's own list of what this model offers.
184
+ this.session.setThinkingLevel(level);
185
+ this.effort = this.session.thinkingLevel ?? level;
186
+ this.emit({ type: "effort_changed", effort: this.effort });
187
+ }
188
+ /**
189
+ * Report the thinking level pi is already on, for a session nobody has chosen one for.
190
+ *
191
+ * pi differs from the Claude adapter here, and it is a real difference rather than an oversight in
192
+ * either: pi exposes `thinkingLevel` as state that can be read at any time, while Claude reports
193
+ * its effort only in the init message that arrives with the first turn. So a pi session can say
194
+ * what it is running at from the moment it starts, and a Claude one cannot — each reports what it
195
+ * is able to, which is the same rule Capabilities sets.
196
+ */
197
+ noteStartingEffort() {
198
+ const settled = this.session.thinkingLevel;
199
+ if (!settled || settled === this.effort)
200
+ return;
201
+ this.effort = settled;
202
+ this.emit({ type: "effort_changed", effort: settled });
203
+ }
204
+ reapplyEffort() {
205
+ // With nothing asked for, whatever pi settled on *is* the answer.
206
+ if (!this.wantedEffort) {
207
+ this.noteStartingEffort();
208
+ return;
209
+ }
210
+ if (clampEffort(this.wantedEffort, availableEffort(this.session)) === this.effort)
211
+ return;
212
+ this.applyEffort(this.wantedEffort);
213
+ }
214
+ dispose() {
215
+ return this.disposal ??= this.disposeOnce();
216
+ }
217
+ async disposeOnce() {
218
+ this.disposed = true;
219
+ this.completions.length = 0;
220
+ try {
221
+ await Promise.all([this.abort(), this.work?.dispose(), ...[...this.workflows.values()].map((handle) => handle.cancel())]);
222
+ }
223
+ finally {
224
+ this.unsubscribe();
225
+ this.session.dispose();
226
+ }
227
+ }
228
+ completed(completion) {
229
+ if (this.disposed)
230
+ return;
231
+ this.completions.push(completion);
232
+ this.scheduleCompletions();
233
+ }
234
+ scheduleCompletions() {
235
+ queueMicrotask(() => {
236
+ if (this.disposed || this.turnId || this.compactionTurnId || this.session.isStreaming || !this.completions.length)
237
+ return;
238
+ const completed = this.completions.splice(0).map(({ brief, state, result }) => ({ ...brief, state, output: resultText(result) }));
239
+ const turnId = `turn-${++this.messageSeq}`;
240
+ this.turnId = turnId;
241
+ this.turnReason = "complete";
242
+ this.emit({ type: "turn_started", turnId });
243
+ void this.session.sendCustomMessage({ customType: "flow_completion", content: JSON.stringify(completed), display: false }, { triggerTurn: true }).catch((error) => {
244
+ this.emit({ type: "notice", level: "error", text: error instanceof Error ? error.message : String(error) });
245
+ if (this.turnId === turnId)
246
+ this.finishTurn("error");
247
+ });
248
+ });
249
+ }
250
+ finishTurn(reason) {
251
+ const turnId = this.turnId;
252
+ if (!turnId)
253
+ return;
254
+ this.turnId = undefined;
255
+ this.aborting = false;
256
+ this.turnReason = "complete";
257
+ this.reportContextUsage();
258
+ this.emit({ type: "turn_ended", turnId, reason });
259
+ this.scheduleCompletions();
260
+ }
261
+ translate(event) {
262
+ switch (event.type) {
263
+ case "agent_start":
264
+ // turn_started is emitted on prompt() so the host sees it without waiting on the backend.
265
+ return;
266
+ case "message_start":
267
+ this.currentMessageId = randomUUID();
268
+ this.emitMessage(event.message, false);
269
+ return;
270
+ case "message_update":
271
+ this.emitMessage(event.message, false);
272
+ return;
273
+ case "message_end":
274
+ this.emitMessage(event.message, true);
275
+ this.currentMessageId = undefined;
276
+ return;
277
+ case "tool_execution_start":
278
+ this.emit({ type: "tool_started", callId: event.toolCallId, name: event.toolName, input: event.args });
279
+ return;
280
+ case "tool_execution_update":
281
+ this.emit({ type: "tool_updated", callId: event.toolCallId, update: event.partialResult });
282
+ return;
283
+ case "tool_execution_end":
284
+ this.emit({
285
+ type: "tool_ended",
286
+ callId: event.toolCallId,
287
+ result: event.result,
288
+ isError: event.isError,
289
+ });
290
+ return;
291
+ case "agent_end": {
292
+ if (event.willRetry)
293
+ return;
294
+ const last = event.messages.findLast((message) => message.role === "assistant");
295
+ this.turnReason = this.aborting || last?.stopReason === "aborted" ? "aborted"
296
+ : last?.stopReason === "error" ? "error" : "complete";
297
+ if (last?.stopReason === "error" && last.errorMessage) {
298
+ this.emit({ type: "notice", level: "error", text: last.errorMessage });
299
+ }
300
+ return;
301
+ }
302
+ case "agent_settled":
303
+ this.finishTurn(this.aborting ? "aborted" : this.turnReason);
304
+ return;
305
+ case "auto_retry_start":
306
+ this.emit({
307
+ type: "notice",
308
+ level: "warn",
309
+ text: `Retrying ${event.attempt}/${event.maxAttempts}: ${event.errorMessage}`,
310
+ });
311
+ return;
312
+ case "auto_retry_end":
313
+ if (!event.success && event.finalError) {
314
+ this.emit({ type: "notice", level: "error", text: event.finalError });
315
+ }
316
+ return;
317
+ /*
318
+ * The start drives the chrome, never a transcript row — which is why it is translated now and
319
+ * was not before. One compaction is still one row in both backends, because that row is
320
+ * `compacted` and it comes from the end.
321
+ *
322
+ * pi announces its own compactions before they begin, so this fires for automatic ones too.
323
+ * The Claude SDK reports only the boundary after the fact, so there the same state means "a
324
+ * human asked and it has not come back". Each says what it can see.
325
+ */
326
+ case "compaction_start":
327
+ this.emit({ type: "compacting", active: true });
328
+ return;
329
+ /*
330
+ * A compaction that aborted or is about to be retried did not happen yet, so it records
331
+ * nothing — the same rule `agent_end` applies to `willRetry` above. It still has to stop
332
+ * saying it is working, so the state is cleared before any of that is decided.
333
+ */
334
+ case "compaction_end":
335
+ this.emit({ type: "compacting", active: false });
336
+ if (event.errorMessage) {
337
+ this.emit({ type: "notice", level: "error", text: event.errorMessage });
338
+ }
339
+ if (event.willRetry)
340
+ return;
341
+ // pi counts what it started from and never what it ended at, so `after` goes unreported
342
+ // rather than guessed. Only "manual" is somebody asking; a threshold and an overflow are
343
+ // both pi deciding on its own.
344
+ if (!event.aborted && event.result) {
345
+ this.emit({
346
+ type: "compacted",
347
+ trigger: event.reason === "manual" ? "manual" : "auto",
348
+ before: event.result.tokensBefore,
349
+ });
350
+ }
351
+ // Last, so the marker lands while the turn is still open — `turn_ended` is what returns the
352
+ // session to idle and lets the Steering Queue drain behind it.
353
+ this.endCompactionTurn(event.aborted ? "aborted" : event.errorMessage ? "error" : "complete");
354
+ return;
355
+ default:
356
+ return;
357
+ }
358
+ }
359
+ emitMessage(message, final) {
360
+ if (message.role !== "assistant")
361
+ return;
362
+ const id = this.currentMessageId ?? randomUUID();
363
+ this.currentMessageId = id;
364
+ const text = joinBlocks(message.content, "text");
365
+ const thinking = joinBlocks(message.content, "thinking");
366
+ if (text)
367
+ this.emit({ type: "message", id, text, final });
368
+ if (thinking)
369
+ this.emit({ type: "thinking", id: `${id}-thinking`, text: thinking, final });
370
+ }
371
+ reportContextUsage() {
372
+ const usage = this.session.getContextUsage();
373
+ if (usage && typeof usage.tokens === "number") {
374
+ this.emit({ type: "context_usage", used: usage.tokens, window: usage.contextWindow });
375
+ }
376
+ }
377
+ }
378
+ export class PiBackend {
379
+ name = "pi";
380
+ options;
381
+ constructor(options = {}) {
382
+ this.options = options;
383
+ }
384
+ async create(options) {
385
+ const agentDir = getAgentDir();
386
+ // Extensions are not loaded: they expect pi's own UI surface, and a background session that
387
+ // registers UI hooks has nowhere to render them.
388
+ const settingsManager = SettingsManager.create(options.scope, agentDir);
389
+ const resourceLoader = new DefaultResourceLoader({
390
+ cwd: options.scope,
391
+ agentDir,
392
+ settingsManager,
393
+ noExtensions: true,
394
+ });
395
+ await resourceLoader.reload();
396
+ // Reviving reopens the most recent pi session in the directory we gave this Agent Session;
397
+ // a fresh Agent Session starts a new one there.
398
+ const sessionDir = options.stateDir;
399
+ const sessionManager = sessionDir
400
+ ? options.resume
401
+ ? SessionManager.continueRecent(options.scope, sessionDir)
402
+ : SessionManager.create(options.scope, sessionDir)
403
+ : undefined;
404
+ const defaults = settingsManager.getDefaultTools() ?? ["read", "bash", "edit", "write"];
405
+ const tools = options.tools === "none" ? [] : [...(this.options.tools ?? [
406
+ ...defaults, ASK_TOOL, SUBAGENT_TOOL, ...(defaults.includes("bash") ? ["bash_output", "kill_shell"] : []),
407
+ ])];
408
+ const mcp = options.tools === "none" ? undefined : options.mcp;
409
+ const workflowTools = workflowParentTools(options.tools === "none" ? undefined : options.workflow);
410
+ tools.push(...workflowTools.map(tool => tool.name), ...piMcpTools(mcp).map((tool) => tool.name));
411
+ const enabled = (name) => tools.includes(name);
412
+ const enquiries = enabled(ASK_TOOL) ? new PiEnquiries(options.emit) : undefined;
413
+ const work = new PiWork(options.emit, (completion) => piSession.completed(completion));
414
+ const subagents = enabled(SUBAGENT_TOOL);
415
+ const customTools = [
416
+ ...workflowTools,
417
+ ...piMcpTools(mcp),
418
+ ...backgroundTools(options.scope, settingsManager, work).filter((tool) => enabled(tool.name)),
419
+ ...(enquiries ? [enquiries.tool] : []),
420
+ ...(subagents ? [subagentTool(work, (id, input, signal) => runSubagent(session, options.scope, agentDir, work, id, input, signal, options.emit, mcp))] : []),
421
+ ];
422
+ const { session } = await createAgentSession({
423
+ cwd: options.scope,
424
+ agentDir,
425
+ resourceLoader,
426
+ settingsManager,
427
+ customTools,
428
+ tools,
429
+ ...(sessionManager ? { sessionManager } : {}),
430
+ ...(tools.length === 0 ? { noTools: "all" } : {}),
431
+ });
432
+ const autoCompaction = structuredClone(options.autoCompaction ?? {});
433
+ const piSession = new PiSession(session, options.emit, sessionDir, { ...(mcp ? { mcp } : {}), work, subagents, standingAuthorisations: options.standingAuthorisations ?? [], autoCompaction: piAutoCompaction(settingsManager, autoCompaction), workflowAutoCompaction: autoCompaction, ...(enquiries ? { enquiries } : {}) });
434
+ if (options.modelId) {
435
+ try {
436
+ await piSession.setModel(options.modelId);
437
+ }
438
+ catch (error) {
439
+ await piSession.dispose();
440
+ throw error;
441
+ }
442
+ }
443
+ options.emit({ type: "capabilities_changed", capabilities: piSession.capabilities });
444
+ // Which model is in force decides which effort levels a client may offer, so say it up front,
445
+ // preferring the registry entry: that is the one carrying pi's own answer about its levels.
446
+ if (session.model) {
447
+ const described = describeModel(session.model);
448
+ const listed = piSession.capabilities.models.find((model) => model.id === described.id);
449
+ options.emit({ type: "model_changed", model: listed ?? described });
450
+ }
451
+ // Announced after the model, because which model is in force is what decides whether an effort
452
+ // level means anything at all.
453
+ if (options.effort)
454
+ await piSession.setEffort(options.effort);
455
+ else
456
+ piSession.noteStartingEffort();
457
+ return piSession;
458
+ }
459
+ }
460
+ async function runSubagent(parent, scope, agentDir, work, id, input, signal, emit, mcp) {
461
+ const available = parent.modelRuntime.getAvailableSnapshot();
462
+ const model = input.model ? available.find((model) => describeModel(model).id === input.model) : parent.model;
463
+ if (!model)
464
+ throw new Error(`Unknown model: ${input.model}. Available: ${available.map((model) => describeModel(model).id).join(", ")}`);
465
+ const effort = (input.effort ?? parent.thinkingLevel);
466
+ const tools = [...new Set([...parent.getActiveToolNames(), ...piMcpTools(mcp).map((tool) => tool.name)])].filter((name) => name !== ASK_TOOL && name !== SUBAGENT_TOOL && !name.startsWith("workflow_"));
467
+ const settingsManager = SettingsManager.create(scope, agentDir);
468
+ const resourceLoader = new DefaultResourceLoader({ cwd: scope, agentDir, settingsManager, noExtensions: true,
469
+ 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."] });
470
+ await resourceLoader.reload();
471
+ signal.throwIfAborted();
472
+ const producer = { subagentId: id };
473
+ const { session: child } = await createAgentSession({ cwd: scope, agentDir, model, modelRuntime: parent.modelRuntime,
474
+ resourceLoader, settingsManager, sessionManager: SessionManager.inMemory(scope), tools,
475
+ customTools: [...piMcpTools(mcp), ...backgroundTools(scope, settingsManager, work, producer, input.run_in_background === false).filter((tool) => tools.includes(tool.name))],
476
+ });
477
+ let output = "";
478
+ let failure;
479
+ let reason = "complete";
480
+ const adapter = new PiSession(child, (event) => {
481
+ switch (event.type) {
482
+ case "message":
483
+ case "thinking":
484
+ work.waiting(id, false);
485
+ if (event.type === "message" && event.final)
486
+ output = event.text;
487
+ emit({ ...event, id: callIdFor(event.id, producer), producer });
488
+ break;
489
+ case "tool_started":
490
+ case "tool_updated":
491
+ case "tool_ended":
492
+ if (event.type === "tool_started")
493
+ work.waiting(id, false);
494
+ emit({ ...event, callId: callIdFor(event.callId, producer), producer });
495
+ break;
496
+ case "notice":
497
+ if (event.level === "warn")
498
+ work.waiting(id, true);
499
+ if (event.level === "error")
500
+ failure = event.text;
501
+ emit({ ...event, text: `${input.name ?? "Subagent"}: ${event.text}` });
502
+ break;
503
+ case "turn_ended":
504
+ reason = event.reason;
505
+ break;
506
+ }
507
+ });
508
+ const abort = () => { void adapter.abort(); };
509
+ signal.addEventListener("abort", abort, { once: true });
510
+ try {
511
+ signal.throwIfAborted();
512
+ await adapter.setEffort(effort);
513
+ signal.throwIfAborted();
514
+ await adapter.prompt(input.prompt);
515
+ if (reason !== "complete")
516
+ throw new Error(failure ?? `Subagent ${reason}`);
517
+ return textResult(output || "Subagent completed without text output");
518
+ }
519
+ finally {
520
+ signal.removeEventListener("abort", abort);
521
+ await adapter.dispose();
522
+ if (input.run_in_background === false)
523
+ await work.stopOwnedCalls(id);
524
+ }
525
+ }
526
+ function capabilitiesOf(session, enquiries, subagents) {
527
+ const current = session.model ? describeModel(session.model).id : undefined;
528
+ // The SDK populates this auth-filtered snapshot before createAgentSession resolves.
529
+ const models = session.modelRuntime.getAvailableSnapshot().map((model) => {
530
+ const described = describeModel(model);
531
+ // pi will only answer for the model it has selected, and that answer is the authoritative one.
532
+ // Every other entry is inferred from the registry and firms up if you switch to it.
533
+ if (described.id !== current)
534
+ return described;
535
+ const available = availableEffort(session);
536
+ return available.length > 0 ? { ...described, effortLevels: available } : omitEffort(described);
537
+ });
538
+ const providers = [...new Set(models.map((model) => model.provider).filter(isString))];
539
+ return {
540
+ providers: providers.length > 0 ? providers : ["pi"],
541
+ models,
542
+ compaction: true,
543
+ autoCompaction: "model-change",
544
+ fork: false,
545
+ subagents,
546
+ enquiries,
547
+ permissions: false,
548
+ };
549
+ }
550
+ function describeModel(model) {
551
+ const effortLevels = inferredEffort(model);
552
+ return {
553
+ id: model.provider ? `${model.provider}/${model.id}` : model.id,
554
+ ...(model.contextWindow !== undefined && Number.isFinite(model.contextWindow) && model.contextWindow > 0 ? { contextWindow: model.contextWindow } : {}),
555
+ ...(model.provider ? { provider: model.provider } : {}),
556
+ ...(model.name ? { label: model.name } : {}),
557
+ ...(effortLevels.length > 0 ? { effortLevels } : {}),
558
+ // Read from the registry rather than inferred, and so trustworthy for every entry rather than
559
+ // only the selected one — unlike the Effort levels above, pi does not make this depend on which
560
+ // model is in force.
561
+ ...(model.input?.includes("image") ? { acceptsImages: true } : {}),
562
+ };
563
+ }
564
+ /** The levels pi will accept for the model it currently has selected. */
565
+ function availableEffort(session) {
566
+ return session.supportsThinking() ? session.getAvailableThinkingLevels() : [];
567
+ }
568
+ /**
569
+ * What a model that is not currently selected probably offers. A model that cannot reason offers
570
+ * nothing; otherwise its thinkingLevelMap names the levels it was configured with.
571
+ */
572
+ function inferredEffort(model) {
573
+ if (model.reasoning === false)
574
+ return [];
575
+ const map = model.thinkingLevelMap;
576
+ if (!map)
577
+ return model.reasoning ? PI_EFFORT_LEVELS : [];
578
+ return PI_EFFORT_LEVELS.filter((level) => map[level] !== undefined && map[level] !== null);
579
+ }
580
+ const PI_EFFORT_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh"];
581
+ function omitEffort(model) {
582
+ const { effortLevels: _dropped, ...rest } = model;
583
+ return rest;
584
+ }
585
+ function joinBlocks(content, kind) {
586
+ if (typeof content === "string")
587
+ return kind === "text" ? content : "";
588
+ if (!Array.isArray(content))
589
+ return "";
590
+ return content
591
+ .filter((block) => Boolean(block) && typeof block === "object" && block.type === kind)
592
+ .map((block) => (kind === "text" ? block.text : block.thinking) ?? "")
593
+ .join("");
594
+ }
595
+ function isString(value) {
596
+ return typeof value === "string";
597
+ }
@@ -0,0 +1,35 @@
1
+ import { Type } from "typebox";
2
+ export function piMcpTools(mcp) {
3
+ return (mcp?.tools() ?? []).map((tool) => ({
4
+ name: tool.name,
5
+ label: tool.definition.title ?? tool.definition.name,
6
+ description: `${tool.definition.name}: ${tool.definition.description ?? "MCP tool"}`,
7
+ parameters: Type.Unsafe(tool.definition.inputSchema),
8
+ execute: async (_id, input, signal) => {
9
+ const result = await tool.call(input, signal);
10
+ const text = result.content
11
+ .filter((block) => block.type !== "image")
12
+ .map((block) => block.type === "text" ? block.text : JSON.stringify(block))
13
+ .join("\n") ||
14
+ (result.structuredContent
15
+ ? JSON.stringify(result.structuredContent)
16
+ : "");
17
+ const output = text;
18
+ if (result.isError)
19
+ throw new Error(output);
20
+ return {
21
+ content: [
22
+ ...(output ? [{ type: "text", text: output }] : []),
23
+ ...result.content
24
+ .filter((block) => block.type === "image")
25
+ .map((block) => ({
26
+ type: "image",
27
+ data: block.data,
28
+ mimeType: block.mimeType,
29
+ })),
30
+ ],
31
+ details: {},
32
+ };
33
+ },
34
+ }));
35
+ }
@@ -0,0 +1,23 @@
1
+ import { defineTool } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+ import { EFFORT_ORDER } from "../effort.js";
4
+ export const SUBAGENT_TOOL = "subagent";
5
+ const parameters = Type.Object({
6
+ description: Type.String({ minLength: 1, description: "Short description of the delegated work" }),
7
+ prompt: Type.String({ minLength: 1, description: "Complete instructions; the Subagent cannot see your conversation" }),
8
+ name: Type.Optional(Type.String({ minLength: 1 })),
9
+ model: Type.Optional(Type.String({ description: "Provider-qualified model id; defaults to the parent's model at launch" })),
10
+ effort: Type.Optional(Type.String({ enum: EFFORT_ORDER, description: "Defaults to the parent's Effort at launch" })),
11
+ run_in_background: Type.Optional(Type.Boolean({ description: "Defaults to true. Set false only when your next action requires the result." })),
12
+ });
13
+ export function subagentTool(work, run) {
14
+ return defineTool({
15
+ name: SUBAGENT_TOOL,
16
+ label: "Subagent",
17
+ 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
+ promptSnippet: "Delegate independent work to Subagents",
19
+ parameters,
20
+ execute: async (id, input, signal) => work.run({ type: "subagent", subagentId: id,
21
+ name: input.name ?? "Subagent", description: input.description }, (childSignal) => run(id, input, childSignal), input.run_in_background !== false, signal),
22
+ });
23
+ }