@agimon-ai/po-file-edit 0.0.0-alpha.111 → 0.0.0-alpha.112

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.
@@ -30,233 +30,363 @@ let _agimon_ai_po_core_platform = require("@agimon-ai/po-core/platform");
30
30
  let _agimon_ai_po_core_childSession = require("@agimon-ai/po-core/childSession");
31
31
  let _agimon_ai_po_core_hubChannel = require("@agimon-ai/po-core/hubChannel");
32
32
  let _agimon_ai_po_core_packageApi = require("@agimon-ai/po-core/packageApi");
33
- let node_fs_promises = require("node:fs/promises");
34
- node_fs_promises = __toESM(node_fs_promises, 1);
35
33
  let node_path = require("node:path");
36
34
  node_path = __toESM(node_path, 1);
37
35
  let _agimon_ai_po_hashline = require("@agimon-ai/po-hashline");
38
36
  let _agimon_ai_po_hashline_files = require("@agimon-ai/po-hashline/files");
39
- let _agimon_ai_po_core_childProcess = require("@agimon-ai/po-core/childProcess");
40
- let _agimon_ai_po_core_telemetry = require("@agimon-ai/po-core/telemetry");
37
+ let node_fs_promises = require("node:fs/promises");
38
+ node_fs_promises = __toESM(node_fs_promises, 1);
39
+ let node_os = require("node:os");
40
+ node_os = __toESM(node_os, 1);
41
+ let _agimon_ai_po_config = require("@agimon-ai/po-config");
41
42
  let node_crypto = require("node:crypto");
43
+ let _agimon_ai_po_core_childProcess = require("@agimon-ai/po-core/childProcess");
42
44
  let _agimon_ai_po_core_piSettings = require("@agimon-ai/po-core/piSettings");
43
45
  let node_child_process = require("node:child_process");
44
46
  let node_util = require("node:util");
45
47
  let ignore = require("ignore");
46
48
  ignore = __toESM(ignore, 1);
47
- let node_os = require("node:os");
48
- node_os = __toESM(node_os, 1);
49
- let _agimon_ai_po_config = require("@agimon-ai/po-config");
49
+ let _agimon_ai_po_core_telemetry = require("@agimon-ai/po-core/telemetry");
50
50
  let hono = require("hono");
51
51
  //#region src/constants/editPresence.ts
52
52
  const PRESENCE_NOTE_TITLE = "[Po: other active agents edited files in this result]";
53
53
  const PRESENCE_NOTE_GUIDANCE = "Preserve unrelated edits. If coordination would help, you can use intercom to send to the session id, or ask the subagent by name if it is on your team. Contact is optional; this notice does not block editing.";
54
54
  //#endregion
55
- //#region src/services/editPresence/index.ts
56
- const PATH_TOOLS = /* @__PURE__ */ new Set([
57
- "read",
58
- "edit",
59
- "write"
60
- ]);
61
- const EDIT_TOOLS = /* @__PURE__ */ new Set(["edit", "write"]);
62
- const MAX_GREP_FILES = 50;
63
- const MAX_NOTE_LINES = 10;
64
- const MINUTE_MS = 6e4;
65
- const SHORT_ID_LENGTH = 8;
66
- /** Pi's built-in grep prints match rows as `relative/path:line: text`. */
67
- const PI_GREP_ROW = /^(.+?):(\d+): /u;
68
- function stringArg(args, key) {
69
- if (typeof args !== "object" || args === null) return void 0;
70
- const value = args[key];
71
- return typeof value === "string" && value.length > 0 ? value : void 0;
72
- }
73
- function textOf(content) {
74
- return content.map((part) => part.type === "text" && "text" in part && typeof part.text === "string" ? part.text : "").join("\n");
75
- }
76
- async function grepFiles(call) {
77
- const lines = textOf(call.content).split("\n");
78
- const headers = lines.flatMap((line) => {
79
- const header = (0, _agimon_ai_po_hashline.parseFileHeader)(line);
80
- return header === void 0 ? [] : [(0, _agimon_ai_po_hashline_files.resolveInputPath)(header.path, call.cwd)];
81
- });
82
- if (headers.length > 0) return [...new Set(headers)].slice(0, MAX_GREP_FILES);
83
- const rows = lines.flatMap((line) => {
84
- const match = PI_GREP_ROW.exec(line)?.[1];
85
- return match === void 0 ? [] : [match];
86
- });
87
- if (rows.length === 0) return [];
88
- const searchPath = (0, _agimon_ai_po_hashline_files.resolveInputPath)(stringArg(call.args, "path") ?? ".", call.cwd);
89
- if ((await node_fs_promises.default.stat(searchPath).catch(() => void 0))?.isFile()) return [searchPath];
90
- return [...new Set(rows.map((row) => node_path.default.resolve(searchPath, row)))].slice(0, MAX_GREP_FILES);
55
+ //#region src/services/editPathNames/index.ts
56
+ /** The directory this package owns, under whichever root holds agent state. */
57
+ const STATE_DIRECTORY = "po-file-edit";
58
+ /** A stable short name for a path or session key, so state files are found from those two alone. */
59
+ function pathHash(value) {
60
+ return (0, node_crypto.createHash)("sha256").update(value).digest("hex").slice(0, 16);
91
61
  }
92
- async function touchedFiles(call) {
93
- if (PATH_TOOLS.has(call.toolName)) {
94
- const input = stringArg(call.args, "path");
95
- return input === void 0 ? [] : [await (0, _agimon_ai_po_hashline_files.resolveReadInputPath)(input, call.cwd)];
62
+ /** A subagent child writes to its parent's timeline, so the two stay one session to every reader. */
63
+ function sessionKeyFor(sessionId, environment) {
64
+ if (environment[_agimon_ai_po_core_childProcess.SUBAGENT_CHILD_ENV]) {
65
+ const parent = environment[_agimon_ai_po_core_childProcess.SUBAGENT_PARENT_SESSION_ENV];
66
+ if (parent) return parent;
96
67
  }
97
- return call.toolName === "grep" ? grepFiles(call) : [];
68
+ return sessionId;
98
69
  }
99
- function ago(elapsed) {
100
- const minutes = Math.floor(elapsed / MINUTE_MS);
101
- return minutes < 1 ? "under 1m ago" : `${minutes}m ago`;
70
+ /** Where every session's state lives: beside the other Po packages' agent state, never in the working tree. */
71
+ function stateDirectoryFor(environment) {
72
+ return node_path.default.join((0, _agimon_ai_po_core_piSettings.piAgentDirectory)(environment, environment.HOME), STATE_DIRECTORY);
102
73
  }
103
- function renderNote(lines) {
104
- const shown = lines.slice(0, MAX_NOTE_LINES);
105
- const more = lines.length - shown.length;
106
- return [
107
- PRESENCE_NOTE_TITLE,
108
- ...shown,
109
- ...more > 0 ? [`- and ${more} more`] : [],
110
- PRESENCE_NOTE_GUIDANCE
111
- ].join("\n");
74
+ /** Snapshots sit beside their timeline and take its name, so the two are found and cleared together. */
75
+ function snapshotsPathOf(timelinePath) {
76
+ return `${timelinePath.replace(/\.jsonl$/u, "")}.blobs`;
112
77
  }
113
- /**
114
- * Notes live editors of the files a tool call touched, then records the caller's own successful edit.
115
- * Returns the content with one note appended, or undefined when there is nothing to add, so callers
116
- * never rewrite a result needlessly.
117
- */
118
- async function observePresence(presence, agent, call, now = Date.now()) {
119
- const recording = EDIT_TOOLS.has(call.toolName) && !call.isError;
120
- const lines = [];
121
- for (const file of await touchedFiles(call)) {
122
- const real = await node_fs_promises.default.realpath(file).catch(() => void 0);
123
- if (real === void 0) continue;
124
- const others = presence.touch(real, agent);
125
- let bytes;
126
- if (others.length > 0) {
127
- bytes = await node_fs_promises.default.readFile(real).catch(() => void 0);
128
- const current = bytes === void 0 ? void 0 : (0, _agimon_ai_po_hashline_files.computeFileTag)(bytes);
129
- const shown = (0, _agimon_ai_po_hashline_files.displayPath)(file, call.cwd);
130
- for (const entry of others) {
131
- const state = entry.tag === current ? "unchanged" : "changed";
132
- lines.push(`- ${shown}: ${entry.agent.label()}, ${ago(now - entry.at)}, file ${state} since their edit.`);
133
- }
134
- }
135
- if (recording) {
136
- bytes ??= await node_fs_promises.default.readFile(real).catch(() => void 0);
137
- if (bytes !== void 0) presence.record(real, {
138
- agent,
139
- tag: (0, _agimon_ai_po_hashline_files.computeFileTag)(bytes),
140
- at: now
141
- });
142
- }
78
+ //#endregion
79
+ //#region src/services/fileEditPaths/index.ts
80
+ var FileEditPaths = class {
81
+ environment;
82
+ constructor(environment = process.env) {
83
+ this.environment = environment;
143
84
  }
144
- if (lines.length === 0) return void 0;
145
- return [...call.content, {
146
- type: "text",
147
- text: renderNote(lines)
148
- }];
149
- }
150
- /** Edit presence for one hub session and the in-process children it spawns. */
151
- function createSessionPresence(options) {
152
- const { sessionId, presence } = options;
153
- const sessionAgent = {
154
- key: `session:${sessionId}`,
155
- label: () => `session ${sessionId}${options.workflowStep ? " (workflow step)" : ""}`,
156
- contact: sessionId,
157
- isLive: options.isLive
158
- };
159
- const safely = async (work) => {
160
- try {
161
- return await work();
162
- } catch (error) {
163
- options.onError?.(error);
164
- return;
165
- }
166
- };
167
- return {
168
- toolResult: {
169
- event: "tool_result",
170
- async handle(event, execution) {
171
- const toolName = event.toolName;
172
- if (execution.sessionId !== sessionId || typeof toolName !== "string" || !Array.isArray(event.content)) return;
173
- const content = event.content;
174
- const next = await safely(() => observePresence(presence, sessionAgent, {
175
- toolName,
176
- args: event.args,
177
- content,
178
- isError: event.isError === true,
179
- cwd: execution.cwd
180
- }));
181
- return next === void 0 ? void 0 : { content: next };
182
- }
183
- },
184
- childHooks: { bind(scope) {
185
- const { runId, parentSessionId, agent } = scope.request;
186
- const child = {
187
- key: `run:${runId}`,
188
- label: () => `${options.labelFor(runId) ?? `${agent} (run ${runId.slice(0, SHORT_ID_LENGTH)})`} (subagent of session ${parentSessionId})`,
189
- contact: parentSessionId,
190
- isLive: () => !scope.signal.aborted
191
- };
192
- return {
193
- beforeTool: () => void 0,
194
- async afterTool(event) {
195
- const next = await safely(() => observePresence(presence, child, {
196
- toolName: event.toolName,
197
- args: event.args,
198
- content: event.content,
199
- isError: event.isError,
200
- cwd: scope.request.cwd || options.cwd
201
- }));
202
- return next === void 0 ? void 0 : { content: next };
203
- },
204
- dispose: async () => presence.forget(child.key)
205
- };
206
- } },
207
- dispose: () => presence.forget(sessionAgent.key)
208
- };
209
- }
85
+ sessionKey(sessionId, env = this.environment) {
86
+ return sessionKeyFor(sessionId, env);
87
+ }
88
+ /**
89
+ * Where every session's state lives: the Pi agent directory, the same root
90
+ * every other Po package writes to, and never inside the working tree.
91
+ *
92
+ * An earlier layout put this in the repository's git common directory. That
93
+ * is git's own storage: nothing in git's lifecycle prunes a directory we add
94
+ * to it, a linked worktree writes into the main checkout rather than its own,
95
+ * a submodule writes inside `.git/modules`, and `PI_CODING_AGENT_DIR` was
96
+ * ignored outright. The snapshots are verbatim copies of files the session
97
+ * touched, so where they land is a question about handling content, not a
98
+ * question about convenience.
99
+ */
100
+ stateDirectory() {
101
+ return stateDirectoryFor(this.environment);
102
+ }
103
+ /**
104
+ * One session's timeline, named from its working directory and its session so
105
+ * the hub and the session API can find it from another process knowing only
106
+ * those two things.
107
+ */
108
+ async timelinePath(cwd, sessionKey) {
109
+ const directory = this.stateDirectory();
110
+ await node_fs_promises.default.mkdir(directory, { recursive: true });
111
+ return node_path.default.join(directory, `${pathHash(await node_fs_promises.default.realpath(cwd))}-${pathHash(sessionKey)}.jsonl`);
112
+ }
113
+ /**
114
+ * Where this session's content snapshots live: beside its timeline and named
115
+ * after it, so the two are found together and cleared together.
116
+ */
117
+ async snapshotsPath(cwd, sessionKey) {
118
+ return snapshotsPathOf(await this.timelinePath(cwd, sessionKey));
119
+ }
120
+ };
210
121
  //#endregion
211
- //#region src/services/lineDiff/index.ts
122
+ //#region src/services/gitStatus/index.ts
212
123
  /**
213
- * The line difference between two versions of a file, as bounded hunks.
124
+ * Answers the unchanged question with git, in two batched calls per chunk.
214
125
  *
215
- * This is deliberately the package's own rather than Pi's `generateDiffString`:
216
- * that helper reaches the session process through an optional peer dependency,
217
- * and these routes run in a host that imports only the built entry, so its
218
- * presence is an assumption rather than a fact. A line diff is small enough to
219
- * own outright, and owning it means the wire carries structured rows instead of
220
- * a formatted string the browser has to parse back apart.
126
+ * One technology per adapter. This is where git enters the scan path; the
127
+ * tracker that depends on the capability keeps importing the port.
221
128
  *
222
- * Bounded twice over. Common prefix and suffix are trimmed first, which is what
223
- * makes a one-line change in a large file cheap. What remains is matched with a
224
- * longest-common-subsequence table, and only while that table stays under
225
- * MAX_MATRIX_CELLS: past it the changed region is reported as one replacement
226
- * rather than growing a matrix that would outweigh the file.
129
+ * `ls-files` names which of the given paths git tracks at all, and `status`
130
+ * names which of those moved. Everything else, an ignored build artefact, a
131
+ * temporary file, a tree with no repository, falls out of both answers and is
132
+ * therefore never reported as unchanged: the caller must keep recording it,
133
+ * because git has nothing to say about a file it never saw.
227
134
  */
228
- /** Lines of unchanged context kept either side of a change. */
229
- const CONTEXT_LINES = 3;
230
- /** The largest LCS table worth building; past it the changed region is one replacement. */
231
- const MAX_MATRIX_CELLS = 1e6;
232
- function splitLines(text) {
233
- const normalized = text.replaceAll("\r\n", "\n").replaceAll("\r", "\n");
234
- return normalized === "" ? [] : normalized.split("\n");
235
- }
236
- /** How many leading lines the two sides share. */
237
- function commonPrefix(before, after) {
238
- const limit = Math.min(before.length, after.length);
239
- let count = 0;
240
- while (count < limit && before[count] === after[count]) count += 1;
241
- return count;
135
+ /** Paths per git invocation, so a large scan cannot overflow the argument list. */
136
+ const CHUNK = 200;
137
+ const MAX_BUFFER = 4194304;
138
+ const run = (0, node_util.promisify)(node_child_process.execFile);
139
+ function chunked(values, size) {
140
+ const groups = [];
141
+ for (let index = 0; index < values.length; index += size) groups.push(values.slice(index, index + size));
142
+ return groups;
242
143
  }
243
- /** How many trailing lines the two sides share, never overlapping the prefix. */
244
- function commonSuffix(before, after, prefix) {
245
- const limit = Math.min(before.length, after.length) - prefix;
246
- let count = 0;
247
- while (count < limit && before[before.length - 1 - count] === after[after.length - 1 - count]) count += 1;
248
- return count;
144
+ function splitRecords(output) {
145
+ return output.split("\0").filter((entry) => entry !== "");
249
146
  }
250
147
  /**
251
- * The classic LCS length table. Only ever called once the caller has checked
252
- * the region against MAX_MATRIX_CELLS, so the allocation is bounded.
148
+ * The paths named by `status --porcelain -z`, whose records carry a two-letter
149
+ * code and a space. A rename adds a bare second record; keeping it is harmless,
150
+ * because every path in this set is one the caller records anyway.
253
151
  */
254
- function lcsTable(before, after) {
255
- const rows = before.length + 1;
256
- const columns = after.length + 1;
257
- const table = new Uint32Array(rows * columns);
258
- for (let row = before.length - 1; row >= 0; row -= 1) for (let column = after.length - 1; column >= 0; column -= 1) {
259
- const index = row * columns + column;
152
+ function statusPaths(output) {
153
+ return splitRecords(output).map((record) => record.length > 3 && record[2] === " " ? record.slice(3) : record);
154
+ }
155
+ function isInside$1(root, filePath) {
156
+ const relative = node_path.default.relative(root, filePath);
157
+ return relative !== "" && !relative.startsWith("..") && !node_path.default.isAbsolute(relative);
158
+ }
159
+ var NodeGitStatusAdapter = class {
160
+ async unchanged(cwd, filePaths) {
161
+ const clean = /* @__PURE__ */ new Set();
162
+ if (filePaths.length === 0) return clean;
163
+ const root = await this.topLevel(cwd);
164
+ if (root === void 0) return clean;
165
+ for (const group of chunked(filePaths.filter((filePath) => isInside$1(root, filePath)), CHUNK)) {
166
+ const relative = group.map((filePath) => node_path.default.relative(root, filePath));
167
+ const tracked = await this.git(root, [
168
+ "ls-files",
169
+ "-z",
170
+ "--",
171
+ ...relative
172
+ ]);
173
+ if (tracked === void 0) continue;
174
+ const dirty = await this.git(root, [
175
+ "status",
176
+ "--porcelain",
177
+ "-z",
178
+ "--untracked-files=no",
179
+ "--",
180
+ ...relative
181
+ ]);
182
+ if (dirty === void 0) continue;
183
+ const moved = new Set(statusPaths(dirty));
184
+ for (const entry of splitRecords(tracked)) if (!moved.has(entry)) clean.add(node_path.default.resolve(root, entry));
185
+ }
186
+ return clean;
187
+ }
188
+ /** The repository root, or undefined when this tree is not one. */
189
+ async topLevel(cwd) {
190
+ const root = (await this.git(cwd, ["rev-parse", "--show-toplevel"]))?.trim();
191
+ return root === void 0 || root === "" ? void 0 : node_path.default.resolve(root);
192
+ }
193
+ /** Git's stdout, or undefined when the call failed for any reason at all. */
194
+ async git(cwd, args) {
195
+ try {
196
+ const { stdout } = await run("git", [...args], {
197
+ cwd,
198
+ encoding: "utf8",
199
+ maxBuffer: MAX_BUFFER
200
+ });
201
+ return stdout;
202
+ } catch {
203
+ return;
204
+ }
205
+ }
206
+ };
207
+ //#endregion
208
+ //#region src/services/fileChanges/index.ts
209
+ const TOOLS = /* @__PURE__ */ new Set([
210
+ "edit",
211
+ "write",
212
+ "bash",
213
+ "user"
214
+ ]);
215
+ function isRecord(value) {
216
+ return typeof value === "object" && value !== null && !Array.isArray(value);
217
+ }
218
+ function optionalString(value) {
219
+ return typeof value === "string" && value !== "" ? value : void 0;
220
+ }
221
+ function optionalCount(value) {
222
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
223
+ }
224
+ /** Narrows one parsed line, or answers null so a malformed line can be skipped. */
225
+ function parseTimelineEvent(value) {
226
+ if (!isRecord(value)) return null;
227
+ const { version, path: filePath, tool, at } = value;
228
+ if (typeof filePath !== "string" || filePath === "") return null;
229
+ if (typeof at !== "number" || !Number.isFinite(at)) return null;
230
+ if (typeof tool !== "string" || !TOOLS.has(tool)) return null;
231
+ if (version === 1) {
232
+ if (tool === "user") return null;
233
+ return {
234
+ version: 1,
235
+ path: filePath,
236
+ tool,
237
+ at
238
+ };
239
+ }
240
+ if (version !== 2) return null;
241
+ return {
242
+ version: 2,
243
+ path: filePath,
244
+ tool,
245
+ at,
246
+ origin: value.origin === "scan" ? "scan" : "tool",
247
+ ...optionalString(value.before) === void 0 ? {} : { before: value.before },
248
+ ...optionalString(value.after) === void 0 ? {} : { after: value.after },
249
+ ...optionalCount(value.additions) === void 0 ? {} : { additions: value.additions },
250
+ ...optionalCount(value.removals) === void 0 ? {} : { removals: value.removals },
251
+ ...value.verified === true ? { verified: true } : {},
252
+ ...value.created === true ? { created: true } : {}
253
+ };
254
+ }
255
+ /** Every recorded line of the timeline, malformed ones dropped, in file order. */
256
+ function parseTimeline(content, onMalformed) {
257
+ const events = [];
258
+ for (const line of content.split("\n")) {
259
+ if (line === "") continue;
260
+ let parsed;
261
+ try {
262
+ parsed = JSON.parse(line);
263
+ } catch {
264
+ onMalformed?.(line);
265
+ continue;
266
+ }
267
+ const event = parseTimelineEvent(parsed);
268
+ if (event === null) onMalformed?.(line);
269
+ else events.push(event);
270
+ }
271
+ return events;
272
+ }
273
+ /**
274
+ * Whether a recorded change is evidence that the file's content actually moved.
275
+ *
276
+ * A tool change names its file and reads both sides, so it always is. A scan
277
+ * change is a tree comparison of size and modification time, which a checkout,
278
+ * an install, or a command that merely touched a file moves as readily as an
279
+ * edit does; only a scan the tracker confirmed carries `verified`. Version 1
280
+ * lines predate the distinction entirely, so a bash one cannot be trusted.
281
+ */
282
+ function isConfirmedChange(event) {
283
+ if (event.version !== 2) return event.tool !== "bash";
284
+ return event.origin !== "scan" || event.verified === true;
285
+ }
286
+ /** The recorded changes worth listing, which is every change but an unconfirmed touch. */
287
+ function confirmedChanges(events) {
288
+ return events.filter(isConfirmedChange);
289
+ }
290
+ /** One row per file, newest change first, which is the order both docks list in. */
291
+ function foldEntries(events) {
292
+ const folded = /* @__PURE__ */ new Map();
293
+ for (const event of events) {
294
+ const current = folded.get(event.path);
295
+ folded.set(event.path, {
296
+ path: event.path,
297
+ tool: event.at >= (current?.at ?? 0) ? event.tool : current?.tool ?? event.tool,
298
+ at: Math.max(event.at, current?.at ?? 0),
299
+ count: (current?.count ?? 0) + 1
300
+ });
301
+ }
302
+ return [...folded.values()].sort((left, right) => right.at - left.at);
303
+ }
304
+ /** One file's history, oldest first, numbered so a reader can name a version. */
305
+ function foldVersions(events, filePath) {
306
+ return events.filter((event) => event.path === filePath).sort((left, right) => left.at - right.at).map((event, offset) => {
307
+ const version = {
308
+ index: offset + 1,
309
+ tool: event.tool,
310
+ at: event.at,
311
+ origin: event.version === 2 ? event.origin : "scan"
312
+ };
313
+ if (event.version !== 2) return version;
314
+ return {
315
+ ...version,
316
+ ...event.before === void 0 ? {} : { before: event.before },
317
+ ...event.after === void 0 ? {} : { after: event.after },
318
+ ...event.additions === void 0 ? {} : { additions: event.additions },
319
+ ...event.removals === void 0 ? {} : { removals: event.removals },
320
+ ...event.verified === true ? { verified: true } : {},
321
+ ...event.created === true ? { created: true } : {}
322
+ };
323
+ });
324
+ }
325
+ /**
326
+ * Whether a file can be diffed at all: some version has to give the diff a
327
+ * starting point. A captured baseline is one. So is a version that created the
328
+ * file, whose starting point is nothing at all.
329
+ *
330
+ * A file only ever seen after the fact, which is every file a bash script
331
+ * wrote, still cannot be.
332
+ */
333
+ function isDiffable(versions) {
334
+ return versions.some((version) => version.before !== void 0 || version.created === true);
335
+ }
336
+ /** The oldest captured baseline for a file, which is what the whole-session diff starts from. */
337
+ function baselineOf(versions) {
338
+ return versions.find((version) => version.before !== void 0)?.before;
339
+ }
340
+ //#endregion
341
+ //#region src/services/lineDiff/index.ts
342
+ /**
343
+ * The line difference between two versions of a file, as bounded hunks.
344
+ *
345
+ * This is deliberately the package's own rather than Pi's `generateDiffString`:
346
+ * that helper reaches the session process through an optional peer dependency,
347
+ * and these routes run in a host that imports only the built entry, so its
348
+ * presence is an assumption rather than a fact. A line diff is small enough to
349
+ * own outright, and owning it means the wire carries structured rows instead of
350
+ * a formatted string the browser has to parse back apart.
351
+ *
352
+ * Bounded twice over. Common prefix and suffix are trimmed first, which is what
353
+ * makes a one-line change in a large file cheap. What remains is matched with a
354
+ * longest-common-subsequence table, and only while that table stays under
355
+ * MAX_MATRIX_CELLS: past it the changed region is reported as one replacement
356
+ * rather than growing a matrix that would outweigh the file.
357
+ */
358
+ /** Lines of unchanged context kept either side of a change. */
359
+ const CONTEXT_LINES = 3;
360
+ /** The largest LCS table worth building; past it the changed region is one replacement. */
361
+ const MAX_MATRIX_CELLS = 1e6;
362
+ function splitLines(text) {
363
+ const normalized = text.replaceAll("\r\n", "\n").replaceAll("\r", "\n");
364
+ return normalized === "" ? [] : normalized.split("\n");
365
+ }
366
+ /** How many leading lines the two sides share. */
367
+ function commonPrefix(before, after) {
368
+ const limit = Math.min(before.length, after.length);
369
+ let count = 0;
370
+ while (count < limit && before[count] === after[count]) count += 1;
371
+ return count;
372
+ }
373
+ /** How many trailing lines the two sides share, never overlapping the prefix. */
374
+ function commonSuffix(before, after, prefix) {
375
+ const limit = Math.min(before.length, after.length) - prefix;
376
+ let count = 0;
377
+ while (count < limit && before[before.length - 1 - count] === after[after.length - 1 - count]) count += 1;
378
+ return count;
379
+ }
380
+ /**
381
+ * The classic LCS length table. Only ever called once the caller has checked
382
+ * the region against MAX_MATRIX_CELLS, so the allocation is bounded.
383
+ */
384
+ function lcsTable(before, after) {
385
+ const rows = before.length + 1;
386
+ const columns = after.length + 1;
387
+ const table = new Uint32Array(rows * columns);
388
+ for (let row = before.length - 1; row >= 0; row -= 1) for (let column = after.length - 1; column >= 0; column -= 1) {
389
+ const index = row * columns + column;
260
390
  table[index] = before[row] === after[column] ? (table[index + columns + 1] ?? 0) + 1 : Math.max(table[index + columns] ?? 0, table[index + 1] ?? 0);
261
391
  }
262
392
  return table;
@@ -410,389 +540,716 @@ function lineDiff(before, after) {
410
540
  };
411
541
  }
412
542
  //#endregion
413
- //#region src/services/editTracker/index.ts
414
- const EDIT_TOOL = "edit";
415
- const WRITE_TOOL = "write";
416
- const BASH_TOOL = "bash";
417
- /** Code mode scripts can write files like a shell can, so they get the same before/after scan. */
418
- const EXEC_TOOL = "exec";
419
- function objectValue(value, key) {
420
- if (!value || typeof value !== "object") return void 0;
421
- const found = value[key];
422
- return typeof found === "string" ? found : void 0;
423
- }
543
+ //#region src/services/fileEditsViews/index.ts
544
+ /** Past this, the working view reports the file rather than carrying it. */
545
+ const MAX_WORKING_BYTES = 1048576;
546
+ const NO_BASELINE_NOTE = "changed by a command, so no baseline was captured; showing the file as it stands";
424
547
  /**
425
- * How far before a call started a write may claim to have happened and still be
426
- * attributed to it. A working tree can sit on a filesystem that stores whole
427
- * seconds, which floors a write made just after the call began to a stamp just
428
- * before it, and the cost of being generous here is one second of the staleness
429
- * this check exists to remove.
548
+ * A change the tool layer named but never captured content for. That is what
549
+ * every record written before this package learned to snapshot looks like, and
550
+ * calling those "changed by a command" would be wrong: the tool is right there
551
+ * in the record.
430
552
  */
431
- const MODIFIED_TOLERANCE_MS = 1e3;
432
- var EditTracker = class {
433
- timeline;
434
- snapshots;
435
- manifests;
436
- pending = /* @__PURE__ */ new Map();
437
- /** Start time per in-flight bash call, so its end knows what it may claim. */
438
- bracketed = /* @__PURE__ */ new Map();
439
- /**
440
- * The tree as this tracker last saw it. A bash call compares against it and
441
- * then replaces it, so each call costs one walk rather than two, and a change
442
- * made between calls is still noticed on the next one.
443
- */
444
- manifest;
445
- /**
446
- * This package's own storage, which the walk must never report. The timeline
447
- * and its snapshots can land inside the tree being watched, and recording
448
- * them would make every change cause another one.
449
- */
450
- excluded = [];
451
- /**
452
- * The project's own ignore rules. A path the project disowns is not worth a
453
- * git call, a read, or a stored copy of its content, so it is dropped before
454
- * it costs any of them.
455
- */
456
- isIgnored;
457
- /**
458
- * The last content hash this session saw per path, from either mechanism.
459
- * A candidate whose hash has not moved was touched, not edited.
460
- */
461
- contents = /* @__PURE__ */ new Map();
462
- now;
463
- git;
464
- /**
465
- * The scan deferred by the last bash call. Every bracket joins this chain, so
466
- * at most one walk runs at a time and each one sees the baseline the previous
467
- * one left behind.
468
- */
469
- scanning = Promise.resolve();
470
- constructor(timeline, snapshots, manifests, options = {}) {
471
- this.timeline = timeline;
472
- this.snapshots = snapshots;
473
- this.manifests = manifests;
474
- this.now = options.now ?? Date.now;
475
- this.git = options.git;
553
+ const NO_SNAPSHOT_NOTE = "recorded before this session began capturing content, so there is no diff for it";
554
+ const NO_AFTER_NOTE = "the new content could not be captured: the file is binary or past the size cap";
555
+ const NO_BEFORE_NOTE = "the previous content could not be captured: it was binary or past the size cap";
556
+ const APPROXIMATE_NOTE = "the changed region was too large to match line by line";
557
+ /** Like Node's utf8 read, a byte-order mark stays in the text. */
558
+ const decoder = new TextDecoder("utf-8", {
559
+ fatal: false,
560
+ ignoreBOM: true
561
+ });
562
+ function hashOf(content) {
563
+ return (0, node_crypto.createHash)("sha256").update(content, "utf8").digest("hex");
564
+ }
565
+ function isInside(root, candidate) {
566
+ return candidate === root || candidate.startsWith(`${root}${node_path.default.sep}`);
567
+ }
568
+ /** A file the source view cannot show, with the reason it says instead. */
569
+ function unavailable(reason) {
570
+ return {
571
+ content: "",
572
+ hash: "",
573
+ unavailable: true,
574
+ reason
575
+ };
576
+ }
577
+ /** The source view of a file's bytes: refused when oversized or binary, otherwise its text and hash. */
578
+ function workingViewOf(raw) {
579
+ if (raw.byteLength > 1048576) return unavailable(`the file is larger than ${MAX_WORKING_BYTES} bytes`);
580
+ if (raw.subarray(0, 8192).includes(0)) return unavailable("the file is binary");
581
+ const content = decoder.decode(raw);
582
+ return {
583
+ content,
584
+ hash: hashOf(content),
585
+ unavailable: false
586
+ };
587
+ }
588
+ /**
589
+ * One recorded change as the page renders it. A change with both sides captured
590
+ * carries its own diff; one without says why, rather than showing nothing.
591
+ *
592
+ * A file this session created counts as captured on both sides. Its baseline is
593
+ * empty rather than missing, so the whole file reads as arriving at once, which
594
+ * is exactly what happened.
595
+ */
596
+ async function toVersionView(version, snapshots) {
597
+ const view = {
598
+ index: version.index,
599
+ tool: version.tool,
600
+ at: version.at,
601
+ origin: version.origin,
602
+ additions: version.additions ?? 0,
603
+ removals: version.removals ?? 0
604
+ };
605
+ const createdHere = version.before === void 0 && version.created === true;
606
+ if (version.after === void 0 || version.before === void 0 && !createdHere) {
607
+ if (version.origin === "tool") return {
608
+ ...view,
609
+ note: version.after === void 0 ? NO_AFTER_NOTE : NO_BEFORE_NOTE
610
+ };
611
+ return {
612
+ ...view,
613
+ note: version.tool === "bash" ? NO_BASELINE_NOTE : NO_SNAPSHOT_NOTE
614
+ };
476
615
  }
477
- /**
478
- * Forgets the previous session's tree so a new one does not inherit its
479
- * baseline, and takes the paths this session's own bookkeeping occupies.
480
- */
481
- reset(options = {}) {
482
- this.pending.clear();
483
- this.bracketed.clear();
484
- this.contents.clear();
485
- this.manifest = void 0;
486
- this.scanning = Promise.resolve();
487
- this.excluded = options.exclude ?? [];
488
- this.isIgnored = options.isIgnored;
616
+ const after = await snapshots.read(version.after);
617
+ if (after === void 0) return {
618
+ ...view,
619
+ note: "the content behind this change is no longer held"
620
+ };
621
+ if (version.before === void 0) {
622
+ const fresh = lineDiffFromEmpty(after);
623
+ return {
624
+ ...view,
625
+ additions: fresh.additions,
626
+ removals: fresh.removals,
627
+ hunks: fresh.hunks,
628
+ ...fresh.approximate ? { note: APPROXIMATE_NOTE } : {}
629
+ };
489
630
  }
490
- /**
491
- * Awaits a scan still running in the background. A caller that is about to
492
- * clear the timeline needs this, or the scan appends after the clear.
493
- */
494
- async flush() {
495
- await this.scanning;
631
+ const before = await snapshots.read(version.before);
632
+ if (before === void 0) return {
633
+ ...view,
634
+ note: "the content behind this change is no longer held"
635
+ };
636
+ const diff = lineDiff(before, after);
637
+ return {
638
+ ...view,
639
+ additions: diff.additions,
640
+ removals: diff.removals,
641
+ hunks: diff.hunks,
642
+ ...diff.approximate ? { note: APPROXIMATE_NOTE } : {}
643
+ };
644
+ }
645
+ /** Everything the session did to the file: its oldest baseline against what is on disk now. */
646
+ async function toCumulativeView(versions, working, snapshots) {
647
+ const createdHere = versions[0]?.created === true;
648
+ const baseline = baselineOf(versions);
649
+ if (!createdHere && baseline === void 0) return {
650
+ additions: 0,
651
+ removals: 0,
652
+ note: versions[0]?.origin === "tool" ? NO_BEFORE_NOTE : NO_BASELINE_NOTE
653
+ };
654
+ if (working.unavailable) return {
655
+ additions: 0,
656
+ removals: 0,
657
+ note: working.reason ?? "the file cannot be read"
658
+ };
659
+ if (createdHere || baseline === void 0) {
660
+ const fresh = lineDiffFromEmpty(working.content);
661
+ return {
662
+ additions: fresh.additions,
663
+ removals: fresh.removals,
664
+ hunks: fresh.hunks,
665
+ ...fresh.approximate ? { note: APPROXIMATE_NOTE } : {}
666
+ };
496
667
  }
497
- async start(id, tool, args, cwd) {
498
- await this.scanning;
499
- if (tool === EDIT_TOOL || tool === WRITE_TOOL) {
500
- const supplied = objectValue(args, "path");
501
- if (!supplied) return false;
502
- const filePath = node_path.default.resolve(cwd, supplied);
503
- const [before, fingerprint] = await Promise.all([this.snapshots.capture(filePath), this.manifests.fingerprint(filePath)]);
504
- this.pending.set(id, {
505
- tool,
506
- filePath,
507
- before,
508
- existed: fingerprint !== void 0
668
+ const before = await snapshots.read(baseline);
669
+ if (before === void 0) return {
670
+ additions: 0,
671
+ removals: 0,
672
+ note: "the content this session started from is no longer held"
673
+ };
674
+ const diff = lineDiff(before, working.content);
675
+ return {
676
+ additions: diff.additions,
677
+ removals: diff.removals,
678
+ hunks: diff.hunks,
679
+ ...diff.approximate ? { note: APPROXIMATE_NOTE } : {}
680
+ };
681
+ }
682
+ //#endregion
683
+ //#region src/services/nodeWorkingFiles/index.ts
684
+ /**
685
+ * The routes' file operations over Node's real files.
686
+ *
687
+ * One technology per adapter. This is where node enters the API: a link or a
688
+ * rename can swap what a path names between two checks, so every read and write
689
+ * pins the file it checked by its open descriptor instead of by its name.
690
+ */
691
+ function hasCode$2(error, code) {
692
+ return error instanceof Error && "code" in error && error.code === code;
693
+ }
694
+ function describe(error) {
695
+ return error instanceof Error ? error.message : String(error);
696
+ }
697
+ /**
698
+ * The same containment check after symlinks are followed. A path that does not
699
+ * exist yet resolves to nothing, and there is nothing to hand out, so it
700
+ * passes and the read below reports it missing.
701
+ */
702
+ async function isRealPathInside(root, candidate) {
703
+ let realRoot;
704
+ let real;
705
+ try {
706
+ realRoot = await node_fs_promises.default.realpath(root);
707
+ real = await node_fs_promises.default.realpath(candidate);
708
+ } catch (error) {
709
+ return hasCode$2(error, "ENOENT");
710
+ }
711
+ return isInside(realRoot, real);
712
+ }
713
+ /** Reads the file as the source view will show it, or says why it cannot. */
714
+ async function readWorking(filePath, opened, allowedRoot) {
715
+ let handle = opened;
716
+ let raw;
717
+ try {
718
+ handle ??= await (0, _agimon_ai_po_core_platform.openGuardedFile)(filePath, { root: allowedRoot });
719
+ const stats = await handle.stat();
720
+ if (!stats.isFile()) return unavailable("the file is not a regular file");
721
+ const named = await node_fs_promises.default.lstat(filePath);
722
+ if (!named.isFile() || stats.dev !== named.dev || stats.ino !== named.ino || allowedRoot !== void 0 && !await isRealPathInside(allowedRoot, filePath)) return unavailable("the file path changed or leaves its readable directory");
723
+ raw = Buffer.alloc(1048577);
724
+ if (stats.size <= 1048576) {
725
+ let offset = 0;
726
+ while (offset < raw.length) {
727
+ const { bytesRead } = await handle.read(raw, offset, raw.length - offset, offset);
728
+ if (bytesRead === 0) break;
729
+ offset += bytesRead;
730
+ }
731
+ raw = raw.subarray(0, offset);
732
+ }
733
+ } catch {
734
+ return unavailable("the file no longer exists or cannot be safely read");
735
+ } finally {
736
+ if (opened === void 0) await handle?.close();
737
+ }
738
+ return workingViewOf(raw);
739
+ }
740
+ async function isInsideRoot(root, filePath) {
741
+ return isInside(root, filePath) && await isRealPathInside(root, filePath);
742
+ }
743
+ var NodeWorkingFiles = class {
744
+ readWorking(filePath, allowedRoot) {
745
+ return readWorking(filePath, void 0, allowedRoot);
746
+ }
747
+ isRealPathInside(root, candidate) {
748
+ return isRealPathInside(root, candidate);
749
+ }
750
+ async save({ filePath, root, content, expectedHash }) {
751
+ const canonical = await node_fs_promises.default.realpath(filePath);
752
+ return _agimon_ai_po_core_platform.fileMutationRunner.forKey(canonical)(async () => {
753
+ const handle = await (0, _agimon_ai_po_core_platform.openGuardedFile)(filePath, {
754
+ write: true,
755
+ root
509
756
  });
510
- return true;
757
+ try {
758
+ if (await node_fs_promises.default.realpath(filePath) !== canonical) return { status: "moved" };
759
+ const current = await readWorking(filePath, handle, root);
760
+ if (current.unavailable) return {
761
+ status: "unreadable",
762
+ reason: current.reason ?? "The file cannot be read."
763
+ };
764
+ if (current.hash !== expectedHash) return {
765
+ status: "stale",
766
+ hash: current.hash
767
+ };
768
+ const opened = await handle.stat();
769
+ const named = await node_fs_promises.default.lstat(filePath);
770
+ if (!opened.isFile() || opened.nlink !== 1 || !named.isFile() || named.nlink !== 1 || opened.dev !== named.dev || opened.ino !== named.ino || await node_fs_promises.default.realpath(filePath) !== canonical || !await isInsideRoot(root, filePath)) return { status: "moved" };
771
+ await handle.writeFile(content, "utf8");
772
+ await handle.truncate(Buffer.byteLength(content, "utf8"));
773
+ return {
774
+ status: "saved",
775
+ hash: hashOf(content)
776
+ };
777
+ } finally {
778
+ await handle.close();
779
+ }
780
+ });
781
+ }
782
+ async remove(filePath, root) {
783
+ try {
784
+ const canonical = await node_fs_promises.default.realpath(filePath).catch((error) => {
785
+ if (hasCode$2(error, "ENOENT")) return filePath;
786
+ throw error;
787
+ });
788
+ return await _agimon_ai_po_core_platform.fileMutationRunner.forKey(canonical)(async () => {
789
+ if (!await isInsideRoot(root, filePath)) return { status: "outside" };
790
+ await node_fs_promises.default.unlink(filePath);
791
+ return { status: "removed" };
792
+ });
793
+ } catch (error) {
794
+ if (hasCode$2(error, "ENOENT")) return { status: "removed" };
795
+ return {
796
+ status: "failed",
797
+ reason: describe(error)
798
+ };
511
799
  }
512
- if (tool !== BASH_TOOL && tool !== EXEC_TOOL) return false;
513
- this.bracketed.set(id, this.now());
514
- this.manifest ??= await this.manifests.take(cwd, this.excluded);
515
- return true;
516
800
  }
517
- async end(id, isError, cwd) {
518
- const pending = this.pending.get(id);
519
- this.pending.delete(id);
520
- const startedAt = this.bracketed.get(id);
521
- this.bracketed.delete(id);
522
- if (pending) {
523
- if (!isError) await this.recordTool(pending);
524
- return;
525
- }
526
- if (startedAt === void 0) return;
527
- this.scanning = this.scanning.then(async () => {
528
- try {
529
- await this.recordScan(cwd, startedAt);
530
- } catch {}
531
- });
801
+ };
802
+ //#endregion
803
+ //#region src/services/sessionStateSweep/index.ts
804
+ /**
805
+ * Remove the state sessions left behind when they never got to clean up.
806
+ *
807
+ * A session clears its own timeline and snapshots on shutdown, which covers the
808
+ * ordinary case and nothing else: a killed process, a crash, or a machine that
809
+ * lost power leaves both behind, and nothing ever looked at the directory
810
+ * again. One week of that filled a real checkout with hundreds of megabytes.
811
+ *
812
+ * Age is the only signal used, because it is the only one that is true from
813
+ * another process. A running session appends as it works, so its timeline is
814
+ * recent; a dead one stops moving at the moment it died.
815
+ */
816
+ /**
817
+ * How long state may sit untouched before a later session removes it.
818
+ *
819
+ * Generous on purpose. The cost of waiting is disk, and the cost of being wrong
820
+ * is deleting a live session's history, so this is set far beyond any plausible
821
+ * gap between two appends rather than close to it.
822
+ */
823
+ const STATE_MAX_AGE_MS = 6048e5;
824
+ const TIMELINE_SUFFIX = ".jsonl";
825
+ const SNAPSHOTS_SUFFIX = ".blobs";
826
+ async function remove(target) {
827
+ await node_fs_promises.default.rm(target, {
828
+ recursive: true,
829
+ force: true
830
+ });
831
+ }
832
+ /** The most recent time anything under this session's state moved. */
833
+ async function lastTouched(paths) {
834
+ let newest;
835
+ for (const target of paths) try {
836
+ const stat = await node_fs_promises.default.stat(target);
837
+ if (newest === void 0 || stat.mtimeMs > newest) newest = stat.mtimeMs;
838
+ } catch {}
839
+ return newest;
840
+ }
841
+ /** How many sessions' worth of state was removed. */
842
+ async function sweepSessionState(options) {
843
+ const { directory, keep, removeDirectory = false, now = Date.now(), maxAgeMs = STATE_MAX_AGE_MS } = options;
844
+ let entries;
845
+ try {
846
+ entries = await node_fs_promises.default.readdir(directory);
847
+ } catch {
848
+ return 0;
849
+ }
850
+ const floor = now - maxAgeMs;
851
+ const timelines = new Set(entries.filter((entry) => entry.endsWith(TIMELINE_SUFFIX)));
852
+ let removed = 0;
853
+ for (const entry of timelines) {
854
+ const timelinePath = node_path.default.join(directory, entry);
855
+ if (keep !== void 0 && timelinePath === keep) continue;
856
+ const snapshotsPath = `${timelinePath.slice(0, -6)}${SNAPSHOTS_SUFFIX}`;
857
+ const lockPath = `${timelinePath}.lock`;
858
+ const touched = await lastTouched([
859
+ timelinePath,
860
+ snapshotsPath,
861
+ lockPath
862
+ ]);
863
+ if (touched === void 0 || touched >= floor) continue;
864
+ await remove(snapshotsPath);
865
+ await remove(timelinePath);
866
+ await remove(lockPath);
867
+ removed += 1;
868
+ }
869
+ for (const entry of entries) {
870
+ if (!entry.endsWith(SNAPSHOTS_SUFFIX)) continue;
871
+ if (timelines.has(`${entry.slice(0, -6)}${TIMELINE_SUFFIX}`)) continue;
872
+ const orphan = node_path.default.join(directory, entry);
873
+ const touched = await lastTouched([orphan]);
874
+ if (touched === void 0 || touched >= floor) continue;
875
+ await remove(orphan);
532
876
  }
533
- /** An `edit` or `write` whose file was read on both sides of the call. */
534
- async recordTool(pending) {
535
- const after = await this.snapshots.capture(pending.filePath);
536
- const created = !pending.existed;
537
- const counts = await this.countChanges(pending.before, after, created);
538
- if (after !== void 0) this.contents.set(pending.filePath, after);
539
- await this.append({
540
- version: 2,
541
- path: pending.filePath,
542
- tool: pending.tool,
543
- at: this.now(),
544
- origin: "tool",
545
- ...pending.before === void 0 ? {} : { before: pending.before },
546
- ...after === void 0 ? {} : { after },
547
- ...created ? { created: true } : {},
548
- ...counts
549
- });
550
- await this.remember(pending.filePath);
877
+ if (removeDirectory) try {
878
+ await node_fs_promises.default.rmdir(directory);
879
+ } catch {}
880
+ return removed;
881
+ }
882
+ //#endregion
883
+ //#region src/services/snapshotStore/index.ts
884
+ /**
885
+ * Store and read the file content this session's diffs are built from.
886
+ *
887
+ * One technology per adapter. This is where node enters the package; the
888
+ * services that depend on the capability keep importing the port.
889
+ *
890
+ * Snapshots are content-addressed, so a file written twice with the same bytes
891
+ * occupies one blob and the second capture is a hash and an exists check. The
892
+ * whole directory goes when the session's timeline does, which is what keeps
893
+ * this from growing without bound across a machine's lifetime.
894
+ */
895
+ const MISSING_CODES = /* @__PURE__ */ new Set([
896
+ "ENOENT",
897
+ "ENOTDIR",
898
+ "EISDIR",
899
+ "ENAMETOOLONG"
900
+ ]);
901
+ function hasCode$1(error, codes) {
902
+ return error instanceof Error && "code" in error && typeof error.code === "string" && codes.has(error.code);
903
+ }
904
+ var NodeSnapshotStoreAdapter = class {
905
+ directory;
906
+ initialize(directory) {
907
+ this.directory = directory;
551
908
  }
552
- /** Whatever a bash call actually edited, however the command wrote it. */
553
- async recordScan(cwd, startedAt) {
554
- const before = this.manifest;
555
- if (before === void 0) return;
556
- const after = await this.manifests.take(cwd, this.excluded);
557
- this.manifest = after;
558
- const disowned = this.isIgnored;
559
- const named = this.manifests.changed(before, after).filter((filePath) => disowned === void 0 || !disowned(filePath));
560
- const candidates = await this.writtenDuring(named, startedAt);
561
- if (candidates.length === 0) return;
562
- const unchanged = await this.unchangedInGit(cwd, candidates);
563
- for (const filePath of candidates) {
564
- const known = this.contents.get(filePath);
565
- if (known === void 0 && unchanged.has(filePath)) continue;
566
- const beforePrint = before.entries.get(filePath);
567
- const afterPrint = after.entries.get(filePath);
568
- const captured = afterPrint === void 0 ? void 0 : await this.snapshots.capture(filePath);
569
- if (captured !== void 0) this.contents.set(filePath, captured);
570
- if (captured !== void 0 && captured === known) continue;
571
- const proven = beforePrint === void 0 || afterPrint === void 0 || this.manifests.sizeChanged(beforePrint, afterPrint) || known !== void 0 && captured !== void 0 && captured !== known;
572
- await this.append({
573
- version: 2,
574
- path: filePath,
575
- tool: BASH_TOOL,
576
- at: this.now(),
577
- origin: "scan",
578
- ...proven ? { verified: true } : {},
579
- ...captured === void 0 ? {} : { after: captured }
580
- });
909
+ async capture(filePath) {
910
+ let raw;
911
+ try {
912
+ if ((await node_fs_promises.default.stat(filePath)).size > 1048576) return void 0;
913
+ raw = await node_fs_promises.default.readFile(filePath);
914
+ } catch (error) {
915
+ if (hasCode$1(error, MISSING_CODES)) return void 0;
916
+ throw error;
581
917
  }
918
+ if (raw.byteLength > 1048576) return void 0;
919
+ if (raw.subarray(0, 8192).includes(0)) return void 0;
920
+ return this.put(raw.toString("utf8"));
582
921
  }
583
- /**
584
- * Narrows candidates to the ones that could have been written by the call
585
- * being closed.
586
- *
587
- * This is what keeps a working tree that was already dirty out of the list. A
588
- * file whose bytes were last written before the call began was differed by
589
- * something else, whatever moved its fingerprint. A file that is no longer
590
- * there has no time to read and a delete is a change the call may well have
591
- * made, so it stays a candidate.
592
- */
593
- async writtenDuring(candidates, startedAt) {
594
- const floor = startedAt - MODIFIED_TOLERANCE_MS;
595
- const written = [];
596
- for (const filePath of candidates) {
597
- const modifiedAt = await this.manifests.modifiedAt(filePath);
598
- if (modifiedAt === void 0 || modifiedAt >= floor) written.push(filePath);
922
+ async put(content) {
923
+ const hash = (0, node_crypto.createHash)("sha256").update(content, "utf8").digest("hex");
924
+ const blobPath = node_path.default.join(this.requireDirectory(), hash);
925
+ try {
926
+ await node_fs_promises.default.access(blobPath);
927
+ return hash;
928
+ } catch (error) {
929
+ if (!hasCode$1(error, MISSING_CODES)) throw error;
599
930
  }
600
- return written;
601
- }
602
- /** Which candidates git tracks and reports as untouched; empty when it cannot say. */
603
- async unchangedInGit(cwd, candidates) {
604
- const unseen = candidates.filter((filePath) => !this.contents.has(filePath));
605
- if (this.git === void 0 || unseen.length === 0) return /* @__PURE__ */ new Set();
606
- return this.git.unchanged(cwd, unseen);
931
+ await node_fs_promises.default.mkdir(this.requireDirectory(), { recursive: true });
932
+ await node_fs_promises.default.writeFile(blobPath, content, "utf8");
933
+ return hash;
607
934
  }
608
- /** How many lines moved, when there is enough captured content to say. */
609
- async countChanges(before, after, created) {
610
- if (after === void 0) return {};
611
- if (before === void 0) {
612
- if (!created) return {};
613
- const createdText = await this.snapshots.read(after);
614
- if (createdText === void 0) return {};
615
- const fresh = lineDiffFromEmpty(createdText);
616
- return {
617
- additions: fresh.additions,
618
- removals: fresh.removals
619
- };
935
+ async read(hash) {
936
+ if (!/^[0-9a-f]{64}$/u.test(hash)) return void 0;
937
+ try {
938
+ return await node_fs_promises.default.readFile(node_path.default.join(this.requireDirectory(), hash), "utf8");
939
+ } catch (error) {
940
+ if (hasCode$1(error, MISSING_CODES)) return void 0;
941
+ throw error;
620
942
  }
621
- if (before === after) return {
622
- additions: 0,
623
- removals: 0
624
- };
625
- const [beforeText, afterText] = await Promise.all([this.snapshots.read(before), this.snapshots.read(after)]);
626
- if (beforeText === void 0 || afterText === void 0) return {};
627
- const diff = lineDiff(beforeText, afterText);
628
- return {
629
- additions: diff.additions,
630
- removals: diff.removals
631
- };
632
943
  }
633
- /** Records the change unless it turned out to be no change at all. */
634
- async append(event) {
635
- if (event.before !== void 0 && event.before === event.after) return;
636
- await this.timeline.append(event);
944
+ async clear() {
945
+ if (this.directory === void 0) return;
946
+ await node_fs_promises.default.rm(this.directory, {
947
+ recursive: true,
948
+ force: true
949
+ });
637
950
  }
638
- /**
639
- * Folds a path the tool layer just handled into the tracked manifest, so the
640
- * next bash comparison sees it as already accounted for.
641
- *
642
- * The fingerprint has to be the one a walk would read, not a stand-in, or the
643
- * next comparison reports the file again under bash and every tool edit is
644
- * recorded twice.
645
- */
646
- async remember(filePath) {
647
- if (this.manifest === void 0) return;
648
- const entries = new Map(this.manifest.entries);
649
- const fingerprint = await this.manifests.fingerprint(filePath);
650
- if (fingerprint === void 0) entries.delete(filePath);
651
- else entries.set(filePath, fingerprint);
652
- this.manifest = {
653
- entries,
654
- truncated: this.manifest.truncated
655
- };
951
+ requireDirectory() {
952
+ if (this.directory === void 0) throw new Error("Snapshot store is not initialized");
953
+ return this.directory;
656
954
  }
657
955
  };
658
956
  //#endregion
659
- //#region src/services/fileEditPaths/index.ts
660
- /** The directory this package owns, under whichever root holds agent state. */
661
- const STATE_DIRECTORY = "po-file-edit";
662
- function hash(value) {
663
- return (0, node_crypto.createHash)("sha256").update(value).digest("hex").slice(0, 16);
957
+ //#region src/services/timelineStore/index.ts
958
+ const LOCK_RETRY_MS = 25;
959
+ const LOCK_RETRIES = 400;
960
+ /**
961
+ * How long a lock file may sit untouched before a waiter treats it as abandoned.
962
+ *
963
+ * An append writes one line, so a holder that has been there for half a minute
964
+ * is a process that died without unlinking. Without this, that one file would
965
+ * block every later append to the same timeline permanently.
966
+ */
967
+ const LOCK_STALE_MS = 3e4;
968
+ function hasCode(error, code) {
969
+ return error instanceof Error && "code" in error && error.code === code;
664
970
  }
665
- var FileEditPaths = class {
666
- environment;
667
- constructor(environment = process.env) {
668
- this.environment = environment;
971
+ var TimelineStore = class {
972
+ filePath;
973
+ initialize(filePath) {
974
+ this.filePath = filePath;
669
975
  }
670
- sessionKey(sessionId, env = this.environment) {
671
- if (env[_agimon_ai_po_core_childProcess.SUBAGENT_CHILD_ENV]) {
672
- const parent = env[_agimon_ai_po_core_childProcess.SUBAGENT_PARENT_SESSION_ENV];
673
- if (parent) return parent;
976
+ async append(event) {
977
+ await this.withLock(async () => node_fs_promises.default.appendFile(this.requirePath(), `${JSON.stringify(event)}\n`, "utf8"));
978
+ }
979
+ async list() {
980
+ return foldEntries(confirmedChanges(await this.events()));
981
+ }
982
+ async versions(filePath) {
983
+ return foldVersions(confirmedChanges(await this.events()), filePath);
984
+ }
985
+ async clear() {
986
+ try {
987
+ await node_fs_promises.default.unlink(this.requirePath());
988
+ } catch (error) {
989
+ if (!hasCode(error, "ENOENT")) throw error;
990
+ }
991
+ }
992
+ /** Every recorded change, or none at all when the session has not written yet. */
993
+ async events() {
994
+ let content;
995
+ try {
996
+ content = await node_fs_promises.default.readFile(this.requirePath(), "utf8");
997
+ } catch (error) {
998
+ if (hasCode(error, "ENOENT")) return [];
999
+ throw error;
1000
+ }
1001
+ return parseTimeline(content, (line) => console.warn(`Ignoring malformed file edit timeline line: ${line.slice(0, 200)}`));
1002
+ }
1003
+ requirePath() {
1004
+ if (!this.filePath) throw new Error("Timeline store is not initialized");
1005
+ return this.filePath;
1006
+ }
1007
+ async withLock(operation) {
1008
+ const lockPath = `${this.requirePath()}.lock`;
1009
+ const lock = await this.acquire(lockPath);
1010
+ try {
1011
+ return await operation();
1012
+ } finally {
1013
+ await lock.close();
1014
+ await this.release(lockPath);
674
1015
  }
675
- return sessionId;
676
1016
  }
677
- /**
678
- * Where every session's state lives: the Pi agent directory, the same root
679
- * every other Po package writes to, and never inside the working tree.
680
- *
681
- * An earlier layout put this in the repository's git common directory. That
682
- * is git's own storage: nothing in git's lifecycle prunes a directory we add
683
- * to it, a linked worktree writes into the main checkout rather than its own,
684
- * a submodule writes inside `.git/modules`, and `PI_CODING_AGENT_DIR` was
685
- * ignored outright. The snapshots are verbatim copies of files the session
686
- * touched, so where they land is a question about handling content, not a
687
- * question about convenience.
688
- */
689
- stateDirectory() {
690
- return node_path.default.join((0, _agimon_ai_po_core_piSettings.piAgentDirectory)(this.environment, this.environment.HOME), STATE_DIRECTORY);
1017
+ /** Waits for the lock file, breaking one an earlier process left behind. */
1018
+ async acquire(lockPath) {
1019
+ for (let attempt = 0; attempt < LOCK_RETRIES; attempt += 1) try {
1020
+ return await node_fs_promises.default.open(lockPath, "wx");
1021
+ } catch (error) {
1022
+ if (!hasCode(error, "EEXIST")) throw error;
1023
+ if (await this.breakStale(lockPath)) continue;
1024
+ await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));
1025
+ }
1026
+ throw new Error(`Timed out acquiring timeline lock ${lockPath}`);
691
1027
  }
692
- /**
693
- * One session's timeline, named from its working directory and its session so
694
- * the hub and the session API can find it from another process knowing only
695
- * those two things.
696
- */
697
- async timelinePath(cwd, sessionKey) {
698
- const directory = this.stateDirectory();
699
- await node_fs_promises.default.mkdir(directory, { recursive: true });
700
- return node_path.default.join(directory, `${hash(await node_fs_promises.default.realpath(cwd))}-${hash(sessionKey)}.jsonl`);
1028
+ /** Whether the lock is now free to take, having removed it when its holder is gone. */
1029
+ async breakStale(lockPath) {
1030
+ try {
1031
+ const stats = await node_fs_promises.default.stat(lockPath);
1032
+ if (Date.now() - stats.mtimeMs < LOCK_STALE_MS) return false;
1033
+ await node_fs_promises.default.unlink(lockPath);
1034
+ return true;
1035
+ } catch (error) {
1036
+ if (hasCode(error, "ENOENT")) return true;
1037
+ throw error;
1038
+ }
701
1039
  }
702
- /**
703
- * Where this session's content snapshots live: beside its timeline and named
704
- * after it, so the two are found together and cleared together.
705
- */
706
- async snapshotsPath(cwd, sessionKey) {
707
- return `${(await this.timelinePath(cwd, sessionKey)).replace(/\.jsonl$/u, "")}.blobs`;
1040
+ async release(lockPath) {
1041
+ try {
1042
+ await node_fs_promises.default.unlink(lockPath);
1043
+ } catch (error) {
1044
+ if (!hasCode(error, "ENOENT")) console.warn(`Could not remove timeline lock: ${String(error)}`);
1045
+ }
708
1046
  }
709
1047
  };
710
1048
  //#endregion
711
- //#region src/services/gitStatus/index.ts
1049
+ //#region src/services/manifestComparison/index.ts
712
1050
  /**
713
- * Answers the unchanged question with git, in two batched calls per chunk.
714
- *
715
- * One technology per adapter. This is where git enters the scan path; the
716
- * tracker that depends on the capability keeps importing the port.
1051
+ * Directories a working tree fills with output nobody wants listed as an edit.
717
1052
  *
718
- * `ls-files` names which of the given paths git tracks at all, and `status`
719
- * names which of those moved. Everything else, an ignored build artefact, a
720
- * temporary file, a tree with no repository, falls out of both answers and is
721
- * therefore never reported as unchanged: the caller must keep recording it,
722
- * because git has nothing to say about a file it never saw.
1053
+ * Two kinds live here. Most are the build and dependency trees every checkout
1054
+ * grows. The rest are where tooling, including this agent's own, writes while a
1055
+ * session runs: a telemetry log under `logs`, a test run's artifacts under
1056
+ * `test-results` and `playwright-report`, scratch space under `tmp`, and agent
1057
+ * state under `.pi`. Those are skipped by construction rather than judged file
1058
+ * by file, because a walk that enters them reports the session watching itself.
723
1059
  */
724
- /** Paths per git invocation, so a large scan cannot overflow the argument list. */
725
- const CHUNK = 200;
726
- const MAX_BUFFER = 4194304;
727
- const run = (0, node_util.promisify)(node_child_process.execFile);
728
- function chunked(values, size) {
729
- const groups = [];
730
- for (let index = 0; index < values.length; index += size) groups.push(values.slice(index, index + size));
731
- return groups;
732
- }
733
- function splitRecords(output) {
734
- return output.split("\0").filter((entry) => entry !== "");
735
- }
1060
+ const IGNORED_DIRECTORIES = /* @__PURE__ */ new Set([
1061
+ ".git",
1062
+ ".hg",
1063
+ ".svn",
1064
+ ".cache",
1065
+ ".gradle",
1066
+ ".next",
1067
+ ".nuxt",
1068
+ ".nx",
1069
+ ".pi",
1070
+ ".pnpm-store",
1071
+ ".turbo",
1072
+ ".venv",
1073
+ "__pycache__",
1074
+ "build",
1075
+ "coverage",
1076
+ "dist",
1077
+ "logs",
1078
+ "node_modules",
1079
+ "out",
1080
+ "playwright-report",
1081
+ "target",
1082
+ "test-results",
1083
+ "tmp",
1084
+ "vendor",
1085
+ "venv"
1086
+ ]);
736
1087
  /**
737
- * The paths named by `status --porcelain -z`, whose records carry a two-letter
738
- * code and a space. A rename adds a bare second record; keeping it is harmless,
739
- * because every path in this set is one the caller records anyway.
1088
+ * How a file is summarised. Size and modification time are what a walk can read
1089
+ * cheaply for thousands of files; hashing every one of them would turn a scan
1090
+ * into a read of the whole tree.
740
1091
  */
741
- function statusPaths(output) {
742
- return splitRecords(output).map((record) => record.length > 3 && record[2] === " " ? record.slice(3) : record);
1092
+ function fingerprintOf(size, modifiedMs) {
1093
+ return `${size}:${modifiedMs}`;
743
1094
  }
744
- function isInside$1(root, filePath) {
745
- const relative = node_path.default.relative(root, filePath);
746
- return relative !== "" && !relative.startsWith("..") && !node_path.default.isAbsolute(relative);
1095
+ /** The size half of a fingerprint, which only the adapter that wrote it can read. */
1096
+ function sizeOf(fingerprint) {
1097
+ const separator = fingerprint.indexOf(":");
1098
+ return separator === -1 ? fingerprint : fingerprint.slice(0, separator);
747
1099
  }
748
- var NodeGitStatusAdapter = class {
749
- async unchanged(cwd, filePaths) {
750
- const clean = /* @__PURE__ */ new Set();
751
- if (filePaths.length === 0) return clean;
752
- const root = await this.topLevel(cwd);
753
- if (root === void 0) return clean;
754
- for (const group of chunked(filePaths.filter((filePath) => isInside$1(root, filePath)), CHUNK)) {
755
- const relative = group.map((filePath) => node_path.default.relative(root, filePath));
756
- const tracked = await this.git(root, [
757
- "ls-files",
758
- "-z",
759
- "--",
760
- ...relative
761
- ]);
762
- if (tracked === void 0) continue;
763
- const dirty = await this.git(root, [
764
- "status",
765
- "--porcelain",
766
- "-z",
767
- "--untracked-files=no",
768
- "--",
769
- ...relative
770
- ]);
771
- if (dirty === void 0) continue;
772
- const moved = new Set(statusPaths(dirty));
773
- for (const entry of splitRecords(tracked)) if (!moved.has(entry)) clean.add(node_path.default.resolve(root, entry));
774
- }
775
- return clean;
1100
+ /** Every path added, removed, or modified between two manifests, sorted. */
1101
+ function changedBetween(before, after) {
1102
+ const moved = /* @__PURE__ */ new Set();
1103
+ for (const [filePath, fingerprint] of after.entries) if (before.entries.get(filePath) !== fingerprint) moved.add(filePath);
1104
+ for (const filePath of before.entries.keys()) if (!after.entries.has(filePath)) moved.add(filePath);
1105
+ return [...moved].sort();
1106
+ }
1107
+ /** Whether two fingerprints disagree about size; false when either side is absent. */
1108
+ function sizesDiffer(before, after) {
1109
+ if (before === void 0 || after === void 0) return false;
1110
+ return sizeOf(before) !== sizeOf(after);
1111
+ }
1112
+ //#endregion
1113
+ //#region src/services/treeManifest/index.ts
1114
+ var NodeTreeManifestAdapter = class {
1115
+ maxEntries;
1116
+ maxDepth;
1117
+ ignored;
1118
+ constructor(options = {}) {
1119
+ this.maxEntries = options.maxEntries ?? 2e4;
1120
+ this.maxDepth = options.maxDepth ?? 12;
1121
+ this.ignored = options.ignoredDirectories ?? IGNORED_DIRECTORIES;
776
1122
  }
777
- /** The repository root, or undefined when this tree is not one. */
778
- async topLevel(cwd) {
779
- const root = (await this.git(cwd, ["rev-parse", "--show-toplevel"]))?.trim();
780
- return root === void 0 || root === "" ? void 0 : node_path.default.resolve(root);
1123
+ async take(root, exclude = []) {
1124
+ const entries = /* @__PURE__ */ new Map();
1125
+ const skipped = new Set(exclude.map((entry) => node_path.default.resolve(entry)));
1126
+ return {
1127
+ entries,
1128
+ truncated: await this.walk(root, 0, entries, skipped)
1129
+ };
781
1130
  }
782
- /** Git's stdout, or undefined when the call failed for any reason at all. */
783
- async git(cwd, args) {
1131
+ async fingerprint(filePath) {
784
1132
  try {
785
- const { stdout } = await run("git", [...args], {
786
- cwd,
787
- encoding: "utf8",
788
- maxBuffer: MAX_BUFFER
789
- });
790
- return stdout;
1133
+ const stat = await node_fs_promises.default.stat(filePath);
1134
+ return stat.isFile() ? fingerprintOf(stat.size, stat.mtimeMs) : void 0;
1135
+ } catch {
1136
+ return;
1137
+ }
1138
+ }
1139
+ async modifiedAt(filePath) {
1140
+ try {
1141
+ const stat = await node_fs_promises.default.stat(filePath);
1142
+ return stat.isFile() ? stat.mtimeMs : void 0;
791
1143
  } catch {
792
1144
  return;
793
1145
  }
794
- }
795
- };
1146
+ }
1147
+ changed(before, after) {
1148
+ return changedBetween(before, after);
1149
+ }
1150
+ sizeChanged(before, after) {
1151
+ return sizesDiffer(before, after);
1152
+ }
1153
+ /** Fills `entries` depth-first and answers whether a cap cut the walk short. */
1154
+ async walk(directory, depth, entries, skipped) {
1155
+ if (depth > this.maxDepth) return true;
1156
+ let listing;
1157
+ try {
1158
+ listing = await node_fs_promises.default.readdir(directory, { withFileTypes: true });
1159
+ } catch {
1160
+ return false;
1161
+ }
1162
+ let truncated = false;
1163
+ for (const entry of listing) {
1164
+ if (entries.size >= this.maxEntries) return true;
1165
+ const entryPath = node_path.default.join(directory, entry.name);
1166
+ if (skipped.has(entryPath)) continue;
1167
+ if (entry.isSymbolicLink()) continue;
1168
+ if (entry.isDirectory()) {
1169
+ if (this.ignored.has(entry.name)) continue;
1170
+ truncated = await this.walk(entryPath, depth + 1, entries, skipped) || truncated;
1171
+ continue;
1172
+ }
1173
+ if (!entry.isFile()) continue;
1174
+ try {
1175
+ const stat = await node_fs_promises.default.stat(entryPath);
1176
+ entries.set(entryPath, fingerprintOf(stat.size, stat.mtimeMs));
1177
+ } catch {}
1178
+ }
1179
+ return truncated;
1180
+ }
1181
+ };
1182
+ //#endregion
1183
+ //#region src/types/webFiles.ts
1184
+ /** The frame type the hub publishes and the web plugin claims; declared in the poWeb block too. */
1185
+ const filesChannelType = "file_edits";
1186
+ /** Footer status key whose presence shows the activity group; the extension publishes it. */
1187
+ const filesStatusKey = "po-file-edit-files";
1188
+ //#endregion
1189
+ //#region src/services/filesChannel/index.ts
1190
+ /**
1191
+ * The changed-files channel consumes snapshots emitted by the owning session's
1192
+ * server plugin. Durable timeline reads seed a channel that starts after session
1193
+ * startup.
1194
+ */
1195
+ function filesPayload(value) {
1196
+ return typeof value === "object" && value !== null && Array.isArray(value.items);
1197
+ }
1198
+ /**
1199
+ * The files data channel: one direct-event subscription per managed session,
1200
+ * published as { items } payloads under the 'file_edits' frame type.
1201
+ */
1202
+ function createFilesChannel(storage) {
1203
+ return {
1204
+ frameType: filesChannelType,
1205
+ start(host) {
1206
+ const latest = /* @__PURE__ */ new Map();
1207
+ const subscriptions = /* @__PURE__ */ new Map();
1208
+ return {
1209
+ payloadFor(scope) {
1210
+ const items = latest.get(scope.sessionId);
1211
+ return items === void 0 ? void 0 : { items };
1212
+ },
1213
+ sessionAdded(scope) {
1214
+ subscriptions.get(scope.sessionId)?.();
1215
+ const paths = storage.paths(scope.environment);
1216
+ let current = true;
1217
+ let receivedDirect = false;
1218
+ const unsubscribe = host.directEvents.subscribe(filesChannelType, scope.sessionId, (payload) => {
1219
+ if (!filesPayload(payload)) return;
1220
+ receivedDirect = true;
1221
+ latest.set(scope.sessionId, payload.items);
1222
+ host.publish(scope.sessionId, payload);
1223
+ }, { replayLatest: true });
1224
+ subscriptions.set(scope.sessionId, () => {
1225
+ current = false;
1226
+ unsubscribe();
1227
+ });
1228
+ (async () => {
1229
+ let items = [];
1230
+ try {
1231
+ const timelinePath = await paths.timelinePath(scope.cwd, paths.sessionKey(scope.sessionId));
1232
+ items = await storage.sessionFiles(timelinePath, scope.cwd);
1233
+ } catch {}
1234
+ if (!current || receivedDirect) return;
1235
+ latest.set(scope.sessionId, items);
1236
+ host.publish(scope.sessionId, { items });
1237
+ })().catch((error) => host.onNotice(`File-edit channel seed failed: ${String(error)}`));
1238
+ },
1239
+ sessionRemoved(sessionId) {
1240
+ subscriptions.get(sessionId)?.();
1241
+ subscriptions.delete(sessionId);
1242
+ latest.delete(sessionId);
1243
+ },
1244
+ close() {
1245
+ for (const unsubscribe of subscriptions.values()) unsubscribe();
1246
+ subscriptions.clear();
1247
+ latest.clear();
1248
+ }
1249
+ };
1250
+ }
1251
+ };
1252
+ }
796
1253
  //#endregion
797
1254
  //#region src/services/poIgnore/index.ts
798
1255
  function matchablePath(relPath) {
@@ -828,438 +1285,511 @@ function filterPoIgnoredFiles(items, content) {
828
1285
  if (ignored === void 0) return items;
829
1286
  return items.filter((item) => !ignored(item.relPath));
830
1287
  }
831
- /** How much of a file is read before deciding it is binary. */
832
- const BINARY_SAMPLE_BYTES$1 = 8192;
833
- const MISSING_CODES = /* @__PURE__ */ new Set([
834
- "ENOENT",
835
- "ENOTDIR",
836
- "EISDIR",
837
- "ENAMETOOLONG"
838
- ]);
839
- function hasCode$2(error, codes) {
840
- return error instanceof Error && "code" in error && typeof error.code === "string" && codes.has(error.code);
841
- }
842
- var NodeSnapshotStoreAdapter = class {
843
- directory;
844
- initialize(directory) {
845
- this.directory = directory;
846
- }
847
- async capture(filePath) {
848
- let raw;
849
- try {
850
- if ((await node_fs_promises.default.stat(filePath)).size > 1048576) return void 0;
851
- raw = await node_fs_promises.default.readFile(filePath);
852
- } catch (error) {
853
- if (hasCode$2(error, MISSING_CODES)) return void 0;
854
- throw error;
855
- }
856
- if (raw.byteLength > 1048576) return void 0;
857
- if (raw.subarray(0, BINARY_SAMPLE_BYTES$1).includes(0)) return void 0;
858
- return this.put(raw.toString("utf8"));
859
- }
860
- async put(content) {
861
- const hash = (0, node_crypto.createHash)("sha256").update(content, "utf8").digest("hex");
862
- const blobPath = node_path.default.join(this.requireDirectory(), hash);
863
- try {
864
- await node_fs_promises.default.access(blobPath);
865
- return hash;
866
- } catch (error) {
867
- if (!hasCode$2(error, MISSING_CODES)) throw error;
868
- }
869
- await node_fs_promises.default.mkdir(this.requireDirectory(), { recursive: true });
870
- await node_fs_promises.default.writeFile(blobPath, content, "utf8");
871
- return hash;
872
- }
873
- async read(hash) {
874
- if (!/^[0-9a-f]{64}$/u.test(hash)) return void 0;
875
- try {
876
- return await node_fs_promises.default.readFile(node_path.default.join(this.requireDirectory(), hash), "utf8");
877
- } catch (error) {
878
- if (hasCode$2(error, MISSING_CODES)) return void 0;
879
- throw error;
880
- }
881
- }
882
- async clear() {
883
- if (this.directory === void 0) return;
884
- await node_fs_promises.default.rm(this.directory, {
885
- recursive: true,
886
- force: true
887
- });
888
- }
889
- requireDirectory() {
890
- if (this.directory === void 0) throw new Error("Snapshot store is not initialized");
891
- return this.directory;
892
- }
893
- };
894
1288
  //#endregion
895
- //#region src/services/fileChanges/index.ts
896
- const TOOLS = /* @__PURE__ */ new Set([
897
- "edit",
898
- "write",
899
- "bash",
900
- "user"
901
- ]);
902
- function isRecord(value) {
903
- return typeof value === "object" && value !== null && !Array.isArray(value);
904
- }
905
- function optionalString(value) {
906
- return typeof value === "string" && value !== "" ? value : void 0;
907
- }
908
- function optionalCount(value) {
909
- return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
910
- }
911
- /** Narrows one parsed line, or answers null so a malformed line can be skipped. */
912
- function parseTimelineEvent(value) {
913
- if (!isRecord(value)) return null;
914
- const { version, path: filePath, tool, at } = value;
915
- if (typeof filePath !== "string" || filePath === "") return null;
916
- if (typeof at !== "number" || !Number.isFinite(at)) return null;
917
- if (typeof tool !== "string" || !TOOLS.has(tool)) return null;
918
- if (version === 1) {
919
- if (tool === "user") return null;
920
- return {
921
- version: 1,
922
- path: filePath,
923
- tool,
924
- at
925
- };
926
- }
927
- if (version !== 2) return null;
928
- return {
929
- version: 2,
930
- path: filePath,
931
- tool,
932
- at,
933
- origin: value.origin === "scan" ? "scan" : "tool",
934
- ...optionalString(value.before) === void 0 ? {} : { before: value.before },
935
- ...optionalString(value.after) === void 0 ? {} : { after: value.after },
936
- ...optionalCount(value.additions) === void 0 ? {} : { additions: value.additions },
937
- ...optionalCount(value.removals) === void 0 ? {} : { removals: value.removals },
938
- ...value.verified === true ? { verified: true } : {},
939
- ...value.created === true ? { created: true } : {}
940
- };
941
- }
942
- /** Every recorded line of the timeline, malformed ones dropped, in file order. */
943
- function parseTimeline(content, onMalformed) {
944
- const events = [];
945
- for (const line of content.split("\n")) {
946
- if (line === "") continue;
947
- let parsed;
948
- try {
949
- parsed = JSON.parse(line);
950
- } catch {
951
- onMalformed?.(line);
952
- continue;
953
- }
954
- const event = parseTimelineEvent(parsed);
955
- if (event === null) onMalformed?.(line);
956
- else events.push(event);
957
- }
958
- return events;
959
- }
1289
+ //#region src/services/sessionFileRows/index.ts
960
1290
  /**
961
- * Whether a recorded change is evidence that the file's content actually moved.
1291
+ * Presents a session's timeline as the rows the dock lists.
962
1292
  *
963
- * A tool change names its file and reads both sides, so it always is. A scan
964
- * change is a tree comparison of size and modification time, which a checkout,
965
- * an install, or a command that merely touched a file moves as readily as an
966
- * edit does; only a scan the tracker confirmed carries `verified`. Version 1
967
- * lines predate the distinction entirely, so a bash one cannot be trusted.
1293
+ * A file the session changed and then removed is left out, and so is a path a
1294
+ * bash call only touched: a command that moves a modification time without
1295
+ * changing a byte is not an edit, and listing it buries the ones that are. The
1296
+ * dock is a list of things to open, and a row that can only ever answer "this
1297
+ * is gone" is a dead end; the timeline still holds the change, so a tab already
1298
+ * open on the file keeps working and says so.
968
1299
  */
969
- function isConfirmedChange(event) {
970
- if (event.version !== 2) return event.tool !== "bash";
971
- return event.origin !== "scan" || event.verified === true;
972
- }
973
- /** The recorded changes worth listing, which is every change but an unconfirmed touch. */
974
- function confirmedChanges(events) {
975
- return events.filter(isConfirmedChange);
976
- }
977
- /** One row per file, newest change first, which is the order both docks list in. */
978
- function foldEntries(events) {
979
- const folded = /* @__PURE__ */ new Map();
980
- for (const event of events) {
981
- const current = folded.get(event.path);
982
- folded.set(event.path, {
983
- path: event.path,
984
- tool: event.at >= (current?.at ?? 0) ? event.tool : current?.tool ?? event.tool,
985
- at: Math.max(event.at, current?.at ?? 0),
986
- count: (current?.count ?? 0) + 1
987
- });
1300
+ async function sessionFileRows({ content, cwd, exists, readPoIgnore }) {
1301
+ const events = confirmedChanges(parseTimeline(content));
1302
+ const entries = foldEntries(events);
1303
+ const present = await Promise.all(entries.map((entry) => exists(entry.path)));
1304
+ const items = entries.filter((_entry, index) => present[index]).map((entry) => ({
1305
+ path: entry.path,
1306
+ relPath: node_path.default.relative(cwd, entry.path) || entry.path,
1307
+ tool: entry.tool,
1308
+ at: entry.at,
1309
+ count: entry.count,
1310
+ diffable: isDiffable(foldVersions(events, entry.path))
1311
+ }));
1312
+ try {
1313
+ return filterPoIgnoredFiles(items, await readPoIgnore());
1314
+ } catch {
1315
+ return items;
988
1316
  }
989
- return [...folded.values()].sort((left, right) => right.at - left.at);
990
- }
991
- /** One file's history, oldest first, numbered so a reader can name a version. */
992
- function foldVersions(events, filePath) {
993
- return events.filter((event) => event.path === filePath).sort((left, right) => left.at - right.at).map((event, offset) => {
994
- const version = {
995
- index: offset + 1,
996
- tool: event.tool,
997
- at: event.at,
998
- origin: event.version === 2 ? event.origin : "scan"
999
- };
1000
- if (event.version !== 2) return version;
1001
- return {
1002
- ...version,
1003
- ...event.before === void 0 ? {} : { before: event.before },
1004
- ...event.after === void 0 ? {} : { after: event.after },
1005
- ...event.additions === void 0 ? {} : { additions: event.additions },
1006
- ...event.removals === void 0 ? {} : { removals: event.removals },
1007
- ...event.verified === true ? { verified: true } : {},
1008
- ...event.created === true ? { created: true } : {}
1009
- };
1010
- });
1011
1317
  }
1012
- /**
1013
- * Whether a file can be diffed at all: some version has to give the diff a
1014
- * starting point. A captured baseline is one. So is a version that created the
1015
- * file, whose starting point is nothing at all.
1016
- *
1017
- * A file only ever seen after the fact, which is every file a bash script
1018
- * wrote, still cannot be.
1019
- */
1020
- function isDiffable(versions) {
1021
- return versions.some((version) => version.before !== void 0 || version.created === true);
1318
+ //#endregion
1319
+ //#region src/services/webFilesChannel/index.ts
1320
+ /** Whether the file is still there to be opened. */
1321
+ async function stillExists(filePath) {
1322
+ try {
1323
+ return (await node_fs_promises.default.stat(filePath)).isFile();
1324
+ } catch {
1325
+ return false;
1326
+ }
1022
1327
  }
1023
- /** The oldest captured baseline for a file, which is what the whole-session diff starts from. */
1024
- function baselineOf(versions) {
1025
- return versions.find((version) => version.before !== void 0)?.before;
1328
+ /** Reads one session's timeline from Node's files and presents it as the rows the dock lists. */
1329
+ async function readSessionFiles(timelinePath, cwd) {
1330
+ let content;
1331
+ try {
1332
+ content = await node_fs_promises.default.readFile(timelinePath, "utf8");
1333
+ } catch {
1334
+ return [];
1335
+ }
1336
+ return sessionFileRows({
1337
+ content,
1338
+ cwd,
1339
+ exists: stillExists,
1340
+ readPoIgnore: () => node_fs_promises.default.readFile(node_path.default.join(cwd, ".poignore"), "utf8")
1341
+ });
1026
1342
  }
1027
1343
  //#endregion
1028
- //#region src/services/timelineStore/index.ts
1029
- const LOCK_RETRY_MS = 25;
1030
- const LOCK_RETRIES = 400;
1344
+ //#region src/services/fileEditStorage/index.ts
1031
1345
  /**
1032
- * How long a lock file may sit untouched before a waiter treats it as abandoned.
1346
+ * The storage a session's file history uses on Node: the real file system,
1347
+ * read directly, with the cross-process lock a subagent child's appends need.
1033
1348
  *
1034
- * An append writes one line, so a holder that has been there for half a minute
1035
- * is a process that died without unlinking. Without this, that one file would
1036
- * block every later append to the same timeline permanently.
1349
+ * The edge build replaces this module with `index.edge.ts`, which reads the
1350
+ * file system the host injects. Node has no use for one, so the parameter is
1351
+ * accepted to keep the two builds callable alike and left unused.
1037
1352
  */
1038
- const LOCK_STALE_MS = 3e4;
1039
- function hasCode$1(error, code) {
1040
- return error instanceof Error && "code" in error && error.code === code;
1041
- }
1042
- var TimelineStore = class {
1043
- filePath;
1044
- initialize(filePath) {
1045
- this.filePath = filePath;
1046
- }
1047
- async append(event) {
1048
- await this.withLock(async () => node_fs_promises.default.appendFile(this.requirePath(), `${JSON.stringify(event)}\n`, "utf8"));
1049
- }
1050
- async list() {
1051
- return foldEntries(confirmedChanges(await this.events()));
1353
+ const nodePresenceFiles = {
1354
+ isFile: async (filePath) => (await node_fs_promises.default.stat(filePath).catch(() => void 0))?.isFile() === true,
1355
+ realpath: (filePath) => node_fs_promises.default.realpath(filePath).catch(() => void 0),
1356
+ read: (filePath) => node_fs_promises.default.readFile(filePath).catch(() => void 0)
1357
+ };
1358
+ /**
1359
+ * The plans directory Plan mode writes to, resolved the way Plan resolves it, so
1360
+ * a plan link in the transcript opens in the file view. A config that cannot be
1361
+ * read admits nothing extra rather than failing the preview.
1362
+ */
1363
+ function plansRoots(cwd, environment, homeDirectory) {
1364
+ const home = homeDirectory ?? environment.HOME ?? node_os.default.homedir();
1365
+ try {
1366
+ const configured = (0, _agimon_ai_po_config.loadPoConfig)(cwd, home, environment).modes?.planning?.plansDirectory;
1367
+ return [(0, _agimon_ai_po_config.resolvePlanningPlansDirectory)(configured, cwd, home)];
1368
+ } catch {
1369
+ return [];
1052
1370
  }
1053
- async versions(filePath) {
1054
- return foldVersions(confirmedChanges(await this.events()), filePath);
1371
+ }
1372
+ function createFileEditStorage(_fileSystem) {
1373
+ return {
1374
+ paths: (environment) => new FileEditPaths(environment),
1375
+ timeline: () => new TimelineStore(),
1376
+ snapshots: () => new NodeSnapshotStoreAdapter(),
1377
+ manifests: () => new NodeTreeManifestAdapter(),
1378
+ git: () => new NodeGitStatusAdapter(),
1379
+ workingFiles: () => new NodeWorkingFiles(),
1380
+ presenceFiles: () => nodePresenceFiles,
1381
+ sessionFiles: readSessionFiles,
1382
+ readableRoots: ({ cwd, environment, homeDirectory }) => () => plansRoots(cwd, environment, homeDirectory),
1383
+ sweepAbandoned: (directory, keep) => sweepSessionState({
1384
+ directory,
1385
+ keep
1386
+ }),
1387
+ clearOnClose: true
1388
+ };
1389
+ }
1390
+ //#endregion
1391
+ //#region src/services/editPresence/index.ts
1392
+ const PATH_TOOLS = /* @__PURE__ */ new Set([
1393
+ "read",
1394
+ "edit",
1395
+ "write"
1396
+ ]);
1397
+ const EDIT_TOOLS = /* @__PURE__ */ new Set(["edit", "write"]);
1398
+ const MAX_GREP_FILES = 50;
1399
+ const MAX_NOTE_LINES = 10;
1400
+ const MINUTE_MS = 6e4;
1401
+ const SHORT_ID_LENGTH = 8;
1402
+ /** Pi's built-in grep prints match rows as `relative/path:line: text`. */
1403
+ const PI_GREP_ROW = /^(.+?):(\d+): /u;
1404
+ function stringArg(args, key) {
1405
+ if (typeof args !== "object" || args === null) return void 0;
1406
+ const value = args[key];
1407
+ return typeof value === "string" && value.length > 0 ? value : void 0;
1408
+ }
1409
+ function textOf(content) {
1410
+ return content.map((part) => part.type === "text" && "text" in part && typeof part.text === "string" ? part.text : "").join("\n");
1411
+ }
1412
+ async function grepFiles(call, files) {
1413
+ const lines = textOf(call.content).split("\n");
1414
+ const headers = lines.flatMap((line) => {
1415
+ const header = (0, _agimon_ai_po_hashline.parseFileHeader)(line);
1416
+ return header === void 0 ? [] : [(0, _agimon_ai_po_hashline_files.resolveInputPath)(header.path, call.cwd)];
1417
+ });
1418
+ if (headers.length > 0) return [...new Set(headers)].slice(0, MAX_GREP_FILES);
1419
+ const rows = lines.flatMap((line) => {
1420
+ const match = PI_GREP_ROW.exec(line)?.[1];
1421
+ return match === void 0 ? [] : [match];
1422
+ });
1423
+ if (rows.length === 0) return [];
1424
+ const searchPath = (0, _agimon_ai_po_hashline_files.resolveInputPath)(stringArg(call.args, "path") ?? ".", call.cwd);
1425
+ if (await files.isFile(searchPath)) return [searchPath];
1426
+ return [...new Set(rows.map((row) => node_path.default.resolve(searchPath, row)))].slice(0, MAX_GREP_FILES);
1427
+ }
1428
+ async function touchedFiles(call, files) {
1429
+ if (PATH_TOOLS.has(call.toolName)) {
1430
+ const input = stringArg(call.args, "path");
1431
+ return input === void 0 ? [] : [await (0, _agimon_ai_po_hashline_files.resolveReadInputPath)(input, call.cwd)];
1055
1432
  }
1056
- async clear() {
1057
- try {
1058
- await node_fs_promises.default.unlink(this.requirePath());
1059
- } catch (error) {
1060
- if (!hasCode$1(error, "ENOENT")) throw error;
1433
+ return call.toolName === "grep" ? grepFiles(call, files) : [];
1434
+ }
1435
+ function ago(elapsed) {
1436
+ const minutes = Math.floor(elapsed / MINUTE_MS);
1437
+ return minutes < 1 ? "under 1m ago" : `${minutes}m ago`;
1438
+ }
1439
+ function renderNote(lines) {
1440
+ const shown = lines.slice(0, MAX_NOTE_LINES);
1441
+ const more = lines.length - shown.length;
1442
+ return [
1443
+ PRESENCE_NOTE_TITLE,
1444
+ ...shown,
1445
+ ...more > 0 ? [`- and ${more} more`] : [],
1446
+ PRESENCE_NOTE_GUIDANCE
1447
+ ].join("\n");
1448
+ }
1449
+ /**
1450
+ * Notes live editors of the files a tool call touched, then records the caller's own successful edit.
1451
+ * Returns the content with one note appended, or undefined when there is nothing to add, so callers
1452
+ * never rewrite a result needlessly.
1453
+ */
1454
+ async function observePresence(presence, agent, call, now = Date.now(), files = createFileEditStorage().presenceFiles()) {
1455
+ const recording = EDIT_TOOLS.has(call.toolName) && !call.isError;
1456
+ const lines = [];
1457
+ for (const file of await touchedFiles(call, files)) {
1458
+ const real = await files.realpath(file);
1459
+ if (real === void 0) continue;
1460
+ const others = presence.touch(real, agent);
1461
+ let bytes;
1462
+ if (others.length > 0) {
1463
+ bytes = await files.read(real);
1464
+ const current = bytes === void 0 ? void 0 : (0, _agimon_ai_po_hashline_files.computeFileTag)(bytes);
1465
+ const shown = (0, _agimon_ai_po_hashline_files.displayPath)(file, call.cwd);
1466
+ for (const entry of others) {
1467
+ const state = entry.tag === current ? "unchanged" : "changed";
1468
+ lines.push(`- ${shown}: ${entry.agent.label()}, ${ago(now - entry.at)}, file ${state} since their edit.`);
1469
+ }
1470
+ }
1471
+ if (recording) {
1472
+ bytes ??= await files.read(real);
1473
+ if (bytes !== void 0) presence.record(real, {
1474
+ agent,
1475
+ tag: (0, _agimon_ai_po_hashline_files.computeFileTag)(bytes),
1476
+ at: now
1477
+ });
1061
1478
  }
1062
1479
  }
1063
- /** Every recorded change, or none at all when the session has not written yet. */
1064
- async events() {
1065
- let content;
1480
+ if (lines.length === 0) return void 0;
1481
+ return [...call.content, {
1482
+ type: "text",
1483
+ text: renderNote(lines)
1484
+ }];
1485
+ }
1486
+ /** Edit presence for one hub session and the in-process children it spawns. */
1487
+ function createSessionPresence(options) {
1488
+ const { sessionId, presence } = options;
1489
+ const sessionAgent = {
1490
+ key: `session:${sessionId}`,
1491
+ label: () => `session ${sessionId}${options.workflowStep ? " (workflow step)" : ""}`,
1492
+ contact: sessionId,
1493
+ isLive: options.isLive
1494
+ };
1495
+ const safely = async (work) => {
1066
1496
  try {
1067
- content = await node_fs_promises.default.readFile(this.requirePath(), "utf8");
1497
+ return await work();
1068
1498
  } catch (error) {
1069
- if (hasCode$1(error, "ENOENT")) return [];
1070
- throw error;
1499
+ options.onError?.(error);
1500
+ return;
1071
1501
  }
1072
- return parseTimeline(content, (line) => console.warn(`Ignoring malformed file edit timeline line: ${line.slice(0, 200)}`));
1073
- }
1074
- requirePath() {
1075
- if (!this.filePath) throw new Error("Timeline store is not initialized");
1076
- return this.filePath;
1502
+ };
1503
+ return {
1504
+ toolResult: {
1505
+ event: "tool_result",
1506
+ async handle(event, execution) {
1507
+ const toolName = event.toolName;
1508
+ if (execution.sessionId !== sessionId || typeof toolName !== "string" || !Array.isArray(event.content)) return;
1509
+ const content = event.content;
1510
+ const next = await safely(() => observePresence(presence, sessionAgent, {
1511
+ toolName,
1512
+ args: event.args,
1513
+ content,
1514
+ isError: event.isError === true,
1515
+ cwd: execution.cwd
1516
+ }, void 0, options.files));
1517
+ return next === void 0 ? void 0 : { content: next };
1518
+ }
1519
+ },
1520
+ childHooks: { bind(scope) {
1521
+ const { runId, parentSessionId, agent } = scope.request;
1522
+ const child = {
1523
+ key: `run:${runId}`,
1524
+ label: () => `${options.labelFor(runId) ?? `${agent} (run ${runId.slice(0, SHORT_ID_LENGTH)})`} (subagent of session ${parentSessionId})`,
1525
+ contact: parentSessionId,
1526
+ isLive: () => !scope.signal.aborted
1527
+ };
1528
+ return {
1529
+ beforeTool: () => void 0,
1530
+ async afterTool(event) {
1531
+ const next = await safely(() => observePresence(presence, child, {
1532
+ toolName: event.toolName,
1533
+ args: event.args,
1534
+ content: event.content,
1535
+ isError: event.isError,
1536
+ cwd: scope.request.cwd || options.cwd
1537
+ }, void 0, options.files));
1538
+ return next === void 0 ? void 0 : { content: next };
1539
+ },
1540
+ dispose: async () => presence.forget(child.key)
1541
+ };
1542
+ } },
1543
+ dispose: () => presence.forget(sessionAgent.key)
1544
+ };
1545
+ }
1546
+ //#endregion
1547
+ //#region src/services/editTracker/index.ts
1548
+ const EDIT_TOOL = "edit";
1549
+ const WRITE_TOOL = "write";
1550
+ const BASH_TOOL = "bash";
1551
+ /** Code mode scripts can write files like a shell can, so they get the same before/after scan. */
1552
+ const EXEC_TOOL = "exec";
1553
+ function objectValue(value, key) {
1554
+ if (!value || typeof value !== "object") return void 0;
1555
+ const found = value[key];
1556
+ return typeof found === "string" ? found : void 0;
1557
+ }
1558
+ /**
1559
+ * How far before a call started a write may claim to have happened and still be
1560
+ * attributed to it. A working tree can sit on a filesystem that stores whole
1561
+ * seconds, which floors a write made just after the call began to a stamp just
1562
+ * before it, and the cost of being generous here is one second of the staleness
1563
+ * this check exists to remove.
1564
+ */
1565
+ const MODIFIED_TOLERANCE_MS = 1e3;
1566
+ var EditTracker = class {
1567
+ timeline;
1568
+ snapshots;
1569
+ manifests;
1570
+ pending = /* @__PURE__ */ new Map();
1571
+ /** Start time per in-flight bash call, so its end knows what it may claim. */
1572
+ bracketed = /* @__PURE__ */ new Map();
1573
+ /**
1574
+ * The tree as this tracker last saw it. A bash call compares against it and
1575
+ * then replaces it, so each call costs one walk rather than two, and a change
1576
+ * made between calls is still noticed on the next one.
1577
+ */
1578
+ manifest;
1579
+ /**
1580
+ * This package's own storage, which the walk must never report. The timeline
1581
+ * and its snapshots can land inside the tree being watched, and recording
1582
+ * them would make every change cause another one.
1583
+ */
1584
+ excluded = [];
1585
+ /**
1586
+ * The project's own ignore rules. A path the project disowns is not worth a
1587
+ * git call, a read, or a stored copy of its content, so it is dropped before
1588
+ * it costs any of them.
1589
+ */
1590
+ isIgnored;
1591
+ /**
1592
+ * The last content hash this session saw per path, from either mechanism.
1593
+ * A candidate whose hash has not moved was touched, not edited.
1594
+ */
1595
+ contents = /* @__PURE__ */ new Map();
1596
+ now;
1597
+ git;
1598
+ /**
1599
+ * The scan deferred by the last bash call. Every bracket joins this chain, so
1600
+ * at most one walk runs at a time and each one sees the baseline the previous
1601
+ * one left behind.
1602
+ */
1603
+ scanning = Promise.resolve();
1604
+ constructor(timeline, snapshots, manifests, options = {}) {
1605
+ this.timeline = timeline;
1606
+ this.snapshots = snapshots;
1607
+ this.manifests = manifests;
1608
+ this.now = options.now ?? Date.now;
1609
+ this.git = options.git;
1077
1610
  }
1078
- async withLock(operation) {
1079
- const lockPath = `${this.requirePath()}.lock`;
1080
- const lock = await this.acquire(lockPath);
1081
- try {
1082
- return await operation();
1083
- } finally {
1084
- await lock.close();
1085
- await this.release(lockPath);
1086
- }
1611
+ /**
1612
+ * Forgets the previous session's tree so a new one does not inherit its
1613
+ * baseline, and takes the paths this session's own bookkeeping occupies.
1614
+ */
1615
+ reset(options = {}) {
1616
+ this.pending.clear();
1617
+ this.bracketed.clear();
1618
+ this.contents.clear();
1619
+ this.manifest = void 0;
1620
+ this.scanning = Promise.resolve();
1621
+ this.excluded = options.exclude ?? [];
1622
+ this.isIgnored = options.isIgnored;
1087
1623
  }
1088
- /** Waits for the lock file, breaking one an earlier process left behind. */
1089
- async acquire(lockPath) {
1090
- for (let attempt = 0; attempt < LOCK_RETRIES; attempt += 1) try {
1091
- return await node_fs_promises.default.open(lockPath, "wx");
1092
- } catch (error) {
1093
- if (!hasCode$1(error, "EEXIST")) throw error;
1094
- if (await this.breakStale(lockPath)) continue;
1095
- await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));
1096
- }
1097
- throw new Error(`Timed out acquiring timeline lock ${lockPath}`);
1624
+ /**
1625
+ * Awaits a scan still running in the background. A caller that is about to
1626
+ * clear the timeline needs this, or the scan appends after the clear.
1627
+ */
1628
+ async flush() {
1629
+ await this.scanning;
1098
1630
  }
1099
- /** Whether the lock is now free to take, having removed it when its holder is gone. */
1100
- async breakStale(lockPath) {
1101
- try {
1102
- const stats = await node_fs_promises.default.stat(lockPath);
1103
- if (Date.now() - stats.mtimeMs < LOCK_STALE_MS) return false;
1104
- await node_fs_promises.default.unlink(lockPath);
1631
+ async start(id, tool, args, cwd) {
1632
+ await this.scanning;
1633
+ if (tool === EDIT_TOOL || tool === WRITE_TOOL) {
1634
+ const supplied = objectValue(args, "path");
1635
+ if (!supplied) return false;
1636
+ const filePath = node_path.default.resolve(cwd, supplied);
1637
+ const [before, fingerprint] = await Promise.all([this.snapshots.capture(filePath), this.manifests.fingerprint(filePath)]);
1638
+ this.pending.set(id, {
1639
+ tool,
1640
+ filePath,
1641
+ before,
1642
+ existed: fingerprint !== void 0
1643
+ });
1105
1644
  return true;
1106
- } catch (error) {
1107
- if (hasCode$1(error, "ENOENT")) return true;
1108
- throw error;
1109
1645
  }
1646
+ if (tool !== BASH_TOOL && tool !== EXEC_TOOL) return false;
1647
+ this.bracketed.set(id, this.now());
1648
+ this.manifest ??= await this.manifests.take(cwd, this.excluded);
1649
+ return true;
1110
1650
  }
1111
- async release(lockPath) {
1112
- try {
1113
- await node_fs_promises.default.unlink(lockPath);
1114
- } catch (error) {
1115
- if (!hasCode$1(error, "ENOENT")) console.warn(`Could not remove timeline lock: ${String(error)}`);
1651
+ async end(id, isError, cwd) {
1652
+ const pending = this.pending.get(id);
1653
+ this.pending.delete(id);
1654
+ const startedAt = this.bracketed.get(id);
1655
+ this.bracketed.delete(id);
1656
+ if (pending) {
1657
+ if (!isError) await this.recordTool(pending);
1658
+ return;
1116
1659
  }
1660
+ if (startedAt === void 0) return;
1661
+ this.scanning = this.scanning.then(async () => {
1662
+ try {
1663
+ await this.recordScan(cwd, startedAt);
1664
+ } catch {}
1665
+ });
1117
1666
  }
1118
- };
1119
- //#endregion
1120
- //#region src/services/treeManifest/index.ts
1121
- /**
1122
- * Take a bounded manifest of a working tree and report which files moved
1123
- * between two of them.
1124
- *
1125
- * One technology per adapter. This is where node enters the package; the
1126
- * services that depend on the capability keep importing the port.
1127
- *
1128
- * The caps are the whole design. An unbounded walk of a working directory is
1129
- * dominated by dependency and build trees, which change constantly and tell a
1130
- * reader nothing, so those are skipped by name; what remains is capped on both
1131
- * entries and depth so the walk stays a fixed cost rather than a function of
1132
- * how large the checkout grew. Hitting a cap is reported, never hidden.
1133
- */
1134
- /**
1135
- * Directories a working tree fills with output nobody wants listed as an edit.
1136
- *
1137
- * Two kinds live here. Most are the build and dependency trees every checkout
1138
- * grows. The rest are where tooling, including this agent's own, writes while a
1139
- * session runs: a telemetry log under `logs`, a test run's artifacts under
1140
- * `test-results` and `playwright-report`, scratch space under `tmp`, and agent
1141
- * state under `.pi`. Those are skipped by construction rather than judged file
1142
- * by file, because a walk that enters them reports the session watching itself.
1143
- */
1144
- const IGNORED_DIRECTORIES = /* @__PURE__ */ new Set([
1145
- ".git",
1146
- ".hg",
1147
- ".svn",
1148
- ".cache",
1149
- ".gradle",
1150
- ".next",
1151
- ".nuxt",
1152
- ".nx",
1153
- ".pi",
1154
- ".pnpm-store",
1155
- ".turbo",
1156
- ".venv",
1157
- "__pycache__",
1158
- "build",
1159
- "coverage",
1160
- "dist",
1161
- "logs",
1162
- "node_modules",
1163
- "out",
1164
- "playwright-report",
1165
- "target",
1166
- "test-results",
1167
- "tmp",
1168
- "vendor",
1169
- "venv"
1170
- ]);
1171
- /**
1172
- * How a file is summarised. Size and modification time are what a walk can read
1173
- * cheaply for thousands of files; hashing every one of them would turn a scan
1174
- * into a read of the whole tree.
1175
- */
1176
- function fingerprintOf(size, modifiedMs) {
1177
- return `${size}:${modifiedMs}`;
1178
- }
1179
- /** The size half of a fingerprint, which only the adapter that wrote it can read. */
1180
- function sizeOf(fingerprint) {
1181
- const separator = fingerprint.indexOf(":");
1182
- return separator === -1 ? fingerprint : fingerprint.slice(0, separator);
1183
- }
1184
- var NodeTreeManifestAdapter = class {
1185
- maxEntries;
1186
- maxDepth;
1187
- ignored;
1188
- constructor(options = {}) {
1189
- this.maxEntries = options.maxEntries ?? 2e4;
1190
- this.maxDepth = options.maxDepth ?? 12;
1191
- this.ignored = options.ignoredDirectories ?? IGNORED_DIRECTORIES;
1192
- }
1193
- async take(root, exclude = []) {
1194
- const entries = /* @__PURE__ */ new Map();
1195
- const skipped = new Set(exclude.map((entry) => node_path.default.resolve(entry)));
1196
- return {
1197
- entries,
1198
- truncated: await this.walk(root, 0, entries, skipped)
1199
- };
1667
+ /** An `edit` or `write` whose file was read on both sides of the call. */
1668
+ async recordTool(pending) {
1669
+ const after = await this.snapshots.capture(pending.filePath);
1670
+ const created = !pending.existed;
1671
+ const counts = await this.countChanges(pending.before, after, created);
1672
+ if (after !== void 0) this.contents.set(pending.filePath, after);
1673
+ await this.append({
1674
+ version: 2,
1675
+ path: pending.filePath,
1676
+ tool: pending.tool,
1677
+ at: this.now(),
1678
+ origin: "tool",
1679
+ ...pending.before === void 0 ? {} : { before: pending.before },
1680
+ ...after === void 0 ? {} : { after },
1681
+ ...created ? { created: true } : {},
1682
+ ...counts
1683
+ });
1684
+ await this.remember(pending.filePath);
1200
1685
  }
1201
- async fingerprint(filePath) {
1202
- try {
1203
- const stat = await node_fs_promises.default.stat(filePath);
1204
- return stat.isFile() ? fingerprintOf(stat.size, stat.mtimeMs) : void 0;
1205
- } catch {
1206
- return;
1686
+ /** Whatever a bash call actually edited, however the command wrote it. */
1687
+ async recordScan(cwd, startedAt) {
1688
+ const before = this.manifest;
1689
+ if (before === void 0) return;
1690
+ const after = await this.manifests.take(cwd, this.excluded);
1691
+ this.manifest = after;
1692
+ const disowned = this.isIgnored;
1693
+ const named = this.manifests.changed(before, after).filter((filePath) => disowned === void 0 || !disowned(filePath));
1694
+ const candidates = await this.writtenDuring(named, startedAt);
1695
+ if (candidates.length === 0) return;
1696
+ const unchanged = await this.unchangedInGit(cwd, candidates);
1697
+ for (const filePath of candidates) {
1698
+ const known = this.contents.get(filePath);
1699
+ if (known === void 0 && unchanged.has(filePath)) continue;
1700
+ const beforePrint = before.entries.get(filePath);
1701
+ const afterPrint = after.entries.get(filePath);
1702
+ const captured = afterPrint === void 0 ? void 0 : await this.snapshots.capture(filePath);
1703
+ if (captured !== void 0) this.contents.set(filePath, captured);
1704
+ if (captured !== void 0 && captured === known) continue;
1705
+ const proven = beforePrint === void 0 || afterPrint === void 0 || this.manifests.sizeChanged(beforePrint, afterPrint) || known !== void 0 && captured !== void 0 && captured !== known;
1706
+ await this.append({
1707
+ version: 2,
1708
+ path: filePath,
1709
+ tool: BASH_TOOL,
1710
+ at: this.now(),
1711
+ origin: "scan",
1712
+ ...proven ? { verified: true } : {},
1713
+ ...captured === void 0 ? {} : { after: captured }
1714
+ });
1207
1715
  }
1208
1716
  }
1209
- async modifiedAt(filePath) {
1210
- try {
1211
- const stat = await node_fs_promises.default.stat(filePath);
1212
- return stat.isFile() ? stat.mtimeMs : void 0;
1213
- } catch {
1214
- return;
1717
+ /**
1718
+ * Narrows candidates to the ones that could have been written by the call
1719
+ * being closed.
1720
+ *
1721
+ * This is what keeps a working tree that was already dirty out of the list. A
1722
+ * file whose bytes were last written before the call began was differed by
1723
+ * something else, whatever moved its fingerprint. A file that is no longer
1724
+ * there has no time to read and a delete is a change the call may well have
1725
+ * made, so it stays a candidate.
1726
+ */
1727
+ async writtenDuring(candidates, startedAt) {
1728
+ const floor = startedAt - MODIFIED_TOLERANCE_MS;
1729
+ const written = [];
1730
+ for (const filePath of candidates) {
1731
+ const modifiedAt = await this.manifests.modifiedAt(filePath);
1732
+ if (modifiedAt === void 0 || modifiedAt >= floor) written.push(filePath);
1215
1733
  }
1734
+ return written;
1216
1735
  }
1217
- changed(before, after) {
1218
- const moved = /* @__PURE__ */ new Set();
1219
- for (const [filePath, fingerprint] of after.entries) if (before.entries.get(filePath) !== fingerprint) moved.add(filePath);
1220
- for (const filePath of before.entries.keys()) if (!after.entries.has(filePath)) moved.add(filePath);
1221
- return [...moved].sort();
1736
+ /** Which candidates git tracks and reports as untouched; empty when it cannot say. */
1737
+ async unchangedInGit(cwd, candidates) {
1738
+ const unseen = candidates.filter((filePath) => !this.contents.has(filePath));
1739
+ if (this.git === void 0 || unseen.length === 0) return /* @__PURE__ */ new Set();
1740
+ return this.git.unchanged(cwd, unseen);
1741
+ }
1742
+ /** How many lines moved, when there is enough captured content to say. */
1743
+ async countChanges(before, after, created) {
1744
+ if (after === void 0) return {};
1745
+ if (before === void 0) {
1746
+ if (!created) return {};
1747
+ const createdText = await this.snapshots.read(after);
1748
+ if (createdText === void 0) return {};
1749
+ const fresh = lineDiffFromEmpty(createdText);
1750
+ return {
1751
+ additions: fresh.additions,
1752
+ removals: fresh.removals
1753
+ };
1754
+ }
1755
+ if (before === after) return {
1756
+ additions: 0,
1757
+ removals: 0
1758
+ };
1759
+ const [beforeText, afterText] = await Promise.all([this.snapshots.read(before), this.snapshots.read(after)]);
1760
+ if (beforeText === void 0 || afterText === void 0) return {};
1761
+ const diff = lineDiff(beforeText, afterText);
1762
+ return {
1763
+ additions: diff.additions,
1764
+ removals: diff.removals
1765
+ };
1222
1766
  }
1223
- sizeChanged(before, after) {
1224
- if (before === void 0 || after === void 0) return false;
1225
- return sizeOf(before) !== sizeOf(after);
1767
+ /** Records the change unless it turned out to be no change at all. */
1768
+ async append(event) {
1769
+ if (event.before !== void 0 && event.before === event.after) return;
1770
+ await this.timeline.append(event);
1226
1771
  }
1227
- /** Fills `entries` depth-first and answers whether a cap cut the walk short. */
1228
- async walk(directory, depth, entries, skipped) {
1229
- if (depth > this.maxDepth) return true;
1230
- let listing;
1231
- try {
1232
- listing = await node_fs_promises.default.readdir(directory, { withFileTypes: true });
1233
- } catch {
1234
- return false;
1235
- }
1236
- let truncated = false;
1237
- for (const entry of listing) {
1238
- if (entries.size >= this.maxEntries) return true;
1239
- const entryPath = node_path.default.join(directory, entry.name);
1240
- if (skipped.has(entryPath)) continue;
1241
- if (entry.isSymbolicLink()) continue;
1242
- if (entry.isDirectory()) {
1243
- if (this.ignored.has(entry.name)) continue;
1244
- truncated = await this.walk(entryPath, depth + 1, entries, skipped) || truncated;
1245
- continue;
1246
- }
1247
- if (!entry.isFile()) continue;
1248
- try {
1249
- const stat = await node_fs_promises.default.stat(entryPath);
1250
- entries.set(entryPath, fingerprintOf(stat.size, stat.mtimeMs));
1251
- } catch {}
1252
- }
1253
- return truncated;
1772
+ /**
1773
+ * Folds a path the tool layer just handled into the tracked manifest, so the
1774
+ * next bash comparison sees it as already accounted for.
1775
+ *
1776
+ * The fingerprint has to be the one a walk would read, not a stand-in, or the
1777
+ * next comparison reports the file again under bash and every tool edit is
1778
+ * recorded twice.
1779
+ */
1780
+ async remember(filePath) {
1781
+ if (this.manifest === void 0) return;
1782
+ const entries = new Map(this.manifest.entries);
1783
+ const fingerprint = await this.manifests.fingerprint(filePath);
1784
+ if (fingerprint === void 0) entries.delete(filePath);
1785
+ else entries.set(filePath, fingerprint);
1786
+ this.manifest = {
1787
+ entries,
1788
+ truncated: this.manifest.truncated
1789
+ };
1254
1790
  }
1255
1791
  };
1256
1792
  //#endregion
1257
- //#region src/types/webFiles.ts
1258
- /** The frame type the hub publishes and the web plugin claims; declared in the poWeb block too. */
1259
- const filesChannelType = "file_edits";
1260
- /** Footer status key whose presence shows the activity group; the extension publishes it. */
1261
- const filesStatusKey = "po-file-edit-files";
1262
- //#endregion
1263
1793
  //#region src/types/apiRoutes.ts
1264
1794
  /**
1265
1795
  * This package's routes, as data.
@@ -1306,249 +1836,41 @@ const routes = {
1306
1836
  */
1307
1837
  file: {
1308
1838
  method: "GET",
1309
- path: "/file",
1310
- raw: true,
1311
- query: ["path"],
1312
- host: true
1313
- }
1314
- };
1315
- //#endregion
1316
- //#region src/types/fileEditsApi.ts
1317
- /**
1318
- * The wire vocabulary this package's API shares with whatever calls it.
1319
- *
1320
- * It lives under src/types because that is the one server root a browser
1321
- * bundle may read: the cockpit plugin builds its URLs from these and the
1322
- * routes answer them, so neither half can drift from the other.
1323
- *
1324
- * Routes live in `./apiRoutes`, which the contract, the Hono app and the
1325
- * generated client all read. This file holds the shapes that travel over them.
1326
- *
1327
- * Opening a changed file wants its whole history at once, so `detail` answers
1328
- * in one round trip rather than making the page stitch three reads together;
1329
- * `content` takes the manual save back; `preview` reads a file the session
1330
- * never changed, which has no history to answer with.
1331
- */
1332
- /** Where a host mounts this package's API; the segment after /api/plugins/. */
1333
- const API_BASE_PATH = "file-edits";
1334
- /** Query parameter naming the file a request is about. */
1335
- const PATH_QUERY_PARAM = "path";
1336
- //#endregion
1337
- //#region src/services/fileEditsApi/index.ts
1338
- /**
1339
- * This package's HTTP surface: one file's history, and the manual save.
1340
- *
1341
- * Routes are relative to the mount its host gives it, so nothing here repeats
1342
- * where it was mounted. The host is one session's own server, which is what
1343
- * makes the session id and working directory available without the page
1344
- * supplying either: a page names a file, never a session's private paths.
1345
- *
1346
- * The detail route answers everything a reader needs to open a changed file,
1347
- * because splitting it would make the page stitch three responses together for
1348
- * one click. The save route is the only mutation, and it refuses unless the
1349
- * reader proves they were looking at the content that is still on disk. The
1350
- * preview route is the read-only way in to a file the session never changed,
1351
- * bounded by the working directory instead of by the timeline.
1352
- */
1353
- /** Past this, the working view reports the file rather than carrying it. */
1354
- const MAX_WORKING_BYTES = 1048576;
1355
- const BINARY_SAMPLE_BYTES = 8192;
1356
- const NO_BASELINE_NOTE = "changed by a command, so no baseline was captured; showing the file as it stands";
1357
- /**
1358
- * A change the tool layer named but never captured content for. That is what
1359
- * every record written before this package learned to snapshot looks like, and
1360
- * calling those "changed by a command" would be wrong: the tool is right there
1361
- * in the record.
1362
- */
1363
- const NO_SNAPSHOT_NOTE = "recorded before this session began capturing content, so there is no diff for it";
1364
- const NO_AFTER_NOTE = "the new content could not be captured: the file is binary or past the size cap";
1365
- const NO_BEFORE_NOTE = "the previous content could not be captured: it was binary or past the size cap";
1366
- const APPROXIMATE_NOTE = "the changed region was too large to match line by line";
1367
- function hashOf(content) {
1368
- return (0, node_crypto.createHash)("sha256").update(content, "utf8").digest("hex");
1369
- }
1370
- function hasCode(error, code) {
1371
- return error instanceof Error && "code" in error && error.code === code;
1372
- }
1373
- function describe(error) {
1374
- return error instanceof Error ? error.message : String(error);
1375
- }
1376
- /** Reads the file as the source view will show it, or says why it cannot. */
1377
- async function readWorking(filePath, opened, allowedRoot) {
1378
- let handle = opened;
1379
- let raw;
1380
- try {
1381
- handle ??= await (0, _agimon_ai_po_core_platform.openGuardedFile)(filePath, { root: allowedRoot });
1382
- const stats = await handle.stat();
1383
- if (!stats.isFile()) return {
1384
- content: "",
1385
- hash: "",
1386
- unavailable: true,
1387
- reason: "the file is not a regular file"
1388
- };
1389
- const named = await node_fs_promises.default.lstat(filePath);
1390
- if (!named.isFile() || stats.dev !== named.dev || stats.ino !== named.ino || allowedRoot !== void 0 && !await isRealPathInside(allowedRoot, filePath)) return {
1391
- content: "",
1392
- hash: "",
1393
- unavailable: true,
1394
- reason: "the file path changed or leaves its readable directory"
1395
- };
1396
- raw = Buffer.alloc(1048577);
1397
- if (stats.size <= 1048576) {
1398
- let offset = 0;
1399
- while (offset < raw.length) {
1400
- const { bytesRead } = await handle.read(raw, offset, raw.length - offset, offset);
1401
- if (bytesRead === 0) break;
1402
- offset += bytesRead;
1403
- }
1404
- raw = raw.subarray(0, offset);
1405
- }
1406
- } catch {
1407
- return {
1408
- content: "",
1409
- hash: "",
1410
- unavailable: true,
1411
- reason: "the file no longer exists or cannot be safely read"
1412
- };
1413
- } finally {
1414
- if (opened === void 0) await handle?.close();
1415
- }
1416
- if (raw.byteLength > 1048576) return {
1417
- content: "",
1418
- hash: "",
1419
- unavailable: true,
1420
- reason: `the file is larger than ${MAX_WORKING_BYTES} bytes`
1421
- };
1422
- if (raw.subarray(0, BINARY_SAMPLE_BYTES).includes(0)) return {
1423
- content: "",
1424
- hash: "",
1425
- unavailable: true,
1426
- reason: "the file is binary"
1427
- };
1428
- const content = raw.toString("utf8");
1429
- return {
1430
- content,
1431
- hash: hashOf(content),
1432
- unavailable: false
1433
- };
1434
- }
1435
- function isInside(root, candidate) {
1436
- return candidate === root || candidate.startsWith(`${root}${node_path.default.sep}`);
1437
- }
1438
- /**
1439
- * The same containment check after symlinks are followed. A path that does not
1440
- * exist yet resolves to nothing, and there is nothing to hand out, so it
1441
- * passes and the read below reports it missing.
1442
- */
1443
- async function isRealPathInside(root, candidate) {
1444
- let realRoot;
1445
- let real;
1446
- try {
1447
- realRoot = await node_fs_promises.default.realpath(root);
1448
- real = await node_fs_promises.default.realpath(candidate);
1449
- } catch (error) {
1450
- return hasCode(error, "ENOENT");
1451
- }
1452
- return isInside(realRoot, real);
1453
- }
1454
- /**
1455
- * One recorded change as the page renders it. A change with both sides captured
1456
- * carries its own diff; one without says why, rather than showing nothing.
1457
- *
1458
- * A file this session created counts as captured on both sides. Its baseline is
1459
- * empty rather than missing, so the whole file reads as arriving at once, which
1460
- * is exactly what happened.
1461
- */
1462
- async function toVersionView(version, snapshots) {
1463
- const view = {
1464
- index: version.index,
1465
- tool: version.tool,
1466
- at: version.at,
1467
- origin: version.origin,
1468
- additions: version.additions ?? 0,
1469
- removals: version.removals ?? 0
1470
- };
1471
- const createdHere = version.before === void 0 && version.created === true;
1472
- if (version.after === void 0 || version.before === void 0 && !createdHere) {
1473
- if (version.origin === "tool") return {
1474
- ...view,
1475
- note: version.after === void 0 ? NO_AFTER_NOTE : NO_BEFORE_NOTE
1476
- };
1477
- return {
1478
- ...view,
1479
- note: version.tool === "bash" ? NO_BASELINE_NOTE : NO_SNAPSHOT_NOTE
1480
- };
1481
- }
1482
- const after = await snapshots.read(version.after);
1483
- if (after === void 0) return {
1484
- ...view,
1485
- note: "the content behind this change is no longer held"
1486
- };
1487
- if (version.before === void 0) {
1488
- const fresh = lineDiffFromEmpty(after);
1489
- return {
1490
- ...view,
1491
- additions: fresh.additions,
1492
- removals: fresh.removals,
1493
- hunks: fresh.hunks,
1494
- ...fresh.approximate ? { note: APPROXIMATE_NOTE } : {}
1495
- };
1496
- }
1497
- const before = await snapshots.read(version.before);
1498
- if (before === void 0) return {
1499
- ...view,
1500
- note: "the content behind this change is no longer held"
1501
- };
1502
- const diff = lineDiff(before, after);
1503
- return {
1504
- ...view,
1505
- additions: diff.additions,
1506
- removals: diff.removals,
1507
- hunks: diff.hunks,
1508
- ...diff.approximate ? { note: APPROXIMATE_NOTE } : {}
1509
- };
1510
- }
1511
- /** Everything the session did to the file: its oldest baseline against what is on disk now. */
1512
- async function toCumulativeView(versions, working, snapshots) {
1513
- const createdHere = versions[0]?.created === true;
1514
- const baseline = baselineOf(versions);
1515
- if (!createdHere && baseline === void 0) return {
1516
- additions: 0,
1517
- removals: 0,
1518
- note: versions[0]?.origin === "tool" ? NO_BEFORE_NOTE : NO_BASELINE_NOTE
1519
- };
1520
- if (working.unavailable) return {
1521
- additions: 0,
1522
- removals: 0,
1523
- note: working.reason ?? "the file cannot be read"
1524
- };
1525
- if (createdHere || baseline === void 0) {
1526
- const fresh = lineDiffFromEmpty(working.content);
1527
- return {
1528
- additions: fresh.additions,
1529
- removals: fresh.removals,
1530
- hunks: fresh.hunks,
1531
- ...fresh.approximate ? { note: APPROXIMATE_NOTE } : {}
1532
- };
1839
+ path: "/file",
1840
+ raw: true,
1841
+ query: ["path"],
1842
+ host: true
1533
1843
  }
1534
- const before = await snapshots.read(baseline);
1535
- if (before === void 0) return {
1536
- additions: 0,
1537
- removals: 0,
1538
- note: "the content this session started from is no longer held"
1539
- };
1540
- const diff = lineDiff(before, working.content);
1541
- return {
1542
- additions: diff.additions,
1543
- removals: diff.removals,
1544
- hunks: diff.hunks,
1545
- ...diff.approximate ? { note: APPROXIMATE_NOTE } : {}
1546
- };
1547
- }
1844
+ };
1845
+ //#endregion
1846
+ //#region src/types/fileEditsApi.ts
1847
+ /**
1848
+ * The wire vocabulary this package's API shares with whatever calls it.
1849
+ *
1850
+ * It lives under src/types because that is the one server root a browser
1851
+ * bundle may read: the cockpit plugin builds its URLs from these and the
1852
+ * routes answer them, so neither half can drift from the other.
1853
+ *
1854
+ * Routes live in `./apiRoutes`, which the contract, the Hono app and the
1855
+ * generated client all read. This file holds the shapes that travel over them.
1856
+ *
1857
+ * Opening a changed file wants its whole history at once, so `detail` answers
1858
+ * in one round trip rather than making the page stitch three reads together;
1859
+ * `content` takes the manual save back; `preview` reads a file the session
1860
+ * never changed, which has no history to answer with.
1861
+ */
1862
+ /** Where a host mounts this package's API; the segment after /api/plugins/. */
1863
+ const API_BASE_PATH = "file-edits";
1864
+ /** Query parameter naming the file a request is about. */
1865
+ const PATH_QUERY_PARAM = "path";
1866
+ //#endregion
1867
+ //#region src/services/fileEditsApi/index.ts
1548
1868
  function createFileEditsApi(options = {}) {
1549
- const timeline = options.timeline ?? new TimelineStore();
1550
- const snapshots = options.snapshots ?? new NodeSnapshotStoreAdapter();
1551
- const paths = options.paths ?? new FileEditPaths();
1869
+ const storage = options.storage ?? createFileEditStorage();
1870
+ const timeline = options.timeline ?? storage.timeline();
1871
+ const snapshots = options.snapshots ?? storage.snapshots();
1872
+ const paths = options.paths ?? storage.paths();
1873
+ const files = options.files ?? storage.workingFiles();
1552
1874
  const cwd = options.cwd ?? "";
1553
1875
  const app = new hono.Hono();
1554
1876
  if (options.sessionId !== void 0 && cwd !== "") {
@@ -1577,13 +1899,13 @@ function createFileEditsApi(options = {}) {
1577
1899
  const isInsideSession = async (filePath) => {
1578
1900
  if (cwd === "") return false;
1579
1901
  const root = node_path.default.resolve(cwd);
1580
- return isInside(root, filePath) && await isRealPathInside(root, filePath);
1902
+ return isInside(root, filePath) && await files.isRealPathInside(root, filePath);
1581
1903
  };
1582
1904
  /** The Po-owned folder holding the file, checked the same two ways as the working directory. */
1583
1905
  const readableRootOf = async (filePath) => {
1584
- for (const root of options.readableRoots?.() ?? []) {
1906
+ for (const root of await options.readableRoots?.() ?? []) {
1585
1907
  const resolved = node_path.default.resolve(root);
1586
- if (isInside(resolved, filePath) && await isRealPathInside(resolved, filePath)) return resolved;
1908
+ if (isInside(resolved, filePath) && await files.isRealPathInside(resolved, filePath)) return resolved;
1587
1909
  }
1588
1910
  };
1589
1911
  app.get(routes.detail.path, async (context) => {
@@ -1591,7 +1913,8 @@ function createFileEditsApi(options = {}) {
1591
1913
  const versions = await recordedVersions(requested);
1592
1914
  if (versions === void 0 || requested === void 0) return context.json({ error: "This session recorded no changes to that file." }, 404);
1593
1915
  const filePath = node_path.default.resolve(cwd, requested);
1594
- const working = await readWorking(filePath, void 0, cwd !== "" && isInside(node_path.default.resolve(cwd), filePath) ? node_path.default.resolve(cwd) : void 0);
1916
+ const allowedRoot = cwd !== "" && isInside(node_path.default.resolve(cwd), filePath) ? node_path.default.resolve(cwd) : void 0;
1917
+ const working = await files.readWorking(filePath, allowedRoot);
1595
1918
  const body = {
1596
1919
  path: filePath,
1597
1920
  relPath: cwd === "" ? filePath : node_path.default.relative(cwd, filePath),
@@ -1624,7 +1947,7 @@ function createFileEditsApi(options = {}) {
1624
1947
  const body = {
1625
1948
  path: filePath,
1626
1949
  relPath: inSession ? node_path.default.relative(root, filePath) : filePath,
1627
- working: await readWorking(filePath, void 0, allowedRoot)
1950
+ working: await files.readWorking(filePath, allowedRoot)
1628
1951
  };
1629
1952
  return context.json(body);
1630
1953
  });
@@ -1640,33 +1963,26 @@ function createFileEditsApi(options = {}) {
1640
1963
  if (await recordedVersions(requested) === void 0) return context.json({ error: "This session recorded no changes to that file." }, 404);
1641
1964
  const filePath = node_path.default.resolve(cwd, requested);
1642
1965
  if (!await isInsideSession(filePath)) return context.json({ error: "Files outside the session directory are read-only." }, 403);
1643
- if (Buffer.byteLength(content, "utf8") > 1048576) return context.json({ error: `The file is larger than ${MAX_WORKING_BYTES} bytes.` }, 413);
1966
+ if (new TextEncoder().encode(content).byteLength > 1048576) return context.json({ error: `The file is larger than ${MAX_WORKING_BYTES} bytes.` }, 413);
1644
1967
  try {
1645
- const canonical = await node_fs_promises.default.realpath(filePath);
1646
- return await _agimon_ai_po_core_platform.fileMutationRunner.forKey(canonical)(async () => {
1647
- const handle = await (0, _agimon_ai_po_core_platform.openGuardedFile)(filePath, {
1648
- write: true,
1649
- root: node_path.default.resolve(cwd)
1650
- });
1651
- try {
1652
- if (await node_fs_promises.default.realpath(filePath) !== canonical) return context.json({ error: "The file changed before it could be written." }, 409);
1653
- const current = await readWorking(filePath, handle, node_path.default.resolve(cwd));
1654
- if (current.unavailable) return context.json({ error: current.reason ?? "The file cannot be read." }, 409);
1655
- if (current.hash !== expectedHash) return context.json({
1656
- error: "The file changed since it was opened.",
1657
- hash: current.hash
1658
- }, 409);
1659
- const opened = await handle.stat();
1660
- const named = await node_fs_promises.default.lstat(filePath);
1661
- if (!opened.isFile() || opened.nlink !== 1 || !named.isFile() || named.nlink !== 1 || opened.dev !== named.dev || opened.ino !== named.ino || await node_fs_promises.default.realpath(filePath) !== canonical || !await isInsideSession(filePath)) return context.json({ error: "The file changed before it could be written." }, 409);
1662
- await handle.writeFile(content, "utf8");
1663
- await handle.truncate(Buffer.byteLength(content, "utf8"));
1664
- const body = { hash: hashOf(content) };
1968
+ const outcome = await files.save({
1969
+ filePath,
1970
+ root: node_path.default.resolve(cwd),
1971
+ content,
1972
+ expectedHash
1973
+ });
1974
+ switch (outcome.status) {
1975
+ case "saved": {
1976
+ const body = { hash: outcome.hash };
1665
1977
  return context.json(body);
1666
- } finally {
1667
- await handle.close();
1668
1978
  }
1669
- });
1979
+ case "stale": return context.json({
1980
+ error: "The file changed since it was opened.",
1981
+ hash: outcome.hash
1982
+ }, 409);
1983
+ case "unreadable": return context.json({ error: outcome.reason }, 409);
1984
+ case "moved": return context.json({ error: "The file changed before it could be written." }, 409);
1985
+ }
1670
1986
  } catch {
1671
1987
  return context.json({ error: "The file cannot be safely written." }, 409);
1672
1988
  }
@@ -1676,242 +1992,41 @@ function createFileEditsApi(options = {}) {
1676
1992
  if (await recordedVersions(requested) === void 0 || requested === void 0) return context.json({ error: "This session recorded no changes to that file." }, 404);
1677
1993
  const filePath = node_path.default.resolve(cwd, requested);
1678
1994
  if (!await isInsideSession(filePath)) return context.json({ error: "Files outside the session directory are read-only." }, 403);
1679
- try {
1680
- const canonical = await node_fs_promises.default.realpath(filePath).catch((error) => {
1681
- if (hasCode(error, "ENOENT")) return filePath;
1682
- throw error;
1683
- });
1684
- return await _agimon_ai_po_core_platform.fileMutationRunner.forKey(canonical)(async () => {
1685
- if (!await isInsideSession(filePath)) return context.json({ error: "Files outside the session directory are read-only." }, 403);
1686
- await node_fs_promises.default.unlink(filePath);
1687
- return context.body(null, 204);
1688
- });
1689
- } catch (error) {
1690
- if (!hasCode(error, "ENOENT")) return context.json({ error: `The file could not be deleted: ${describe(error)}` }, 409);
1995
+ const outcome = await files.remove(filePath, node_path.default.resolve(cwd));
1996
+ switch (outcome.status) {
1997
+ case "outside": return context.json({ error: "Files outside the session directory are read-only." }, 403);
1998
+ case "failed": return context.json({ error: `The file could not be deleted: ${outcome.reason}` }, 409);
1999
+ case "removed": return context.body(null, 204);
1691
2000
  }
1692
- return context.body(null, 204);
1693
2001
  });
1694
2002
  return app;
1695
2003
  }
1696
- /** The named export a host imports from this package's built entry. */
1697
- const api = {
1698
- basePath: API_BASE_PATH,
1699
- start(context) {
1700
- const environment = context.environment ?? {};
1701
- const cwd = context.cwd;
1702
- const app = createFileEditsApi({
1703
- paths: new FileEditPaths({
1704
- ...environment,
1705
- HOME: context.homeDirectory ?? environment.HOME
1706
- }),
1707
- ...context.sessionId === void 0 ? {} : { sessionId: context.sessionId },
1708
- ...cwd === void 0 ? {} : {
1709
- cwd,
1710
- readableRoots: () => plansRoots(cwd, environment, context.homeDirectory)
1711
- }
1712
- });
1713
- return {
1714
- fetch: (request) => app.fetch(request),
1715
- close: () => void 0
1716
- };
1717
- }
1718
- };
1719
- /**
1720
- * The plans directory Plan mode writes to, resolved the way Plan resolves it, so
1721
- * a plan link in the transcript opens in the file view. A config that cannot be
1722
- * read admits nothing extra rather than failing the preview.
1723
- */
1724
- function plansRoots(cwd, environment, homeDirectory) {
1725
- const home = homeDirectory ?? environment.HOME ?? node_os.default.homedir();
1726
- try {
1727
- const configured = (0, _agimon_ai_po_config.loadPoConfig)(cwd, home, environment).modes?.planning?.plansDirectory;
1728
- return [(0, _agimon_ai_po_config.resolvePlanningPlansDirectory)(configured, cwd, home)];
1729
- } catch {
1730
- return [];
1731
- }
1732
- }
1733
- //#endregion
1734
- //#region src/services/sessionStateSweep/index.ts
1735
- /**
1736
- * Remove the state sessions left behind when they never got to clean up.
1737
- *
1738
- * A session clears its own timeline and snapshots on shutdown, which covers the
1739
- * ordinary case and nothing else: a killed process, a crash, or a machine that
1740
- * lost power leaves both behind, and nothing ever looked at the directory
1741
- * again. One week of that filled a real checkout with hundreds of megabytes.
1742
- *
1743
- * Age is the only signal used, because it is the only one that is true from
1744
- * another process. A running session appends as it works, so its timeline is
1745
- * recent; a dead one stops moving at the moment it died.
1746
- */
1747
- /**
1748
- * How long state may sit untouched before a later session removes it.
1749
- *
1750
- * Generous on purpose. The cost of waiting is disk, and the cost of being wrong
1751
- * is deleting a live session's history, so this is set far beyond any plausible
1752
- * gap between two appends rather than close to it.
1753
- */
1754
- const STATE_MAX_AGE_MS = 6048e5;
1755
- const TIMELINE_SUFFIX = ".jsonl";
1756
- const SNAPSHOTS_SUFFIX = ".blobs";
1757
- async function remove(target) {
1758
- await node_fs_promises.default.rm(target, {
1759
- recursive: true,
1760
- force: true
1761
- });
1762
- }
1763
- /** The most recent time anything under this session's state moved. */
1764
- async function lastTouched(paths) {
1765
- let newest;
1766
- for (const target of paths) try {
1767
- const stat = await node_fs_promises.default.stat(target);
1768
- if (newest === void 0 || stat.mtimeMs > newest) newest = stat.mtimeMs;
1769
- } catch {}
1770
- return newest;
1771
- }
1772
- /** How many sessions' worth of state was removed. */
1773
- async function sweepSessionState(options) {
1774
- const { directory, keep, removeDirectory = false, now = Date.now(), maxAgeMs = STATE_MAX_AGE_MS } = options;
1775
- let entries;
1776
- try {
1777
- entries = await node_fs_promises.default.readdir(directory);
1778
- } catch {
1779
- return 0;
1780
- }
1781
- const floor = now - maxAgeMs;
1782
- const timelines = new Set(entries.filter((entry) => entry.endsWith(TIMELINE_SUFFIX)));
1783
- let removed = 0;
1784
- for (const entry of timelines) {
1785
- const timelinePath = node_path.default.join(directory, entry);
1786
- if (keep !== void 0 && timelinePath === keep) continue;
1787
- const snapshotsPath = `${timelinePath.slice(0, -6)}${SNAPSHOTS_SUFFIX}`;
1788
- const lockPath = `${timelinePath}.lock`;
1789
- const touched = await lastTouched([
1790
- timelinePath,
1791
- snapshotsPath,
1792
- lockPath
1793
- ]);
1794
- if (touched === void 0 || touched >= floor) continue;
1795
- await remove(snapshotsPath);
1796
- await remove(timelinePath);
1797
- await remove(lockPath);
1798
- removed += 1;
1799
- }
1800
- for (const entry of entries) {
1801
- if (!entry.endsWith(SNAPSHOTS_SUFFIX)) continue;
1802
- if (timelines.has(`${entry.slice(0, -6)}${TIMELINE_SUFFIX}`)) continue;
1803
- const orphan = node_path.default.join(directory, entry);
1804
- const touched = await lastTouched([orphan]);
1805
- if (touched === void 0 || touched >= floor) continue;
1806
- await remove(orphan);
1807
- }
1808
- if (removeDirectory) try {
1809
- await node_fs_promises.default.rmdir(directory);
1810
- } catch {}
1811
- return removed;
1812
- }
1813
- //#endregion
1814
- //#region src/services/webFilesChannel/index.ts
1815
- /**
1816
- * The changed-files channel consumes snapshots emitted by the owning session's
1817
- * server plugin. Durable timeline reads seed a channel that starts after session
1818
- * startup.
1819
- */
1820
- /** Whether the file is still there to be opened. */
1821
- async function stillExists(filePath) {
1822
- try {
1823
- return (await node_fs_promises.default.stat(filePath)).isFile();
1824
- } catch {
1825
- return false;
1826
- }
1827
- }
1828
- /**
1829
- * Reads one session's timeline and presents it as the rows the dock lists.
1830
- *
1831
- * A file the session changed and then removed is left out, and so is a path a
1832
- * bash call only touched: a command that moves a modification time without
1833
- * changing a byte is not an edit, and listing it buries the ones that are. The
1834
- * dock is a list of things to open, and a row that can only ever answer "this
1835
- * is gone" is a dead end; the timeline still holds the change, so a tab already
1836
- * open on the file keeps working and says so.
1837
- */
1838
- async function readSessionFiles(timelinePath, cwd) {
1839
- let content;
1840
- try {
1841
- content = await node_fs_promises.default.readFile(timelinePath, "utf8");
1842
- } catch {
1843
- return [];
1844
- }
1845
- const events = confirmedChanges(parseTimeline(content));
1846
- const entries = foldEntries(events);
1847
- const existing = await Promise.all(entries.map((entry) => stillExists(entry.path)));
1848
- const items = entries.filter((_entry, index) => existing[index]).map((entry) => ({
1849
- path: entry.path,
1850
- relPath: node_path.default.relative(cwd, entry.path) || entry.path,
1851
- tool: entry.tool,
1852
- at: entry.at,
1853
- count: entry.count,
1854
- diffable: isDiffable(foldVersions(events, entry.path))
1855
- }));
1856
- try {
1857
- return filterPoIgnoredFiles(items, await node_fs_promises.default.readFile(node_path.default.join(cwd, ".poignore"), "utf8"));
1858
- } catch {
1859
- return items;
1860
- }
1861
- }
1862
- function filesPayload(value) {
1863
- return typeof value === "object" && value !== null && Array.isArray(value.items);
1864
- }
1865
- /**
1866
- * The files data channel: one direct-event subscription per managed session,
1867
- * published as { items } payloads under the 'file_edits' frame type.
1868
- */
1869
- function createFilesChannel() {
2004
+ /** The named export a host mounts, built over the storage it runs on. */
2005
+ function createFileEditsPoApi(storage) {
1870
2006
  return {
1871
- frameType: filesChannelType,
1872
- start(host) {
1873
- const latest = /* @__PURE__ */ new Map();
1874
- const subscriptions = /* @__PURE__ */ new Map();
1875
- return {
1876
- payloadFor(scope) {
1877
- const items = latest.get(scope.sessionId);
1878
- return items === void 0 ? void 0 : { items };
1879
- },
1880
- sessionAdded(scope) {
1881
- subscriptions.get(scope.sessionId)?.();
1882
- const paths = new FileEditPaths(scope.environment);
1883
- let current = true;
1884
- let receivedDirect = false;
1885
- const unsubscribe = host.directEvents.subscribe(filesChannelType, scope.sessionId, (payload) => {
1886
- if (!filesPayload(payload)) return;
1887
- receivedDirect = true;
1888
- latest.set(scope.sessionId, payload.items);
1889
- host.publish(scope.sessionId, payload);
1890
- }, { replayLatest: true });
1891
- subscriptions.set(scope.sessionId, () => {
1892
- current = false;
1893
- unsubscribe();
1894
- });
1895
- (async () => {
1896
- let items = [];
1897
- try {
1898
- items = await readSessionFiles(await paths.timelinePath(scope.cwd, paths.sessionKey(scope.sessionId)), scope.cwd);
1899
- } catch {}
1900
- if (!current || receivedDirect) return;
1901
- latest.set(scope.sessionId, items);
1902
- host.publish(scope.sessionId, { items });
1903
- })().catch((error) => host.onNotice(`File-edit channel seed failed: ${String(error)}`));
1904
- },
1905
- sessionRemoved(sessionId) {
1906
- subscriptions.get(sessionId)?.();
1907
- subscriptions.delete(sessionId);
1908
- latest.delete(sessionId);
1909
- },
1910
- close() {
1911
- for (const unsubscribe of subscriptions.values()) unsubscribe();
1912
- subscriptions.clear();
1913
- latest.clear();
2007
+ basePath: API_BASE_PATH,
2008
+ start(context) {
2009
+ const environment = context.environment ?? {};
2010
+ const cwd = context.cwd;
2011
+ const app = createFileEditsApi({
2012
+ storage,
2013
+ paths: storage.paths({
2014
+ ...environment,
2015
+ HOME: context.homeDirectory ?? environment.HOME
2016
+ }),
2017
+ ...context.sessionId === void 0 ? {} : { sessionId: context.sessionId },
2018
+ ...cwd === void 0 ? {} : {
2019
+ cwd,
2020
+ readableRoots: storage.readableRoots({
2021
+ cwd,
2022
+ environment,
2023
+ ...context.homeDirectory === void 0 ? {} : { homeDirectory: context.homeDirectory }
2024
+ })
1914
2025
  }
2026
+ });
2027
+ return {
2028
+ fetch: (request) => app.fetch(request),
2029
+ close: () => void 0
1915
2030
  };
1916
2031
  }
1917
2032
  };
@@ -1953,13 +2068,14 @@ function stringValue(value, key) {
1953
2068
  const candidate = value[key];
1954
2069
  return typeof candidate === "string" && candidate.length > 0 ? candidate : void 0;
1955
2070
  }
1956
- function createFileEditSession({ agent, host }, fs) {
1957
- if (!agent) return { api: [api] };
2071
+ function createFileEditSession({ agent, host }, fs, storage = createFileEditStorage(fs)) {
2072
+ const fileEditsApi = createFileEditsPoApi(storage);
2073
+ if (!agent) return { api: [fileEditsApi] };
1958
2074
  const environment = Object.freeze({ ...host.context.environment });
1959
- const paths = new FileEditPaths(environment);
1960
- const timeline = new TimelineStore();
1961
- const snapshots = new NodeSnapshotStoreAdapter();
1962
- const editTracker = new EditTracker(timeline, snapshots, new NodeTreeManifestAdapter(), { git: new NodeGitStatusAdapter() });
2075
+ const paths = storage.paths(environment);
2076
+ const timeline = storage.timeline();
2077
+ const snapshots = storage.snapshots();
2078
+ const editTracker = new EditTracker(timeline, snapshots, storage.manifests(), { git: storage.git() });
1963
2079
  if (host.context.directEvents === void 0) throw new Error("File-edit server plugin requires the session direct event bus.");
1964
2080
  const directEvents = host.context.directEvents;
1965
2081
  const telemetry = (0, _agimon_ai_po_core_telemetry.createPoTelemetry)({
@@ -1993,7 +2109,7 @@ function createFileEditSession({ agent, host }, fs) {
1993
2109
  * has edited nothing publishes a key with no content and stays hidden.
1994
2110
  */
1995
2111
  const publish = async (runtime) => {
1996
- const items = await readSessionFiles(runtime.timelinePath, runtime.context.cwd);
2112
+ const items = await storage.sessionFiles(runtime.timelinePath, runtime.context.cwd);
1997
2113
  if (active !== runtime || closed || stopping) return;
1998
2114
  directEvents.publish(filesChannelType, runtime.context.sessionId, { items });
1999
2115
  runtime.context.client.setStatus(filesStatusKey, items.length === 0 ? "" : `${items.length} ${items.length === 1 ? "file" : "files"}`);
@@ -2019,10 +2135,10 @@ function createFileEditSession({ agent, host }, fs) {
2019
2135
  disposal = (0, _agimon_ai_po_core_extensionFile.runCleanups)([
2020
2136
  stopActivity,
2021
2137
  async () => {
2022
- if (lastRuntime && !environment[_agimon_ai_po_core_childProcess.SUBAGENT_CHILD_ENV]) await timeline.clear();
2138
+ if (storage.clearOnClose && lastRuntime && !environment[_agimon_ai_po_core_childProcess.SUBAGENT_CHILD_ENV]) await timeline.clear();
2023
2139
  },
2024
2140
  async () => {
2025
- if (lastRuntime && !environment[_agimon_ai_po_core_childProcess.SUBAGENT_CHILD_ENV]) await snapshots.clear();
2141
+ if (storage.clearOnClose && lastRuntime && !environment[_agimon_ai_po_core_childProcess.SUBAGENT_CHILD_ENV]) await snapshots.clear();
2026
2142
  },
2027
2143
  async () => {
2028
2144
  if (lastRuntime) await telemetry.recordEvent("po_file_edit.timeline_finished", { outcome: "closed" });
@@ -2032,7 +2148,7 @@ function createFileEditSession({ agent, host }, fs) {
2032
2148
  return disposal;
2033
2149
  };
2034
2150
  return {
2035
- api: [api],
2151
+ api: [fileEditsApi],
2036
2152
  activities: [{
2037
2153
  name: "file-edits",
2038
2154
  start: async (executionContext) => {
@@ -2068,10 +2184,7 @@ function createFileEditSession({ agent, host }, fs) {
2068
2184
  await publish(runtime);
2069
2185
  track(async () => {
2070
2186
  try {
2071
- await sweepSessionState({
2072
- directory: paths.stateDirectory(),
2073
- keep: timelinePath
2074
- });
2187
+ await storage.sweepAbandoned?.(paths.stateDirectory(), timelinePath);
2075
2188
  } catch {}
2076
2189
  });
2077
2190
  if (!initialized) {
@@ -2138,13 +2251,14 @@ function createFileEditSession({ agent, host }, fs) {
2138
2251
  }
2139
2252
  //#endregion
2140
2253
  //#region src/extensions/workspaces/sessions/(backend)/_lib/serverRoot.ts
2141
- function createPresence({ agent, host, context }, presence) {
2254
+ function createPresence({ agent, host, context }, presence, files) {
2142
2255
  if (!agent || !presence) return void 0;
2143
2256
  const execution = agent.context;
2144
2257
  return createSessionPresence({
2145
2258
  presence,
2146
2259
  sessionId: execution.sessionId,
2147
2260
  cwd: execution.cwd,
2261
+ files,
2148
2262
  workflowStep: execution.sessionContext?.provenance === _agimon_ai_po_core_hubChannel.WORKFLOW_STEP_SESSION_PROVENANCE,
2149
2263
  isLive: () => host.context.sessionService?.isLive(execution.sessionId) ?? true,
2150
2264
  labelFor: (runId) => (0, _agimon_ai_po_core_childSession.readPoChildSessionLabels)(context)?.labelFor(runId),
@@ -2152,7 +2266,8 @@ function createPresence({ agent, host, context }, presence) {
2152
2266
  });
2153
2267
  }
2154
2268
  const createFileEditServerRoot = (context, fs) => {
2155
- const runtime = createFileEditSession(context, fs);
2269
+ const storage = createFileEditStorage(fs);
2270
+ const runtime = createFileEditSession(context, fs, storage);
2156
2271
  let presence;
2157
2272
  let disposePresence = () => {};
2158
2273
  let closed = false;
@@ -2168,7 +2283,7 @@ const createFileEditServerRoot = (context, fs) => {
2168
2283
  services: [(cordis) => {
2169
2284
  cordis.inject([_agimon_ai_po_core_packageApi.PO_EDIT_PRESENCE_SERVICE], (presenceContext) => {
2170
2285
  if (closed) return;
2171
- const bound = createPresence(context, presenceContext.get(_agimon_ai_po_core_packageApi.PO_EDIT_PRESENCE_SERVICE));
2286
+ const bound = createPresence(context, presenceContext.get(_agimon_ai_po_core_packageApi.PO_EDIT_PRESENCE_SERVICE), storage.presenceFiles());
2172
2287
  if (!bound) return;
2173
2288
  presence = bound;
2174
2289
  let disposed = false;
@@ -2197,9 +2312,9 @@ const createFileEditServerRoot = (context, fs) => {
2197
2312
  var root_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoot)((context) => createFileEditServerRoot(context, (0, _agimon_ai_po_core_platform.requirePoFs)(context.context)));
2198
2313
  //#endregion
2199
2314
  //#region src/extensions/(backend)/channel/fileEdits.server.ts
2200
- var fileEdits_server_default = (0, _agimon_ai_po_core_extensionFile.defineChannel)(function fileEditsChannel() {
2201
- return createFilesChannel();
2202
- });
2315
+ var fileEdits_server_default = (0, _agimon_ai_po_core_extensionFile.defineChannel)(function fileEditsChannel(context) {
2316
+ return createFilesChannel(createFileEditStorage((0, _agimon_ai_po_core_platform.readPoFs)(context.context)));
2317
+ }, { context: true });
2203
2318
  //#endregion
2204
2319
  //#region src/extensions/workspaces/sessions/(backend)/api/file-edits/route.server.ts
2205
2320
  /**
@@ -2209,8 +2324,11 @@ var fileEdits_server_default = (0, _agimon_ai_po_core_extensionFile.defineChanne
2209
2324
  * returns a runtime carrying `api`, but a root's `api` is not folded into the
2210
2325
  * generated entry the way its services and activities are, so the registration
2211
2326
  * was dropped in silence and the cockpit called routes that answered 404.
2327
+ *
2328
+ * The API reads the files of the host it runs on, so it is built from the file
2329
+ * system the session was given.
2212
2330
  */
2213
- var route_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoute)(api);
2331
+ var route_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoute)((context) => createFileEditsPoApi(createFileEditStorage((0, _agimon_ai_po_core_platform.readPoFs)(context.context))));
2214
2332
  //#endregion
2215
2333
  //#region src/extensions/workspaces/sessions/(backend)/hook/tool-execution-end.server.ts
2216
2334
  var tool_execution_end_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)((context) => context.root.hooks[1]);