@fastagent-sh/fastagent 0.19.0 → 0.20.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 (131) hide show
  1. package/dist/atomic-write.d.ts +11 -7
  2. package/dist/atomic-write.js +16 -11
  3. package/dist/channels/agentcore-limits.d.ts +9 -0
  4. package/dist/channels/agentcore-limits.js +9 -0
  5. package/dist/channels/agentcore-service.d.ts +12 -11
  6. package/dist/channels/agentcore-service.js +14 -18
  7. package/dist/channels/agentcore.d.ts +11 -19
  8. package/dist/channels/agentcore.js +14 -7
  9. package/dist/channels/control.d.ts +50 -12
  10. package/dist/channels/control.js +239 -96
  11. package/dist/channels/discover.d.ts +26 -4
  12. package/dist/channels/discover.js +12 -23
  13. package/dist/channels/feishu/feishu-api.js +5 -8
  14. package/dist/channels/feishu/feishu.js +35 -18
  15. package/dist/channels/kit/attachment-path.d.ts +12 -0
  16. package/dist/channels/kit/attachment-path.js +43 -0
  17. package/dist/channels/kit/context-buffer.d.ts +9 -0
  18. package/dist/channels/kit/context-buffer.js +11 -0
  19. package/dist/channels/kit/signature.d.ts +12 -0
  20. package/dist/channels/kit/signature.js +17 -0
  21. package/dist/channels/kit/stop-command.js +3 -3
  22. package/dist/channels/kit/tasks.d.ts +1 -1
  23. package/dist/channels/kit/tasks.js +10 -4
  24. package/dist/channels/kit/turn-store.d.ts +19 -3
  25. package/dist/channels/kit/turn-store.js +29 -2
  26. package/dist/channels/slack/invoke-turn.d.ts +1 -1
  27. package/dist/channels/slack/invoke-turn.js +5 -1
  28. package/dist/channels/slack/onboard.js +5 -5
  29. package/dist/channels/slack/onboarding-state.d.ts +7 -3
  30. package/dist/channels/slack/onboarding-state.js +13 -20
  31. package/dist/channels/slack/register-webhook.js +1 -1
  32. package/dist/channels/slack/scaffold/slack-send.ts +2 -17
  33. package/dist/channels/slack/slack-api.js +22 -54
  34. package/dist/channels/slack/slack.js +13 -13
  35. package/dist/channels/telegram/parse.d.ts +21 -1
  36. package/dist/channels/telegram/parse.js +65 -11
  37. package/dist/channels/telegram/scaffold/channel.ts +7 -3
  38. package/dist/channels/telegram/telegram-api.js +5 -6
  39. package/dist/channels/telegram/telegram.d.ts +2 -2
  40. package/dist/channels/telegram/telegram.js +57 -69
  41. package/dist/cli/add-slack.js +6 -5
  42. package/dist/cli/commands/add.js +1 -5
  43. package/dist/cli/commands/attach.d.ts +2 -4
  44. package/dist/cli/commands/attach.js +17 -15
  45. package/dist/cli/commands/deploy.d.ts +50 -5
  46. package/dist/cli/commands/deploy.js +183 -134
  47. package/dist/cli/commands/dev.js +4 -31
  48. package/dist/cli/commands/info.js +1 -2
  49. package/dist/cli/commands/init.js +1 -2
  50. package/dist/cli/commands/start.js +31 -41
  51. package/dist/cli/serve.d.ts +12 -21
  52. package/dist/cli/serve.js +20 -25
  53. package/dist/cli/shared.d.ts +40 -10
  54. package/dist/cli/shared.js +51 -4
  55. package/dist/deploy/agentcore/logs.d.ts +2 -2
  56. package/dist/deploy/agentcore/logs.js +2 -2
  57. package/dist/deploy/agentcore/plan.d.ts +12 -10
  58. package/dist/deploy/agentcore/plan.js +39 -31
  59. package/dist/deploy/agentcore/run.d.ts +5 -4
  60. package/dist/deploy/agentcore/run.js +13 -36
  61. package/dist/deploy/channel-ingress.d.ts +73 -0
  62. package/dist/deploy/channel-ingress.js +101 -0
  63. package/dist/deploy/docker/plan.d.ts +3 -7
  64. package/dist/deploy/docker/plan.js +4 -15
  65. package/dist/deploy/docker/run.d.ts +18 -1
  66. package/dist/deploy/docker/run.js +10 -0
  67. package/dist/deploy/fly/plan.d.ts +4 -5
  68. package/dist/deploy/fly/plan.js +7 -22
  69. package/dist/deploy/fly/run.d.ts +9 -23
  70. package/dist/deploy/fly/run.js +32 -68
  71. package/dist/deploy/preflight.d.ts +6 -7
  72. package/dist/deploy/preflight.js +26 -22
  73. package/dist/deploy/railway/plan.d.ts +4 -5
  74. package/dist/deploy/railway/plan.js +11 -26
  75. package/dist/deploy/railway/run.d.ts +9 -9
  76. package/dist/deploy/railway/run.js +40 -40
  77. package/dist/deploy/runner.js +22 -2
  78. package/dist/deploy/secrets.d.ts +18 -9
  79. package/dist/deploy/secrets.js +64 -12
  80. package/dist/dev-supervisor.js +3 -4
  81. package/dist/engines/pi/agent-session-factory.js +20 -39
  82. package/dist/engines/pi/auth.js +43 -43
  83. package/dist/engines/pi/config.d.ts +1 -1
  84. package/dist/engines/pi/create.d.ts +14 -2
  85. package/dist/engines/pi/create.js +2 -2
  86. package/dist/engines/pi/definition.d.ts +1 -1
  87. package/dist/engines/pi/definition.js +3 -4
  88. package/dist/engines/pi/login.js +32 -16
  89. package/dist/engines/pi/open.d.ts +1 -2
  90. package/dist/engines/pi/open.js +1 -1
  91. package/dist/engines/pi/search-tools.js +1 -1
  92. package/dist/engines/pi/service.d.ts +1 -1
  93. package/dist/engines/pi/service.js +8 -0
  94. package/dist/engines/pi/session-builder.js +6 -33
  95. package/dist/engines/pi/session-control.d.ts +19 -6
  96. package/dist/engines/pi/session-control.js +565 -470
  97. package/dist/engines/pi/session-inheritance.d.ts +8 -22
  98. package/dist/engines/pi/session-inheritance.js +95 -76
  99. package/dist/engines/pi/session-markers.d.ts +48 -0
  100. package/dist/engines/pi/session-markers.js +59 -0
  101. package/dist/engines/pi/session-settings.d.ts +4 -4
  102. package/dist/engines/pi/session-settings.js +7 -4
  103. package/dist/engines/pi/session-store.d.ts +83 -13
  104. package/dist/engines/pi/session-store.js +408 -55
  105. package/dist/engines/pi/tool-context.d.ts +21 -8
  106. package/dist/engines/pi/tool-context.js +29 -4
  107. package/dist/engines/pi/tool.js +2 -2
  108. package/dist/env.js +1 -2
  109. package/dist/loader.d.ts +49 -7
  110. package/dist/loader.js +79 -18
  111. package/dist/paths.d.ts +19 -0
  112. package/dist/paths.js +27 -2
  113. package/dist/scaffold/add-channel.js +2 -2
  114. package/dist/scaffold/init.js +7 -2
  115. package/dist/scaffold/templates/tools/fetch-url.ts +0 -2
  116. package/dist/schedule/discover.js +3 -15
  117. package/dist/schedule/wake-alarm.d.ts +13 -7
  118. package/dist/schedule/wake-alarm.js +88 -46
  119. package/dist/schedule/wakeups.d.ts +1 -1
  120. package/dist/schedule/wakeups.js +10 -7
  121. package/dist/service.d.ts +1 -2
  122. package/dist/service.js +27 -5
  123. package/dist/session-remote.d.ts +7 -2
  124. package/dist/session-remote.js +162 -92
  125. package/dist/session.d.ts +226 -92
  126. package/dist/session.js +61 -23
  127. package/dist/telegram.d.ts +1 -1
  128. package/dist/telegram.js +1 -1
  129. package/dist/tunnel.d.ts +18 -3
  130. package/dist/tunnel.js +32 -40
  131. package/package.json +1 -1
@@ -6,11 +6,13 @@
6
6
  * to run on) are the same v3 jsonl and are continued in place — see `legacySessionId`. That is a
7
7
  * READ path for existing conversations, not a second engine.
8
8
  */
9
- import { existsSync, mkdirSync, renameSync, writeFileSync } from "node:fs";
9
+ import { existsSync, mkdirSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
10
10
  import { basename, dirname, join, resolve } from "node:path";
11
11
  import { SessionManager } from "@earendil-works/pi-coding-agent";
12
12
  import { log } from "../../log.js";
13
- import { copyBranchInto, forkForInheritance, inheritanceCut } from "./session-inheritance.js";
13
+ import { LEAF_ANCHOR, publishedLeaf, stampProvenance } from "./session-markers.js";
14
+ import { activePath } from "./session-settings.js";
15
+ import { copyBranchForInheritance, copyBranchInto, inheritanceCut, } from "./session-inheritance.js";
14
16
  /**
15
17
  * A Caller's session id, as a name pi will accept.
16
18
  *
@@ -43,24 +45,51 @@ export function piSessionId(sessionId) {
43
45
  const body = sessionId.replace(/[^A-Za-z0-9.-]/g, hex).replace(/[.-]$/, hex);
44
46
  return `s${body}`;
45
47
  }
48
+ /**
49
+ * {@link piSessionId} backwards — what `list()` needs, because a session id belongs to the CALLER and
50
+ * a record name is storage detail. The encoding is self-describing (fixed widths, `_` escapes
51
+ * itself), so this is a decode rather than a guess; a name this store did not write (no `s` head, a
52
+ * truncated escape) answers undefined and is left out of the listing rather than reported under a
53
+ * name nobody can dial.
54
+ */
55
+ export function callerSessionId(recordId) {
56
+ if (!recordId.startsWith("s"))
57
+ return undefined;
58
+ let out = "";
59
+ for (let i = 1; i < recordId.length; i++) {
60
+ const c = recordId[i];
61
+ if (c !== "_") {
62
+ out += c;
63
+ continue;
64
+ }
65
+ const wide = recordId[i + 1] === "u";
66
+ const start = i + (wide ? 2 : 1);
67
+ const width = wide ? 4 : 2;
68
+ const hex = recordId.slice(start, start + width);
69
+ if (hex.length !== width || !/^[0-9A-F]+$/.test(hex))
70
+ return undefined;
71
+ out += String.fromCharCode(Number.parseInt(hex, 16));
72
+ i = start + width - 1;
73
+ }
74
+ return out;
75
+ }
46
76
  /**
47
77
  * Disk-backed store under `dir`: restart the process, conversations continue.
48
78
  *
49
- * Lookup is a directory scan (`SessionManager.list`) because pi names files `<timestamp>_<id>.jsonl`
50
- * and the timestamp is not ours to predict the same trade sessions.ts makes today.
51
- *
52
- * A record written before this store existed keeps ITS id (the older path spelled them differently),
53
- * so the scan accepts either: a conversation that predates this store is continued rather than
54
- * silently restarted as an empty one. Nothing is rewritten on disk.
79
+ * Lookup is a directory scan of THIS store's own directory, reading ids out of the filenames pi
80
+ * writes (`<timestamp>_<id>.jsonl`) not `SessionManager.list`, which filters by the cwd recorded in
81
+ * each header and would make a renamed agent directory look like an empty store (see
82
+ * {@link recordFiles}).
55
83
  *
56
84
  * NEW records live in a subdirectory of their own, because the two engines cannot share a namespace:
57
85
  * both spell ids into `[A-Za-z0-9._-]`, so neither can claim a prefix the other cannot produce, and
58
86
  * a directory holding both would have names that belong to two conversations at once — in whichever
59
87
  * direction it is read. Separate directories make each side's own injectivity sufficient.
60
88
  *
61
- * A PRE-EXISTING record is still continued in place: it is looked up by the older spelling, which is
62
- * injective on its own terms, and appended to where it lies. Both spellings are the same v3 jsonl,
63
- * so a conversation started before this store keeps going rather than restarting empty.
89
+ * A PRE-EXISTING record is continued in place: looked up by the older spelling, which is injective
90
+ * on its own terms, and appended to where it lies. Both spellings are the same v3 jsonl, so a
91
+ * conversation started before this store keeps going rather than restarting empty. Nothing on disk
92
+ * is rewritten.
64
93
  *
65
94
  * SCOPE OF "open-or-create": idempotent against a store that is serialized per session, which is what
66
95
  * the serving path provides — the single-writer lease is taken before any store call, so no two
@@ -80,74 +109,363 @@ export function piSessionRecordStore(options) {
80
109
  /** Where a forked record is finished before it becomes discoverable. A SUBDIRECTORY of the store,
81
110
  * so `list()` (one level, `*.jsonl`) never sees a record that is still being prepared. */
82
111
  const staging = join(own, ".staging");
112
+ /** An empty record under `id`, ON DISK (see {@link materialize}) and not yet discoverable. Copying
113
+ * into it appends immediately, so a crash leaves a partial record in staging rather than a
114
+ * complete-looking one under the id. */
115
+ const stage = (id) => {
116
+ mkdirSync(staging, { recursive: true });
117
+ return materialize(SessionManager.create(cwd, staging, { id }), staging);
118
+ };
119
+ /** Fill a staged record and move it in — or leave nothing behind. The partial file is deleted on
120
+ * the way out and the failure is rethrown untouched: `fork` turns it into a coded result and
121
+ * inheritance falls back to an empty session, but neither can see `.staging`, which would
122
+ * otherwise accumulate a file per failed attempt (ENOSPC being the realistic repeat offender) in
123
+ * a directory nothing ever reads. */
124
+ const fillStaged = (id, fill) => {
125
+ const staged = stage(id);
126
+ // WHERE the record is, so cleanup deletes the file that exists rather than the path it used to
127
+ // have: after the rename, removing the staging path succeeds against nothing while the record it
128
+ // was supposed to undo sits in the store.
129
+ let published;
130
+ try {
131
+ fill(staged);
132
+ // Publishing is a mkdir + rename, and both can fail (EACCES, a store root on another
133
+ // filesystem) — a finished record stranded in staging is the same accumulation as a partial
134
+ // one. NOT covered by a test: the tests reach a fill failure by making a copy throw, and there
135
+ // is no equivalent injection point for rename without mocking node:fs for the whole file.
136
+ published = publishStaged(staged);
137
+ return SessionManager.open(published, own);
138
+ }
139
+ catch (error) {
140
+ rmSync(published ?? staged.getSessionFile() ?? "", { force: true });
141
+ throw error;
142
+ }
143
+ };
144
+ /** Move a finished record into the store: one same-filesystem rename, so a reader sees the whole
145
+ * thing or nothing at all. Answers WHERE it landed — the caller opens it, and can undo it. */
146
+ const publishStaged = (staged) => {
147
+ const file = staged.getSessionFile();
148
+ if (!file)
149
+ throw new Error(`staged record ${staged.getSessionId()} has no file to publish`);
150
+ mkdirSync(own, { recursive: true });
151
+ const target = join(own, basename(file));
152
+ renameSync(file, target);
153
+ return target;
154
+ };
83
155
  /** Fork the named parent into `id`, or answer undefined so the caller starts empty. Every failure
84
156
  * is a warn: a thread must not lose its first turn to an inheritance edge. */
85
- const inheritInto = async (id, inherit) => {
86
- const parentId = piSessionId(inherit.parentSession);
87
- const found = (await SessionManager.list(cwd, own)).find((r) => r.id === parentId) ??
88
- (await SessionManager.list(cwd, root)).find((r) => r.id === legacySessionId(inherit.parentSession));
157
+ const inheritInto = async (sessionId, inherit) => {
158
+ const found = locate(inherit.parentSession);
89
159
  if (!found) {
90
- log.warn(`[fastagent] session "${id}" names parent "${inherit.parentSession}", which has no record — starting empty`);
160
+ log.warn(`[fastagent] session "${sessionId}" names parent "${inherit.parentSession}", which has no record — starting empty`);
91
161
  return undefined;
92
162
  }
93
163
  try {
94
- const parentDir = found.id === parentId ? own : root;
95
- mkdirSync(staging, { recursive: true });
96
- const staged = forkForInheritance({
97
- // A parent that crashed mid tool-execution would otherwise pass its dangling tool_use down
98
- // to the child, whose very first request the provider then rejects.
99
- parent: reconcileInterruptedToolCalls(SessionManager.open(found.path, parentDir)),
100
- id,
101
- cwd,
102
- stagingDir: staging,
103
- branchHints: inherit.branchHints,
104
- });
105
- if (!staged)
164
+ // A parent that crashed mid tool-execution would otherwise pass its dangling tool_use down
165
+ // to the child, whose very first request the provider then rejects.
166
+ const parent = reconcileInterruptedToolCalls(SessionManager.open(found.path, found.dir));
167
+ const cut = inheritanceCut(parent, inherit.branchHints);
168
+ if (!cut)
106
169
  return undefined;
107
- // Publish only once the record is complete: same-filesystem rename, so a reader sees the whole
108
- // thing or nothing at all.
109
- const stagedFile = staged.getSessionFile();
110
- if (!stagedFile)
111
- return staged; // non-persisting backend: nothing to publish
112
- const target = join(own, basename(stagedFile));
113
- renameSync(stagedFile, target);
114
- return SessionManager.open(target, own);
170
+ return fillStaged(piSessionId(sessionId), (staged) => copyBranchForInheritance(parent, staged, cut.at));
115
171
  }
116
172
  catch (error) {
117
173
  // Unattributed on purpose: this spans reading the parent AND writing the child.
118
- log.warn(`[fastagent] could not inherit from "${inherit.parentSession}" into "${id}" (${String(error)}) — starting empty`);
174
+ log.warn(`[fastagent] could not inherit from "${inherit.parentSession}" into "${sessionId}" (${String(error)}) — starting empty`);
119
175
  return undefined;
120
176
  }
121
177
  };
178
+ /** The unreadable records the last listing reported, so a polled endpoint states the condition
179
+ * once rather than once a second. */
180
+ let lastUnreadable = "";
181
+ /** WHERE a session's record is, under either spelling — the one lookup every caller shares, so a
182
+ * fix to it (this store's own directory rather than pi's cwd-filtered listing) cannot reach three
183
+ * of the four. */
184
+ const locate = (sessionId) => {
185
+ const mine = recordFiles(own).find((f) => f.id === piSessionId(sessionId));
186
+ if (mine)
187
+ return { path: mine.path, dir: own };
188
+ const legacy = recordFiles(root).find((f) => f.id === legacySessionId(sessionId));
189
+ return legacy ? { path: legacy.path, dir: root } : undefined;
190
+ };
191
+ /** Open an existing record, or undefined. A closure rather than a method call, so `fork` cannot be
192
+ * broken by a caller that spreads this object into another one. */
193
+ const openExisting = async (sessionId) => {
194
+ const found = locate(sessionId);
195
+ return found ? SessionManager.open(found.path, found.dir) : undefined;
196
+ };
122
197
  return {
123
198
  async openOrCreate(sessionId, inherit) {
124
- const id = piSessionId(sessionId);
125
- const mine = (await SessionManager.list(cwd, own)).find((r) => r.id === id);
126
- if (mine)
127
- return reconcileInterruptedToolCalls(SessionManager.open(mine.path, own));
128
- const legacy = (await SessionManager.list(cwd, root)).find((r) => r.id === legacySessionId(sessionId));
129
- if (legacy)
130
- return reconcileInterruptedToolCalls(SessionManager.open(legacy.path, root));
199
+ const found = locate(sessionId);
200
+ if (found)
201
+ return reconcileInterruptedToolCalls(SessionManager.open(found.path, found.dir));
131
202
  mkdirSync(own, { recursive: true });
132
203
  // Inheritance is a CREATE-path decision: an existing session above ignores it entirely, which
133
204
  // is what makes it one-time by construction.
134
205
  if (inherit) {
135
- const inherited = await inheritInto(id, inherit);
206
+ const inherited = await inheritInto(sessionId, inherit);
136
207
  if (inherited)
137
208
  return inherited;
138
209
  }
139
- return publish(SessionManager.create(cwd, own, { id }), own);
210
+ // The CALLER's id in every message above; pi's spelling only where pi names the file.
211
+ return materialize(SessionManager.create(cwd, own, { id: piSessionId(sessionId) }), own);
140
212
  },
141
- async openIfExists(sessionId) {
142
- const id = piSessionId(sessionId);
143
- const mine = (await SessionManager.list(cwd, own)).find((r) => r.id === id);
144
- if (mine)
145
- return SessionManager.open(mine.path, own);
146
- const legacy = (await SessionManager.list(cwd, root)).find((r) => r.id === legacySessionId(sessionId));
147
- return legacy ? SessionManager.open(legacy.path, root) : undefined;
213
+ openIfExists: openExisting,
214
+ applyProperties: (sessionId, writes) => applyProperties(() => openExisting(sessionId), writes),
215
+ async list() {
216
+ const files = recordFiles(own);
217
+ const rows = [];
218
+ const unreadable = [];
219
+ for (const file of files) {
220
+ // A record this store did not write (the older spelling) cannot be decoded back to a Caller
221
+ // id, and a row nobody can dial is worse than a row that is missing. It stays openable BY id.
222
+ const session = callerSessionId(file.id);
223
+ if (!session)
224
+ continue;
225
+ try {
226
+ rows.push(summarize(session, SessionManager.open(file.path, own)));
227
+ }
228
+ catch (error) {
229
+ // ONE unreadable record must not take the listing down — the other conversations are fine,
230
+ // and a GUI that shows nothing is worse than one missing a row. But it must not vanish
231
+ // silently either: that is the same conflation `sessions_unavailable` prevents one level
232
+ // up, just per record. Named, with its reason, every time it is polled: a record that
233
+ // cannot be read is a condition someone has to act on.
234
+ unreadable.push(`${basename(file.path)} (${String(error)})`);
235
+ }
236
+ // A TURN for everything else. Reading a record is synchronous (pi parses the whole file and
237
+ // builds its index), and this endpoint is POLLED — so without a yield the process stops for
238
+ // the length of the whole listing, once a second, while SSE heartbeats and in-flight turns
239
+ // wait. pi's own listing streamed and interleaved; this reads faster and must not take that
240
+ // away.
241
+ await new Promise((resolve) => setImmediate(resolve));
242
+ }
243
+ // NEWEST ACTIVITY first. The filenames sort by CREATION, so an old conversation that just
244
+ // received a message would otherwise sit below a newer idle one — the wrong answer for the
245
+ // column a conversation list is read by.
246
+ rows.sort((a, b) => b.updatedAt - a.updatedAt);
247
+ // Said when the SET changes, not on every poll: this endpoint is polled once a second or so,
248
+ // and an unreadable record stays unreadable until someone acts on it.
249
+ const reported = unreadable.join("; ");
250
+ if (reported !== lastUnreadable) {
251
+ lastUnreadable = reported;
252
+ if (unreadable.length > 0) {
253
+ log.warn(`[fastagent] ${unreadable.length} of ${files.length} session records in ${own} could not be read and are missing from this listing: ${reported}`);
254
+ }
255
+ }
256
+ return rows;
257
+ },
258
+ async fork(from, at, into, provenance) {
259
+ const parent = await openExisting(from);
260
+ if (!parent)
261
+ throw new Error(`session "${from}" has no record`);
262
+ // The port promises a NEW record, so the guarantee belongs here rather than in the one caller
263
+ // that happens to check: two records under one id makes which one a lookup finds a matter of
264
+ // directory order.
265
+ if (await openExisting(into))
266
+ throw new Error(`session "${into}" already exists`);
267
+ fillStaged(piSessionId(into), (staged) => {
268
+ // METADATA FIRST, history last. pi has one leaf pointer and every append advances it, so
269
+ // whatever is written last becomes the fork's `leafEntryId` — and a client opening a fresh
270
+ // fork would find its head on an empty `custom` record instead of on the exchange it forked
271
+ // at. The name and the provenance describe the record; the history is what the session IS.
272
+ const name = parent.getSessionName();
273
+ // The name travels: a fork of "Deploy notes" that lists as untitled is a row a user cannot
274
+ // place. A client that wants "(copy)" calls `update({ name })`.
275
+ if (name)
276
+ staged.appendSessionInfo(name);
277
+ stampProvenance(staged, provenance);
278
+ // NOT reconciled: the repair appends at the parent's LEAF, which a copy stopping at `at` can
279
+ // never reach — it would only write to the record being copied FROM. The child is reconciled
280
+ // on its own first open, like every other record.
281
+ copyBranchInto(parent, staged, at);
282
+ });
283
+ },
284
+ async delete(sessionId) {
285
+ const found = locate(sessionId);
286
+ if (!found)
287
+ return false;
288
+ // A record that cannot be deleted must not report success — the caller turns the throw into a
289
+ // coded failure, and the session is still there for the next attempt.
290
+ rmSync(found.path);
291
+ return true;
148
292
  },
149
293
  };
150
294
  }
295
+ /**
296
+ * The property write, for both backends: the ONE place that knows how pi records a property.
297
+ *
298
+ * ORDER IS THE POINT. pi has a single leaf pointer and every append advances it, so the leaf ends up
299
+ * wherever the last write landed — which is why the move goes FIRST (the properties below it must
300
+ * hang off the branch the caller asked for, not the one it left) and why a fork writes its metadata
301
+ * before its history (session-store's `fork`). The handle is opened HERE, inside the caller's lease:
302
+ * one taken earlier could be a snapshot of a run that finished in the window, and appending to it
303
+ * would hang the property off a stale leaf.
304
+ */
305
+ async function applyProperties(open, writes) {
306
+ const record = await open();
307
+ if (!record)
308
+ return undefined;
309
+ const landed = [];
310
+ let moved = false;
311
+ let failure;
312
+ try {
313
+ if (writes.leafEntryId !== undefined) {
314
+ // A move to where the head ALREADY is asks for nothing: a client retry, or a UI firing on
315
+ // every selection, must not grow the session. Compared against the PUBLISHED head, because
316
+ // pi's leaf may be the anchor a previous move left there.
317
+ if (publishedLeaf(record) !== writes.leafEntryId) {
318
+ record.branch(writes.leafEntryId);
319
+ moved = true;
320
+ }
321
+ landed.push("leafEntryId");
322
+ }
323
+ if (writes.model) {
324
+ record.appendModelChange(writes.model.provider, writes.model.id);
325
+ landed.push("model");
326
+ }
327
+ if (writes.thinkingLevel !== undefined) {
328
+ record.appendThinkingLevelChange(writes.thinkingLevel);
329
+ landed.push("thinkingLevel");
330
+ }
331
+ if (writes.name !== undefined) {
332
+ record.appendSessionInfo(writes.name);
333
+ landed.push("name");
334
+ }
335
+ }
336
+ catch (error) {
337
+ // Held, not rethrown: what already landed still has to be reported, and the report is the only
338
+ // way a caller learns the record moved.
339
+ failure = error;
340
+ }
341
+ // THE ANCHOR, outside the try so a failed property write cannot skip it — that is precisely the
342
+ // case reporting a MOVE as landed. pi's `branch()` writes nothing (the leaf is runtime state, and
343
+ // `open()` puts it back on the file's last entry), so a move nothing followed is forgotten the
344
+ // moment anything reopens the record. Appending anything pins it; this appends only when nothing
345
+ // else in the patch already did.
346
+ if (moved && record.getLeafId() === writes.leafEntryId) {
347
+ try {
348
+ record.appendCustomEntry(LEAF_ANCHOR, {});
349
+ }
350
+ catch (error) {
351
+ // The move is runtime-only and will not survive the next open, so it did NOT land: saying it
352
+ // did is the one thing a partial report cannot afford. A first failure keeps its place — it is
353
+ // what stopped the patch — and this one is reported when nothing else went wrong.
354
+ landed.splice(landed.indexOf("leafEntryId"), 1);
355
+ failure ??= error;
356
+ }
357
+ }
358
+ // READ BACK, never echo: pi rewrites a name (newlines collapse, ends trim), and the settings a
359
+ // path resolves to can change under a moved leaf. The caller reports THIS, so `state()` and
360
+ // `list()` cannot disagree with what it said.
361
+ const name = record.getSessionName();
362
+ // The PUBLISHED head, not pi's: the anchor above is ours, and a client must be told the position
363
+ // it asked for — the one it can find in `entries()`.
364
+ const leafEntryId = publishedLeaf(record);
365
+ let path;
366
+ try {
367
+ path = activePath(record);
368
+ }
369
+ catch (error) {
370
+ // An unreadable chain is the caller's decision (design §7), not a silent short path. The writes
371
+ // are already durable either way.
372
+ log.warn(`[fastagent] session ${record.getSessionId()}: written, active path unreadable: ${String(error)}`);
373
+ }
374
+ return {
375
+ landed,
376
+ ...(failure !== undefined ? { failure } : {}),
377
+ ...(name ? { name } : {}),
378
+ ...(leafEntryId ? { leafEntryId } : {}),
379
+ ...(path ? { path } : {}),
380
+ };
381
+ }
382
+ /**
383
+ * The record files in a directory, newest first — pi names them `<ISO timestamp>_<id>.jsonl`, so the
384
+ * name sorts by time and carries the id without opening anything.
385
+ *
386
+ * OUR readdir, not pi's `SessionManager.list`, and the difference is the reason this exists: that one
387
+ * filters by the cwd recorded in each header — right for a TUI showing "this project's sessions",
388
+ * wrong for a repository, where renaming the agent directory made every conversation vanish from the
389
+ * listing AND from lookup, so the next turn started an empty session on top of the old one. It also
390
+ * swallows per-file faults, which a listing needs to see.
391
+ *
392
+ * ENOENT is the one condition that is not a fault: a store nobody has written to holds no records.
393
+ * Anything else — an unreadable ancestor, a file where the directory should be — travels with its
394
+ * code, because "this deployment has no conversations" is not an answer for a store we cannot read.
395
+ */
396
+ function recordFiles(dir) {
397
+ let names;
398
+ try {
399
+ names = readdirSync(dir);
400
+ }
401
+ catch (error) {
402
+ if (error.code !== "ENOENT")
403
+ throw error;
404
+ return [];
405
+ }
406
+ // UNORDERED. Lookup does not care, and `list()` sorts its rows by activity — a filename order kept
407
+ // here would be one nobody consumes and the next reader has to prove is unused.
408
+ return names
409
+ .filter((name) => name.endsWith(RECORD_SUFFIX))
410
+ .flatMap((name) => {
411
+ // The FIRST underscore: the timestamp holds none, and an encoded id may hold several
412
+ // (`piSessionId` escapes with `_`).
413
+ const cut = name.indexOf("_");
414
+ return cut < 0 ? [] : [{ path: join(dir, name), id: name.slice(cut + 1, -RECORD_SUFFIX.length) }];
415
+ });
416
+ }
417
+ /** One record as a conversation-list row. Read out of the record itself rather than from pi's
418
+ * listing, which is not asked for one — so the fields mean exactly what they say: no sentinel
419
+ * standing in for "no first message", and `updatedAt` floored at the record's own creation (a
420
+ * fork's entries carry the SOURCE's timestamps, so a branch made today would otherwise sort into
421
+ * whenever the original was written — the one column a conversation list orders by). */
422
+ function summarize(session, record) {
423
+ const entries = record.getEntries();
424
+ const createdAt = Date.parse(record.getHeader()?.timestamp ?? "") || 0;
425
+ // `|| 0` on both: an unparseable timestamp is NaN, and NaN in `updatedAt` serializes to `null` —
426
+ // which the contract types as a number and a client sorts by.
427
+ const lastAt = Date.parse(entries.at(-1)?.timestamp ?? "") || 0;
428
+ const messages = entries.filter((e) => e.type === "message");
429
+ const name = record.getSessionName();
430
+ const preview = firstUserText(messages);
431
+ return {
432
+ session,
433
+ ...(name ? { name } : {}),
434
+ createdAt,
435
+ updatedAt: Math.max(lastAt, createdAt),
436
+ messageCount: messages.length,
437
+ ...(preview ? { preview } : {}),
438
+ };
439
+ }
440
+ /** The first user message with text in it, truncated by CODE POINT (a cut through a surrogate pair
441
+ * would put a lone half in the row, which renders as U+FFFD). A session opened with a caption-less
442
+ * photo has none, and answers undefined — a row without a preview, not a row claiming one. */
443
+ function firstUserText(messages) {
444
+ for (const entry of messages) {
445
+ const message = entry.message;
446
+ if (message?.role !== "user")
447
+ continue;
448
+ const content = message.content;
449
+ const text = typeof content === "string"
450
+ ? content
451
+ : Array.isArray(content)
452
+ ? content
453
+ .filter((block) => block.type === "text")
454
+ .map((block) => block.text ?? "")
455
+ .join(" ")
456
+ : "";
457
+ // Cut to UTF-16 units FIRST: a pasted megabyte would otherwise become a million-element array
458
+ // on the way to keeping 200 of them. Two units per code point is the ceiling, so this cannot
459
+ // take fewer characters than the slice below wants.
460
+ if (text.trim())
461
+ return [...text.slice(0, PREVIEW_CHARS * 2)].slice(0, PREVIEW_CHARS).join("");
462
+ }
463
+ return undefined;
464
+ }
465
+ /** What pi names a record file. */
466
+ const RECORD_SUFFIX = ".jsonl";
467
+ /** How much of the first message a list row carries. A row, not a transcript. */
468
+ const PREVIEW_CHARS = 200;
151
469
  /**
152
470
  * Crash-safety reconciliation, run on every OPEN of an existing record.
153
471
  *
@@ -243,7 +561,7 @@ const OWN_RECORDS_DIR = "agent-session";
243
561
  * Writing pi's OWN header (`getHeader()`, not a hand-built literal) and reopening puts the manager
244
562
  * on its normal "file exists" path, where every append lands immediately.
245
563
  */
246
- function publish(session, dir) {
564
+ function materialize(session, dir) {
247
565
  const file = session.getSessionFile();
248
566
  if (!file || existsSync(file))
249
567
  return session; // in-memory, or already on disk
@@ -283,7 +601,7 @@ export function piInMemorySessionRecordStore(options = {}) {
283
601
  const staged = fresh();
284
602
  const cut = inheritanceCut(reconcileInterruptedToolCalls(parent), inherit.branchHints);
285
603
  if (cut)
286
- copyBranchInto(parent, staged, cut.at);
604
+ copyBranchForInheritance(parent, staged, cut.at);
287
605
  created = staged;
288
606
  }
289
607
  catch (error) {
@@ -300,6 +618,41 @@ export function piInMemorySessionRecordStore(options = {}) {
300
618
  async openIfExists(sessionId) {
301
619
  return live.get(sessionId);
302
620
  },
621
+ applyProperties: (sessionId, writes) => applyProperties(async () => live.get(sessionId), writes),
622
+ async list() {
623
+ // The SAME row builder the disk store uses, ordered the same way: a backend difference here is
624
+ // one an embedder discovers as a missing field (this one had no `preview` for exactly that
625
+ // reason). Nothing to read from disk, so nothing can be unreadable.
626
+ return [...live].map(([session, record]) => summarize(session, record)).sort((a, b) => b.updatedAt - a.updatedAt);
627
+ },
628
+ async fork(from, at, into, provenance) {
629
+ const parent = live.get(from);
630
+ if (!parent)
631
+ throw new Error(`session "${from}" has no record`);
632
+ // The port's promise, not the caller's: registering over a live session would replace its
633
+ // history outright.
634
+ if (live.has(into))
635
+ throw new Error(`session "${into}" already exists`);
636
+ // Entry-by-entry, like the in-memory inheritance path: there is no file to fork. Registered
637
+ // only once complete, so a failure leaves no half-copied session behind. NO inheritance
638
+ // window: this is the same user keeping their own history, not a new thread bounded from a
639
+ // parent's.
640
+ const staged = SessionManager.inMemory(cwd, { id: piSessionId(into) });
641
+ // METADATA FIRST, history last — the same order the disk store writes in, and for the same
642
+ // reason: pi has one leaf pointer, so whatever is appended last is where a client opening this
643
+ // fork finds its head. That should be the exchange it was forked at, not a metadata record.
644
+ // The name travels so a fork of "Deploy notes" is not an untitled row a user cannot place; a
645
+ // client that wants "(copy)" calls `update({ name })`.
646
+ const name = parent.getSessionName();
647
+ if (name)
648
+ staged.appendSessionInfo(name);
649
+ stampProvenance(staged, provenance);
650
+ copyBranchInto(parent, staged, at);
651
+ live.set(into, staged);
652
+ },
653
+ async delete(sessionId) {
654
+ return live.delete(sessionId);
655
+ },
303
656
  };
304
657
  }
305
658
  /** The spelling used before this store existed — read-only, so older records still resolve. */
@@ -4,8 +4,7 @@
4
4
  * closures. Deploy-time ambients a tool closes over at build time do NOT belong here.
5
5
  */
6
6
  import { AsyncLocalStorage } from "node:async_hooks";
7
- import type { SessionEntry as PiSessionEntry } from "@earendil-works/pi-coding-agent";
8
- import type { AgentSession } from "@earendil-works/pi-coding-agent";
7
+ import type { SessionEntry as PiSessionEntry, AgentSession } from "@earendil-works/pi-coding-agent";
9
8
  /** FastAgent's read-only port over the current conversation manager. Serving and chat adapt their
10
9
  * different concrete session implementations to this one tool-runtime contract. */
11
10
  export interface ReadonlySessionManager {
@@ -42,9 +41,27 @@ export interface ToolActivation {
42
41
  description: string;
43
42
  }>;
44
43
  /** ADDITIVE activation. Unknown names are filtered out before reaching pi (whose `setActiveTools`
45
- * THROWS on them); resolves the names actually newly activated (already-active names don't repeat). */
46
- activate(names: string[]): Promise<string[]>;
44
+ * THROWS on them); answers the names actually newly activated (already-active names don't repeat).
45
+ *
46
+ * SYNCHRONOUS, and that is the contract, not an implementation detail: read-modify-write against
47
+ * pi's active set cannot be interleaved as long as no caller can await inside it. An async
48
+ * signature would need a lock to say the same thing, and the lock is what a previous version had
49
+ * — one rebuilt per tool call, so the parallel batch it existed for never met on it. If pi's
50
+ * setters ever become async, this signature is where that breaks, loudly. */
51
+ activate(names: string[]): string[];
47
52
  }
53
+ /**
54
+ * The activation bridge over a live pi session — the ONE implementation, for both consumers.
55
+ *
56
+ * Serving (`agent-session-factory.ts`) and chat (`session-builder.ts`) had a copy each, identical
57
+ * but for the persistence line; the neighbouring `definitionResourceLoaderOptions` exists because
58
+ * that exact duplication drifted once before. The difference is a PARAMETER now: `onActivated` is
59
+ * what a served session uses to record the delta that carries the discovery into its next turn,
60
+ * and chat has nowhere to put one (pi's SessionContext has no active-tool set).
61
+ *
62
+ * Bind it to the SESSION, never to a tool call: the next call has to see what this one activated.
63
+ */
64
+ export declare function sessionToolActivation(session: AgentSession, onActivated?: (added: string[]) => void): ToolActivation;
48
65
  export interface TurnContext {
49
66
  /** Working directory for this execution. Falls back to process.cwd() only for an unbound direct call. */
50
67
  cwd?: string;
@@ -56,7 +73,3 @@ export interface TurnContext {
56
73
  tools?: ToolActivation;
57
74
  }
58
75
  export declare const turnContext: AsyncLocalStorage<TurnContext>;
59
- /** The additive-activation contract, in ONE place for both bridges (the served session,
60
- * chat.ts over pi's AgentSession): dedupe → keep registered names only (pi's setters THROW on
61
- * unknown) → exclude already-active → the names to actually add (empty = nothing to set). */
62
- export declare function additiveActivation(registered: string[], current: string[], names: string[]): string[];
@@ -26,11 +26,36 @@ export function agentSessionManager(session, sessionId) {
26
26
  },
27
27
  };
28
28
  }
29
+ /**
30
+ * The activation bridge over a live pi session — the ONE implementation, for both consumers.
31
+ *
32
+ * Serving (`agent-session-factory.ts`) and chat (`session-builder.ts`) had a copy each, identical
33
+ * but for the persistence line; the neighbouring `definitionResourceLoaderOptions` exists because
34
+ * that exact duplication drifted once before. The difference is a PARAMETER now: `onActivated` is
35
+ * what a served session uses to record the delta that carries the discovery into its next turn,
36
+ * and chat has nowhere to put one (pi's SessionContext has no active-tool set).
37
+ *
38
+ * Bind it to the SESSION, never to a tool call: the next call has to see what this one activated.
39
+ */
40
+ export function sessionToolActivation(session, onActivated) {
41
+ return {
42
+ active: () => session.getActiveToolNames(),
43
+ registered: () => session.getAllTools().map((t) => ({ name: t.name, description: t.description ?? "" })),
44
+ activate(names) {
45
+ const current = session.getActiveToolNames();
46
+ const added = additiveActivation(session.getAllTools().map((t) => t.name), current, names);
47
+ if (added.length === 0)
48
+ return added;
49
+ session.setActiveToolsByName([...current, ...added]);
50
+ onActivated?.(added);
51
+ return added;
52
+ },
53
+ };
54
+ }
29
55
  export const turnContext = new AsyncLocalStorage();
30
- /** The additive-activation contract, in ONE place for both bridges (the served session,
31
- * chat.ts over pi's AgentSession): dedupe keep registered names only (pi's setters THROW on
32
- * unknown) exclude already-active → the names to actually add (empty = nothing to set). */
33
- export function additiveActivation(registered, current, names) {
56
+ /** dedupe keep registered names only (pi's setters THROW on unknown) → exclude already-active →
57
+ * the names to actually add (empty = nothing to set). */
58
+ function additiveActivation(registered, current, names) {
34
59
  const known = new Set(registered);
35
60
  const active = new Set(current);
36
61
  return [...new Set(names)].filter((name) => known.has(name) && !active.has(name));
@@ -62,9 +62,9 @@ export function defineTool(options) {
62
62
  const tools = store?.tools
63
63
  ? {
64
64
  ...store.tools,
65
- activate: async (names) => {
65
+ activate: (names) => {
66
66
  // biome-ignore lint/style/noNonNullAssertion: guarded by the ternary above
67
- const activated = await store.tools.activate(names);
67
+ const activated = store.tools.activate(names);
68
68
  added.push(...activated);
69
69
  return activated;
70
70
  },
package/dist/env.js CHANGED
@@ -1,6 +1,5 @@
1
- import { readFileSync } from "node:fs";
1
+ import { readFileSync, existsSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import { existsSync } from "node:fs";
4
3
  import { log } from "./log.js";
5
4
  import { SECRETS_DIRNAME, resolveSecretsDir } from "./paths.js";
6
5
  /**