arco-workbench 0.1.7 → 0.1.9

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 (301) hide show
  1. package/CONTRIBUTING.md +63 -12
  2. package/README.md +21 -17
  3. package/client/dist/assets/{PhosphorBackdrop-DVQdBrTw.js → PhosphorBackdrop-DRu16-Is.js} +1 -1
  4. package/client/dist/assets/{ThemedBackgroundShaderImpl-BfSs2tB4.js → ThemedBackgroundShaderImpl-BLdwwQ4D.js} +1 -1
  5. package/client/dist/assets/{XtermView-DaMjC8Ny.js → XtermView-Xk7_9JaH.js} +1 -1
  6. package/client/dist/assets/{galleryEditor-BCQnXj7R.js → galleryEditor-CI8ClzBa.js} +1 -1
  7. package/client/dist/assets/{index-DD9kFGsF.css → index-BEFgrUJJ.css} +1 -1
  8. package/client/dist/assets/{index-COfbHCYv.js → index-C7WzZfsr.js} +257 -255
  9. package/client/dist/index.html +2 -2
  10. package/client/src/App.tsx +2 -0
  11. package/client/src/components/ChatMessage.tsx +33 -8
  12. package/client/src/components/ChatModeView.tsx +2 -0
  13. package/client/src/components/ClusterRightPanel/ReplaceMemberDialog.tsx +65 -15
  14. package/client/src/components/ClusterRightPanel/SkillsControl.tsx +124 -0
  15. package/client/src/components/ClusterRightPanel/index.tsx +4 -0
  16. package/client/src/components/ClusterTaskBoardTab.tsx +9 -22
  17. package/client/src/components/CodexLateCommand.tsx +34 -0
  18. package/client/src/components/DialogShell.tsx +2 -0
  19. package/client/src/components/MemberCard.tsx +4 -1
  20. package/client/src/components/MemberPane.tsx +3 -1
  21. package/client/src/components/NeedsYouBadge.tsx +3 -3
  22. package/client/src/components/PhoneUpload.tsx +288 -0
  23. package/client/src/components/PrimaryStatus.tsx +14 -6
  24. package/client/src/components/ProviderReleasesModal.tsx +8 -4
  25. package/client/src/components/ProvidersPopover.tsx +28 -23
  26. package/client/src/components/RuntimeStateBanner.tsx +5 -0
  27. package/client/src/components/SettingsPanel.tsx +2 -2
  28. package/client/src/components/SkillEditorDialog.tsx +2 -2
  29. package/client/src/components/SkillsSettings.tsx +21 -4
  30. package/client/src/components/TabBar.tsx +91 -9
  31. package/client/src/components/TerminalInput.tsx +15 -11
  32. package/client/src/components/TranscriptSendDialog.tsx +12 -8
  33. package/client/src/components/TranscriptWorkerDialog.tsx +119 -0
  34. package/client/src/components/WorkflowView.tsx +2 -0
  35. package/client/src/components/clusterNeedsYou.ts +11 -18
  36. package/client/src/explorer/ArtifactsLens.tsx +37 -28
  37. package/client/src/explorer/ExplorerApp.tsx +5 -4
  38. package/client/src/explorer/types.ts +8 -3
  39. package/client/src/help/content/cluster.tsx +48 -17
  40. package/client/src/help/content/composer.tsx +40 -1
  41. package/client/src/help/content/header.tsx +18 -1
  42. package/client/src/help/content/misc.tsx +9 -1
  43. package/client/src/help/content/settings.tsx +18 -4
  44. package/client/src/help/content/tabbar.tsx +5 -0
  45. package/client/src/help/manualSections/actions.tsx +31 -0
  46. package/client/src/help/manualSections/clusters.tsx +44 -20
  47. package/client/src/help/manualSections/configuration.tsx +20 -0
  48. package/client/src/help/manualSections/gettingStarted.tsx +4 -4
  49. package/client/src/help/manualSections/maintenance.tsx +25 -6
  50. package/client/src/help/manualSections/powerFeatures.tsx +3 -2
  51. package/client/src/help/manualSections/providers.tsx +32 -8
  52. package/client/src/help/manualSections/troubleshooting.tsx +2 -1
  53. package/client/src/help/manualSections/workflows.tsx +12 -0
  54. package/client/src/help/manualSections/workspace.tsx +36 -0
  55. package/client/src/stores/appStore.ts +7 -0
  56. package/client/src/stores/appStore.types.ts +4 -0
  57. package/client/src/styles/global.css +109 -0
  58. package/client/src/utils/phoneTheme.ts +38 -0
  59. package/client/src/utils/phoneUploadApi.ts +10 -0
  60. package/client/src/utils/transcriptWorkerRequest.ts +24 -0
  61. package/client/src/ws/handleServerMessage.ts +31 -8
  62. package/docs/ARCHITECTURE.md +1 -1
  63. package/docs/CLIENT.md +16 -9
  64. package/docs/FEATURES.md +13 -7
  65. package/docs/GETTING_STARTED.md +12 -6
  66. package/docs/GOTCHAS.md +2 -1
  67. package/docs/INDEX.md +1 -1
  68. package/docs/OPERATIONS.md +213 -52
  69. package/docs/PERSISTENCE.md +7 -2
  70. package/docs/PRIMITIVES.md +42 -0
  71. package/docs/PROTOCOL_CLUSTER.md +51 -4
  72. package/docs/PROTOCOL_PRIMITIVES.md +39 -0
  73. package/docs/PROVIDERS.md +84 -13
  74. package/docs/SETTINGS.md +29 -3
  75. package/docs/TASK_LEDGER.md +7 -15
  76. package/native/linux-x64/manifest.json +1 -1
  77. package/native/win32-x64/manifest.json +1 -1
  78. package/node_modules/@arco/shared/dist/clusterCoordination.d.ts +2 -0
  79. package/node_modules/@arco/shared/dist/clusterCoordination.js +5 -1
  80. package/node_modules/@arco/shared/dist/protocol/chat.d.ts +1 -0
  81. package/node_modules/@arco/shared/dist/protocol/clientMessages.d.ts +3 -2
  82. package/node_modules/@arco/shared/dist/protocol/clusters.d.ts +15 -1
  83. package/node_modules/@arco/shared/dist/protocol/index.d.ts +1 -0
  84. package/node_modules/@arco/shared/dist/protocol/index.js +1 -0
  85. package/node_modules/@arco/shared/dist/protocol/models.d.ts +4 -3
  86. package/node_modules/@arco/shared/dist/protocol/models.js +26 -2
  87. package/node_modules/@arco/shared/dist/protocol/serverMessages.d.ts +13 -1
  88. package/node_modules/@arco/shared/dist/protocol/tasks.d.ts +4 -0
  89. package/node_modules/@arco/shared/dist/protocol/transcriptWorker.d.ts +47 -0
  90. package/node_modules/@arco/shared/dist/protocol/transcriptWorker.js +2 -0
  91. package/node_modules/@arco/shared/dist/protocol/workflows.d.ts +1 -0
  92. package/node_modules/@arco/shared/dist/runtimeVersions.d.ts +1 -0
  93. package/node_modules/@arco/shared/dist/runtimeVersions.js +14 -0
  94. package/node_modules/@arco/shared/package.json +1 -1
  95. package/package.json +2 -2
  96. package/scripts/packaging/arco.mjs +1 -1
  97. package/scripts/packaging/native-repair.mjs +32 -4
  98. package/server/dist/atomicFile.js +1 -2
  99. package/server/dist/capabilities.d.ts +5 -2
  100. package/server/dist/capabilities.js +59 -9
  101. package/server/dist/cliUpdateDecision.d.ts +1 -1
  102. package/server/dist/cliUpdateDecision.js +5 -3
  103. package/server/dist/clusterDirector.js +2 -1
  104. package/server/dist/clusterPeerOps.js +14 -8
  105. package/server/dist/clusterProgress.js +1 -1
  106. package/server/dist/clusterRehydrate.js +2 -0
  107. package/server/dist/clusterSkills.d.ts +13 -0
  108. package/server/dist/clusterSkills.js +81 -0
  109. package/server/dist/clusterSnapshots.js +2 -0
  110. package/server/dist/clusterStore.d.ts +7 -2
  111. package/server/dist/clusterStore.js +42 -1
  112. package/server/dist/diagnostics/codeSkew.js +1 -0
  113. package/server/dist/eventLog.d.ts +7 -0
  114. package/server/dist/eventLog.js +70 -13
  115. package/server/dist/explorerDocs.d.ts +10 -6
  116. package/server/dist/explorerDocs.js +75 -34
  117. package/server/dist/historyLimits.d.ts +1 -0
  118. package/server/dist/historyLimits.js +3 -0
  119. package/server/dist/http/attachmentUpload.d.ts +13 -0
  120. package/server/dist/http/attachmentUpload.js +38 -0
  121. package/server/dist/http/browserWorktrees.d.ts +23 -0
  122. package/server/dist/http/browserWorktrees.js +120 -0
  123. package/server/dist/http/phoneUploadDrafts.d.ts +13 -0
  124. package/server/dist/http/phoneUploadDrafts.js +125 -0
  125. package/server/dist/http/phoneUploadListener.d.ts +17 -0
  126. package/server/dist/http/phoneUploadListener.js +81 -0
  127. package/server/dist/http/phoneUploadNetwork.d.ts +9 -0
  128. package/server/dist/http/phoneUploadNetwork.js +106 -0
  129. package/server/dist/http/phoneUploadPage.d.ts +2 -0
  130. package/server/dist/http/phoneUploadPage.js +136 -0
  131. package/server/dist/http/phoneUploadRouteHistory.d.ts +4 -0
  132. package/server/dist/http/phoneUploadRouteHistory.js +72 -0
  133. package/server/dist/http/phoneUploadRoutes.d.ts +4 -0
  134. package/server/dist/http/phoneUploadRoutes.js +419 -0
  135. package/server/dist/http/phoneUploadTheme.d.ts +17 -0
  136. package/server/dist/http/phoneUploadTheme.js +96 -0
  137. package/server/dist/http/projectBinding.d.ts +1 -0
  138. package/server/dist/http/projectBinding.js +3 -2
  139. package/server/dist/http/readConfinement.js +5 -1
  140. package/server/dist/http/router.js +14 -25
  141. package/server/dist/http/writeConfinement.js +19 -2
  142. package/server/dist/index.js +24 -1
  143. package/server/dist/jsonlLines.d.ts +4 -0
  144. package/server/dist/jsonlLines.js +53 -0
  145. package/server/dist/management/identity.js +1 -0
  146. package/server/dist/mcp/clusterMcpTools.js +4 -4
  147. package/server/dist/primitives/seedWorker.d.ts +1 -0
  148. package/server/dist/primitives/seedWorker.js +2 -1
  149. package/server/dist/project/taskLedger.d.ts +4 -0
  150. package/server/dist/project/taskLedger.js +7 -4
  151. package/server/dist/providerConversation.d.ts +1 -0
  152. package/server/dist/providerConversation.js +17 -0
  153. package/server/dist/providers/claude-native/resumeSummary.d.ts +9 -0
  154. package/server/dist/providers/claude-native/resumeSummary.js +102 -49
  155. package/server/dist/providers/claude-native/worker.js +8 -4
  156. package/server/dist/providers/claude.js +2 -1
  157. package/server/dist/providers/clusterTaskToolDefinitions.js +4 -4
  158. package/server/dist/providers/codex-appserver/catalog.js +16 -1
  159. package/server/dist/providers/codex-appserver/heldCommands.d.ts +14 -0
  160. package/server/dist/providers/codex-appserver/heldCommands.js +54 -0
  161. package/server/dist/providers/codex-appserver/index.d.ts +52 -2
  162. package/server/dist/providers/codex-appserver/index.js +239 -21
  163. package/server/dist/providers/codex-appserver/lateCommands.d.ts +62 -0
  164. package/server/dist/providers/codex-appserver/lateCommands.js +195 -0
  165. package/server/dist/providers/codex-appserver/worker.d.ts +23 -1
  166. package/server/dist/providers/codex-appserver/worker.js +89 -20
  167. package/server/dist/providers/codex.js +2 -1
  168. package/server/dist/providers/codexCodeMode.d.ts +2 -1
  169. package/server/dist/providers/codexCodeMode.js +8 -3
  170. package/server/dist/providers/cursor/print.js +2 -1
  171. package/server/dist/providers/cursor/worker.js +2 -1
  172. package/server/dist/providers/llamacpp.js +17 -8
  173. package/server/dist/providers/ollamaRecovery.js +6 -6
  174. package/server/dist/providers/ollamaResilience.js +3 -3
  175. package/server/dist/providers/ollamaTokens.js +1 -1
  176. package/server/dist/quota.d.ts +0 -18
  177. package/server/dist/quota.js +0 -44
  178. package/server/dist/replacementHistory.d.ts +19 -0
  179. package/server/dist/replacementHistory.js +49 -0
  180. package/server/dist/server/broadcast.d.ts +2 -1
  181. package/server/dist/server/broadcast.js +1 -0
  182. package/server/dist/server/prompts.d.ts +1 -0
  183. package/server/dist/server/prompts.js +6 -1
  184. package/server/dist/sessionJsonl.d.ts +1 -1
  185. package/server/dist/sessionJsonl.js +115 -40
  186. package/server/dist/smartPickupAdapters.js +15 -2
  187. package/server/dist/transcriptWorker.d.ts +34 -0
  188. package/server/dist/transcriptWorker.js +201 -0
  189. package/server/dist/workers/WorkerManager.d.ts +1 -0
  190. package/server/dist/workers/WorkerManager.js +1 -0
  191. package/server/dist/workers/processKill.d.ts +9 -1
  192. package/server/dist/workers/processKill.js +26 -10
  193. package/server/dist/workflowStore.d.ts +1 -0
  194. package/server/dist/workflowStore.js +31 -0
  195. package/server/dist/ws/clusterHandlers.d.ts +1 -0
  196. package/server/dist/ws/clusterHandlers.js +62 -26
  197. package/server/dist/ws/handoffHandlers.js +7 -2
  198. package/server/dist/ws/transcriptWorkerHandlers.d.ts +25 -0
  199. package/server/dist/ws/transcriptWorkerHandlers.js +139 -0
  200. package/server/dist/ws/turnEngine.js +40 -9
  201. package/server/dist/ws/updatePrimaryConfig.js +27 -8
  202. package/server/dist/ws/workflowHandlers.d.ts +4 -1
  203. package/server/dist/ws/workflowHandlers.js +3 -1
  204. package/server/package.json +1 -1
  205. package/server/src/atomicFile.ts +1 -2
  206. package/server/src/capabilities.ts +58 -17
  207. package/server/src/cliUpdateDecision.ts +5 -4
  208. package/server/src/clusterDirector.ts +2 -1
  209. package/server/src/clusterPeerOps.ts +15 -9
  210. package/server/src/clusterProgress.ts +1 -1
  211. package/server/src/clusterRehydrate.ts +2 -0
  212. package/server/src/clusterSkills.ts +79 -0
  213. package/server/src/clusterSnapshots.ts +1 -0
  214. package/server/src/clusterStore.ts +38 -0
  215. package/server/src/diagnostics/codeSkew.ts +1 -0
  216. package/server/src/eventLog.ts +73 -13
  217. package/server/src/explorerDocs.ts +75 -34
  218. package/server/src/historyLimits.ts +2 -0
  219. package/server/src/http/attachmentUpload.ts +49 -0
  220. package/server/src/http/browserWorktrees.ts +124 -0
  221. package/server/src/http/phoneUploadDrafts.ts +118 -0
  222. package/server/src/http/phoneUploadListener.ts +96 -0
  223. package/server/src/http/phoneUploadNetwork.ts +117 -0
  224. package/server/src/http/phoneUploadPage.ts +137 -0
  225. package/server/src/http/phoneUploadRouteHistory.ts +73 -0
  226. package/server/src/http/phoneUploadRoutes.ts +398 -0
  227. package/server/src/http/phoneUploadTheme.ts +97 -0
  228. package/server/src/http/projectBinding.ts +3 -2
  229. package/server/src/http/readConfinement.ts +5 -1
  230. package/server/src/http/router.ts +12 -26
  231. package/server/src/http/writeConfinement.ts +13 -2
  232. package/server/src/index.ts +23 -0
  233. package/server/src/jsonlLines.ts +52 -0
  234. package/server/src/management/identity.ts +1 -0
  235. package/server/src/mcp/clusterMcpTools.ts +4 -4
  236. package/server/src/primitives/seedWorker.ts +3 -1
  237. package/server/src/project/taskLedger.ts +7 -5
  238. package/server/src/providerConversation.ts +15 -0
  239. package/server/src/providers/claude-native/resumeSummary.ts +98 -50
  240. package/server/src/providers/claude-native/worker.ts +8 -4
  241. package/server/src/providers/claude.ts +2 -1
  242. package/server/src/providers/clusterTaskToolDefinitions.ts +4 -4
  243. package/server/src/providers/codex-appserver/catalog.ts +14 -1
  244. package/server/src/providers/codex-appserver/heldCommands.ts +58 -0
  245. package/server/src/providers/codex-appserver/index.ts +222 -20
  246. package/server/src/providers/codex-appserver/lateCommands.ts +225 -0
  247. package/server/src/providers/codex-appserver/worker.ts +85 -21
  248. package/server/src/providers/codex.ts +2 -1
  249. package/server/src/providers/codexCodeMode.ts +9 -4
  250. package/server/src/providers/cursor/print.ts +2 -1
  251. package/server/src/providers/cursor/worker.ts +2 -1
  252. package/server/src/providers/llamacpp.ts +18 -7
  253. package/server/src/providers/llamacppRecovery.ts +2 -0
  254. package/server/src/providers/ollamaRecovery.ts +6 -6
  255. package/server/src/providers/ollamaResilience.ts +3 -3
  256. package/server/src/providers/ollamaTokens.ts +1 -1
  257. package/server/src/providers/ollamaToolSubset.ts +3 -3
  258. package/server/src/quota.ts +0 -50
  259. package/server/src/replacementHistory.ts +44 -0
  260. package/server/src/server/broadcast.ts +2 -0
  261. package/server/src/server/prompts.ts +8 -1
  262. package/server/src/sessionJsonl.ts +92 -32
  263. package/server/src/smartPickupAdapters.ts +17 -3
  264. package/server/src/transcriptWorker.ts +182 -0
  265. package/server/src/workers/WorkerManager.ts +2 -0
  266. package/server/src/workers/processKill.ts +35 -7
  267. package/server/src/workflowStore.ts +21 -0
  268. package/server/src/ws/clusterHandlers.ts +43 -25
  269. package/server/src/ws/handoffHandlers.ts +7 -1
  270. package/server/src/ws/transcriptWorkerHandlers.ts +126 -0
  271. package/server/src/ws/turnEngine.ts +35 -8
  272. package/server/src/ws/updatePrimaryConfig.ts +25 -6
  273. package/server/src/ws/workflowHandlers.ts +3 -1
  274. package/shared/dist/clusterCoordination.d.ts +2 -0
  275. package/shared/dist/clusterCoordination.js +5 -1
  276. package/shared/dist/protocol/chat.d.ts +1 -0
  277. package/shared/dist/protocol/clientMessages.d.ts +3 -2
  278. package/shared/dist/protocol/clusters.d.ts +15 -1
  279. package/shared/dist/protocol/index.d.ts +1 -0
  280. package/shared/dist/protocol/index.js +1 -0
  281. package/shared/dist/protocol/models.d.ts +4 -3
  282. package/shared/dist/protocol/models.js +26 -2
  283. package/shared/dist/protocol/serverMessages.d.ts +13 -1
  284. package/shared/dist/protocol/tasks.d.ts +4 -0
  285. package/shared/dist/protocol/transcriptWorker.d.ts +47 -0
  286. package/shared/dist/protocol/transcriptWorker.js +2 -0
  287. package/shared/dist/protocol/workflows.d.ts +1 -0
  288. package/shared/dist/runtimeVersions.d.ts +1 -0
  289. package/shared/dist/runtimeVersions.js +14 -0
  290. package/shared/src/clusterCoordination.ts +7 -1
  291. package/shared/src/protocol/chat.ts +1 -0
  292. package/shared/src/protocol/clientMessages.ts +5 -0
  293. package/shared/src/protocol/clusters.ts +20 -6
  294. package/shared/src/protocol/index.ts +1 -0
  295. package/shared/src/protocol/models.ts +31 -5
  296. package/shared/src/protocol/serverMessages.ts +13 -0
  297. package/shared/src/protocol/settings.ts +2 -3
  298. package/shared/src/protocol/tasks.ts +4 -7
  299. package/shared/src/protocol/transcriptWorker.ts +49 -0
  300. package/shared/src/protocol/workflows.ts +4 -0
  301. package/shared/src/runtimeVersions.ts +14 -0
@@ -20,7 +20,7 @@
20
20
  // a segment, or that a checked segment holds.
21
21
 
22
22
  import { promises as fs, createReadStream, closeSync, fstatSync, openSync, readFileSync, readSync, readdirSync, statSync, constants as fsConstants } from 'node:fs';
23
- import { createInterface } from 'node:readline';
23
+ import { jsonlLines } from './jsonlLines.js';
24
24
  import { brotliCompress, brotliDecompress, brotliDecompressSync, createBrotliDecompress, constants as zc } from 'node:zlib';
25
25
  import { promisify } from 'node:util';
26
26
  import { randomUUID } from 'node:crypto';
@@ -225,7 +225,7 @@ async function firstLiveSeq(file: string): Promise<number | null> {
225
225
  const fh = await openLive(file);
226
226
  if (!fh) return null;
227
227
  try {
228
- for await (const line of handleLines(fh)) { const seq = lineSeq(line); if (seq !== null) return seq; }
228
+ for await (const line of handleLines(fh, file)) { const seq = lineSeq(line); if (seq !== null) return seq; }
229
229
  return null;
230
230
  } finally { await fh.close(); }
231
231
  }
@@ -241,18 +241,17 @@ function reportUnreadable(err: unknown): void {
241
241
  }
242
242
 
243
243
  async function* segmentLines(seg: Segment): AsyncGenerator<string> {
244
- const input = createReadStream(seg.file);
244
+ const input = createReadStream(seg.file, { highWaterMark: 64 * 1024 });
245
245
  const decompressed = createBrotliDecompress();
246
246
  // An error opening or reading the file (a segment removed or replaced since
247
247
  // it was listed) reaches the reader below instead of going unhandled.
248
248
  input.on('error', (err) => decompressed.destroy(err));
249
- const rl = createInterface({ input: input.pipe(decompressed), crlfDelay: Infinity });
250
249
  try {
251
- for await (const line of rl) if (line) yield line;
250
+ for await (const line of jsonlLines(input.pipe(decompressed), seg.file)) if (line) yield line;
252
251
  } catch (err) {
253
252
  throw new SegmentReadError(seg.file, err);
254
253
  } finally {
255
- rl.close(); input.destroy();
254
+ input.destroy(); decompressed.destroy();
256
255
  }
257
256
  }
258
257
 
@@ -261,17 +260,16 @@ async function openLive(file: string): Promise<FileHandle | null> {
261
260
  catch (err) { if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null; throw err; }
262
261
  }
263
262
 
264
- async function* handleLines(fh: FileHandle): AsyncGenerator<string> {
265
- const input = fh.createReadStream({ autoClose: false });
266
- const rl = createInterface({ input, crlfDelay: Infinity });
267
- try { for await (const line of rl) if (line) yield line; }
268
- finally { rl.close(); input.destroy(); }
263
+ async function* handleLines(fh: FileHandle, source: string): AsyncGenerator<string> {
264
+ const input = fh.createReadStream({ autoClose: false, highWaterMark: 64 * 1024 });
265
+ try { for await (const line of jsonlLines(input, source)) if (line) yield line; }
266
+ finally { input.destroy(); }
269
267
  }
270
268
 
271
269
  async function* liveLines(file: string): AsyncGenerator<string> {
272
270
  const fh = await openLive(file);
273
271
  if (!fh) return;
274
- try { yield* handleLines(fh); } finally { await fh.close(); }
272
+ try { yield* handleLines(fh, file); } finally { await fh.close(); }
275
273
  }
276
274
 
277
275
  // Every record line in sequence order: sealed segments, then the live file.
@@ -319,7 +317,7 @@ export async function* readLogLines(dir: string, opts: { fromSeq?: number } = {}
319
317
  try {
320
318
  yield* drainSegments();
321
319
  if (!fh) return;
322
- for await (const line of handleLines(fh)) if (!copies.drop(line)) yield line;
320
+ for await (const line of handleLines(fh, path.join(dir, LIVE_LOG))) if (!copies.drop(line)) yield line;
323
321
  } finally { await fh?.close(); }
324
322
  }
325
323
 
@@ -331,6 +329,68 @@ export async function readLogText(dir: string): Promise<string> {
331
329
  return parts.length ? parts.join('\n') + '\n' : '';
332
330
  }
333
331
 
332
+ // Byte offsets retain the old resume reader's accounting: raw file bytes for
333
+ // a plain log, or the newline-normalized, overlap-filtered readLogText bytes
334
+ // when segments exist. Ranges stream without concatenating the whole log.
335
+ export interface LogByteSource {
336
+ size: number;
337
+ chunks(start: number, length: number): AsyncGenerator<Buffer>;
338
+ read(start: number, length: number): Promise<string>;
339
+ close(): Promise<void>;
340
+ }
341
+ export async function openLogByteSource(dir: string): Promise<LogByteSource | null> {
342
+ let size = 0;
343
+ let chunks: LogByteSource['chunks'];
344
+ let close: LogByteSource['close'] = async () => {};
345
+ if ((await listSegments(dir)).length) {
346
+ for await (const line of readLogLines(dir)) size += Buffer.byteLength(line, 'utf8') + 1;
347
+ chunks = async function* (start, length) {
348
+ const end = Math.min(size, start + length);
349
+ let position = 0;
350
+ for await (const line of readLogLines(dir)) {
351
+ const next = position + Buffer.byteLength(line, 'utf8') + 1;
352
+ if (next > start && position < end) {
353
+ const buffer = Buffer.from(line + '\n', 'utf8');
354
+ const from = Math.max(0, start - position), through = Math.min(buffer.length, end - position);
355
+ for (let offset = from; offset < through; offset += 64 * 1024) {
356
+ yield buffer.subarray(offset, Math.min(through, offset + 64 * 1024));
357
+ }
358
+ }
359
+ position = next;
360
+ if (position >= end) break;
361
+ }
362
+ };
363
+ } else {
364
+ const file = path.join(dir, LIVE_LOG);
365
+ const fh = await openLive(file);
366
+ if (!fh) return null;
367
+ try {
368
+ const stat = await fh.stat();
369
+ if (!stat.isFile()) throw new Error(`Expected a history file at ${file}`);
370
+ size = stat.size;
371
+ } catch (err) {
372
+ await fh.close();
373
+ throw err;
374
+ }
375
+ close = () => fh.close();
376
+ chunks = async function* (start, length) {
377
+ const end = Math.min(size, start + length);
378
+ for (let position = start; position < end;) {
379
+ const buffer = Buffer.alloc(Math.min(64 * 1024, end - position));
380
+ const { bytesRead } = await fh.read(buffer, 0, buffer.length, position);
381
+ if (!bytesRead) break;
382
+ position += bytesRead;
383
+ yield buffer.subarray(0, bytesRead);
384
+ }
385
+ };
386
+ }
387
+ return { size, chunks, close, read: async (start, length) => {
388
+ const parts: Buffer[] = [];
389
+ for await (const chunk of chunks(start, length)) parts.push(chunk);
390
+ return Buffer.concat(parts).toString('utf8');
391
+ } };
392
+ }
393
+
334
394
  function decompressSegmentSync(seg: Segment): string {
335
395
  try { return brotliDecompressSync(readFileSync(seg.file)).toString('utf8'); }
336
396
  catch (err) { throw new SegmentReadError(seg.file, err); }
@@ -1,6 +1,8 @@
1
1
  import { scanBeforeDeadline } from './scanDeadline.js';
2
2
  import { projectFiles, scanBudget, exhausted, type ScanBudget } from './projectScan.js';
3
- import { confinedPath } from './fileAccessPolicy.js';
3
+ import { confinedPath, createReadAccessContext } from './fileAccessPolicy.js';
4
+ import { resolveBoundCwd } from './http/writeConfinement.js';
5
+ import { browserWorktreeFile, browserWorktreeRegistry, confirmBrowserWorktree } from './http/browserWorktrees.js';
4
6
  // ARCHIVE (docs/CLIENT.md) - project-DOCUMENT scan. The ARTIFACTS
5
7
  // lens is a project-artifact tool, and the documents an operator most wants to
6
8
  // find live in the PROJECT TREE (e.g. `Codex/Reports/2026-07-10_*.md`, top-level
@@ -9,16 +11,14 @@ import { confinedPath } from './fileAccessPolicy.js';
9
11
  // scan is the other half: readable documents in the real tree, so drilling into
10
12
  // a project shows the docs written FOR it, not just agent workflow spill.
11
13
  //
12
- // Portable pruned walk (no `fd`), $HOME-jailed, depth/count-capped. `.arco` is
14
+ // Portable pruned walk (no `fd`), depth/count-capped. The global scan stays
15
+ // inside HOME; a scoped project can include Git-confirmed siblings. `.arco` is
13
16
  // pruned wholesale here (the artifacts join owns it — merging both client-side
14
17
  // gives the full picture without double-counting).
15
18
 
16
- import { readdir, stat } from 'fs/promises';
17
- import { basename, join, relative } from 'path';
18
- import { readFile } from 'fs/promises';
19
- import { homedir } from 'os';
20
- import { realpathWithinHome } from './explorerArtifacts.js';
21
- import { arcoHome } from './arcoHome.js';
19
+ import { stat } from 'node:fs/promises';
20
+ import { basename, relative } from 'node:path';
21
+ import { readKnownCwds, realpathWithinHome } from './explorerArtifacts.js';
22
22
 
23
23
  export interface DocEntry {
24
24
  path: string;
@@ -27,7 +27,14 @@ export interface DocEntry {
27
27
  mtime: number;
28
28
  project: string;
29
29
  cwd: string; // the owning project root (drill scoping + reveal-in-tree)
30
- rel: string; // path relative to the project root (shows the subdir)
30
+ rel: string; // path relative to its checkout (shows the subdir)
31
+ branch?: string;
32
+ }
33
+
34
+ interface DocsPage {
35
+ entries: DocEntry[];
36
+ partial: boolean;
37
+ projects?: Array<{ cwd: string; project: string }>;
31
38
  }
32
39
 
33
40
  const PRUNE_DIRS = new Set([
@@ -44,8 +51,28 @@ function isDoc(name: string): boolean {
44
51
  return DOC_EXT.has(ext);
45
52
  }
46
53
 
54
+ async function scanDocuments(root: string, owner: string, budget: ScanBudget, out: DocEntry[],
55
+ authorize: (file: string) => string | Promise<string>, branch?: string): Promise<void> {
56
+ for await (const file of projectFiles(root, { budget, skip: PRUNE_DIRS, hidden: true, maxDepth: MAX_DEPTH })) {
57
+ if (!isDoc(file.name)) continue;
58
+ try {
59
+ const authorized = await scanBeforeDeadline(Promise.resolve(authorize(file.path)), budget);
60
+ if (!authorized) break;
61
+ const st = await scanBeforeDeadline(stat(authorized), budget);
62
+ if (!st) break;
63
+ out.push({ path: file.path, name: file.name, size: st.size, mtime: st.mtimeMs, project: basename(owner), cwd: owner,
64
+ rel: relative(root, file.path), ...(branch ? { branch } : {}) });
65
+ } catch { /* unreadable or outside the project */ }
66
+ }
67
+ }
68
+
69
+ function finishPage(out: DocEntry[], limit: number, budget: ScanBudget): DocsPage {
70
+ out.sort((a, b) => b.mtime - a.mtime);
71
+ return { entries: out.slice(0, limit), partial: budget.partial || out.length > limit };
72
+ }
73
+
47
74
  // Walk one project tree for document files, newest-first, capped.
48
- export async function collectProjectDocsPage(project: string, limit = 1000, global?: ScanBudget): Promise<{ entries: DocEntry[]; partial: boolean }> {
75
+ export async function collectProjectDocsPage(project: string, limit = 1000, global?: ScanBudget): Promise<DocsPage> {
49
76
  const budget = scanBudget();
50
77
  if (global) budget.deadline = Math.min(budget.deadline, global.deadline);
51
78
  const root = await scanBeforeDeadline(realpathWithinHome(project), budget);
@@ -53,54 +80,68 @@ export async function collectProjectDocsPage(project: string, limit = 1000, glob
53
80
  if (global) budget.entries = Math.min(budget.entries, global.entries);
54
81
  const starting = budget.entries;
55
82
  const out: DocEntry[] = [];
56
- for await (const file of projectFiles(root, { budget, skip: PRUNE_DIRS, hidden: true, maxDepth: MAX_DEPTH })) {
57
- if (!isDoc(file.name)) continue;
58
- try {
59
- confinedPath(file.path, [root], 'file');
60
- const st = await scanBeforeDeadline(stat(file.path), budget);
61
- if (!st) break;
62
- out.push({ path: file.path, name: file.name, size: st.size, mtime: st.mtimeMs, project: basename(root), cwd: root, rel: relative(root, file.path) });
63
- } catch { /* unreadable or outside the project */ }
64
- }
83
+ await scanDocuments(root, root, budget, out, file => confinedPath(file, [root], 'file'));
65
84
  if (global) global.entries -= starting - budget.entries;
66
- out.sort((a, b) => b.mtime - a.mtime);
67
- return { entries: out.slice(0, limit), partial: budget.partial || out.length > limit };
85
+ return finishPage(out, limit, budget);
68
86
  }
87
+
69
88
  export async function collectProjectDocs(project: string, limit = 1000): Promise<DocEntry[]> {
70
89
  return (await collectProjectDocsPage(project, limit)).entries;
71
90
  }
72
91
 
73
- const KNOWN_CWDS = join(arcoHome(), 'known-cwds.json');
92
+ async function collectScopedDocs(project: string): Promise<DocsPage> {
93
+ const budget = scanBudget();
94
+ const out: DocEntry[] = [];
95
+ const root = await scanBeforeDeadline(realpathWithinHome(project), budget);
96
+ if (root) await scanDocuments(root, root, budget, out, file => confinedPath(file, [root], 'file'));
97
+ if (exhausted(budget)) return finishPage(out, 1000, budget);
74
98
 
75
- async function readKnownCwds(): Promise<string[]> {
76
- try {
77
- const raw = await readFile(KNOWN_CWDS, 'utf8');
78
- const parsed = JSON.parse(raw);
79
- if (!Array.isArray(parsed)) return [];
80
- return parsed.filter((x): x is string => typeof x === 'string' && x.length > 0);
81
- } catch {
82
- return [];
99
+ const bound = await scanBeforeDeadline(resolveBoundCwd(project, undefined), budget);
100
+ if (!bound?.ok) return finishPage(out, 1000, budget);
101
+ const access = await scanBeforeDeadline(createReadAccessContext(), budget);
102
+ if (!access) return finishPage(out, 1000, budget);
103
+ const owner = root ?? await scanBeforeDeadline(access.safeDirectory(bound.cwd), budget);
104
+ if (!owner) return finishPage(out, 1000, budget);
105
+ const signal = AbortSignal.timeout(Math.max(1, Math.ceil(budget.deadline - performance.now())));
106
+ const registry = await scanBeforeDeadline(browserWorktreeRegistry(owner, signal), budget);
107
+ if (!registry) {
108
+ if (signal.aborted) budget.partial = true;
109
+ return finishPage(out, 1000, budget);
110
+ }
111
+ for (const entry of registry.entries) {
112
+ if (exhausted(budget)) break;
113
+ const tree = await scanBeforeDeadline(confirmBrowserWorktree(registry, entry, access, signal), budget);
114
+ if (!tree) continue;
115
+ await scanDocuments(tree.canonical, owner, budget, out, file => browserWorktreeFile(file, tree, access), tree.branch);
83
116
  }
117
+ if (signal.aborted) budget.partial = true;
118
+ return finishPage(out, 1000, budget);
84
119
  }
85
120
 
86
121
  // Global doc scan across known projects, bounded per-project so a home load over
87
122
  // dozens of projects stays responsive. `project` scopes to one (full limit).
88
- export async function collectDocsPage(opts: { project?: string } = {}): Promise<{ entries: DocEntry[]; partial: boolean }> {
89
- if (opts.project) return collectProjectDocsPage(opts.project);
123
+ export async function collectDocsPage(opts: { project?: string } = {}): Promise<DocsPage> {
124
+ if (opts.project) return collectScopedDocs(opts.project);
90
125
  const global = scanBudget(50_000, 650);
91
126
  const known = await scanBeforeDeadline(readKnownCwds(), global);
92
127
  if (!known) return { entries: [], partial: true };
93
128
  const cwds = [...new Set(known)];
94
129
  const all: DocEntry[] = [];
130
+ const projects = new Map<string, { cwd: string; project: string }>();
131
+ const access = await scanBeforeDeadline(createReadAccessContext(), global);
132
+ if (!access) return { entries: [], partial: true };
95
133
  let partial = false;
96
134
  for (const cwd of cwds) {
97
135
  if (exhausted(global)) { partial = true; break; }
98
- const page = await collectProjectDocsPage(cwd, 150, global).catch(() => ({ entries: [], partial: true }));
136
+ const root = await scanBeforeDeadline(access.safeDirectory(cwd).catch(() => null), global);
137
+ if (!root) continue;
138
+ projects.set(root, { cwd: root, project: basename(root) });
139
+ const page = await collectProjectDocsPage(root, 150, global).catch(() => ({ entries: [], partial: true }));
99
140
  all.push(...page.entries);
100
141
  partial ||= page.partial;
101
142
  }
102
143
  all.sort((a, b) => b.mtime - a.mtime);
103
- return { entries: all.slice(0, 600), partial: partial || all.length > 600 };
144
+ return { entries: all.slice(0, 600), partial: partial || global.partial || all.length > 600, projects: [...projects.values()] };
104
145
  }
105
146
  export async function collectDocs(opts: { project?: string } = {}): Promise<DocEntry[]> {
106
147
  return (await collectDocsPage(opts)).entries;
@@ -0,0 +1,2 @@
1
+ // Shared byte budget for recent replacement history and Native resume digests.
2
+ export const RECENT_HISTORY_MAX_BYTES = 128 * 1024;
@@ -0,0 +1,49 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+ import { writeFile } from 'node:fs/promises';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { basename, extname, join } from 'node:path';
5
+ import { shrinkUploadedImage } from '../uploadImages.js';
6
+ import { queueModelImage } from '../providers/attachments.js';
7
+ import { UPLOADS_DIR, UPLOAD_IMAGE_EXT } from '../server/constants.js';
8
+ import { ensureStorageRoot } from '../storageRoot.js';
9
+
10
+ export interface StoredAttachment {
11
+ fileId: string;
12
+ filename: string;
13
+ path: string;
14
+ }
15
+
16
+ export class UploadTooLarge extends Error {}
17
+
18
+ export async function readAttachmentBody(req: IncomingMessage, limit?: number): Promise<Buffer> {
19
+ const chunks: Buffer[] = [];
20
+ let size = 0;
21
+ for await (const chunk of req.iterator({ destroyOnReturn: false })) {
22
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
23
+ size += bytes.length;
24
+ if (limit !== undefined && size > limit) throw new UploadTooLarge();
25
+ chunks.push(bytes);
26
+ }
27
+ return Buffer.concat(chunks, size);
28
+ }
29
+
30
+ export async function storeAttachment(
31
+ body: Buffer,
32
+ rawFilename: string,
33
+ contentType: string,
34
+ reservation?: { fileId: string; beforeWrite: (file: StoredAttachment) => Promise<void> },
35
+ ): Promise<StoredAttachment> {
36
+ const inferredExt = !extname(rawFilename) ? UPLOAD_IMAGE_EXT[contentType] : undefined;
37
+ const filename = basename(rawFilename) + (inferredExt ?? '');
38
+ const fileId = reservation?.fileId ?? randomUUID().slice(0, 8);
39
+ const root = await ensureStorageRoot(UPLOADS_DIR);
40
+ const path = join(root, `${fileId}-${filename}`);
41
+ const stored = { fileId, filename, path };
42
+ await reservation?.beforeWrite(stored);
43
+ await writeFile(path, body, { flag: 'wx', mode: 0o600 });
44
+ if (!reservation) console.log(`[arco] File uploaded: ${filename} -> ${path}`);
45
+ // Finish any replacement before publishing the stable path.
46
+ await shrinkUploadedImage(path);
47
+ queueModelImage(path);
48
+ return stored;
49
+ }
@@ -0,0 +1,124 @@
1
+ // A read grant for a single Git-confirmed checkout. This does not register the
2
+ // checkout with the global project roots or use the managed-task write grant.
3
+ import { realpath } from 'node:fs';
4
+ import { lstat } from 'node:fs/promises';
5
+ import { homedir } from 'node:os';
6
+ import path from 'node:path';
7
+ import { promisify } from 'node:util';
8
+ import { FileAccessError, isPathWithin, type ReadAccessContext } from '../fileAccessPolicy.js';
9
+ import { gitOutput } from './projectBinding.js';
10
+
11
+ const nativePath = promisify(realpath.native);
12
+ const samePath = (a: string, b: string) => path.relative(a, b) === '';
13
+
14
+ interface RegisteredWorktree {
15
+ directory: string;
16
+ branch: string;
17
+ }
18
+
19
+ interface WorktreeRegistry {
20
+ checkout: string;
21
+ common: string;
22
+ entries: RegisteredWorktree[];
23
+ }
24
+
25
+ interface BrowserWorktree {
26
+ directory: string;
27
+ canonical: string;
28
+ native: string;
29
+ branch: string;
30
+ device: number;
31
+ inode: number;
32
+ }
33
+
34
+ function refuseArcoState(target: string): void {
35
+ if (path.resolve(target).split(path.sep).some(part => part.toLowerCase() === '.arco')) throw new FileAccessError();
36
+ }
37
+
38
+ async function gitDirectory(cwd: string, arg: string, signal?: AbortSignal): Promise<string> {
39
+ const stdout = await gitOutput(cwd, ['rev-parse', '--path-format=absolute', arg], signal);
40
+ return nativePath(stdout.replace(process.platform === 'win32' ? /\r?\n$/ : /\n$/, ''));
41
+ }
42
+
43
+ export async function browserWorktreeRegistry(boundCwd: string, signal?: AbortSignal): Promise<WorktreeRegistry | null> {
44
+ try {
45
+ const output = await gitOutput(boundCwd, ['worktree', 'list', '--porcelain', '-z'], signal);
46
+ const entries = output.split('\0\0').flatMap(record => {
47
+ const [worktree, ...fields] = record.split('\0');
48
+ if (!worktree.startsWith('worktree ') || fields.some(field => /^(bare|prunable)( |$)/.test(field))) return [];
49
+ const directory = path.normalize(worktree.slice('worktree '.length));
50
+ const branch = fields.find(field => field.startsWith('branch refs/heads/'))?.slice('branch refs/heads/'.length);
51
+ const head = fields.find(field => /^HEAD [0-9a-f]{7,64}$/.test(field))?.slice(5, 12);
52
+ return path.isAbsolute(directory) && (branch || head)
53
+ ? [{ directory, branch: branch || ('Detached HEAD ' + head) }] : [];
54
+ });
55
+ if (entries.length < 2) return null;
56
+ const [checkout, common] = await Promise.all([
57
+ gitDirectory(boundCwd, '--show-toplevel', signal),
58
+ gitDirectory(boundCwd, '--git-common-dir', signal),
59
+ ]);
60
+ return { checkout, common, entries: entries.filter(entry => !samePath(entry.directory, checkout)) };
61
+ } catch { return null; }
62
+ }
63
+
64
+ export async function confirmBrowserWorktree(registry: WorktreeRegistry, entry: RegisteredWorktree, access: ReadAccessContext, signal?: AbortSignal): Promise<BrowserWorktree | null> {
65
+ try {
66
+ refuseArcoState(entry.directory);
67
+ const root = await lstat(entry.directory);
68
+ if (!root.isDirectory()) return null;
69
+ const canonical = await access.safeDirectory(entry.directory);
70
+ refuseArcoState(canonical);
71
+ const real = await nativePath(canonical);
72
+ access.assertSafePath(real);
73
+ const home = await nativePath(homedir()).catch(() => homedir());
74
+ if (samePath(real, registry.checkout) || samePath(real, path.parse(real).root) || isPathWithin(real, home)) return null;
75
+ const [top, common] = await Promise.all([
76
+ gitDirectory(real, '--show-toplevel', signal),
77
+ gitDirectory(real, '--git-common-dir', signal),
78
+ ]);
79
+ if (!samePath(real, top) || !samePath(common, registry.common)) return null;
80
+ return { ...entry, canonical, native: real, device: root.dev, inode: root.ino };
81
+ } catch { return null; }
82
+ }
83
+
84
+ export async function browserWorktreeFile(target: string, tree: BrowserWorktree, access: ReadAccessContext): Promise<string> {
85
+ refuseArcoState(target);
86
+ if (!isPathWithin(tree.directory, target) && !isPathWithin(tree.canonical, target)) throw new FileAccessError();
87
+ const { real } = await access.inspect(target, undefined, 'file');
88
+ // Git for Windows and Node may spell the same directory differently when
89
+ // a parent has an 8.3 name. Compare both resolved paths in native spelling.
90
+ const expanded = await nativePath(real);
91
+ access.assertSafePath(expanded);
92
+ refuseArcoState(real);
93
+ refuseArcoState(expanded);
94
+ if (!isPathWithin(tree.native, expanded)) throw new FileAccessError();
95
+ const root = await lstat(tree.directory);
96
+ if (!root.isDirectory() || root.dev !== tree.device || root.ino !== tree.inode) throw new FileAccessError();
97
+ return real;
98
+ }
99
+
100
+ export async function resolveWorktreeFile(target: string, boundCwd: string, access: ReadAccessContext): Promise<string> {
101
+ const registry = await browserWorktreeRegistry(boundCwd);
102
+ if (!registry) throw new FileAccessError();
103
+ let alias: string | undefined;
104
+ let entry = registry.entries.filter(candidate => isPathWithin(candidate.directory, target))
105
+ .sort((a, b) => b.directory.length - a.directory.length)[0];
106
+ if (!entry) {
107
+ // Parent aliases occur on macOS and Windows. Match the root's expanded
108
+ // spelling but keep the request's spelling for read confinement below.
109
+ const spellings = await Promise.all(registry.entries.map(async candidate => ({
110
+ candidate,
111
+ real: await nativePath(candidate.directory).catch(() => null),
112
+ })));
113
+ for (let dir = path.dirname(target); dir !== path.dirname(dir); dir = path.dirname(dir)) {
114
+ const stat = await lstat(dir).catch(() => null);
115
+ if (!stat?.isDirectory()) continue;
116
+ const real = await nativePath(dir);
117
+ const registered = spellings.find(candidate => candidate.real && samePath(candidate.real, real))?.candidate;
118
+ if (registered) { entry = registered; alias = dir; break; }
119
+ }
120
+ }
121
+ const verified = entry && await confirmBrowserWorktree(registry, entry, access);
122
+ if (!verified) throw new FileAccessError();
123
+ return browserWorktreeFile(target, alias ? { ...verified, directory: alias } : verified, access);
124
+ }
@@ -0,0 +1,118 @@
1
+ import { lstatSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
2
+ import { basename, join } from 'node:path';
3
+ import { arcoHome } from '../arcoHome.js';
4
+ import { UPLOADS_DIR, UUID_PATTERN } from '../server/constants.js';
5
+ import { ensureStorageRoot } from '../storageRoot.js';
6
+ import type { StoredAttachment } from './attachmentUpload.js';
7
+
8
+ export const PHONE_DRAFT_TTL_MS = 30 * 60_000;
9
+ const ROOT_NAME = '.phone-upload-drafts';
10
+
11
+ export interface PhoneDraft extends StoredAttachment {
12
+ workflowId: string;
13
+ owner: string;
14
+ expiresAt: number;
15
+ }
16
+
17
+ function recordsDirectory(): string {
18
+ return join(arcoHome(), ROOT_NAME);
19
+ }
20
+
21
+ function recordPath(fileId: string): string {
22
+ if (!UUID_PATTERN.test(fileId)) throw new Error('Invalid phone upload ID');
23
+ return join(recordsDirectory(), fileId + '.json');
24
+ }
25
+
26
+ function safeName(filename: unknown): filename is string {
27
+ return typeof filename === 'string' && /^[\p{L}\p{N}_()-][\p{L}\p{N} ._()-]{0,119}$/u.test(filename);
28
+ }
29
+
30
+ export function phoneFilename(name: string): string {
31
+ const cleaned = name.normalize('NFC').replace(/[^\p{L}\p{N} ._()-]/gu, '_').replace(/^[. ]+|[. ]+$/g, '');
32
+ // A Windows file system also observes the extension after Unicode sanitizing.
33
+ return safeName(cleaned) ? cleaned : '';
34
+ }
35
+
36
+ function readRecord(id: string): PhoneDraft | null {
37
+ try {
38
+ const directory = lstatSync(recordsDirectory());
39
+ if (!directory.isDirectory() || directory.isSymbolicLink()) return null;
40
+ const target = recordPath(id);
41
+ const stat = lstatSync(target);
42
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 4096) return null;
43
+ const entry = JSON.parse(readFileSync(target, 'utf8')) as Partial<PhoneDraft>;
44
+ if (entry.fileId !== id || !safeName(entry.filename) || typeof entry.path !== 'string'
45
+ || basename(entry.path) !== `${id}-${entry.filename}` || typeof entry.owner !== 'string'
46
+ || typeof entry.workflowId !== 'string' || typeof entry.expiresAt !== 'number'
47
+ || !Number.isSafeInteger(entry.expiresAt)) return null;
48
+ return entry as PhoneDraft;
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
53
+
54
+ export async function rememberPhoneDraft(entry: PhoneDraft): Promise<void> {
55
+ const directory = await ensureStorageRoot(recordsDirectory());
56
+ writeFileSync(join(directory, entry.fileId + '.json'), JSON.stringify(entry), { flag: 'wx', mode: 0o600 });
57
+ }
58
+
59
+ export function phoneDraftForOwner(id: string, owner: string): PhoneDraft | null {
60
+ const entry = readRecord(id);
61
+ return entry && entry.owner === owner && entry.expiresAt > Date.now() ? entry : null;
62
+ }
63
+
64
+ export async function discardPhoneDraft(entry: PhoneDraft): Promise<void> {
65
+ const directory = await ensureStorageRoot(UPLOADS_DIR, false);
66
+ // Send may take ownership while the directory check is in flight.
67
+ if (readRecord(entry.fileId)?.path !== entry.path) return;
68
+ const path = join(directory, `${entry.fileId}-${entry.filename}`);
69
+ // Delete only a filename generated for this phone receipt, never a path
70
+ // supplied by the phone or stored in the receipt.
71
+ for (const name of [path, path + '.model.png', path + '.model.jpg']) {
72
+ try { unlinkSync(name); }
73
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
74
+ }
75
+ forgetRecord(entry.fileId);
76
+ }
77
+
78
+ function forgetRecord(fileId: string): void {
79
+ try { unlinkSync(recordPath(fileId)); }
80
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
81
+ }
82
+
83
+ // Called only at the send acceptance points. Removing the cleanup receipt
84
+ // before queuing or starting the turn keeps sent attachments in history.
85
+ export function adoptPhoneDrafts(workflowId: string, attachments: readonly string[] | undefined): boolean {
86
+ const entries: PhoneDraft[] = [];
87
+ for (const path of attachments ?? []) {
88
+ const id = basename(path).slice(0, 36);
89
+ if (!UUID_PATTERN.test(id)) continue;
90
+ const entry = readRecord(id);
91
+ if (!entry) continue;
92
+ if (entry.workflowId !== workflowId || entry.path !== path || entry.expiresAt <= Date.now()) return false;
93
+ entries.push(entry);
94
+ }
95
+ for (const entry of entries) forgetRecord(entry.fileId);
96
+ return true;
97
+ }
98
+
99
+ let sweeping = false;
100
+ export async function sweepPhoneDrafts(): Promise<void> {
101
+ if (sweeping) return;
102
+ sweeping = true;
103
+ try {
104
+ const directory = lstatSync(recordsDirectory());
105
+ if (!directory.isDirectory() || directory.isSymbolicLink()) return;
106
+ for (const file of readdirSync(recordsDirectory())) {
107
+ if (!file.endsWith('.json')) continue;
108
+ const entry = readRecord(file.slice(0, -5));
109
+ if (entry && entry.expiresAt <= Date.now()) await discardPhoneDraft(entry).catch(() => {});
110
+ }
111
+ } catch {
112
+ // No phone uploads yet, or managed storage is unavailable.
113
+ } finally {
114
+ sweeping = false;
115
+ }
116
+ }
117
+
118
+ setInterval(() => { void sweepPhoneDrafts(); }, 30_000).unref();