maka-agent 0.2.0-dev.52.20260926 → 0.2.0-dev.53.20260927

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/activation-command.js +11 -3
  2. package/dist/pi-tui-mcp-status.js +73 -5
  3. package/dist/pi-tui-runner.js +1 -1
  4. package/dist/runtime-host-run-command.js +39 -6
  5. package/dist/runtime-host-run-mcp.js +161 -0
  6. package/dist/runtime-host-session-driver.js +22 -2
  7. package/dist/tui-copy-catalog.js +6 -0
  8. package/dist/tui-mcp-control.js +11 -2
  9. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  10. package/node_modules/@maka/core/dist/attachments.js +7 -0
  11. package/node_modules/@maka/core/dist/events.js +11 -0
  12. package/node_modules/@maka/core/dist/provider-registry.js +11 -2
  13. package/node_modules/@maka/core/dist/turn-origin.js +6 -0
  14. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +1 -5
  15. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +80 -24
  16. package/node_modules/@maka/runtime/dist/bots/proxied-fetch.js +5 -4
  17. package/node_modules/@maka/runtime/dist/computer-use-tools.js +136 -100
  18. package/node_modules/@maka/runtime/dist/context-budget-helpers.js +4 -0
  19. package/node_modules/@maka/runtime/dist/conversation-copy.js +51 -205
  20. package/node_modules/@maka/runtime/dist/edit-replace.js +7 -7
  21. package/node_modules/@maka/runtime/dist/filesystem-executor.js +4 -20
  22. package/node_modules/@maka/runtime/dist/filesystem-worker/operations.js +17 -28
  23. package/node_modules/@maka/runtime/dist/format-json.js +39 -0
  24. package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +1 -6
  25. package/node_modules/@maka/runtime/dist/image-file.js +22 -14
  26. package/node_modules/@maka/runtime/dist/model-adapter.js +18 -2
  27. package/node_modules/@maka/runtime/dist/model-history.js +201 -3
  28. package/node_modules/@maka/runtime/dist/network/abortable-connector.js +55 -0
  29. package/node_modules/@maka/runtime/dist/network/proxy-dispatcher.js +72 -37
  30. package/node_modules/@maka/runtime/dist/network/proxy-test.js +1 -1
  31. package/node_modules/@maka/runtime/dist/network/scoped-fetch-transport.js +7 -2
  32. package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +1 -3
  33. package/node_modules/@maka/runtime/dist/provider-error-classification.js +36 -8
  34. package/node_modules/@maka/runtime/dist/recovery-resolver.js +1 -91
  35. package/node_modules/@maka/runtime/dist/runtime-kernel.js +44 -0
  36. package/node_modules/@maka/runtime/dist/session-manager.js +54 -58
  37. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +84 -2
  38. package/node_modules/@maka/runtime/dist/workers/filesystem-worker.js +63 -51
  39. package/node_modules/@maka/runtime/dist/workspace-executor.js +5 -6
  40. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +27 -6
  41. package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +4 -1
  42. package/node_modules/@maka/runtime-host/dist/client/host-handoff.js +9 -9
  43. package/node_modules/@maka/runtime-host/dist/client/session-catalog-summary.js +9 -1
  44. package/node_modules/@maka/runtime-host/dist/protocol/index.js +12 -1
  45. package/node_modules/@maka/runtime-host/dist/protocol/session-catalog.js +28 -6
  46. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +12 -2
  47. package/node_modules/@maka/runtime-host/dist/server/client-capability-coordinator.js +10 -7
  48. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +10 -2
  49. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-recovery.js +2 -0
  50. package/node_modules/@maka/runtime-host/dist/server/interactive-turn-coordinator.js +4 -1
  51. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +4 -2
  52. package/node_modules/@maka/runtime-host/dist/server/operation-dispatcher.js +4 -0
  53. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +6 -5
  54. package/node_modules/@maka/runtime-host/dist/server/safe-boundary-resume-policy.js +27 -0
  55. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +5 -3
  56. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +7 -2
  57. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +11 -141
  58. package/node_modules/@maka/runtime-host/dist/server/session-revision-graph-references.js +46 -75
  59. package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +18 -2
  60. package/node_modules/@maka/runtime-host/dist/server/workhub-result-coordinator.js +33 -3
  61. package/node_modules/@maka/runtime-host/dist/transport/framed-byte-stream-transport.js +39 -5
  62. package/node_modules/@maka/storage/dist/agent-run-store-contract.js +7 -1
  63. package/node_modules/@maka/storage/dist/artifact-store.js +1 -5
  64. package/node_modules/@maka/storage/dist/artifact-stores.js +0 -3
  65. package/node_modules/@maka/storage/dist/atomic-file-write.js +1 -0
  66. package/node_modules/@maka/storage/dist/claude-code-session-adapter.js +107 -57
  67. package/node_modules/@maka/storage/dist/codex-session-adapter.js +227 -19
  68. package/node_modules/@maka/storage/dist/external-session-importer.js +1 -1
  69. package/node_modules/@maka/storage/dist/mcp-config-store.js +22 -3
  70. package/node_modules/@maka/storage/dist/settings-store.js +281 -13
  71. package/package.json +1 -1
@@ -65,6 +65,7 @@ export class HostWorkHubResultCoordinator {
65
65
  ports;
66
66
  #active = false;
67
67
  #draining = false;
68
+ #handoffHeld = false;
68
69
  #dirty = false;
69
70
  #timer;
70
71
  #timerDue = 0;
@@ -81,6 +82,27 @@ export class HostWorkHubResultCoordinator {
81
82
  this.#active = true;
82
83
  this.notify();
83
84
  }
85
+ holdForHandoff() {
86
+ if (this.#draining || this.#handoffHeld)
87
+ return undefined;
88
+ this.#handoffHeld = true;
89
+ this.#stopTimer();
90
+ let released = false;
91
+ return {
92
+ // Finish an admitted poll (including delivery and residency release)
93
+ // before the Root coordinator freezes its execution set.
94
+ settled: async () => {
95
+ await this.#running;
96
+ },
97
+ release: () => {
98
+ if (released)
99
+ return;
100
+ released = true;
101
+ this.#handoffHeld = false;
102
+ this.notify();
103
+ },
104
+ };
105
+ }
84
106
  notify(sessionId) {
85
107
  if (!this.#active ||
86
108
  (sessionId && sessionId !== WORKHUB_COORDINATION_SESSION_ID && !this.#targets.has(sessionId)))
@@ -89,7 +111,7 @@ export class HostWorkHubResultCoordinator {
89
111
  this.#schedule(100);
90
112
  }
91
113
  #schedule(delay) {
92
- if (!this.#active || this.#running)
114
+ if (!this.#active || this.#handoffHeld || this.#running)
93
115
  return;
94
116
  const due = Date.now() + delay;
95
117
  if (this.#timer) {
@@ -98,7 +120,11 @@ export class HostWorkHubResultCoordinator {
98
120
  clearTimeout(this.#timer);
99
121
  }
100
122
  this.#timerDue = due;
101
- this.#timer = setTimeout(() => {
123
+ const timer = setTimeout(() => {
124
+ // A callback queued before clearTimeout must not cross a hold, or
125
+ // replace the new timer installed when that hold is cancelled.
126
+ if (this.#timer !== timer || !this.#active || this.#handoffHeld)
127
+ return;
102
128
  this.#timer = undefined;
103
129
  this.#timerDue = 0;
104
130
  const residency = this.ports.acquireResidency();
@@ -116,7 +142,8 @@ export class HostWorkHubResultCoordinator {
116
142
  this.#schedule(this.#dirty ? 100 : this.#needsRetry || retry ? 5000 : 60000);
117
143
  });
118
144
  }, delay);
119
- this.#timer.unref();
145
+ this.#timer = timer;
146
+ timer.unref();
120
147
  }
121
148
  async reconcile() {
122
149
  this.#dirty = false;
@@ -161,6 +188,9 @@ export class HostWorkHubResultCoordinator {
161
188
  beginDrain() {
162
189
  this.#draining = true;
163
190
  this.#active = false;
191
+ this.#stopTimer();
192
+ }
193
+ #stopTimer() {
164
194
  if (this.#timer)
165
195
  clearTimeout(this.#timer);
166
196
  this.#timer = undefined;
@@ -37,6 +37,9 @@ export class FramedByteStreamTransport {
37
37
  #queue = [];
38
38
  #queuedBytes = 0;
39
39
  #buffered = Buffer.alloc(0);
40
+ #bufferStorage = Buffer.alloc(0);
41
+ #searchedBytes = 0;
42
+ #nextNewline;
40
43
  #waiter;
41
44
  #failure;
42
45
  #readTerminal;
@@ -114,16 +117,40 @@ export class FramedByteStreamTransport {
114
117
  this.#failInboundOverflow();
115
118
  return;
116
119
  }
117
- this.#buffered =
118
- this.#buffered.byteLength === 0 ? Buffer.from(chunk) : Buffer.concat([this.#buffered, chunk]);
120
+ this.#appendIncoming(chunk);
119
121
  this.#drainInbound();
120
122
  }
123
+ // Geometric growth copies an incomplete frame a bounded number of times;
124
+ // scanning resumes at the previous tail instead of revisiting every fragment.
125
+ #appendIncoming(chunk) {
126
+ const length = this.#buffered.byteLength + chunk.byteLength;
127
+ let start = this.#buffered.byteOffset - this.#bufferStorage.byteOffset;
128
+ if (this.#buffered.byteLength === 0 || start + length > this.#bufferStorage.byteLength) {
129
+ const capacity = Math.min(MAX_BUFFERED_BYTES, Math.max(length, this.#bufferStorage.byteLength * 2));
130
+ const storage = Buffer.allocUnsafe(capacity);
131
+ this.#buffered.copy(storage);
132
+ this.#bufferStorage = storage;
133
+ this.#buffered = storage.subarray(0, this.#buffered.byteLength);
134
+ start = 0;
135
+ }
136
+ chunk.copy(this.#bufferStorage, start + this.#buffered.byteLength);
137
+ this.#buffered = this.#bufferStorage.subarray(start, start + length);
138
+ }
139
+ #findNewline() {
140
+ if (this.#nextNewline !== undefined)
141
+ return this.#nextNewline;
142
+ const newline = this.#buffered.indexOf(0x0a, this.#searchedBytes);
143
+ this.#searchedBytes = newline === -1 ? this.#buffered.byteLength : newline + 1;
144
+ if (newline !== -1)
145
+ this.#nextNewline = newline;
146
+ return newline;
147
+ }
121
148
  #drainInbound() {
122
149
  if (this.#failure)
123
150
  return;
124
151
  try {
125
152
  while (true) {
126
- const newline = this.#buffered.indexOf(0x0a);
153
+ const newline = this.#findNewline();
127
154
  if (newline === -1) {
128
155
  if (this.#buffered.byteLength > RUNTIME_HOST_MAX_MESSAGE_BYTES) {
129
156
  throw new RuntimeHostProtocolError('frame_too_large', 'Runtime Host message exceeds the byte limit');
@@ -141,16 +168,23 @@ export class FramedByteStreamTransport {
141
168
  encodedBytes === this.#buffered.byteLength
142
169
  ? Buffer.alloc(0)
143
170
  : this.#buffered.subarray(encodedBytes);
171
+ this.#searchedBytes = 0;
172
+ this.#nextNewline = undefined;
173
+ if (this.#buffered.byteLength === 0)
174
+ this.#bufferStorage = Buffer.alloc(0);
144
175
  const frames = this.#decoder.push(encoded);
145
176
  if (frames.length !== 1) {
146
177
  throw new Error('Runtime Host decoder did not produce one complete frame');
147
178
  }
148
179
  this.#deliver(frames[0], encodedBytes);
149
180
  }
150
- if (this.#ended && !this.#decoderEnded && this.#buffered.indexOf(0x0a) === -1) {
181
+ if (this.#ended && !this.#decoderEnded && this.#findNewline() === -1) {
151
182
  if (this.#buffered.byteLength !== 0) {
152
183
  this.#decoder.push(this.#buffered);
153
184
  this.#buffered = Buffer.alloc(0);
185
+ this.#bufferStorage = Buffer.alloc(0);
186
+ this.#searchedBytes = 0;
187
+ this.#nextNewline = undefined;
154
188
  }
155
189
  this.#decoder.end();
156
190
  this.#decoderEnded = true;
@@ -178,7 +212,7 @@ export class FramedByteStreamTransport {
178
212
  }
179
213
  }
180
214
  #updateReadFlow() {
181
- const nextNewline = this.#buffered.indexOf(0x0a);
215
+ const nextNewline = this.#findNewline();
182
216
  const nextFrameBytes = nextNewline === -1 ? undefined : nextNewline + 1;
183
217
  const blocked = this.#queue.length >= MAX_QUEUED_FRAMES ||
184
218
  (nextFrameBytes !== undefined && this.#queuedBytes + nextFrameBytes > MAX_QUEUED_BYTES);
@@ -663,10 +663,15 @@ export function normalizeRootExecutionDescriptor(value) {
663
663
  throw new Error('Invalid root execution descriptor');
664
664
  }
665
665
  if (value.kind === 'external_message') {
666
- const allowedKeys = ['kind', 'inputDigest', 'maxSteps'];
666
+ const decodedOrigin = decodeTurnOrigin(value.origin);
667
+ const origin = decodedOrigin?.kind === 'cloud_activation' ? decodedOrigin : undefined;
668
+ const allowedKeys = ['kind', 'inputDigest', 'maxSteps', 'origin'];
667
669
  if (!Object.keys(value).every((key) => allowedKeys.includes(key))) {
668
670
  throw new Error('Invalid root execution descriptor');
669
671
  }
672
+ if (value.origin !== undefined && origin === undefined) {
673
+ throw new Error('Invalid root execution descriptor');
674
+ }
670
675
  if (value.inputDigest !== undefined && !isSha256Digest(value.inputDigest)) {
671
676
  throw new Error('Invalid root execution descriptor');
672
677
  }
@@ -680,6 +685,7 @@ export function normalizeRootExecutionDescriptor(value) {
680
685
  kind: 'external_message',
681
686
  ...(value.inputDigest !== undefined ? { inputDigest: value.inputDigest } : {}),
682
687
  ...(value.maxSteps !== undefined ? { maxSteps: value.maxSteps } : {}),
688
+ ...(origin !== undefined ? { origin } : {}),
683
689
  });
684
690
  }
685
691
  if (value.kind === 'workhub_coordination') {
@@ -108,7 +108,6 @@ class SqliteArtifactStore {
108
108
  throw new Error('Artifact conversation copy requires distinct Sessions');
109
109
  }
110
110
  const turnIds = new Set(input.turnIds);
111
- const excludedArtifactIds = new Set(input.excludeArtifactIds ?? []);
112
111
  const includedArtifactIds = new Set(input.includeArtifactIds ?? []);
113
112
  for (const turnId of turnIds)
114
113
  assertArtifactTurnKey(turnId);
@@ -129,9 +128,7 @@ class SqliteArtifactStore {
129
128
  const records = await this.enqueue(async () => {
130
129
  await this.load();
131
130
  const selected = this.records
132
- .filter((record) => record.sessionId === input.sourceSessionId &&
133
- turnIds.has(record.turnId) &&
134
- !excludedArtifactIds.has(record.id))
131
+ .filter((record) => record.sessionId === input.sourceSessionId && turnIds.has(record.turnId))
135
132
  .map((record) => ({ ...record }));
136
133
  for (const [sessionId, artifactIds] of requestedLinkedArtifactIds) {
137
134
  for (const artifactId of artifactIds) {
@@ -149,7 +146,6 @@ class SqliteArtifactStore {
149
146
  for (const record of this.records) {
150
147
  if (record.sessionId === input.sourceSessionId &&
151
148
  includedArtifactIds.has(record.id) &&
152
- !excludedArtifactIds.has(record.id) &&
153
149
  !selectedIds.has(record.id)) {
154
150
  selected.push({ ...record });
155
151
  selectedIds.add(record.id);
@@ -85,9 +85,6 @@ function createWriterFacade(lease, authority) {
85
85
  const acceptedInput = Object.freeze({
86
86
  ...input,
87
87
  turnIds: Object.freeze([...input.turnIds]),
88
- ...(input.excludeArtifactIds
89
- ? { excludeArtifactIds: Object.freeze([...input.excludeArtifactIds]) }
90
- : {}),
91
88
  ...(input.includeArtifactIds
92
89
  ? { includeArtifactIds: Object.freeze([...input.includeArtifactIds]) }
93
90
  : {}),
@@ -57,6 +57,7 @@ export async function writeAtomicFile(path, contents, options, dependencies = {}
57
57
  await handle.close().catch(() => { });
58
58
  throw error;
59
59
  }
60
+ await options.beforePublish?.();
60
61
  await rename(tempPath, path);
61
62
  published = true;
62
63
  tempCreated = false;
@@ -70,6 +70,28 @@ const CLAUDE_CATALOG_SUMMARY_TAIL_BYTES = 256 * 1024;
70
70
  * A uuid is what Claude Code writes; anything else is refused rather than
71
71
  * joined onto a path. */
72
72
  const SESSION_ID_PATTERN = /^[0-9a-fA-F-]{1,128}$/u;
73
+ /** Transcript derivations in flight during one listing. The point of
74
+ * concurrency is to overlap the thread-pool round trips (stat, open, read)
75
+ * with the parsing, not to hold every transcript's window at once: an
76
+ * unbounded fan-out would open one descriptor per session and buffer every
77
+ * candidate's summary windows concurrently — bounded only by the corpus
78
+ * size. A pool of 8 keeps libuv's default 4-thread pool saturated while
79
+ * capping open descriptors at 8 and peak buffers at 8 × 512 KiB. */
80
+ const LIST_CONCURRENCY = 8;
81
+ /** Maps with at most `limit` of `worker`'s promises in flight, results in
82
+ * input order. */
83
+ async function mapWithConcurrency(items, limit, worker) {
84
+ const results = new Array(items.length);
85
+ let next = 0;
86
+ const lanes = Array.from({ length: Math.min(limit, items.length) }, async () => {
87
+ while (next < items.length) {
88
+ const index = next++;
89
+ results[index] = await worker(items[index]);
90
+ }
91
+ });
92
+ await Promise.all(lanes);
93
+ return results;
94
+ }
73
95
  export class ClaudeCodeSessionAdapter {
74
96
  id = CLAUDE_CODE_SESSION_ADAPTER_ID;
75
97
  #home;
@@ -115,19 +137,34 @@ export class ClaudeCodeSessionAdapter {
115
137
  const files = await this.#transcriptFiles();
116
138
  for (const file of files)
117
139
  live.add(file.path);
118
- for (const file of files) {
119
- const summary = await this.#summaryOf(file.path, file.sessionId);
120
- if (!summary)
121
- continue;
122
- // The shared matcher, not a local cwd comparison: filtering happens here
123
- // rather than after paging, and every source has to answer a query the
124
- // same way or the catalog lies about which one dropped the term.
125
- if (!externalSessionMatchesQuery(summary, query))
126
- continue;
127
- if (matched++ < offset)
128
- continue;
129
- summaries.push(summary);
130
- if (summaries.length === limit)
140
+ // Derived in bounded chunks rather than one `await` at a time: each
141
+ // summary is a stat-open-read round trip through the thread pool, so a
142
+ // sequential loop serializes waiting rather than work. Whole-set fan-out
143
+ // would defeat the page budget above — it derives every transcript's
144
+ // summary where the loop stops at the first full page — so the chunk
145
+ // boundaries double as early-exit points: at most one chunk of extra
146
+ // derivations past a full page, all of them cache entries the next page
147
+ // (or the next search term) reuses. `#summaryOf` never throws and only
148
+ // touches the cache at distinct keys, and results are consumed in `files`
149
+ // order, so the paged list is the one the sequential loop produced.
150
+ for (let start = 0; start < files.length; start += LIST_CONCURRENCY) {
151
+ const chunk = files.slice(start, start + LIST_CONCURRENCY);
152
+ const derived = await Promise.all(chunk.map((file) => this.#summaryOf(file)));
153
+ for (const summary of derived) {
154
+ if (!summary)
155
+ continue;
156
+ // The shared matcher, not a local cwd comparison: filtering happens here
157
+ // rather than after paging, and every source has to answer a query the
158
+ // same way or the catalog lies about which one dropped the term.
159
+ if (!externalSessionMatchesQuery(summary, query))
160
+ continue;
161
+ if (matched++ < offset)
162
+ continue;
163
+ summaries.push(summary);
164
+ if (summaries.length === limit)
165
+ break;
166
+ }
167
+ if (summaries.length >= limit)
131
168
  break;
132
169
  }
133
170
  // A transcript the source no longer lists must not keep its entry alive,
@@ -146,19 +183,15 @@ export class ClaudeCodeSessionAdapter {
146
183
  *
147
184
  * `undefined` is cached too: a sidechain transcript or an unreadable one is
148
185
  * a stable answer, and re-deriving it every list would defeat the point.
186
+ *
187
+ * The cache key is the walk's own stat, not a fresh one taken here: within
188
+ * a listing that makes the newest-wins choice and the cache key one
189
+ * observation of one file rather than two that can disagree. A transcript
190
+ * appended after the walk lands in the cache under the older key, and the
191
+ * next listing — which sees the new mtime — re-reads it.
149
192
  */
150
- async #summaryOf(path, sessionId) {
151
- let mtimeMs;
152
- let size;
153
- try {
154
- const info = await stat(path);
155
- mtimeMs = info.mtimeMs;
156
- size = info.size;
157
- }
158
- catch {
159
- this.#summaries.delete(path);
160
- return undefined;
161
- }
193
+ async #summaryOf(file) {
194
+ const { path, sessionId, mtimeMs, size } = file;
162
195
  const cached = this.#summaries.get(path);
163
196
  if (cached && cached.mtimeMs === mtimeMs && cached.size === size)
164
197
  return cached.summary;
@@ -199,47 +232,64 @@ export class ClaudeCodeSessionAdapter {
199
232
  catch {
200
233
  return [];
201
234
  }
202
- // Keyed by session id: the same id can legitimately exist under more than
203
- // one project directory after a workspace move or a resumed session. Two
204
- // files with one id are two candidates for the same source session, and
205
- // list and read must pick the same one or a user selects one summary and
206
- // imports the other.
207
- const bySessionId = new Map();
208
- for (const project of projects) {
209
- let entries;
235
+ // Listing one project and stating one file are each a round trip through
236
+ // the thread pool, so the walk is concurrent rather than one await at a
237
+ // time — the cost of a full scan is latency-bound, not work-bound. The
238
+ // pool cap bounds open directory handles during the walk. A project that
239
+ // fails to list or a file that vanishes mid-scan is dropped per item,
240
+ // exactly as the sequential loop dropped it.
241
+ const listings = await mapWithConcurrency(projects, LIST_CONCURRENCY, async (project) => {
210
242
  try {
211
- entries = (await readdir(join(root, project), { withFileTypes: true }))
212
- .filter((entry) => entry.isFile() && entry.name.endsWith('.jsonl'))
213
- .map((entry) => entry.name);
243
+ return (await readdir(join(root, project), { withFileTypes: true })).filter((entry) => entry.isFile() && entry.name.endsWith('.jsonl'));
214
244
  }
215
245
  catch {
216
- continue;
246
+ return [];
217
247
  }
218
- for (const name of entries) {
219
- const sessionId = name.slice(0, -'.jsonl'.length);
248
+ });
249
+ const resolvedRoot = resolve(root);
250
+ const candidates = [];
251
+ for (const [index, project] of projects.entries()) {
252
+ for (const entry of listings[index]) {
253
+ const sessionId = entry.name.slice(0, -'.jsonl'.length);
220
254
  if (!SESSION_ID_PATTERN.test(sessionId))
221
255
  continue;
222
- const path = join(root, project, name);
256
+ const path = join(root, project, entry.name);
223
257
  // The id reaches a path join, so the resolved file must still be under
224
258
  // the projects root — a crafted id must not read outside it.
225
- if (!resolve(path).startsWith(resolve(root)))
259
+ if (!resolve(path).startsWith(resolvedRoot))
226
260
  continue;
227
- let mtimeMs;
228
- try {
229
- mtimeMs = (await stat(path)).mtimeMs;
230
- }
231
- catch {
232
- continue;
233
- }
234
- const existing = bySessionId.get(sessionId);
235
- // Newest wins, and the path breaks a tie so the choice does not depend
236
- // on directory iteration order. A resumed session's continuation is
237
- // the copy a user means when they pick that id.
238
- if (!existing ||
239
- mtimeMs > existing.mtimeMs ||
240
- (mtimeMs === existing.mtimeMs && path < existing.path)) {
241
- bySessionId.set(sessionId, { path, sessionId, mtimeMs });
242
- }
261
+ candidates.push({ path, sessionId });
262
+ }
263
+ }
264
+ // One stat per file, kept: the mtime decides the newest-wins winner and
265
+ // the summary cache key, the size completes that key.
266
+ const stats = await mapWithConcurrency(candidates, LIST_CONCURRENCY, async (candidate) => {
267
+ try {
268
+ const info = await stat(candidate.path);
269
+ return { mtimeMs: info.mtimeMs, size: info.size };
270
+ }
271
+ catch {
272
+ return undefined;
273
+ }
274
+ });
275
+ // Keyed by session id: the same id can legitimately exist under more than
276
+ // one project directory after a workspace move or a resumed session. Two
277
+ // files with one id are two candidates for the same source session, and
278
+ // list and read must pick the same one or a user selects one summary and
279
+ // imports the other.
280
+ const bySessionId = new Map();
281
+ for (const [index, { path, sessionId }] of candidates.entries()) {
282
+ const observed = stats[index];
283
+ if (observed === undefined)
284
+ continue;
285
+ const existing = bySessionId.get(sessionId);
286
+ // Newest wins, and the path breaks a tie so the choice does not depend
287
+ // on directory iteration order. A resumed session's continuation is
288
+ // the copy a user means when they pick that id.
289
+ if (!existing ||
290
+ observed.mtimeMs > existing.mtimeMs ||
291
+ (observed.mtimeMs === existing.mtimeMs && path < existing.path)) {
292
+ bySessionId.set(sessionId, { path, sessionId, ...observed });
243
293
  }
244
294
  }
245
295
  return [...bySessionId.values()].sort((left, right) => right.mtimeMs - left.mtimeMs || left.path.localeCompare(right.path));