@nathanstephenson/flow 0.1.9 → 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.
Files changed (174) hide show
  1. package/README.md +60 -21
  2. package/build/backend-worker-chunks/chunk-3KDHJA5P.mjs +162 -0
  3. package/build/backend-worker-chunks/{chunk-UQDH2COY.mjs → chunk-K774KOGL.mjs} +2 -7
  4. package/build/backend-worker-chunks/chunk-LAEUXDNH.mjs +130 -0
  5. package/build/backend-worker-chunks/{chunk-MLOUI3ZM.mjs → chunk-NZZME2I3.mjs} +6 -1
  6. package/build/backend-worker-chunks/claude-JG2FXYBQ.mjs +35859 -0
  7. package/build/backend-worker-chunks/{pi-M4OA2FGL.mjs → pi-KJSP23AO.mjs} +2138 -93
  8. package/build/backend-worker.mjs +77 -123
  9. package/build/workflow-runtime.cjs +12 -12
  10. package/dist/backend/claude/background-calls.js +7 -3
  11. package/dist/backend/claude/import.js +415 -0
  12. package/dist/backend/claude/index.js +201 -21
  13. package/dist/backend/claude/session-tools.js +14 -0
  14. package/dist/backend/claude/subagents.js +41 -9
  15. package/dist/backend/claude/todo-list.js +114 -0
  16. package/dist/backend/claude/workflow-parent.js +1 -1
  17. package/dist/backend/diff-excerpt-instructions.js +8 -0
  18. package/dist/backend/fake/index.js +54 -6
  19. package/dist/backend/mcp.js +4 -1
  20. package/dist/backend/pi/agent-permissions.js +1 -1
  21. package/dist/backend/pi/cache-warming.js +8 -0
  22. package/dist/backend/pi/canonical-json.js +120 -0
  23. package/dist/backend/pi/compaction-model.js +3 -2
  24. package/dist/backend/pi/host-auth.js +258 -0
  25. package/dist/backend/pi/import.js +269 -0
  26. package/dist/backend/pi/index.js +125 -21
  27. package/dist/backend/pi/model-auth.js +159 -0
  28. package/dist/backend/pi/model-catalog.js +120 -0
  29. package/dist/backend/pi/model-config.js +5 -0
  30. package/dist/backend/pi/model-selection.js +32 -0
  31. package/dist/backend/pi/plan-limits.js +41 -0
  32. package/dist/backend/pi/session-tools.js +21 -0
  33. package/dist/backend/pi/state.js +19 -1
  34. package/dist/backend/pi/subagents.js +7 -3
  35. package/dist/backend/pi/todo-list.js +23 -0
  36. package/dist/backend/pi/work.js +9 -1
  37. package/dist/backend/pi/workflow-parent.js +1 -1
  38. package/dist/backend/pi/workflow-subagent.js +4 -3
  39. package/dist/backend/plan-limits.js +17 -0
  40. package/dist/backend/session-tools.js +27 -0
  41. package/dist/backend/worker/claude-state.js +48 -0
  42. package/dist/backend/worker/entry.js +49 -8
  43. package/dist/backend/worker/index.js +155 -17
  44. package/dist/backend/worker/launcher.js +11 -4
  45. package/dist/backend/worker/protocol.js +2 -1
  46. package/dist/backend/worker/rpc.js +13 -0
  47. package/dist/backend/worker/sandbox-mcp.js +18 -7
  48. package/dist/backend/workflow-tools.js +9 -6
  49. package/dist/build-id +1 -1
  50. package/dist/cli/application.js +48 -42
  51. package/dist/cli/bootstrap.js +2 -2
  52. package/dist/cli/host-control.js +1 -1
  53. package/dist/cli/install-guard.js +2 -2
  54. package/dist/cli/main.js +4 -4
  55. package/dist/cli/systemd-update.js +3 -3
  56. package/dist/cli/update.js +6 -6
  57. package/dist/cli/web-update.js +6 -6
  58. package/dist/client/connection.js +46 -0
  59. package/dist/client/context-usage.js +3 -4
  60. package/dist/client/diff.js +40 -0
  61. package/dist/client/enquiry.js +0 -6
  62. package/dist/client/markdown.js +3 -2
  63. package/dist/client/model-choices.js +1 -1
  64. package/dist/client/permission.js +1 -2
  65. package/dist/client/project-name.js +3 -1
  66. package/dist/client/reduce.js +77 -3
  67. package/dist/client/relative-time.js +1 -1
  68. package/dist/client/scope-kind.js +6 -3
  69. package/dist/client/search.js +1 -1
  70. package/dist/client/status.js +1 -1
  71. package/dist/client/subagent-tree.js +49 -0
  72. package/dist/client/tool-chains.js +1 -1
  73. package/dist/client/tool-summary.js +28 -18
  74. package/dist/daemon/changes.js +128 -0
  75. package/dist/daemon/commit.js +84 -0
  76. package/dist/daemon/config-store.js +8 -3
  77. package/dist/daemon/config.js +105 -4
  78. package/dist/daemon/diff-excerpts.js +52 -0
  79. package/dist/daemon/git-state.js +197 -0
  80. package/dist/daemon/git.js +53 -10
  81. package/dist/daemon/github-image.js +18 -0
  82. package/dist/daemon/github.js +54 -0
  83. package/dist/daemon/host-control-routes.js +1 -1
  84. package/dist/daemon/host.js +1010 -116
  85. package/dist/daemon/http.js +4 -1
  86. package/dist/daemon/log.js +3 -0
  87. package/dist/daemon/mcp-auth.js +1 -1
  88. package/dist/daemon/models.js +2 -2
  89. package/dist/daemon/pi-model-cache.js +44 -0
  90. package/dist/daemon/pull-request.js +223 -138
  91. package/dist/daemon/push.js +43 -0
  92. package/dist/daemon/repository.js +123 -0
  93. package/dist/daemon/runtime.js +103 -22
  94. package/dist/daemon/secret-store.js +1 -1
  95. package/dist/daemon/server.js +111 -14
  96. package/dist/daemon/session-tool-views.js +22 -0
  97. package/dist/daemon/skills.js +24 -0
  98. package/dist/daemon/spend-ledger.js +118 -0
  99. package/dist/daemon/stack-metadata.js +12 -5
  100. package/dist/daemon/stack.js +162 -657
  101. package/dist/daemon/store.js +2 -0
  102. package/dist/daemon/summariser.js +30 -12
  103. package/dist/daemon/tour.js +56 -0
  104. package/dist/daemon/whisper.js +144 -0
  105. package/dist/daemon/workflow-authoring-scope-checks.js +1 -1
  106. package/dist/daemon/workflow-authoring-scope.js +1 -1
  107. package/dist/daemon/workflow-builder-files.js +2 -2
  108. package/dist/daemon/workflow-builder-guidance.js +1 -1
  109. package/dist/daemon/workflow-builder-routes.js +2 -2
  110. package/dist/daemon/workflow-builder.js +44 -17
  111. package/dist/daemon/workflow-environment.js +193 -0
  112. package/dist/daemon/workflow-execution-launch.js +77 -0
  113. package/dist/daemon/workflow-execution-resources.js +76 -0
  114. package/dist/daemon/workflow-execution-routes.js +17 -8
  115. package/dist/daemon/workflow-execution-values.js +128 -0
  116. package/dist/daemon/workflow-executions.js +434 -305
  117. package/dist/daemon/workflow-mcp-authoring-routes.js +2 -2
  118. package/dist/daemon/workflow-mcp-authoring.js +4 -4
  119. package/dist/daemon/workflow-mcp.js +1 -1
  120. package/dist/daemon/workflow-routes.js +60 -2
  121. package/dist/daemon/workflow-schedule-driver.js +251 -0
  122. package/dist/daemon/workflow-schedule-routes.js +137 -0
  123. package/dist/daemon/workflow-schedules.js +342 -0
  124. package/dist/isolation/filesystem.js +6 -2
  125. package/dist/isolation/sandbox.js +61 -18
  126. package/dist/isolation/shared-sandbox.js +3 -3
  127. package/dist/isolation/toolchain-assets.js +1 -1
  128. package/dist/protocol/events.js +3 -0
  129. package/dist/protocol/plan-limits.js +1 -0
  130. package/dist/protocol/settings.js +1 -0
  131. package/dist/protocol/spend.js +2 -0
  132. package/dist/protocol/stack.js +12 -39
  133. package/dist/protocol/workflow-schedules.js +1 -0
  134. package/dist/workflows/calls.js +53 -0
  135. package/dist/workflows/errors.js +2 -0
  136. package/dist/workflows/executors.js +6 -5
  137. package/dist/workflows/graph.js +83 -9
  138. package/dist/workflows/invocations.js +23 -0
  139. package/dist/workflows/mcp.js +1 -1
  140. package/dist/workflows/owner.js +45 -0
  141. package/dist/workflows/records.js +150 -10
  142. package/dist/workflows/recovery.js +87 -2
  143. package/dist/workflows/runtime-settings.js +16 -16
  144. package/dist/workflows/runtime.js +2 -2
  145. package/dist/workflows/schedule-errors.js +2 -0
  146. package/dist/workflows/schedule-store.js +385 -0
  147. package/dist/workflows/scheduler.js +389 -98
  148. package/dist/workflows/schedules.js +130 -0
  149. package/dist/workflows/schema.js +3 -1
  150. package/dist/workflows/store.js +126 -13
  151. package/package.json +10 -6
  152. package/web/dist/assets/index-C76t-z4w.css +2 -0
  153. package/web/dist/assets/{index-DRfeO6GJ.js → index-WPfbYVQ4.js} +39 -23
  154. package/web/dist/assets/{switch-DIogWclb.js → select-C5Ly2OpB.js} +1 -1
  155. package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-BF-yqpeQ.js} +1 -1
  156. package/web/dist/assets/{settings-secrets-BIO_hXZ1.js → settings-secrets-WLarr2QP.js} +1 -1
  157. package/web/dist/assets/settings-workflows-DdcdRWFD.js +23 -0
  158. package/web/dist/assets/workflow-api-GjAmHc22.js +6 -0
  159. package/web/dist/assets/workflows-BhY3Uibo.js +149 -0
  160. package/web/dist/assets/workflows-pane-DElCcEpN.js +1 -0
  161. package/web/dist/index.html +6 -5
  162. package/build/backend-worker-chunks/chunk-J2DBNTL7.mjs +0 -94
  163. package/build/backend-worker-chunks/claude-GTW5KHY5.mjs +0 -30778
  164. package/dist/daemon/publish.js +0 -289
  165. package/dist/tui/app.js +0 -612
  166. package/dist/tui/keys.js +0 -90
  167. package/dist/tui/render.js +0 -411
  168. package/web/dist/assets/index-DgQFpKbn.css +0 -2
  169. package/web/dist/assets/settings-workflows-H-6eCff3.js +0 -23
  170. package/web/dist/assets/workflow-api-BfExddae.js +0 -6
  171. package/web/dist/assets/workflow-editors-CsbVx4WJ.js +0 -139
  172. package/web/dist/assets/workflows-Bv0sj7d0.js +0 -7
  173. package/web/dist/assets/workflows-pane-DHm44w7P.js +0 -1
  174. /package/dist/protocol/{publish.js → imports.js} +0 -0
@@ -0,0 +1,258 @@
1
+ import { constants, closeSync, fstatSync, lstatSync, openSync, readFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { waitForAbort } from "../worker/rpc.js";
5
+ import { projectPi099RadiusCatalog, projectPiStoredRadiusCatalog, registerPiNativeProvider } from "./model-catalog.js";
6
+ import { parsePiModelConfig } from "./model-config.js";
7
+ import { PiCanonicalJson } from "./canonical-json.js";
8
+ function object(value) {
9
+ return typeof value === "object" && value !== null && !Array.isArray(value);
10
+ }
11
+ function oauth(value) {
12
+ return object(value) && value.type === "oauth" && typeof value.access === "string"
13
+ && typeof value.refresh === "string" && typeof value.expires === "number" && Number.isFinite(value.expires);
14
+ }
15
+ function stringMap(value) {
16
+ return object(value) && Object.values(value).every((entry) => typeof entry === "string");
17
+ }
18
+ function radiusGateways(modelsPath) {
19
+ let fd;
20
+ try {
21
+ if (!lstatSync(modelsPath).isFile())
22
+ throw new Error();
23
+ fd = openSync(modelsPath, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
24
+ }
25
+ catch (error) {
26
+ if (error.code === "ENOENT")
27
+ return new Map();
28
+ throw new Error("Pi models.json must be a readable regular file, not a symbolic link");
29
+ }
30
+ try {
31
+ if (!fstatSync(fd).isFile())
32
+ throw new Error("Pi models.json must be a regular file");
33
+ let raw;
34
+ try {
35
+ raw = parsePiModelConfig(readFileSync(fd, "utf8"));
36
+ }
37
+ catch {
38
+ throw new Error("Invalid Pi models.json: expected valid JSON");
39
+ }
40
+ if (!object(raw))
41
+ throw new Error("Invalid Pi models.json: expected an object");
42
+ const gateways = new Map();
43
+ if (!object(raw.providers))
44
+ return gateways;
45
+ for (const [id, config] of Object.entries(raw.providers)) {
46
+ if (!object(config) || config.oauth !== "radius")
47
+ continue;
48
+ if (!id.trim() || typeof config.baseUrl !== "string")
49
+ throw new Error("Invalid Pi models.json: native Radius requires a gateway URL");
50
+ const base = config.baseUrl.replace(/\/v1\/?$/u, "");
51
+ const gateway = (/^https?:\/\//iu.test(base) ? base : `https://${base}`).replace(/\/+$/u, "");
52
+ try {
53
+ const url = new URL(gateway);
54
+ if ((!/^https?:\/\//iu.test(base) && base.includes('://'))
55
+ || !['https:', 'http:'].includes(url.protocol) || !url.hostname || url.username || url.password || url.search || url.hash
56
+ || /[\s\\!${}\u0000-\u001f\u007f]/u.test(gateway))
57
+ throw new Error();
58
+ }
59
+ catch {
60
+ throw new Error("Invalid Pi models.json: native Radius requires a safe gateway URL");
61
+ }
62
+ gateways.set(id, gateway);
63
+ }
64
+ return gateways;
65
+ }
66
+ finally {
67
+ closeSync(fd);
68
+ }
69
+ }
70
+ function metadata(raw, gateways = new Map()) {
71
+ const entries = Object.entries(raw).flatMap(([providerId, credential]) => {
72
+ if (!object(credential))
73
+ return [];
74
+ if (oauth(credential)) {
75
+ const ids = credential.availableModelIds;
76
+ const cachedModels = projectPi099RadiusCatalog(providerId, credential.gatewayConfig);
77
+ return [{ providerId, check: { type: "oauth", source: "OAuth" },
78
+ ...(Array.isArray(ids) && ids.every((id) => typeof id === "string") ? { availableModelIds: [...ids] } : {}),
79
+ ...(cachedModels ? { cachedModels } : {}), }];
80
+ }
81
+ if (credential.type === "api_key" && (credential.key === undefined || typeof credential.key === "string")
82
+ && (credential.env === undefined || stringMap(credential.env))) {
83
+ return [{ providerId, check: { type: "api_key", source: "stored credential" } }];
84
+ }
85
+ return [];
86
+ });
87
+ for (const [providerId, radiusGateway] of gateways) {
88
+ if (providerId === "radius" && radiusGateway === "https://radius.pi.dev")
89
+ continue;
90
+ const entry = entries.find(entry => entry.providerId === providerId);
91
+ if (entry)
92
+ entry.radiusGateway = radiusGateway;
93
+ else
94
+ entries.push({ providerId, radiusGateway });
95
+ }
96
+ return entries;
97
+ }
98
+ class CanonicalCatalogs extends PiCanonicalJson {
99
+ constructor(path) { super(path, "models-store.json"); }
100
+ async importLegacy(providerId, models, signal) {
101
+ await this.locked((raw, assertLock) => {
102
+ if (Object.hasOwn(raw, providerId)) {
103
+ if (!object(raw[providerId]) || !Array.isArray(raw[providerId].models))
104
+ throw new Error("Invalid Pi models-store.json: expected a catalog");
105
+ return;
106
+ }
107
+ assertLock();
108
+ this.writeRaw({ ...raw, [providerId]: { models, checkedAt: Date.now() } });
109
+ assertLock();
110
+ }, signal, true);
111
+ }
112
+ }
113
+ class CanonicalCredentials extends PiCanonicalJson {
114
+ catalogs;
115
+ constructor(authPath, catalogs) { super(authPath, "auth.json"); this.catalogs = catalogs; }
116
+ async read(providerId, options) {
117
+ const raw = await this.raw(options?.signal);
118
+ const credential = Object.hasOwn(raw, providerId) ? raw[providerId] : undefined;
119
+ return oauth(credential) ? structuredClone(credential) : undefined;
120
+ }
121
+ async list(options) {
122
+ return metadata(await this.raw(options?.signal)).map(({ providerId, check }) => ({ providerId, type: check.type }));
123
+ }
124
+ async modify(providerId, fn, options) {
125
+ return this.locked(async (raw, assertLock) => {
126
+ const current = Object.hasOwn(raw, providerId) ? raw[providerId] : undefined;
127
+ if (!oauth(current))
128
+ return undefined;
129
+ const legacy = projectPi099RadiusCatalog(providerId, current.gatewayConfig);
130
+ if (legacy)
131
+ await this.catalogs.importLegacy(providerId, legacy, options?.signal);
132
+ assertLock();
133
+ const next = await fn(structuredClone(current));
134
+ assertLock();
135
+ options?.signal?.throwIfAborted();
136
+ if (next !== undefined) {
137
+ if (!oauth(next))
138
+ throw new Error("Pi host can only persist OAuth credentials");
139
+ raw[providerId] = next;
140
+ this.writeRaw(raw);
141
+ assertLock();
142
+ }
143
+ return next ?? current;
144
+ }, options?.signal);
145
+ }
146
+ async delete() {
147
+ throw new Error("Pi host credential deletion is not supported");
148
+ }
149
+ }
150
+ export function createPiModelAuth(options = {}) {
151
+ const path = options.authPath ?? join(process.env.PI_CODING_AGENT_DIR || join(homedir(), '.pi/agent'), 'auth.json');
152
+ const authPath = resolve(/^~[\\/\\\\]/.test(path) ? join(homedir(), path.slice(2)) : path);
153
+ const catalogs = new CanonicalCatalogs(join(dirname(authPath), "models-store.json"));
154
+ const store = new CanonicalCredentials(authPath, catalogs);
155
+ const modelsPath = join(dirname(authPath), "models.json");
156
+ const registeredGateways = new Map();
157
+ let runtime;
158
+ const pending = new Map();
159
+ const admitted = new Set();
160
+ let closing;
161
+ let closed = false;
162
+ function admit(operation) {
163
+ if (closed)
164
+ return Promise.reject(new Error("Pi model auth is closed"));
165
+ const result = Promise.resolve().then(operation);
166
+ admitted.add(result);
167
+ void result.then(() => admitted.delete(result), () => admitted.delete(result));
168
+ return result;
169
+ }
170
+ return {
171
+ close() {
172
+ closed = true;
173
+ closing ??= (async () => {
174
+ await Promise.allSettled([...admitted]);
175
+ await Promise.allSettled([...pending.values()]);
176
+ })();
177
+ return closing;
178
+ },
179
+ snapshot(signal) {
180
+ return admit(async () => {
181
+ const raw = await store.raw(signal);
182
+ signal?.throwIfAborted();
183
+ const entries = metadata(raw, radiusGateways(modelsPath));
184
+ const radius = entries.filter(entry => entry.check && (entry.providerId === "radius" || entry.radiusGateway !== undefined || entry.cachedModels !== undefined));
185
+ if (radius.length) {
186
+ const stored = await catalogs.raw(signal);
187
+ signal?.throwIfAborted();
188
+ for (const entry of radius) {
189
+ const models = projectPiStoredRadiusCatalog(entry.providerId, stored[entry.providerId]);
190
+ if (models)
191
+ entry.cachedModels = models;
192
+ }
193
+ }
194
+ return entries;
195
+ });
196
+ },
197
+ resolve(providerId, signal) {
198
+ return admit(async () => {
199
+ signal?.throwIfAborted();
200
+ if (typeof providerId !== "string" || !providerId)
201
+ throw new Error("Unknown Pi provider");
202
+ const raw = await store.raw(signal);
203
+ signal?.throwIfAborted();
204
+ if (!metadata(raw).some((entry) => entry.providerId === providerId))
205
+ throw new Error("Unknown Pi provider");
206
+ const gateways = radiusGateways(modelsPath);
207
+ const credential = raw[providerId];
208
+ if (object(credential) && credential.type === "api_key") {
209
+ if (typeof credential.key === "string" && credential.key.startsWith("!")) {
210
+ throw new Error("Pi host refuses !command credentials in auth.json. Move the command to models.json so it runs only in the worker.");
211
+ }
212
+ return { auth: { ...(typeof credential.key === "string" ? { apiKey: credential.key } : {}) },
213
+ ...(stringMap(credential.env) ? { env: { ...credential.env } } : {}), source: "stored credential" };
214
+ }
215
+ runtime ??= import('@earendil-works/pi-coding-agent').then(({ ModelRuntime }) => ModelRuntime.create({ credentials: store, modelsPath: null, refreshOnCreate: false }));
216
+ const current = await waitForAbort(runtime, signal);
217
+ signal?.throwIfAborted();
218
+ const gateway = gateways.get(providerId);
219
+ if (gateway !== undefined || (providerId === "radius" && registeredGateways.has(providerId))) {
220
+ const signature = gateway ?? "https://radius.pi.dev";
221
+ if (registeredGateways.get(providerId) !== signature) {
222
+ const { radiusProvider } = await import('@earendil-works/pi-ai/providers/all');
223
+ signal?.throwIfAborted();
224
+ if (registeredGateways.get(providerId) !== signature) {
225
+ registerPiNativeProvider(current, radiusProvider({ id: providerId, gateway: signature }));
226
+ registeredGateways.set(providerId, signature);
227
+ }
228
+ }
229
+ }
230
+ else if (registeredGateways.has(providerId)) {
231
+ throw new Error(`Pi provider ${providerId} does not support native OAuth`);
232
+ }
233
+ const provider = current.getProvider(providerId);
234
+ if (!provider?.auth.oauth)
235
+ throw new Error(`Pi provider ${providerId} does not support native OAuth`);
236
+ delete provider.auth.apiKey;
237
+ let operation = pending.get(providerId);
238
+ if (!operation) {
239
+ operation = current.getAuth(providerId).then((result) => result ? {
240
+ auth: {
241
+ ...(result.auth.apiKey !== undefined ? { apiKey: result.auth.apiKey } : {}),
242
+ ...(result.auth.headers ? { headers: result.auth.headers } : {}),
243
+ ...(result.auth.baseUrl !== undefined ? { baseUrl: result.auth.baseUrl } : {}),
244
+ },
245
+ ...(result.env ? { env: result.env } : {}),
246
+ ...(result.source !== undefined ? { source: result.source } : {}),
247
+ } : undefined);
248
+ pending.set(providerId, operation);
249
+ const owned = operation;
250
+ void operation.then(() => { if (pending.get(providerId) === owned)
251
+ pending.delete(providerId); }, () => { if (pending.get(providerId) === owned)
252
+ pending.delete(providerId); });
253
+ }
254
+ return waitForAbort(operation, signal);
255
+ });
256
+ },
257
+ };
258
+ }
@@ -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
+ }