@qlairoslabs/acp-client 0.13.0-alpha.1 → 0.13.2-alpha.1

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 (343) hide show
  1. package/CONSUMER_GUIDE.md +181 -8
  2. package/MIGRATION-0.12-to-0.13.md +20 -7
  3. package/package.json +13 -2
  4. package/src/agent/config.ts +2 -0
  5. package/src/agent/conversation-manager.ts +1 -0
  6. package/src/agent/native-operations.ts +40 -0
  7. package/src/agent-session-config.ts +2 -0
  8. package/src/agent-session.ts +12 -2
  9. package/src/agent.ts +100 -2
  10. package/src/client.ts +5 -3
  11. package/src/controller-connection.ts +1 -0
  12. package/src/controller.ts +2 -0
  13. package/src/index.ts +3 -0
  14. package/src/launcher.ts +2 -0
  15. package/src/native/approvals.ts +20 -3
  16. package/src/native/capabilities.ts +2 -2
  17. package/src/native/connection.ts +1 -1
  18. package/src/native/controller.ts +5 -3
  19. package/src/native/host-config.ts +2 -0
  20. package/src/native/host.ts +83 -4
  21. package/src/native/mcp.ts +47 -0
  22. package/src/native/recovery.ts +8 -7
  23. package/src/native/reminders/routine-guard.ts +4 -3
  24. package/src/native/reminders/routine-wire.ts +1 -1
  25. package/src/native-harness/README.md +58 -1
  26. package/src/native-harness/package.json +4 -0
  27. package/src/native-harness/scripts/build-routine-zones.py +47 -0
  28. package/src/native-harness/src/capabilities/attachments/admission.ts +42 -0
  29. package/src/native-harness/src/capabilities/attachments/image-validation.ts +98 -0
  30. package/src/native-harness/src/capabilities/attachments/input.ts +1 -0
  31. package/src/native-harness/src/capabilities/attachments/read.ts +76 -0
  32. package/src/native-harness/src/capabilities/attachments/recovery.ts +26 -0
  33. package/src/native-harness/src/capabilities/attachments/selection.ts +37 -0
  34. package/src/native-harness/src/capabilities/attachments/service.ts +75 -0
  35. package/src/native-harness/src/capabilities/attachments/upload.ts +164 -0
  36. package/src/native-harness/src/capabilities/attachments/vision.ts +45 -0
  37. package/src/native-harness/src/capabilities/context/build.ts +5 -0
  38. package/src/native-harness/src/capabilities/context/session.ts +2 -1
  39. package/src/native-harness/src/capabilities/model/openrouter-stream.ts +80 -17
  40. package/src/native-harness/src/capabilities/model/runner.ts +6 -3
  41. package/src/native-harness/src/capabilities/reminders/cron-calendar.ts +50 -0
  42. package/src/native-harness/src/capabilities/reminders/cron-fields.ts +46 -0
  43. package/src/native-harness/src/capabilities/reminders/cron-proof.ts +32 -0
  44. package/src/native-harness/src/capabilities/reminders/cron-zone.ts +53 -0
  45. package/src/native-harness/src/capabilities/reminders/iana-zones.json.gz +0 -0
  46. package/src/native-harness/src/capabilities/reminders/iana-zones.ts +34 -0
  47. package/src/native-harness/src/capabilities/reminders/interval.ts +30 -0
  48. package/src/native-harness/src/capabilities/reminders/routine-advance.ts +47 -0
  49. package/src/native-harness/src/capabilities/reminders/routine-backlog.ts +47 -0
  50. package/src/native-harness/src/capabilities/reminders/routine-expiry.ts +15 -0
  51. package/src/native-harness/src/capabilities/reminders/routine-occurrence.ts +65 -0
  52. package/src/native-harness/src/capabilities/reminders/routine-schedule.ts +70 -0
  53. package/src/native-harness/src/capabilities/reminders/unattended.ts +8 -0
  54. package/src/native-harness/src/capabilities/tools/mcp/client.ts +97 -0
  55. package/src/native-harness/src/capabilities/tools/mcp/http.ts +183 -0
  56. package/src/native-harness/src/capabilities/tools/mcp/registry.ts +62 -0
  57. package/src/native-harness/src/capabilities/tools/mcp/result.ts +33 -0
  58. package/src/native-harness/src/capabilities/tools/mcp/schema.ts +77 -0
  59. package/src/native-harness/src/capabilities/tools/mcp/secrets.ts +28 -0
  60. package/src/native-harness/src/capabilities/tools/mcp/stdio.ts +105 -0
  61. package/src/native-harness/src/capabilities/tools/reminders/index.ts +27 -5
  62. package/src/native-harness/src/capabilities/tools/runtime/invocations.ts +4 -1
  63. package/src/native-harness/src/capabilities/tools/web/config.ts +1 -0
  64. package/src/native-harness/src/capabilities/tools/web/definitions.ts +18 -0
  65. package/src/native-harness/src/capabilities/tools/web/direct-address.ts +56 -0
  66. package/src/native-harness/src/capabilities/tools/web/direct-transport.ts +235 -0
  67. package/src/native-harness/src/capabilities/tools/web/direct.ts +149 -0
  68. package/src/native-harness/src/capabilities/tools/web/exa-transport.ts +41 -0
  69. package/src/native-harness/src/capabilities/tools/web/exa.ts +71 -0
  70. package/src/native-harness/src/capabilities/tools/web/preview.ts +44 -0
  71. package/src/native-harness/src/capabilities/tools/web/registry.ts +47 -0
  72. package/src/native-harness/src/capabilities/tools/web/usage.ts +1 -0
  73. package/src/native-harness/src/contracts/agent.ts +3 -1
  74. package/src/native-harness/src/contracts/attachments.ts +62 -0
  75. package/src/native-harness/src/contracts/config-permissions.ts +14 -3
  76. package/src/native-harness/src/contracts/context.ts +1 -1
  77. package/src/native-harness/src/contracts/events.ts +2 -2
  78. package/src/native-harness/src/contracts/loop.ts +3 -3
  79. package/src/native-harness/src/contracts/mcp.ts +22 -0
  80. package/src/native-harness/src/contracts/model-execution.ts +2 -1
  81. package/src/native-harness/src/contracts/operator-controls.ts +8 -1
  82. package/src/native-harness/src/contracts/protocol.ts +21 -5
  83. package/src/native-harness/src/contracts/reminders.ts +4 -2
  84. package/src/native-harness/src/contracts/routines.ts +20 -0
  85. package/src/native-harness/src/contracts/session-file.ts +2 -0
  86. package/src/native-harness/src/contracts/session.ts +8 -3
  87. package/src/native-harness/src/contracts/storage.ts +32 -13
  88. package/src/native-harness/src/contracts/tools.ts +2 -0
  89. package/src/native-harness/src/contracts/web.ts +16 -0
  90. package/src/native-harness/src/governance/permissions/gate.ts +9 -2
  91. package/src/native-harness/src/governance/policy/resolve.ts +6 -1
  92. package/src/native-harness/src/index.ts +48 -12
  93. package/src/native-harness/src/interfaces/cli/development.ts +108 -53
  94. package/src/native-harness/src/interfaces/cli/serve.ts +2 -2
  95. package/src/native-harness/src/interfaces/cli/start.ts +22 -13
  96. package/src/native-harness/src/interfaces/client.ts +8 -2
  97. package/src/native-harness/src/interfaces/inspector/index.html +7 -1
  98. package/src/native-harness/src/interfaces/inspector/state.ts +6 -2
  99. package/src/native-harness/src/interfaces/protocol/load.ts +3 -1
  100. package/src/native-harness/src/interfaces/protocol/local.ts +13 -4
  101. package/src/native-harness/src/interfaces/protocol/operator.ts +8 -2
  102. package/src/native-harness/src/interfaces/protocol/server.ts +102 -36
  103. package/src/native-harness/src/interfaces/protocol/stdio-client.ts +8 -0
  104. package/src/native-harness/src/interfaces/web-chat/index.html +65 -12
  105. package/src/native-harness/src/interfaces/web-chat/server.ts +30 -3
  106. package/src/native-harness/src/kernel/channels.ts +27 -15
  107. package/src/native-harness/src/kernel/loop.ts +1 -1
  108. package/src/native-harness/src/runtime/config/inference-key.ts +7 -0
  109. package/src/native-harness/src/runtime/config/managed.ts +1 -1
  110. package/src/native-harness/src/runtime/config/paths.ts +8 -1
  111. package/src/native-harness/src/runtime/execution/mcp-stdio.ts +31 -0
  112. package/src/native-harness/src/runtime/reminder-validation.ts +31 -10
  113. package/src/native-harness/src/runtime/reminders.ts +2 -2
  114. package/src/native-harness/src/state/storage/archive.ts +113 -12
  115. package/src/native-harness/src/state/storage/attachment-files.ts +58 -0
  116. package/src/native-harness/src/state/storage/attachment-import.ts +106 -0
  117. package/src/native-harness/src/state/storage/attachment-tables.ts +123 -0
  118. package/src/native-harness/src/state/storage/engine.ts +396 -45
  119. package/src/native-harness/src/state/storage/inference.ts +30 -2
  120. package/src/native-harness/src/state/storage/memory-attachments.ts +56 -0
  121. package/src/native-harness/src/state/storage/memory-reminders.ts +31 -6
  122. package/src/native-harness/src/state/storage/memory.ts +32 -4
  123. package/src/native-harness/src/state/storage/reminder-archive.ts +53 -12
  124. package/src/native-harness/src/state/storage/reminder-change.ts +60 -14
  125. package/src/native-harness/src/state/storage/reminder-tables.ts +11 -3
  126. package/src/native-harness/src/state/storage/routine-row.ts +25 -0
  127. package/src/native-harness/src/state/storage/session-file.ts +22 -9
  128. package/src/native-harness/src/state/storage/sqlite-reminders.ts +48 -8
  129. package/src/native-harness/src/state/storage/sqlite.ts +59 -11
  130. package/src/native-harness/src/state/storage/web-tables.ts +47 -0
  131. package/src/native-harness/src/testing.ts +151 -56
  132. package/src/native-harness/src/util/attachment-input.ts +42 -0
  133. package/src/native-harness/src/util/config.ts +64 -9
  134. package/src/native-harness/src/util/intake.ts +7 -0
  135. package/src/native-harness/src/util/mcp-config.ts +102 -0
  136. package/src/native-harness/src/util/web-config.ts +34 -0
  137. package/src/native-harness/src/util/web-usage.ts +33 -0
  138. package/src/orchestrator/permissions.ts +6 -3
  139. package/src/permissions/conversation.ts +13 -5
  140. package/src/permissions/matcher.ts +2 -0
  141. package/src/permissions/outcome.ts +12 -1
  142. package/src/permissions/policy.ts +13 -8
  143. package/src/steering/combine.ts +1 -0
  144. package/src/steering/contracts.ts +3 -0
  145. package/src/terminals.ts +9 -6
  146. package/src/native/reminders/reminders.test.ts +0 -553
  147. package/src/native/reminders/routine-config.typecheck.ts +0 -13
  148. package/src/native/reminders/wire.typecheck.ts +0 -13
  149. package/src/native-harness/.res/README.md +0 -1
  150. package/src/native-harness/.res/architecture/README.md +0 -21
  151. package/src/native-harness/.res/architecture/context-and-data.md +0 -31
  152. package/src/native-harness/.res/architecture/execution.md +0 -42
  153. package/src/native-harness/.res/architecture/overview.md +0 -44
  154. package/src/native-harness/.res/architecture/persistence.md +0 -56
  155. package/src/native-harness/.res/architecture/suspend-and-resume.md +0 -45
  156. package/src/native-harness/.res/architecture/technical-architecture.md +0 -50
  157. package/src/native-harness/.res/decisions/0001-basic-loop.md +0 -11
  158. package/src/native-harness/.res/decisions/0002-channel-input.md +0 -17
  159. package/src/native-harness/.res/decisions/0003-inference-inspection.md +0 -14
  160. package/src/native-harness/.res/decisions/0004-shared-context.md +0 -21
  161. package/src/native-harness/.res/decisions/0005-notice-inbox.md +0 -20
  162. package/src/native-harness/.res/decisions/0006-explicit-notices.md +0 -12
  163. package/src/native-harness/.res/decisions/0007-channel-output.md +0 -12
  164. package/src/native-harness/.res/decisions/0008-browser-client.md +0 -16
  165. package/src/native-harness/.res/decisions/0009-scripted-model.md +0 -18
  166. package/src/native-harness/.res/decisions/0010-inprocess-protocol.md +0 -19
  167. package/src/native-harness/.res/decisions/0011-stdio-transport.md +0 -21
  168. package/src/native-harness/.res/decisions/0012-session-storage-contract.md +0 -37
  169. package/src/native-harness/.res/decisions/0013-durable-delivery-contract.md +0 -64
  170. package/src/native-harness/.res/decisions/0014-channel-controls-contract.md +0 -73
  171. package/src/native-harness/.res/decisions/0015-session-file-contract.md +0 -72
  172. package/src/native-harness/.res/decisions/0016-configuration-permissions.md +0 -159
  173. package/src/native-harness/.res/decisions/0017-openrouter-managed-config.md +0 -69
  174. package/src/native-harness/.res/decisions/0018-tool-dispatch-evidence.md +0 -78
  175. package/src/native-harness/.res/decisions/0019-model-execution.md +0 -188
  176. package/src/native-harness/.res/decisions/0020-startup-channel-changes.md +0 -71
  177. package/src/native-harness/.res/decisions/0021-tools-and-host-callbacks.md +0 -100
  178. package/src/native-harness/.res/decisions/0022-operator-controls.md +0 -115
  179. package/src/native-harness/.res/decisions/0023-long-running-mock.md +0 -82
  180. package/src/native-harness/.res/decisions/0024-callback-policy-names.md +0 -46
  181. package/src/native-harness/.res/decisions/0025-external-notices.md +0 -364
  182. package/src/native-harness/.res/decisions/0026-bounded-context.md +0 -81
  183. package/src/native-harness/.res/decisions/0027-development-instructions.md +0 -22
  184. package/src/native-harness/.res/decisions/0028-debug-tools.md +0 -16
  185. package/src/native-harness/.res/decisions/0029-bounded-model-call-pages.md +0 -37
  186. package/src/native-harness/.res/decisions/0030-timeline-retrieval.md +0 -145
  187. package/src/native-harness/.res/decisions/0031-one-off-reminders.md +0 -173
  188. package/src/native-harness/.res/docs/11-15.md +0 -148
  189. package/src/native-harness/.res/docs/BUSINESS_RULES.md +0 -111
  190. package/src/native-harness/.res/docs/WORK.md +0 -65
  191. package/src/native-harness/.res/docs/_/11-16-persistence/LOG.md +0 -312
  192. package/src/native-harness/.res/docs/_/11-16-persistence/PLAN.md +0 -77
  193. package/src/native-harness/.res/docs/_/11-16-persistence/SPEC.md +0 -313
  194. package/src/native-harness/.res/docs/_/11-19-channel-controls/LOG.md +0 -160
  195. package/src/native-harness/.res/docs/_/11-19-channel-controls/PLAN.md +0 -89
  196. package/src/native-harness/.res/docs/_/11-19-channel-controls/SPEC.md +0 -135
  197. package/src/native-harness/.res/docs/_/11-19-config-permissions/LOG.md +0 -143
  198. package/src/native-harness/.res/docs/_/11-19-config-permissions/PLAN.md +0 -93
  199. package/src/native-harness/.res/docs/_/11-19-config-permissions/SPEC.md +0 -181
  200. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/11-20-LOG.md +0 -433
  201. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/PLAN.md +0 -60
  202. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/PROTOCOL.md +0 -141
  203. package/src/native-harness/.res/docs/acp-client-integration/0001-DESIGN/SPEC.md +0 -168
  204. package/src/native-harness/.res/docs/attachments/0001-DESIGN/SPEC.md +0 -111
  205. package/src/native-harness/.res/docs/bounded-context/0001-DESIGN/PLAN.md +0 -129
  206. package/src/native-harness/.res/docs/bounded-context/0001-DESIGN/SPEC.md +0 -135
  207. package/src/native-harness/.res/docs/channel-messaging/0001-DESIGN-external-notices/LOG.md +0 -437
  208. package/src/native-harness/.res/docs/channel-messaging/0001-DESIGN-external-notices/PLAN.md +0 -127
  209. package/src/native-harness/.res/docs/channel-messaging/0001-DESIGN-external-notices/SPEC.md +0 -203
  210. package/src/native-harness/.res/docs/long-running-mock/0001-DESIGN/LOG.md +0 -292
  211. package/src/native-harness/.res/docs/long-running-mock/0001-DESIGN/PLAN.md +0 -91
  212. package/src/native-harness/.res/docs/long-running-mock/0001-DESIGN/SPEC.md +0 -187
  213. package/src/native-harness/.res/docs/model-execution/0001-DESIGN/LOG.md +0 -148
  214. package/src/native-harness/.res/docs/model-execution/0001-DESIGN/PLAN.md +0 -95
  215. package/src/native-harness/.res/docs/model-execution/0001-DESIGN/SPEC.md +0 -200
  216. package/src/native-harness/.res/docs/model-execution/0002-AMENDMENT-accounting/SPEC.md +0 -80
  217. package/src/native-harness/.res/docs/operator-controls/0001-DESIGN/LOG.md +0 -206
  218. package/src/native-harness/.res/docs/operator-controls/0001-DESIGN/PLAN.md +0 -106
  219. package/src/native-harness/.res/docs/operator-controls/0001-DESIGN/SPEC.md +0 -297
  220. package/src/native-harness/.res/docs/persistence/0002-AMENDMENT-session-file/LOG.md +0 -41
  221. package/src/native-harness/.res/docs/persistence/0002-AMENDMENT-session-file/PLAN.md +0 -36
  222. package/src/native-harness/.res/docs/persistence/0002-AMENDMENT-session-file/SPEC.md +0 -84
  223. package/src/native-harness/.res/docs/shell-execution/0001-DESIGN/SPEC.md +0 -147
  224. package/src/native-harness/.res/docs/timeline-retrieval/0001-DESIGN/LOG.md +0 -15
  225. package/src/native-harness/.res/docs/timeline-retrieval/0001-DESIGN/PLAN.md +0 -107
  226. package/src/native-harness/.res/docs/timeline-retrieval/0001-DESIGN/SPEC.md +0 -114
  227. package/src/native-harness/.res/docs/todos/11-19-TODO-auto_review-approve.md +0 -24
  228. package/src/native-harness/.res/docs/todos/11-20-TODO-user-entered-tool-code.md +0 -23
  229. package/src/native-harness/.res/docs/todos/11-21-TODO-node-resource-coordination.md +0 -103
  230. package/src/native-harness/.res/docs/todos/11-22-TODO-harness-m1-sequence.md +0 -50
  231. package/src/native-harness/.res/docs/tools-and-callbacks/0001-DESIGN/LOG.md +0 -337
  232. package/src/native-harness/.res/docs/tools-and-callbacks/0001-DESIGN/PLAN.md +0 -76
  233. package/src/native-harness/.res/docs/tools-and-callbacks/0001-DESIGN/SPEC.md +0 -204
  234. package/src/native-harness/.res/docs/tools-and-callbacks/0002-AMENDMENT-callback-policy/LOG.md +0 -73
  235. package/src/native-harness/.res/docs/tools-and-callbacks/0002-AMENDMENT-callback-policy/SPEC.md +0 -64
  236. package/src/native-harness/.res/docs/tools-and-callbacks/0003-DESIGN-attachment-tools/SPEC.md +0 -58
  237. package/src/native-harness/.res/docs/tools-and-callbacks/0004-DESIGN-reminder-tools/LOG.md +0 -45
  238. package/src/native-harness/.res/docs/tools-and-callbacks/0004-DESIGN-reminder-tools/PLAN.md +0 -108
  239. package/src/native-harness/.res/docs/tools-and-callbacks/0004-DESIGN-reminder-tools/SPEC.md +0 -169
  240. package/src/native-harness/.res/docs/web-tools/0001-DESIGN/SPEC.md +0 -128
  241. package/src/native-harness/.res/marketing-draft.md +0 -22
  242. package/src/native-harness/.res/sandbox/1-simple-harness/README.md +0 -285
  243. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-1.md +0 -19
  244. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-10.md +0 -138
  245. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-11.md +0 -148
  246. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-12.md +0 -172
  247. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-13.md +0 -194
  248. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-14.md +0 -233
  249. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-15.md +0 -249
  250. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-16.md +0 -265
  251. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-17.md +0 -279
  252. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-18.md +0 -293
  253. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-19.md +0 -307
  254. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-2.md +0 -29
  255. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-20.md +0 -317
  256. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-21.md +0 -327
  257. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-3.md +0 -40
  258. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-4.md +0 -59
  259. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-5.md +0 -69
  260. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-6.md +0 -79
  261. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-7.md +0 -89
  262. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-8.md +0 -102
  263. package/src/native-harness/.res/sandbox/1-simple-harness/conversation/context-9.md +0 -116
  264. package/src/native-harness/.res/sandbox/1-simple-harness/conversation.jsonl +0 -49
  265. package/src/native-harness/.res/sandbox/1-simple-harness/doc.md +0 -87
  266. package/src/native-harness/.res/sandbox/1-simple-harness/harness.py +0 -289
  267. package/src/native-harness/.res/sandbox/1-simple-harness/local/harness copy 2.py +0 -221
  268. package/src/native-harness/.res/sandbox/1-simple-harness/local/harness copy 3.py +0 -287
  269. package/src/native-harness/.res/sandbox/1-simple-harness/local/harness copy.py +0 -165
  270. package/src/native-harness/.res/sandbox/1-simple-harness/state.json +0 -22
  271. package/src/native-harness/.res/sandbox/1-simple-harness/system-prompt.md +0 -2
  272. package/src/native-harness/AGENTS.md +0 -70
  273. package/src/native-harness/ARCHITECTURE.md +0 -249
  274. package/src/native-harness/bun.lock +0 -26
  275. package/src/native-harness/test/agent.test.ts +0 -130
  276. package/src/native-harness/test/approval-gate.test.ts +0 -255
  277. package/src/native-harness/test/approval-protocol.test.ts +0 -94
  278. package/src/native-harness/test/boundaries.test.ts +0 -18
  279. package/src/native-harness/test/channel-controls.test.ts +0 -322
  280. package/src/native-harness/test/client-abort.test.ts +0 -136
  281. package/src/native-harness/test/config-policy.test.ts +0 -301
  282. package/src/native-harness/test/conformance/storage.ts +0 -1141
  283. package/src/native-harness/test/context.test.ts +0 -177
  284. package/src/native-harness/test/crash.test.ts +0 -187
  285. package/src/native-harness/test/debug-tools.test.ts +0 -67
  286. package/src/native-harness/test/development-cli.test.ts +0 -67
  287. package/src/native-harness/test/development.test.ts +0 -171
  288. package/src/native-harness/test/dispatch-evidence.test.ts +0 -58
  289. package/src/native-harness/test/e2e.test.ts +0 -186
  290. package/src/native-harness/test/external-notices.test.ts +0 -101
  291. package/src/native-harness/test/fixtures/approval-e2e.jsonl +0 -4
  292. package/src/native-harness/test/fixtures/crash-scenario.jsonl +0 -5
  293. package/src/native-harness/test/fixtures/development-lifecycle.jsonl +0 -10
  294. package/src/native-harness/test/fixtures/echo-scenario.jsonl +0 -3
  295. package/src/native-harness/test/fixtures/format2-schema.ts +0 -27
  296. package/src/native-harness/test/fixtures/format3-schema.ts +0 -16
  297. package/src/native-harness/test/fixtures/hold-scenario.jsonl +0 -4
  298. package/src/native-harness/test/fixtures/model-e2e.jsonl +0 -3
  299. package/src/native-harness/test/fixtures/storage-owner.ts +0 -20
  300. package/src/native-harness/test/format-reply.test.ts +0 -10
  301. package/src/native-harness/test/helpers/operator-view.ts +0 -41
  302. package/src/native-harness/test/helpers/scenario.ts +0 -9
  303. package/src/native-harness/test/helpers/session.ts +0 -38
  304. package/src/native-harness/test/helpers/stdio.ts +0 -46
  305. package/src/native-harness/test/inspector.test.ts +0 -77
  306. package/src/native-harness/test/listeners.test.ts +0 -49
  307. package/src/native-harness/test/loop.test.ts +0 -88
  308. package/src/native-harness/test/model-channel-double.test.ts +0 -87
  309. package/src/native-harness/test/model-crash.test.ts +0 -62
  310. package/src/native-harness/test/model-delivery-regressions.test.ts +0 -55
  311. package/src/native-harness/test/model-e2e.test.ts +0 -71
  312. package/src/native-harness/test/model-final-filter.test.ts +0 -30
  313. package/src/native-harness/test/model-large-reply.test.ts +0 -28
  314. package/src/native-harness/test/model-live-queue.test.ts +0 -33
  315. package/src/native-harness/test/model-runner.test.ts +0 -117
  316. package/src/native-harness/test/model-storage.test.ts +0 -99
  317. package/src/native-harness/test/model-stream-adapter.test.ts +0 -26
  318. package/src/native-harness/test/model-stream-public.test.ts +0 -77
  319. package/src/native-harness/test/notices.test.ts +0 -64
  320. package/src/native-harness/test/openrouter-config.test.ts +0 -218
  321. package/src/native-harness/test/operator-controls.test.ts +0 -132
  322. package/src/native-harness/test/output.test.ts +0 -44
  323. package/src/native-harness/test/owner-config.test.ts +0 -64
  324. package/src/native-harness/test/permissions-e2e.test.ts +0 -68
  325. package/src/native-harness/test/persistence.test.ts +0 -236
  326. package/src/native-harness/test/portability.test.ts +0 -337
  327. package/src/native-harness/test/protocol.test.ts +0 -160
  328. package/src/native-harness/test/reminder-clock.test.ts +0 -61
  329. package/src/native-harness/test/reminder-stdio.test.ts +0 -140
  330. package/src/native-harness/test/reminder-storage.test.ts +0 -124
  331. package/src/native-harness/test/scenario-jsonl.test.ts +0 -112
  332. package/src/native-harness/test/scripted.test.ts +0 -92
  333. package/src/native-harness/test/session-file.test.ts +0 -51
  334. package/src/native-harness/test/startup-channel-changes.test.ts +0 -256
  335. package/src/native-harness/test/stdio.test.ts +0 -132
  336. package/src/native-harness/test/storage-memory.test.ts +0 -4
  337. package/src/native-harness/test/storage-sqlite.test.ts +0 -420
  338. package/src/native-harness/test/suspension.test.ts +0 -430
  339. package/src/native-harness/test/timeline-retrieval.test.ts +0 -211
  340. package/src/native-harness/test/tools-catalog.test.ts +0 -468
  341. package/src/native-harness/test/tools-protocol.test.ts +0 -418
  342. package/src/native-harness/test/transfers.test.ts +0 -94
  343. package/src/native-harness/test/web-chat.test.ts +0 -35
@@ -0,0 +1,98 @@
1
+ import { closeSync, constants, fstatSync, openSync, readSync, writeSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { spawn, spawnSync } from "node:child_process";
4
+ import type { AttachmentMetadata } from "../../contracts/attachments.ts";
5
+ import { ATTACHMENT_LIMITS } from "../../contracts/attachments.ts";
6
+ import { UploadError } from "./upload.ts";
7
+
8
+ const formats: Record<string, { demuxer: string; codec: string }> = {
9
+ "image/png": { demuxer: "png_pipe", codec: "png" },
10
+ "image/jpeg": { demuxer: "jpeg_pipe", codec: "mjpeg" },
11
+ "image/webp": { demuxer: "webp_pipe", codec: "webp" },
12
+ };
13
+ const toolEnvironment = () => ({ PATH: process.env.PATH ?? "/usr/bin:/bin", LANG: "C" });
14
+ // Linux O_TMPFILE creates an unnamed inode; bytes never have a persistent path.
15
+ const anonymousFileFlags = constants.O_RDWR | 0o20200000;
16
+ const childLimits = ["--as=1073741824", "--cpu=20", "--nofile=32", "--"] as const;
17
+ const toolOptions = { timeout: 3000, stdio: "ignore" as const, killSignal: "SIGKILL" as const, env: toolEnvironment() };
18
+ /** Availability is per session: do not infer support from a model name. */
19
+ export function imageValidationAvailable(): boolean {
20
+ if (process.platform !== "linux") return false;
21
+ try { const fd = openSync(tmpdir(), anonymousFileFlags, 0o600); closeSync(fd); } catch { return false; }
22
+ return spawnSync("prlimit", [...childLimits, "ffprobe", "-version"], toolOptions).status === 0
23
+ && spawnSync("prlimit", [...childLimits, "ffmpeg", "-version"], toolOptions).status === 0;
24
+ }
25
+
26
+ /** Always wait for close after killing a timed-out, cancelled or overproducing
27
+ * child. Neither command receives a filename or a network-capable protocol. */
28
+ export function runImageTool(command: string, args: readonly string[], input: Uint8Array,
29
+ options: { signal?: AbortSignal; timeoutMs?: number } = {}): Promise<string> {
30
+ return new Promise((resolve, reject) => {
31
+ if (options.signal?.aborted) { reject(new UploadError("invalid_attachment", "Image validation cancelled")); return; }
32
+ // Bun's child stdin pipes can be nonblocking: ffprobe treats EAGAIN as
33
+ // end of input. Give the child a seekable anonymous inode instead, with
34
+ // positional writes leaving its read offset at zero. There is no pathname
35
+ // to leak on crash and no input URL other than pipe:0.
36
+ let fd: number;
37
+ try {
38
+ fd = openSync(tmpdir(), anonymousFileFlags, 0o600);
39
+ try {
40
+ let offset = 0;
41
+ while (offset < input.length) {
42
+ const count = writeSync(fd, input, offset, input.length - offset, offset);
43
+ if (!count) throw new Error("short write");
44
+ offset += count;
45
+ }
46
+ } catch (error) { closeSync(fd); throw error; }
47
+ } catch { reject(new UploadError("invalid_attachment", "Image validator input is unavailable")); return; }
48
+ let child: ReturnType<typeof spawn>;
49
+ try { child = spawn("prlimit", [...childLimits, command, ...args], { stdio: [fd, "pipe", "pipe"], env: toolEnvironment() }); }
50
+ finally { closeSync(fd); }
51
+ const output: Buffer[] = []; let size = 0, failure: string | undefined;
52
+ const stop = (reason: string) => { failure ??= reason; child.kill("SIGKILL"); };
53
+ const timeout = setTimeout(() => stop("Image validation timed out"), options.timeoutMs ?? 15000);
54
+ const abort = () => stop("Image validation cancelled");
55
+ options.signal?.addEventListener("abort", abort, { once: true });
56
+ if (options.signal?.aborted) abort();
57
+ child.on("error", () => { failure ??= "Image validator is unavailable"; });
58
+ child.stdout!.on("data", (chunk: Buffer) => { size += chunk.length; if (size > 1024 * 1024) stop("Image validator output exceeded limit"); else output.push(chunk); });
59
+ child.stderr!.on("data", (chunk: Buffer) => { size += chunk.length; if (size > 1024 * 1024) stop("Image validator output exceeded limit"); });
60
+ child.on("close", code => {
61
+ clearTimeout(timeout); options.signal?.removeEventListener("abort", abort);
62
+ if (failure || code !== 0) reject(new UploadError("invalid_attachment", failure ?? "Image decoding failed"));
63
+ else resolve(Buffer.concat(output).toString("utf8"));
64
+ });
65
+ });
66
+ }
67
+
68
+ /** Probe dimensions before decoding. Only the three fixed demuxers are used;
69
+ * data arrives on stdin and the protocol whitelist permits only that pipe. */
70
+ export async function validateManagedImage(path: string, metadata: AttachmentMetadata, signal?: AbortSignal): Promise<void> {
71
+ const format = formats[metadata.mediaType];
72
+ if (!format) throw new UploadError("invalid_attachment", "Only PNG, JPEG and WebP images are supported");
73
+ if (!Number.isSafeInteger(metadata.bytes) || metadata.bytes < 1 || metadata.bytes > ATTACHMENT_LIMITS.fileBytes)
74
+ throw new UploadError("invalid_attachment", "Invalid image length");
75
+ let data: Buffer;
76
+ let fd: number;
77
+ try { fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW); }
78
+ catch { throw new UploadError("invalid_attachment", "Image file is unavailable"); }
79
+ try {
80
+ const stat = fstatSync(fd);
81
+ if (!stat.isFile() || stat.size !== metadata.bytes) throw new UploadError("invalid_attachment", "Invalid image length");
82
+ data = Buffer.alloc(metadata.bytes); let offset = 0;
83
+ while (offset < data.length) { const count = readSync(fd, data, offset, data.length - offset, offset); if (!count) throw new UploadError("invalid_attachment", "Invalid image length"); offset += count; }
84
+ if (fstatSync(fd).size !== metadata.bytes) throw new UploadError("invalid_attachment", "Invalid image length");
85
+ }
86
+ finally { closeSync(fd); }
87
+ if (data.length !== metadata.bytes || data.length > ATTACHMENT_LIMITS.fileBytes) throw new UploadError("invalid_attachment", "Invalid image length");
88
+ const common = ["-v", "error", "-protocol_whitelist", "pipe", "-max_alloc", "268435456", "-f", format.demuxer, "-i", "pipe:0"];
89
+ const result = await runImageTool("ffprobe", [...common, "-select_streams", "v:0", "-show_entries", "stream=codec_name,width,height", "-of", "json"], data, { signal });
90
+ let stream: { codec_name?: unknown; width?: unknown; height?: unknown } | undefined;
91
+ try { stream = JSON.parse(result).streams?.[0]; } catch { throw new UploadError("invalid_attachment", "Invalid image probe result"); }
92
+ const width = stream?.width, height = stream?.height;
93
+ if (stream?.codec_name !== format.codec || typeof width !== "number" || typeof height !== "number"
94
+ || !Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 1 || height < 1
95
+ || width > ATTACHMENT_LIMITS.imageSide || height > ATTACHMENT_LIMITS.imageSide || width * height > ATTACHMENT_LIMITS.imagePixels)
96
+ throw new UploadError("invalid_attachment", "Image type or dimensions are invalid");
97
+ await runImageTool("ffmpeg", ["-v", "error", "-xerror", "-err_detect", "explode", "-threads", "1", ...common.slice(2), "-frames:v", "1", "-f", "null", "-"], data, { signal });
98
+ }
@@ -0,0 +1 @@
1
+ export { AttachmentInputError, mixedPartsSignature, validateMixedParts } from "../../util/attachment-input.ts";
@@ -0,0 +1,76 @@
1
+ import { createHash } from "node:crypto";
2
+ import { closeSync, constants, fstatSync, openSync, readSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { ATTACHMENT_LIMITS, type AttachmentMetadata } from "../../contracts/attachments.ts";
5
+ import { mayReadAttachment } from "./selection.ts";
6
+
7
+ export class AttachmentReadError extends Error {
8
+ constructor(readonly code: "not_found" | "invalid_params" | "attachment_unavailable", message: string) { super(message); }
9
+ }
10
+
11
+ /** Resolve authorization against committed state, never against the opaque ID.
12
+ * The session owner supplies both metadata and visibility from one coherent
13
+ * read. Integrity is checked in bounded blocks before returning any bytes. */
14
+ export function readAttachment(input: { root: string; channel: string; id: string; offset: number;
15
+ lookup: (id: string) => { metadata: AttachmentMetadata; timelineVisible: boolean; timelineReadable: boolean } | undefined;
16
+ }) {
17
+ if (!Number.isSafeInteger(input.offset) || input.offset < 0) throw new AttachmentReadError("invalid_params", "Invalid offset");
18
+ const found = input.lookup(input.id);
19
+ if (!found || !mayReadAttachment({ ownerChannel: found.metadata.channel, requestingChannel: input.channel,
20
+ timelineVisible: found.timelineVisible, timelineReadable: found.timelineReadable }))
21
+ throw new AttachmentReadError("not_found", "Unknown attachment");
22
+ const metadata = found.metadata;
23
+ if (input.offset > metadata.bytes) throw new AttachmentReadError("invalid_params", "Invalid offset");
24
+ // IDs are generated UUIDs; never accept a path from storage or a caller.
25
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(metadata.id) || metadata.id !== input.id)
26
+ throw new AttachmentReadError("attachment_unavailable", "Invalid stored attachment identity");
27
+ let fd: number | undefined;
28
+ try {
29
+ fd = openSync(join(input.root, metadata.id), constants.O_RDONLY | constants.O_NOFOLLOW);
30
+ const stat = fstatSync(fd);
31
+ if (!stat.isFile() || stat.size !== metadata.bytes) throw new Error("Invalid length");
32
+ const hash = createHash("sha256"), buffer = Buffer.alloc(64 * 1024);
33
+ for (let pos = 0; pos < metadata.bytes;) {
34
+ const count = readSync(fd, buffer, 0, Math.min(buffer.length, metadata.bytes - pos), pos);
35
+ if (!count) throw new Error("Unexpected end of file");
36
+ hash.update(buffer.subarray(0, count)); pos += count;
37
+ }
38
+ if (hash.digest("hex") !== metadata.sha256) throw new Error("Digest mismatch");
39
+ const chunk = Buffer.alloc(Math.min(ATTACHMENT_LIMITS.chunkBytes, metadata.bytes - input.offset));
40
+ let count = 0;
41
+ while (count < chunk.length) {
42
+ const n = readSync(fd, chunk, count, chunk.length - count, input.offset + count);
43
+ if (!n) throw new Error("Unexpected end of file");
44
+ count += n;
45
+ }
46
+ const next = input.offset + count;
47
+ return { metadata: { ...metadata }, data: chunk.toString("base64"), ...(next < metadata.bytes ? { nextOffset: next } : {}) };
48
+ } catch {
49
+ throw new AttachmentReadError("attachment_unavailable", "Attachment bytes are unavailable or corrupt");
50
+ } finally { if (fd !== undefined) closeSync(fd); }
51
+ }
52
+
53
+ /** Inference needs the complete file; unlike paged download this allocates at
54
+ * most one validated file (20 MiB), and verifies it in a single read pass. */
55
+ export function readAttachmentForInference(input: { root: string; channel: string; id: string;
56
+ lookup: (id: string) => { metadata: AttachmentMetadata; timelineVisible: boolean; timelineReadable: boolean } | undefined;
57
+ }): Uint8Array {
58
+ const found = input.lookup(input.id);
59
+ if (!found || !mayReadAttachment({ ownerChannel: found.metadata.channel, requestingChannel: input.channel,
60
+ timelineVisible: found.timelineVisible, timelineReadable: found.timelineReadable })) throw new AttachmentReadError("not_found", "Unknown attachment");
61
+ const metadata = found.metadata;
62
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(metadata.id) || metadata.id !== input.id
63
+ || !Number.isSafeInteger(metadata.bytes) || metadata.bytes < 1 || metadata.bytes > ATTACHMENT_LIMITS.fileBytes)
64
+ throw new AttachmentReadError("attachment_unavailable", "Invalid stored attachment metadata");
65
+ let fd: number | undefined;
66
+ try {
67
+ fd = openSync(join(input.root, metadata.id), constants.O_RDONLY | constants.O_NOFOLLOW);
68
+ const stat = fstatSync(fd);
69
+ if (!stat.isFile() || stat.size !== metadata.bytes) throw Error("Invalid length");
70
+ const bytes = Buffer.alloc(metadata.bytes); let offset = 0;
71
+ while (offset < bytes.length) { const n = readSync(fd, bytes, offset, bytes.length - offset, offset); if (!n) throw Error("Unexpected end of file"); offset += n; }
72
+ if (createHash("sha256").update(bytes).digest("hex") !== metadata.sha256) throw Error("Digest mismatch");
73
+ return bytes;
74
+ } catch { throw new AttachmentReadError("attachment_unavailable", "Attachment bytes are unavailable or corrupt"); }
75
+ finally { if (fd !== undefined) closeSync(fd); }
76
+ }
@@ -0,0 +1,26 @@
1
+ import { constants, fsyncSync, openSync, closeSync, readdirSync, rmSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ const UUID = "[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}";
5
+ const publishedName = new RegExp(`^${UUID}$`);
6
+ const stagedName = new RegExp(`^\\.stage-${UUID}$`);
7
+
8
+ /** Invoke only under exclusive session ownership after reading committed ready
9
+ * IDs. An orphan is a stage from a dead owner or published bytes without ready
10
+ * metadata. A committed file is never removed here, whether referenced or not.
11
+ * Unknown names are left untouched; no directory entries are followed. */
12
+ export function recoverAttachmentOrphans(root: string, readyIds: ReadonlySet<string>): { removed: string[] } {
13
+ const removed: string[] = [];
14
+ const fd = openSync(root, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
15
+ try {
16
+ for (const entry of readdirSync(root, { withFileTypes: true })) {
17
+ const name = entry.name;
18
+ if (!stagedName.test(name) && !(publishedName.test(name) && !readyIds.has(name))) continue;
19
+ if (entry.isDirectory()) continue;
20
+ rmSync(join(root, name), { force: true });
21
+ removed.push(name);
22
+ }
23
+ if (removed.length) fsyncSync(fd);
24
+ } finally { closeSync(fd); }
25
+ return { removed: removed.sort() };
26
+ }
@@ -0,0 +1,37 @@
1
+ import { ATTACHMENT_LIMITS, type AttachmentMetadata, type InputPart } from "../../contracts/attachments.ts";
2
+
3
+ /** A retained association is shared only after its item appears in the timeline.
4
+ * Withdrawn pending items remain owner-scoped, even though bytes are retained. */
5
+ export function mayReadAttachment(input: { ownerChannel: string; requestingChannel: string; timelineVisible: boolean; timelineReadable: boolean }): boolean {
6
+ return input.requestingChannel === input.ownerChannel || (input.timelineVisible && input.timelineReadable);
7
+ }
8
+
9
+ /** Select a FIFO prefix against the complete turn's already active images.
10
+ * A reference occurs once per part, including repeated IDs. Callers must supply
11
+ * authoritative ready metadata after admission and retain the remainder pending. */
12
+ export function selectImageBudget<T extends { parts: readonly InputPart[] }>(
13
+ active: readonly T[], pending: readonly T[], resolve: (id: string) => AttachmentMetadata | undefined,
14
+ ): { selected: T[]; deferred: boolean; unavailable: string[]; oversized: boolean } {
15
+ const unavailable = new Set<string>();
16
+ const imageBytes = (item: T): number => {
17
+ let bytes = 0;
18
+ for (const part of item.parts) if (part.type === "attachment") {
19
+ const metadata = resolve(part.id);
20
+ if (!metadata) unavailable.add(part.id);
21
+ else if (metadata.mediaType.startsWith("image/")) bytes += metadata.bytes;
22
+ }
23
+ return bytes;
24
+ };
25
+ let used = active.reduce((sum, item) => sum + imageBytes(item), 0);
26
+ const selected: T[] = [];
27
+ if (unavailable.size) return { selected, deferred: false, unavailable: [...unavailable], oversized: false };
28
+ if (used > ATTACHMENT_LIMITS.imageBytesPerTurn) return { selected, deferred: false, unavailable: [], oversized: true };
29
+ for (const item of pending) {
30
+ const size = imageBytes(item);
31
+ if (unavailable.size) return { selected, deferred: false, unavailable: [...unavailable], oversized: false };
32
+ if (size > ATTACHMENT_LIMITS.imageBytesPerTurn) return { selected, deferred: false, unavailable: [], oversized: true };
33
+ if (used + size > ATTACHMENT_LIMITS.imageBytesPerTurn) return { selected, deferred: true, unavailable: [], oversized: false };
34
+ selected.push(item); used += size;
35
+ }
36
+ return { selected, deferred: false, unavailable: [], oversized: false };
37
+ }
@@ -0,0 +1,75 @@
1
+ import { closeSync, constants, existsSync, fsyncSync, mkdirSync, openSync, rmSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import type { SessionStorage, StorageResult } from "../../contracts/storage.ts";
4
+ import { createUploadManager, UploadError } from "./upload.ts";
5
+ import { readAttachment, readAttachmentForInference } from "./read.ts";
6
+ import { recoverAttachmentOrphans } from "./recovery.ts";
7
+ import { mayReadAttachment } from "./selection.ts";
8
+
9
+ export class AttachmentServiceError extends Error {
10
+ constructor(readonly code: string, message: string) { super(message); }
11
+ }
12
+ function take<T>(result: StorageResult<T>): T {
13
+ if (!result.ok) throw new AttachmentServiceError(result.error.code, result.error.message);
14
+ return result.value;
15
+ }
16
+
17
+ /** Created once for the exclusive session owner. All callbacks are synchronous,
18
+ * so publication, admission and cleanup are serialized on that owner. */
19
+ export function createManagedAttachmentService(root: string, storage: SessionStorage,
20
+ validateImage: Parameters<typeof createUploadManager>[0]["validateImage"], now: () => number = Date.now,
21
+ fault?: (point: string) => void) {
22
+ const existed = existsSync(root);
23
+ mkdirSync(root, { recursive: true, mode: 0o700 });
24
+ if (!existed) { const parent = openSync(dirname(root), constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); try { fsyncSync(parent); } finally { closeSync(parent); } }
25
+ recoverAttachmentOrphans(root, new Set(take(storage.managedAttachmentIds())));
26
+ const uploads = createUploadManager({ root, validateImage, publishReady(metadata) { fault?.("attachmentPublished"); take(storage.registerReadyAttachment(metadata)); fault?.("attachmentReady"); } });
27
+ const channel = (id: string, active = false) => {
28
+ const view = take(storage.readChannel(id));
29
+ if (!view) throw new UploadError("not_found", "Unknown channel");
30
+ if (active && view.channel.lifecycle === "retired") throw new AttachmentServiceError("channel_retired", "Channel is retired");
31
+ };
32
+ const cleanup = () => {
33
+ const before = new Date(now() - 24 * 60 * 60 * 1000).toISOString();
34
+ let removed = 0;
35
+ for (const metadata of take(storage.unreferencedAttachments(before))) {
36
+ if (!take(storage.reclaimAttachment(metadata.id, before))) continue;
37
+ // The metadata commit fences admission. If unlink fails or the process
38
+ // dies here, owner recovery removes the now-unreferenced orphan later.
39
+ rmSync(join(root, metadata.id), { force: true }); removed++;
40
+ }
41
+ if (removed) { const fd = openSync(root, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); try { fsyncSync(fd); } finally { closeSync(fd); } }
42
+ return removed;
43
+ };
44
+ cleanup();
45
+ return {
46
+ begin(input: Parameters<typeof uploads.begin>[0]) { channel(input.channel, true); return uploads.begin(input); },
47
+ status(channelId: string, id: string) { channel(channelId); return uploads.status(channelId, id); },
48
+ write(channelId: string, id: string, offset: number, data: string) { channel(channelId); return uploads.write(channelId, id, offset, data); },
49
+ finalize(channelId: string, id: string) { channel(channelId); return uploads.finalize(channelId, id); },
50
+ abort(channelId: string, id: string) { channel(channelId); uploads.abort(channelId, id); },
51
+ read(channelId: string, id: string, offset: number) {
52
+ channel(channelId);
53
+ return readAttachment({ root, channel: channelId, id, offset, lookup: fileId => {
54
+ const found = take(storage.readManagedAttachment(fileId));
55
+ return found && { ...found, timelineReadable: true };
56
+ } });
57
+ },
58
+ readForInference(channelId: string, id: string) {
59
+ channel(channelId);
60
+ return readAttachmentForInference({ root, channel: channelId, id, lookup: fileId => {
61
+ const found = take(storage.readManagedAttachment(fileId));
62
+ return found && { ...found, timelineReadable: true };
63
+ } });
64
+ },
65
+ async verifyForInference(channelId: string, id: string, signal: AbortSignal) {
66
+ channel(channelId);
67
+ const found = take(storage.readManagedAttachment(id));
68
+ if (!found || !mayReadAttachment({ ownerChannel: found.metadata.channel, requestingChannel: channelId, timelineVisible: found.timelineVisible, timelineReadable: true }))
69
+ throw new AttachmentServiceError("not_found", "Unknown attachment");
70
+ await validateImage(join(root, id), found.metadata, signal);
71
+ },
72
+ cleanup,
73
+ close() { uploads.close(); },
74
+ };
75
+ }
@@ -0,0 +1,164 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { closeSync, constants, existsSync, fsyncSync, fstatSync, lstatSync, mkdirSync, openSync, readSync, renameSync, rmSync, writeSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { ATTACHMENT_LIMITS, type AttachmentMetadata } from "../../contracts/attachments.ts";
5
+
6
+ export class UploadError extends Error {
7
+ constructor(readonly code: "invalid_params" | "transfer_limit" | "offset_mismatch" | "invalid_attachment" | "not_found", message: string,
8
+ readonly expectedOffset?: number) { super(message); }
9
+ }
10
+
11
+ type Upload = { metadata: AttachmentMetadata; path: string; fd: number; offset: number; lastUsed: number; validation?: AbortController; timer?: ReturnType<typeof setTimeout> };
12
+ type Finalized = { channel: string; metadata: AttachmentMetadata };
13
+
14
+ /** The session owner must serialize these methods with acceptance and cleanup.
15
+ * publishReady must commit metadata only after durable file publication, and
16
+ * throw on failure. validateImage must verify the complete encoded image and
17
+ * its decoded dimensions; it runs before publication. */
18
+ export function createUploadManager(options: {
19
+ root: string;
20
+ now?: () => number;
21
+ /** Test-only override; production uses the advertised idle interval. */
22
+ idleMs?: number;
23
+ validateImage: (path: string, metadata: AttachmentMetadata, signal: AbortSignal) => void | Promise<void>;
24
+ publishReady: (metadata: AttachmentMetadata) => void;
25
+ }) {
26
+ const existed = existsSync(options.root);
27
+ mkdirSync(options.root, { recursive: true, mode: 0o700 });
28
+ if (!lstatSync(options.root).isDirectory()) throw new Error("Attachment root must be a directory, not a symlink");
29
+ if (!existed) { const parent = openSync(dirname(options.root), constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); try { fsyncSync(parent); } finally { closeSync(parent); } }
30
+ const now = options.now ?? Date.now;
31
+ const idleMs = options.idleMs ?? ATTACHMENT_LIMITS.uploadIdleMs;
32
+ if (!Number.isSafeInteger(idleMs) || idleMs < 1) throw new Error("Invalid upload idle interval");
33
+ const uploads = new Map<string, Upload>();
34
+ const completed = new Map<string, Finalized>();
35
+ const finalizing = new Map<string, Promise<AttachmentMetadata>>();
36
+ const discard = (id: string, upload: Upload) => {
37
+ uploads.delete(id);
38
+ if (upload.timer) clearTimeout(upload.timer);
39
+ upload.validation?.abort();
40
+ closeSync(upload.fd);
41
+ rmSync(upload.path, { force: true });
42
+ };
43
+ const expire = () => {
44
+ for (const [id, upload] of uploads) if (!upload.validation && now() - upload.lastUsed >= idleMs) discard(id, upload);
45
+ };
46
+ const arm = (id: string, upload: Upload, delay = idleMs) => {
47
+ if (upload.timer) clearTimeout(upload.timer);
48
+ upload.timer = setTimeout(() => {
49
+ if (uploads.get(id) !== upload) return;
50
+ const remaining = idleMs - (now() - upload.lastUsed);
51
+ if (upload.validation || remaining > 0) { arm(id, upload, upload.validation ? idleMs : remaining); return; }
52
+ try { discard(id, upload); } catch { /* Owner recovery removes any orphan. */ }
53
+ }, delay);
54
+ upload.timer.unref?.();
55
+ };
56
+ const get = (channel: string, id: string): Upload => {
57
+ expire();
58
+ const upload = uploads.get(id);
59
+ if (!upload || upload.metadata.channel !== channel) throw new UploadError("not_found", "Unknown upload");
60
+ upload.lastUsed = now();
61
+ arm(id, upload);
62
+ return upload;
63
+ };
64
+ return {
65
+ begin(input: { channel: string; filename: string; mediaType: string; bytes: number; sha256: string }) {
66
+ expire();
67
+ if (uploads.size >= ATTACHMENT_LIMITS.openUploads) throw new UploadError("transfer_limit", "Too many uploads");
68
+ if (typeof input.channel !== "string" || !input.channel.trim() || typeof input.filename !== "string" ||
69
+ !input.filename || !input.filename.isWellFormed() || Buffer.byteLength(input.filename) > 255 || /[\u0000-\u001f\u007f-\u009f]/u.test(input.filename) ||
70
+ typeof input.mediaType !== "string" || input.mediaType.length > 127 || !/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(input.mediaType) ||
71
+ !Number.isSafeInteger(input.bytes) || input.bytes <= 0 || typeof input.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(input.sha256))
72
+ throw new UploadError("invalid_params", "Invalid upload metadata");
73
+ if (input.bytes > ATTACHMENT_LIMITS.fileBytes) throw new UploadError("transfer_limit", "File exceeds size limit");
74
+ const id = randomUUID(), uploadId = randomUUID();
75
+ const path = join(options.root, `.stage-${uploadId}`);
76
+ const fd = openSync(path, constants.O_CREAT | constants.O_EXCL | constants.O_RDWR | constants.O_NOFOLLOW, 0o600);
77
+ const upload: Upload = { metadata: { id, ...input }, path, fd, offset: 0, lastUsed: now() };
78
+ uploads.set(uploadId, upload); arm(uploadId, upload);
79
+ return { uploadId, attachmentId: id, offset: 0 };
80
+ },
81
+ status(channel: string, uploadId: string) { return { offset: get(channel, uploadId).offset }; },
82
+ write(channel: string, uploadId: string, offset: number, data: string) {
83
+ const upload = get(channel, uploadId);
84
+ if (upload.validation) throw new UploadError("invalid_params", "Upload is finalizing");
85
+ if (!Number.isSafeInteger(offset) || offset !== upload.offset) throw new UploadError("offset_mismatch", "Unexpected offset", upload.offset);
86
+ if (typeof data !== "string" || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data))
87
+ throw new UploadError("invalid_params", "Invalid base64");
88
+ const bytes = Buffer.from(data, "base64");
89
+ if (bytes.toString("base64") !== data || bytes.length === 0) throw new UploadError("invalid_params", "Invalid base64");
90
+ if (bytes.length > ATTACHMENT_LIMITS.chunkBytes || upload.offset + bytes.length > upload.metadata.bytes)
91
+ throw new UploadError("transfer_limit", "Chunk exceeds upload bounds");
92
+ let written = 0;
93
+ while (written < bytes.length) written += writeSync(upload.fd, bytes, written, bytes.length - written, upload.offset + written);
94
+ upload.offset += bytes.length;
95
+ return { offset: upload.offset };
96
+ },
97
+ async finalize(channel: string, uploadId: string): Promise<AttachmentMetadata> {
98
+ const prior = completed.get(uploadId);
99
+ if (prior) {
100
+ if (prior.channel !== channel) throw new UploadError("not_found", "Unknown upload");
101
+ return { ...prior.metadata };
102
+ }
103
+ const upload = get(channel, uploadId);
104
+ const pending = finalizing.get(uploadId);
105
+ if (pending) return pending;
106
+ const work = (async () => {
107
+ if (upload.offset !== upload.metadata.bytes) throw new UploadError("invalid_attachment", "Incomplete upload");
108
+ const digest = () => {
109
+ const hash = createHash("sha256"), buffer = Buffer.alloc(64 * 1024);
110
+ for (let pos = 0; pos < upload.offset;) {
111
+ const count = readSync(upload.fd, buffer, 0, Math.min(buffer.length, upload.offset - pos), pos);
112
+ if (!count) throw new UploadError("invalid_attachment", "Incomplete upload");
113
+ hash.update(buffer.subarray(0, count)); pos += count;
114
+ }
115
+ return hash.digest("hex");
116
+ };
117
+ if (digest() !== upload.metadata.sha256) throw new UploadError("invalid_attachment", "Digest mismatch");
118
+ if (upload.metadata.mediaType.startsWith("image/")) {
119
+ const controller = new AbortController(); upload.validation = controller;
120
+ try { await options.validateImage(upload.path, upload.metadata, controller.signal); }
121
+ finally { upload.validation = undefined; }
122
+ if (controller.signal.aborted || uploads.get(uploadId) !== upload) throw new UploadError("invalid_attachment", "Image validation cancelled");
123
+ }
124
+ const original = fstatSync(upload.fd);
125
+ let staged: ReturnType<typeof lstatSync>;
126
+ try { staged = lstatSync(upload.path); } catch { throw new UploadError("invalid_attachment", "Staged attachment is unavailable"); }
127
+ if (!original.isFile() || !staged.isFile() || original.dev !== staged.dev || original.ino !== staged.ino || original.size !== upload.metadata.bytes || digest() !== upload.metadata.sha256)
128
+ throw new UploadError("invalid_attachment", "Staged attachment changed during validation");
129
+ fsyncSync(upload.fd);
130
+ const target = join(options.root, upload.metadata.id);
131
+ // Reserve the generated destination exclusively before replacing our
132
+ // own empty reservation with the durable staging inode.
133
+ const reservation = openSync(target, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
134
+ closeSync(reservation);
135
+ renameSync(upload.path, target);
136
+ let published: ReturnType<typeof lstatSync>;
137
+ try { published = lstatSync(target); } catch { throw new UploadError("invalid_attachment", "Published attachment is unavailable"); }
138
+ if (!published.isFile() || published.dev !== original.dev || published.ino !== original.ino)
139
+ throw new UploadError("invalid_attachment", "Published attachment changed during validation");
140
+ const directory = openSync(options.root, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
141
+ try { fsyncSync(directory); } finally { closeSync(directory); }
142
+ // If this callback fails, the published orphan is recovered by the owner.
143
+ // Remove the live handle so a retry cannot publish the same staging path.
144
+ uploads.delete(uploadId); if (upload.timer) clearTimeout(upload.timer); closeSync(upload.fd);
145
+ options.publishReady(upload.metadata);
146
+ completed.set(uploadId, { channel, metadata: upload.metadata });
147
+ return { ...upload.metadata };
148
+ })();
149
+ finalizing.set(uploadId, work);
150
+ try { return await work; } finally { finalizing.delete(uploadId); }
151
+ },
152
+ abort(channel: string, uploadId: string) {
153
+ const upload = uploads.get(uploadId);
154
+ if (!upload) {
155
+ const done = completed.get(uploadId);
156
+ if (done && done.channel !== channel) throw new UploadError("not_found", "Unknown upload");
157
+ return;
158
+ }
159
+ if (upload.metadata.channel !== channel) throw new UploadError("not_found", "Unknown upload");
160
+ discard(uploadId, upload);
161
+ },
162
+ close() { for (const [id, upload] of uploads) discard(id, upload); completed.clear(); },
163
+ };
164
+ }
@@ -0,0 +1,45 @@
1
+ import { createHash } from "node:crypto";
2
+ import { ATTACHMENT_LIMITS, type AttachmentMetadata, type InputPart } from "../../contracts/attachments.ts";
3
+
4
+ export class VisionInputError extends Error {
5
+ constructor(readonly code: "unsupported_image" | "attachment_unavailable" | "transfer_limit", message: string,
6
+ readonly attachmentIds: readonly string[] = []) { super(message); }
7
+ }
8
+
9
+ /** Resolved bytes are ephemeral and must never be passed to capture/log hooks.
10
+ * Caller supplies only active-turn parts. A failed projection returns no partial
11
+ * request, and reports all unavailable image references in input order. */
12
+ export function projectVisionParts(parts: readonly InputPart[], options: { supported: boolean;
13
+ metadata: (id: string) => AttachmentMetadata | undefined;
14
+ read: (metadata: AttachmentMetadata) => Uint8Array;
15
+ }) {
16
+ const resolved: Array<{ part: InputPart; metadata?: AttachmentMetadata; bytes?: Uint8Array }> = [];
17
+ const unavailable = new Set<string>();
18
+ let total = 0, hasImage = false;
19
+ for (const part of parts) {
20
+ if (part.type === "text") { resolved.push({ part }); continue; }
21
+ const metadata = options.metadata(part.id);
22
+ if (!metadata) { unavailable.add(part.id); continue; }
23
+ if (!metadata.mediaType.startsWith("image/")) { resolved.push({ part, metadata }); continue; }
24
+ hasImage = true;
25
+ total += metadata.bytes;
26
+ resolved.push({ part, metadata });
27
+ }
28
+ if (unavailable.size) throw new VisionInputError("attachment_unavailable", "Attachment metadata is unavailable", [...unavailable]);
29
+ if (hasImage && !options.supported) throw new VisionInputError("unsupported_image", "The configured model does not support image input");
30
+ if (total > ATTACHMENT_LIMITS.imageBytesPerTurn) throw new VisionInputError("transfer_limit", "Image request exceeds the turn budget");
31
+ for (const entry of resolved) if (entry.metadata?.mediaType.startsWith("image/")) {
32
+ try {
33
+ const bytes = options.read(entry.metadata);
34
+ if (bytes.length !== entry.metadata.bytes || createHash("sha256").update(bytes).digest("hex") !== entry.metadata.sha256)
35
+ throw new Error("Integrity failure");
36
+ entry.bytes = bytes;
37
+ } catch { unavailable.add(entry.metadata.id); }
38
+ }
39
+ if (unavailable.size) throw new VisionInputError("attachment_unavailable", "Image bytes are unavailable", [...unavailable]);
40
+ return resolved.map(entry => {
41
+ if (entry.part.type === "text") return { type: "text" as const, text: entry.part.text };
42
+ if (!entry.bytes) return { type: "text" as const, text: `[Attachment ${entry.metadata!.id}: ${entry.metadata!.filename}, ${entry.metadata!.mediaType}, ${entry.metadata!.bytes} bytes]` };
43
+ return { type: "image_url" as const, image_url: { url: `data:${entry.metadata!.mediaType};base64,${Buffer.from(entry.bytes).toString("base64")}` } };
44
+ });
45
+ }
@@ -11,6 +11,10 @@ export function renderContextEntry(entry: ContextEntry): Message {
11
11
  role: "user",
12
12
  content: `External notice from ${entry.externalSource === undefined ? "host" : JSON.stringify(entry.externalSource)} to channel ${JSON.stringify(entry.channelId)}:\n${entry.message.content}`,
13
13
  };
14
+ if (entry.message.role === "tool") {
15
+ const { usage: _usage, webNoDispatch: _webNoDispatch, ...message } = entry.message;
16
+ return structuredClone(message);
17
+ }
14
18
  return structuredClone(entry.message);
15
19
  }
16
20
 
@@ -28,6 +32,7 @@ function unfinished(turns: readonly ContextTurnOutcome[]): string {
28
32
  export function buildSharedContext(entries: readonly ContextEntry[], systemPrompt: string, turns: readonly ContextTurnOutcome[] = []): Message[] {
29
33
  const shared = entries.map((entry) => {
30
34
  const { providerState: _opaque, ...message } = renderContextEntry(entry) as Message & { providerState?: unknown };
35
+ if (message.role === "tool") { delete message.usage; delete message.webNoDispatch; }
31
36
  return { seq: entry.seq, at: entry.at, channelId: entry.channelId, turnId: entry.turnId, from: entry.from,
32
37
  kind: entry.kind, sourceChannelId: entry.sourceChannelId, externalSource: entry.externalSource, message };
33
38
  });
@@ -1,3 +1,4 @@
1
+ import { SESSION_INTAKE_LIMITS } from "../../util/intake.ts";
1
2
  import { isTimelineTool } from "../../util/timeline-tool-names.ts";
2
3
  import type { ContextLimits, InferenceContext, InferenceStorageReads, ContextBuildResult, ContextCapture, ContextTurnOutcome } from "../../contracts/context.ts";
3
4
  import { SESSION_INPUT_MAX_BYTES } from "../../contracts/input-limits.ts";
@@ -7,7 +8,7 @@ import { buildContext } from "./build.ts";
7
8
  import { composeSystemPrompt } from "./load-instructions.ts";
8
9
 
9
10
  export const CONTEXT_LIMITS: ContextLimits = {
10
- maxInputBytes: SESSION_INPUT_MAX_BYTES, maxTakenTextBytes: SESSION_INPUT_MAX_BYTES, maxTakenItems: 16,
11
+ maxInputBytes: SESSION_INPUT_MAX_BYTES, ...SESSION_INTAKE_LIMITS,
11
12
  maxReadBytes: 256 * 1024, maxReadRecords: 64, maxSharedCandidates: 128,
12
13
  contextTokens: 16_384, outputReserveTokens: 2048, estimationMarginTokens: 1024,
13
14
  };