@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
@@ -1,5 +1,5 @@
1
1
  import type { ToolDefinition } from "../../../contracts/loop.ts";
2
- import type { AgentReminderSchedule } from "../../../contracts/reminders.ts";
2
+ import type { AgentReminderSchedule, RoutineSchedule, RoutineDeliveryOptions } from "../../../contracts/reminders.ts";
3
3
  import { SESSION_INPUT_MAX_BYTES } from "../../../contracts/input-limits.ts";
4
4
  import { REMINDER_LIMITS, reminderInstant } from "../../../util/reminder-schedule.ts";
5
5
  import type { ReminderStorage } from "../../../contracts/storage.ts";
@@ -23,8 +23,16 @@ const object = (value: unknown): value is Record<string, unknown> => !!value &&
23
23
  const allowed = (value: Record<string, unknown>, keys: string[]) => Object.keys(value).every(key => keys.includes(key));
24
24
  const text = (value: unknown): value is string => typeof value === "string" && !!value.trim() && Buffer.byteLength(value) <= SESSION_INPUT_MAX_BYTES;
25
25
 
26
+ export const guardedReminderDefinitions: ToolDefinition[] = reminderDefinitions.map(tool => tool.name !== "schedule_reminder" ? tool : {
27
+ ...tool, description: "Schedule a reminder or routine in the current channel. Cron uses five numeric fields and requires both day fields to match.",
28
+ parameters: { type: "object", properties: { text: string, expiresAfter: grace, missedRuns: { enum: ["coalesce", "skip", "each"] },
29
+ overlap: { enum: ["skip", "queue"] }, schedule: { type: "object", properties: { at: string, in: string,
30
+ every: { type: "integer" }, startAt: string, cron: string, timezone: string, count: { type: "integer" }, until: string },
31
+ additionalProperties: false } }, required: ["schedule", "text"], additionalProperties: false },
32
+ });
33
+
26
34
  export type ReminderAction =
27
- | { kind: "schedule"; schedule: AgentReminderSchedule; text: string; expiresAfter?: number | null }
35
+ | { kind: "schedule"; schedule: AgentReminderSchedule | RoutineSchedule; text: string; expiresAfter?: number | null; delivery?: RoutineDeliveryOptions }
28
36
  | { kind: "list"; after?: string; limit?: number }
29
37
  | { kind: "cancel"; id: string };
30
38
 
@@ -41,12 +49,26 @@ export function reminderAction(tool: string, input: unknown): ReminderAction | u
41
49
  if (limit !== undefined && (typeof limit !== "number" || !Number.isSafeInteger(limit) || limit < 1 || limit > 100)) return;
42
50
  return { kind: "list", ...(after === undefined ? {} : { after }), ...(limit === undefined ? {} : { limit }) };
43
51
  }
44
- if (!allowed(input, ["schedule", "text", "expiresAfter"]) || !text(input.text)) return;
52
+ if (!allowed(input, ["schedule", "text", "expiresAfter", "missedRuns", "overlap"]) || !text(input.text)) return;
45
53
  const { schedule, expiresAfter } = input;
46
54
  if (expiresAfter !== undefined && expiresAfter !== null && (typeof expiresAfter !== "number" || !Number.isSafeInteger(expiresAfter)
47
55
  || expiresAfter < REMINDER_LIMITS.minExpiryGraceMs || expiresAfter > REMINDER_LIMITS.maxExpiryGraceMs)) return;
48
- if (!object(schedule) || Object.keys(schedule).length !== 1) return;
56
+ if (!object(schedule)) return;
49
57
  const payload = { kind: "schedule" as const, text: input.text, ...(expiresAfter === undefined ? {} : { expiresAfter }) };
58
+ const { missedRuns, overlap } = input;
59
+ if (missedRuns !== undefined && missedRuns !== "coalesce" && missedRuns !== "skip" && missedRuns !== "each") return;
60
+ if (overlap !== undefined && overlap !== "skip" && overlap !== "queue") return;
61
+ const { count, until } = schedule;
62
+ if (count !== undefined && (typeof count !== "number" || !Number.isSafeInteger(count) || count < 1 || until !== undefined)) return;
63
+ if (until !== undefined && !text(until)) return;
64
+ const end = count !== undefined ? { count } : until !== undefined ? { until } : {};
65
+ const delivery: RoutineDeliveryOptions = { missedRuns, overlap };
66
+ if (typeof schedule.every === "number" && Number.isSafeInteger(schedule.every)
67
+ && allowed(schedule, ["every", "startAt", "count", "until"]) && (schedule.startAt === undefined || text(schedule.startAt)))
68
+ return { ...payload, delivery, schedule: { ...end, every: schedule.every, startAt: schedule.startAt } };
69
+ if (text(schedule.cron) && text(schedule.timezone) && allowed(schedule, ["cron", "timezone", "count", "until"]))
70
+ return { ...payload, delivery, schedule: { ...end, cron: schedule.cron, timezone: schedule.timezone } };
71
+ if (Object.keys(schedule).length !== 1 || missedRuns !== undefined || overlap !== undefined) return;
50
72
  if (text(schedule.at) && reminderInstant(schedule.at) !== undefined) return { ...payload, schedule: { at: schedule.at } };
51
73
  if (text(schedule.in) && /^[1-9]\d*[mhd]$/.test(schedule.in)) return { ...payload, schedule: { in: schedule.in } };
52
74
  }
@@ -67,7 +89,7 @@ export function executeReminderTool(
67
89
  if (changed) publish({ type: "reminder_cancelled", reminderId: value.id, by: "agent" }, result.revision);
68
90
  return JSON.stringify(value);
69
91
  }
70
- const result = storage.scheduleAgentReminder(turnId, invocationId, action.schedule, action.text, policies, action.expiresAfter, now);
92
+ const result = storage.scheduleAgentReminder(turnId, invocationId, action.schedule, action.text, policies, action.expiresAfter, now, action.delivery);
71
93
  if (!result.ok) return JSON.stringify({ error: result.error.code });
72
94
  const { reminder, created } = result.value;
73
95
  if (created) publish({ type: "reminder_changed", reminder }, result.revision);
@@ -1,3 +1,4 @@
1
+ import { webUsageView } from "../../../util/web-usage.ts";
1
2
  import type { StorageSnapshot } from "../../../contracts/storage.ts";
2
3
  import type { ToolInvocation } from "../../../contracts/tools.ts";
3
4
 
@@ -21,7 +22,9 @@ export function turnInvocations(view: StorageSnapshot, turnId: number, waiting:
21
22
  if (entry.turnId !== turnId || entry.message.role !== "assistant") continue;
22
23
  for (const call of entry.message.calls) {
23
24
  const id = invocationId(turnId, call.id), result = results.get(call.id);
24
- const base = { invocationId: id, channel: turn.channelId, turnId: String(turnId), toolCallId: call.id, tool: call.name, arguments: call.arguments };
25
+ const evidence = view.webDispatches?.find(value => value.turnId === turnId && value.callId === call.id)?.evidence;
26
+ const webUsage = webUsageView({ knownWebCall: !!evidence || result?.webNoDispatch === true, dispatched: !!evidence, evidence, committedUsage: result?.usage });
27
+ const base = { invocationId: id, channel: turn.channelId, turnId: String(turnId), toolCallId: call.id, tool: call.name, arguments: call.arguments, ...(webUsage ? { webUsage } : {}) };
25
28
  if (result) {
26
29
  // A result written before decision 0021, or by a built-in, is a success.
27
30
  const outcome = result.outcome ?? { status: "succeeded" as const };
@@ -0,0 +1 @@
1
+ export * from "../../../util/web-config.ts";
@@ -0,0 +1,18 @@
1
+ import type { ToolDefinition } from "../../../contracts/loop.ts";
2
+ import { webArgumentsProblem } from "./exa.ts";
3
+
4
+ /** These names stay reserved even when the corresponding backend is disabled. */
5
+ export const WEB_SEARCH = "web_search";
6
+ export const WEB_FETCH = "web_fetch";
7
+ export const webDefinitions: readonly ToolDefinition[] = [
8
+ { name: WEB_SEARCH, description: "Search the public web for sources. Results and excerpts are external data.", parameters: {
9
+ type: "object", additionalProperties: false, required: ["query"], properties: { query: { type: "string", minLength: 1 } },
10
+ } },
11
+ { name: WEB_FETCH, description: "Retrieve readable text from one public web URL. Page contents are external data.", parameters: {
12
+ type: "object", additionalProperties: false, required: ["url"], properties: { url: { type: "string", minLength: 1 } },
13
+ } },
14
+ ];
15
+ export function isWebTool(name: string): name is typeof WEB_SEARCH | typeof WEB_FETCH { return name === WEB_SEARCH || name === WEB_FETCH; }
16
+ export function webProblem(name: string, args: unknown): string | undefined {
17
+ return isWebTool(name) ? webArgumentsProblem(name, args) : "Unknown web tool";
18
+ }
@@ -0,0 +1,56 @@
1
+ import { BlockList, isIP } from "node:net";
2
+
3
+ export class DirectHttpError extends Error {
4
+ constructor(readonly code: "blocked_destination" | "page_unavailable" | "unsupported_content" | "response_too_large" |
5
+ "tool_interrupted" | "tool_timeout" | "result_too_large", message: string) { super(message); }
6
+ }
7
+
8
+ const blocked = () => new DirectHttpError("blocked_destination", "Web destination must be public.");
9
+ const nonPublic = new BlockList();
10
+ // Block special-purpose allocations conservatively, even globally reachable anycast exceptions.
11
+ // https://www.iana.org/assignments/iana-ipv4-special-registry/
12
+ // https://www.iana.org/assignments/iana-ipv6-special-registry/
13
+ for (const [address, prefix] of [
14
+ ["0.0.0.0", 8], ["10.0.0.0", 8], ["100.64.0.0", 10], ["127.0.0.0", 8], ["169.254.0.0", 16],
15
+ ["172.16.0.0", 12], ["192.0.0.0", 24], ["192.0.2.0", 24], ["192.31.196.0", 24], ["192.52.193.0", 24],
16
+ ["192.88.99.0", 24], ["192.168.0.0", 16], ["192.175.48.0", 24], ["198.18.0.0", 15], ["198.51.100.0", 24],
17
+ ["203.0.113.0", 24], ["224.0.0.0", 3],
18
+ ] as const) nonPublic.addSubnet(address, prefix, "ipv4");
19
+ const globalUnicast = new BlockList();
20
+ globalUnicast.addSubnet("2000::", 3, "ipv6");
21
+ for (const [address, prefix] of [
22
+ ["2001::", 23], ["2001:db8::", 32], ["2002::", 16], ["2620:4f:8000::", 48], ["3fff::", 20],
23
+ ] as const) nonPublic.addSubnet(address, prefix, "ipv6");
24
+
25
+ export function publicAddress(address: string): 4 | 6 {
26
+ const family = isIP(address);
27
+ if (family === 4 && !nonPublic.check(address, "ipv4")) return family;
28
+ if (family === 6 && globalUnicast.check(address, "ipv6") && !nonPublic.check(address, "ipv6")) return family;
29
+ throw blocked();
30
+ }
31
+
32
+ export function directHostname(url: URL) {
33
+ return url.hostname.replace(/^\[|\]$/g, "");
34
+ }
35
+
36
+ export function directUrl(input: string, previous?: URL): URL {
37
+ if (!input || Buffer.byteLength(input) > 2048 || /[\x00-\x20\x7f\s\\#]/.test(input)) throw blocked();
38
+ const authority = /^(?:https?:)?\/\/([^/?]+)/i.exec(input)?.[1];
39
+ if ((!previous && !/^https?:\/\//i.test(input)) || (authority === undefined && /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(input))
40
+ || authority?.includes("@") || authority?.includes("%")) throw blocked();
41
+ let url: URL;
42
+ try { url = new URL(input, previous); } catch { throw blocked(); }
43
+ if ((url.protocol !== "http:" && url.protocol !== "https:") || url.username || url.password || url.hash ||
44
+ (previous?.protocol === "https:" && url.protocol !== "https:") || Buffer.byteLength(url.href) > 2048) throw blocked();
45
+ const host = directHostname(url);
46
+ const family = isIP(host);
47
+ if (family) {
48
+ const rawHost = authority?.replace(/:\d+$/, "");
49
+ if (family === 4 && authority !== undefined && rawHost !== host) throw blocked();
50
+ if (family === 6 && authority !== undefined && !rawHost?.startsWith("[")) throw blocked();
51
+ publicAddress(host);
52
+ } else if (!host.includes(".") || /(?:^|\.)(?:localhost|local|internal|onion|test|invalid|example|home\.arpa)\.?$/i.test(host)) {
53
+ throw blocked();
54
+ }
55
+ return url;
56
+ }
@@ -0,0 +1,235 @@
1
+ import { Resolver } from "node:dns/promises";
2
+ import { Readable } from "node:stream";
3
+ import { BlockList, connect, isIP, type Socket } from "node:net";
4
+ import { checkServerIdentity, connect as connectTls, type TLSSocket } from "node:tls";
5
+ import { DirectHttpError, directHostname, publicAddress } from "./direct-address.ts";
6
+
7
+ export interface DirectSocketTarget {
8
+ address: string;
9
+ family: 4 | 6;
10
+ port: number;
11
+ hostname: string;
12
+ secure: boolean;
13
+ }
14
+
15
+ /** The fixture seam supplies candidates, not a bypass around destination checks. */
16
+ export interface DirectTransportDependencies {
17
+ resolve(hostname: string, signal: AbortSignal): Promise<readonly string[]>;
18
+ connect(target: DirectSocketTarget, signal: AbortSignal): Promise<Socket>;
19
+ }
20
+
21
+ async function resolve(hostname: string, signal: AbortSignal): Promise<string[]> {
22
+ signal.throwIfAborted();
23
+ const resolver = new Resolver();
24
+ const stop = () => resolver.cancel();
25
+ const missing = (error: NodeJS.ErrnoException): string[] => {
26
+ if (error.code === "ENODATA" || error.code === "ENOTFOUND") return [];
27
+ throw error;
28
+ };
29
+ signal.addEventListener("abort", stop, { once: true });
30
+ try {
31
+ const [a, aaaa] = await Promise.all([resolver.resolve4(hostname).catch(missing), resolver.resolve6(hostname).catch(missing)]);
32
+ return [...a, ...aaaa];
33
+ } finally { signal.removeEventListener("abort", stop); resolver.cancel(); }
34
+ }
35
+
36
+ function closeSocket(socket: Socket): Promise<void> {
37
+ if (socket.closed) return Promise.resolve();
38
+ return new Promise(resolve => {
39
+ socket.once("close", resolve);
40
+ socket.destroy();
41
+ });
42
+ }
43
+
44
+ export function dialDirect(target: DirectSocketTarget, signal: AbortSignal, trustedCa?: string): Promise<Socket> {
45
+ signal.throwIfAborted();
46
+ return new Promise((resolve, reject) => {
47
+ const options = { host: target.address, family: target.family, port: target.port };
48
+ const socket = target.secure ? connectTls({
49
+ ...options, ...(isIP(target.hostname) ? {} : { servername: target.hostname }),
50
+ ALPNProtocols: ["http/1.1"], ca: trustedCa,
51
+ rejectUnauthorized: true, checkServerIdentity: (_hostname, certificate) => checkServerIdentity(target.hostname, certificate),
52
+ }) : connect(options);
53
+ const event = target.secure ? "secureConnect" : "connect";
54
+ const cleanup = () => {
55
+ socket.removeListener(event, ready);
56
+ socket.removeListener("error", failed);
57
+ signal.removeEventListener("abort", stop);
58
+ };
59
+ const ready = () => {
60
+ if (target.secure) {
61
+ const tls = socket as TLSSocket;
62
+ try {
63
+ if (!tls.authorized || checkServerIdentity(target.hostname, tls.getPeerCertificate())) {
64
+ throw new Error("Web TLS verification failed.");
65
+ }
66
+ } catch {
67
+ failed(new Error("Web TLS verification failed."));
68
+ return;
69
+ }
70
+ }
71
+ cleanup();
72
+ resolve(socket);
73
+ };
74
+ const failed = (error: Error) => {
75
+ cleanup();
76
+ void closeSocket(socket).then(() => reject(error));
77
+ };
78
+ const stop = () => failed(signal.reason);
79
+ socket.once(event, ready);
80
+ socket.once("error", failed);
81
+ signal.addEventListener("abort", stop, { once: true });
82
+ });
83
+ }
84
+
85
+ export const directTransport: DirectTransportDependencies = { resolve, connect: dialDirect };
86
+
87
+ export async function requestDirect(url: URL, signal: AbortSignal, dependencies = directTransport): Promise<DirectResponse> {
88
+ signal.throwIfAborted();
89
+ const hostname = directHostname(url);
90
+ const addresses = isIP(hostname) ? [hostname] : await dependencies.resolve(hostname, signal);
91
+ signal.throwIfAborted();
92
+ if (!addresses.length) throw new DirectHttpError("page_unavailable", "Web hostname had no addresses.");
93
+ const families = addresses.map(publicAddress);
94
+ const address = addresses[0]!, family = families[0]!, secure = url.protocol === "https:";
95
+ const port = url.port ? Number(url.port) : secure ? 443 : 80;
96
+ const socket = await dependencies.connect({ address, family, port, hostname, secure }, signal);
97
+ try {
98
+ signal.throwIfAborted();
99
+ const peer = socket.remoteAddress, type = family === 4 ? "ipv4" : "ipv6";
100
+ const exact = new BlockList();
101
+ exact.addAddress(address, type);
102
+ if (!peer || publicAddress(peer) !== family || !exact.check(peer, type) || socket.remotePort !== port)
103
+ throw new DirectHttpError("blocked_destination", "Connected peer did not match the validated destination.");
104
+ return await readPinnedResponse(socket, url, signal);
105
+ } catch (error) { await closeSocket(socket); throw error; }
106
+ }
107
+
108
+ // This stage takes ownership of the already-connected and verified socket.
109
+ export async function readPinnedResponse(socket: Socket, url: URL, signal: AbortSignal): Promise<DirectResponse> {
110
+ try {
111
+ signal.throwIfAborted();
112
+ const stop = () => socket.destroy(new Error("Web request aborted."));
113
+ signal.addEventListener("abort", stop, { once: true });
114
+ socket.once("close", () => signal.removeEventListener("abort", stop));
115
+ const reader = new ResponseReader(socket);
116
+ socket.write(`GET ${url.pathname}${url.search} HTTP/1.1\r\nHost: ${url.host}\r\nAccept: text/plain, text/html\r\nAccept-Encoding: gzip, deflate, br\r\nConnection: close\r\n\r\n`);
117
+ return await reader.response();
118
+ } catch (error) { await closeSocket(socket); throw error; }
119
+ }
120
+
121
+ interface DirectResponse {
122
+ statusCode: number;
123
+ headers: Record<string, string | undefined>;
124
+ body: Readable;
125
+ close(): Promise<void>;
126
+ }
127
+
128
+ const malformed = () => new DirectHttpError("page_unavailable", "Malformed web response.");
129
+
130
+ // Parse only the response framing required by a one-shot HTTP/1.x GET.
131
+ class ResponseReader {
132
+ readonly #iterator: AsyncIterator<Buffer>;
133
+ #buffer: Buffer = Buffer.alloc(0);
134
+ #offset = 0;
135
+
136
+ constructor(readonly socket: Socket) {
137
+ this.#iterator = socket[Symbol.asyncIterator]();
138
+ }
139
+
140
+ async #fill() {
141
+ const next = await this.#iterator.next();
142
+ this.#buffer = next.done ? Buffer.alloc(0) : next.value;
143
+ this.#offset = 0;
144
+ return !next.done;
145
+ }
146
+
147
+ async #line(limit: number): Promise<string> {
148
+ const chunks: Buffer[] = [];
149
+ let length = 0;
150
+ while (this.#offset < this.#buffer.length || await this.#fill()) {
151
+ const lf = this.#buffer.indexOf(10, this.#offset);
152
+ const end = lf < 0 ? this.#buffer.length : lf + 1;
153
+ const part = this.#buffer.subarray(this.#offset, end);
154
+ length += part.length;
155
+ if (length > limit) throw malformed();
156
+ chunks.push(part);
157
+ this.#offset = end;
158
+ if (lf >= 0) {
159
+ const line = Buffer.concat(chunks, length);
160
+ if (line.length < 2 || line[line.length - 2] !== 13) throw malformed();
161
+ return line.subarray(0, -2).toString("latin1");
162
+ }
163
+ }
164
+ throw malformed();
165
+ }
166
+
167
+ async *#bytes(count?: number) {
168
+ while (count !== 0) {
169
+ if (this.#offset === this.#buffer.length && !await this.#fill()) {
170
+ if (count !== undefined) throw malformed();
171
+ return;
172
+ }
173
+ const take = Math.min(count ?? Infinity, this.#buffer.length - this.#offset);
174
+ const part = this.#buffer.subarray(this.#offset, this.#offset + take);
175
+ this.#offset += take;
176
+ if (count !== undefined) count -= take;
177
+ yield part;
178
+ }
179
+ }
180
+
181
+ async *#body(mode: "chunked" | "fixed", size?: number) {
182
+ try {
183
+ if (mode === "fixed") { yield* this.#bytes(size); return; }
184
+ let framing = 0;
185
+ for (;;) {
186
+ const line = await this.#line(1024);
187
+ framing += line.length + 4;
188
+ if (framing > 64 * 1024) throw malformed();
189
+ const hex = /^([0-9a-f]+)(?:;[^\x00-\x1f\x7f]*)?$/i.exec(line)?.[1];
190
+ const bytes = hex === undefined ? NaN : parseInt(hex, 16);
191
+ if (!Number.isSafeInteger(bytes)) throw malformed();
192
+ if (bytes === 0) { await this.#headers(); return; }
193
+ yield* this.#bytes(bytes);
194
+ if (await this.#line(2) !== "") throw malformed();
195
+ }
196
+ } finally { await closeSocket(this.socket); }
197
+ }
198
+
199
+ async #headers() {
200
+ const headers: Record<string, string | undefined> = Object.create(null);
201
+ let remaining = 16 * 1024;
202
+ for (;;) {
203
+ const line = await this.#line(remaining);
204
+ remaining -= line.length + 2;
205
+ if (line === "") return headers;
206
+ const match = /^([!#$%&'*+.^_`|~\w-]+):[ \t]*([^\x00-\x08\x0a-\x1f\x7f]*)$/.exec(line);
207
+ if (!match) throw malformed();
208
+ const name = match[1]!.toLowerCase();
209
+ if (headers[name] !== undefined && ["content-length", "transfer-encoding", "location", "content-encoding", "content-type"].includes(name)) throw malformed();
210
+ headers[name] = match[2]!.trim();
211
+ }
212
+ }
213
+
214
+ async response(): Promise<DirectResponse> {
215
+ let statusCode: number;
216
+ let headers: Record<string, string | undefined>;
217
+ for (let informational = 0; ; informational++) {
218
+ const status = /^HTTP\/1\.[01] ([1-5][0-9]{2})(?: [^\r\n]*)?$/.exec(await this.#line(1024));
219
+ if (!status || informational === 5) throw malformed();
220
+ statusCode = Number(status[1]);
221
+ headers = await this.#headers();
222
+ if (statusCode >= 200) break;
223
+ if (statusCode === 101) throw malformed();
224
+ }
225
+ const transfer = headers["transfer-encoding"]?.toLowerCase();
226
+ const length = headers["content-length"];
227
+ if (transfer !== undefined && (transfer !== "chunked" || length !== undefined)) throw malformed();
228
+ if (length !== undefined && (!/^\d+$/.test(length) || !Number.isSafeInteger(Number(length)))) throw malformed();
229
+ const empty = statusCode === 204 || statusCode === 304;
230
+ const body = Readable.from(this.#body(!empty && transfer === "chunked" ? "chunked" : "fixed",
231
+ empty ? 0 : length === undefined ? undefined : Number(length)), { objectMode: false });
232
+ body.once("close", () => this.socket.destroy());
233
+ return { statusCode, headers, body, close: () => closeSocket(this.socket) };
234
+ }
235
+ }
@@ -0,0 +1,149 @@
1
+ import { PassThrough, Transform, Writable } from "node:stream";
2
+ import { pipeline } from "node:stream/promises";
3
+ import { createBrotliDecompress, createGunzip, createInflate } from "node:zlib";
4
+ import { DirectHttpError, directUrl } from "./direct-address.ts";
5
+ import { requestDirect, type DirectTransportDependencies } from "./direct-transport.ts";
6
+
7
+ const rawLimit = 2 * 1024 * 1024, decodedLimit = 4 * 1024 * 1024, previewLimit = 2048;
8
+ const tooLarge = () => new DirectHttpError("response_too_large", "Web response exceeded the transfer limit.");
9
+
10
+ async function boundedBody(response: Awaited<ReturnType<typeof requestDirect>>, signal: AbortSignal, discard: boolean): Promise<Buffer> {
11
+ let received = 0, decoded = 0;
12
+ const chunks: Buffer[] = [];
13
+ const encoding = response.headers["content-encoding"]?.trim().toLowerCase();
14
+ const decoder = encoding === "gzip" ? createGunzip() : encoding === "deflate" ? createInflate()
15
+ : encoding === "br" ? createBrotliDecompress() : encoding === undefined || encoding === "identity" ? new PassThrough() : undefined;
16
+ if (!decoder) {
17
+ response.body.destroy();
18
+ await response.close();
19
+ throw new DirectHttpError("unsupported_content", "Unsupported response encoding.");
20
+ }
21
+ const count = new Transform({ transform(chunk: Buffer, _encoding, callback) {
22
+ received += chunk.length;
23
+ callback(received > rawLimit ? tooLarge() : null, chunk);
24
+ } });
25
+ const collect = new Writable({ write(chunk: Buffer, _encoding, callback) {
26
+ decoded += chunk.length;
27
+ if (decoded > decodedLimit) { callback(tooLarge()); return; }
28
+ if (!discard) chunks.push(chunk);
29
+ callback();
30
+ } });
31
+ try {
32
+ await pipeline(response.body, count, decoder, collect, { signal });
33
+ } finally {
34
+ await response.close();
35
+ }
36
+ return Buffer.concat(chunks, discard ? 0 : decoded);
37
+ }
38
+
39
+ const entity = (text: string) => text.replace(/&(#x[\da-fA-F]{1,6}|#\d{1,7}|amp|lt|gt|quot|apos|nbsp);/g, (raw, code: string) => {
40
+ if (code.startsWith("#")) {
41
+ const scalar = code[1] === "x" ? parseInt(code.slice(2), 16) : Number(code.slice(1));
42
+ return scalar > 0 && scalar <= 0x10ffff && (scalar < 0xd800 || scalar > 0xdfff) ? String.fromCodePoint(scalar) : "�";
43
+ }
44
+ return ({ amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " } as Record<string, string>)[code] ?? raw;
45
+ });
46
+
47
+ function readableHtml(input: string) {
48
+ const output: string[] = [], title: string[] = [];
49
+ const excluded = new Set(["script", "style", "head", "nav", "footer", "noscript", "template", "svg"]);
50
+ const tags = /<!--[\s\S]*?(?:-->|$)|<\/?[a-z][^<>]*>/gi;
51
+ let hidden: string | undefined, inTitle = false, offset = 0;
52
+ for (const match of input.matchAll(tags)) {
53
+ const text = input.slice(offset, match.index);
54
+ if (inTitle) title.push(text);
55
+ else if (!hidden) output.push(text);
56
+ const name = /^<(\/?)([a-z][\w:-]*)/i.exec(match[0]);
57
+ const tag = name?.[2]?.toLowerCase();
58
+ if (tag === "title") inTitle = !name?.[1];
59
+ if (tag && excluded.has(tag) && !name?.[1] && !hidden) hidden = tag;
60
+ if (tag === hidden && name?.[1]) hidden = undefined;
61
+ if (!hidden && ["br", "p", "div", "li", "section", "article", "h1", "h2", "h3", "tr"].includes(tag ?? "")) output.push("\n");
62
+ offset = match.index + match[0].length;
63
+ }
64
+ if (!hidden) output.push(input.slice(offset));
65
+ const clean = (text: string) => entity(text).replace(/[^\S\n]+/g, " ").replace(/\n(?:\s*\n)+/g, "\n").trim();
66
+ return { title: clean(title.join("")) || null, text: clean(output.join("")) };
67
+ }
68
+
69
+ interface DirectPage { url: string; title: string | null; text: string; truncated: boolean; coverage: "full" | "unknown" }
70
+
71
+ function preview(page: DirectPage): string {
72
+ const fits = () => Buffer.byteLength(JSON.stringify(page)) <= previewLimit;
73
+ if (fits()) return JSON.stringify(page);
74
+ page.truncated = true;
75
+ function shorten(field: "title" | "text") {
76
+ const units: string[] = [];
77
+ for (const scalar of page[field] ?? "") {
78
+ if (units.length === previewLimit) break;
79
+ units.push(scalar);
80
+ }
81
+ const set = (count: number) => { const value = units.slice(0, count).join("");
82
+ if (field === "title") page.title = value || null;
83
+ else page.text = value; };
84
+ set(0);
85
+ if (!fits()) return;
86
+ let lower = 0, upper = units.length;
87
+ while (lower < upper) {
88
+ const mid = Math.ceil((lower + upper) / 2);
89
+ set(mid);
90
+ if (fits()) lower = mid; else upper = mid - 1;
91
+ }
92
+ set(lower);
93
+ }
94
+ if (page.title !== null) shorten("title");
95
+ if (!fits()) shorten("text");
96
+ if (!fits()) throw new DirectHttpError("result_too_large", "The source URL does not fit the result budget.");
97
+ return JSON.stringify(page);
98
+ }
99
+
100
+ export async function fetchDirect(input: string, deadlineMs: number, signal: AbortSignal, dependencies?: DirectTransportDependencies): Promise<string> {
101
+ const expiresAt = performance.now() + deadlineMs;
102
+ const deadline = AbortSignal.timeout(deadlineMs);
103
+ const stop = AbortSignal.any([signal, deadline]);
104
+ try {
105
+ let url = directUrl(input);
106
+ const source = url.href;
107
+ const seen = new Set<string>();
108
+ for (let hops = 0; ; hops++) {
109
+ if (seen.has(url.href)) throw new DirectHttpError("blocked_destination", "Web redirect loop refused.");
110
+ seen.add(url.href);
111
+ const response = await requestDirect(url, stop, dependencies);
112
+ const status = response.statusCode ?? 0;
113
+ if ([301, 302, 303, 307, 308].includes(status)) {
114
+ await boundedBody(response, stop, true);
115
+ if (hops === 5 || !response.headers.location) throw new DirectHttpError("blocked_destination", "Web redirect refused.");
116
+ url = directUrl(response.headers.location, url);
117
+ continue;
118
+ }
119
+ if (status < 200 || status >= 300 || status === 206) {
120
+ await boundedBody(response, stop, true);
121
+ throw new DirectHttpError("page_unavailable", "Web server did not return a successful page.");
122
+ }
123
+ const [mime, ...parameters] = (response.headers["content-type"] ?? "").toLowerCase().split(";");
124
+ const charset = parameters.map(part => part.trim()).find(part => part.startsWith("charset="))?.slice(8).replace(/^"|"$/g, "") ?? "utf-8";
125
+ const bytes = await boundedBody(response, stop, false);
126
+ if (!["text/html", "text/plain"].includes(mime!.trim()) || !["utf-8", "utf8", "us-ascii", "iso-8859-1", "windows-1252"].includes(charset))
127
+ throw new DirectHttpError("unsupported_content", "Only HTML and plain text in supported charsets are readable.");
128
+ let decoded: string;
129
+ try {
130
+ if (charset === "us-ascii" && bytes.some(byte => byte > 127)) throw new Error();
131
+ decoded = new TextDecoder(charset === "windows-1252" || charset === "iso-8859-1" ? "windows-1252" : "utf-8", { fatal: true }).decode(bytes);
132
+ } catch { throw new DirectHttpError("unsupported_content", "Web response cannot be decoded."); }
133
+ const html = mime!.trim() === "text/html";
134
+ const result = html ? readableHtml(decoded) : { title: null, text: decoded.trim() };
135
+ if (!result.text) throw new DirectHttpError("page_unavailable", "Web page has no readable text.");
136
+ const framed = response.headers["content-length"] !== undefined || response.headers["transfer-encoding"] !== undefined;
137
+ const coverage = html || !framed ? "unknown" : "full";
138
+ const output = preview({ ...result, url: source, truncated: false, coverage });
139
+ stop.throwIfAborted();
140
+ if (performance.now() >= expiresAt) throw new DirectHttpError("tool_timeout", "Web fetch deadline exceeded.");
141
+ return output;
142
+ }
143
+ } catch (error) {
144
+ if (signal.aborted) throw new DirectHttpError("tool_interrupted", "Web fetch interrupted.");
145
+ if (deadline.aborted) throw new DirectHttpError("tool_timeout", "Web fetch deadline exceeded.");
146
+ if (error instanceof DirectHttpError) throw error;
147
+ throw new DirectHttpError("page_unavailable", "Web destination could not be read.");
148
+ }
149
+ }
@@ -0,0 +1,41 @@
1
+ import { request } from "node:https";
2
+ import { Transform, Writable, type TransformCallback } from "node:stream";
3
+ import { pipeline } from "node:stream/promises";
4
+ import { createBrotliDecompress, createGunzip, createInflate } from "node:zlib";
5
+ import type { ExaTransport } from "./exa.ts";
6
+
7
+ const cap = 2 * 1024 * 1024;
8
+ export class ExaResponseLimit extends Error {}
9
+ /** Streaming transform limits input before any decompressing allocation. */
10
+ export function boundedBytes(max: number): Transform {
11
+ let total = 0;
12
+ return new Transform({ transform(chunk: Buffer, _encoding: BufferEncoding, done: TransformCallback) {
13
+ total += chunk.length;
14
+ if (total > max) done(new ExaResponseLimit("Exa response exceeds size limit")); else done(null, chunk);
15
+ } });
16
+ }
17
+ /** Fixed Exa origin: no redirects, proxy forwarding, cookies or source-site secrets. */
18
+ /** Injection is an assembly-only offline test seam, not managed configuration. */
19
+ export function createExaHttpsTransport(send: typeof request = request): ExaTransport {
20
+ return ({ path, key, body, signal }) => new Promise((resolve, reject) => {
21
+ const payload = JSON.stringify(body);
22
+ const req = send({ protocol: "https:", hostname: "api.exa.ai", port: 443, method: "POST", path, signal,
23
+ headers: { "content-type": "application/json", "accept": "application/json", "accept-encoding": "gzip, deflate, br", "content-length": Buffer.byteLength(payload), "x-api-key": key } }, async response => {
24
+ const status = response.statusCode ?? 0;
25
+ const encoding = response.headers["content-encoding"]?.trim().toLowerCase() ?? "identity";
26
+ const decoder = encoding === "gzip" ? createGunzip() : encoding === "deflate" ? createInflate() : encoding === "br" ? createBrotliDecompress() : undefined;
27
+ if (!decoder && encoding !== "identity") { response.destroy(); reject(new Error("Unsupported Exa content encoding")); return; }
28
+ const chunks: Buffer[] = [];
29
+ const sink = new Writable({ write(chunk: Buffer, _encoding, done) { chunks.push(chunk); done(); } });
30
+ try {
31
+ if (decoder) await pipeline(response, boundedBytes(cap), decoder, boundedBytes(cap), sink, { signal });
32
+ else await pipeline(response, boundedBytes(cap), boundedBytes(cap), sink, { signal });
33
+ let parsed: unknown; try { parsed = JSON.parse(Buffer.concat(chunks).toString("utf8")); } catch { parsed = undefined; }
34
+ resolve({ status, body: parsed });
35
+ } catch (error) { reject(error); }
36
+ });
37
+ req.on("error", reject);
38
+ req.end(payload);
39
+ });
40
+ }
41
+ export const exaHttpsTransport = createExaHttpsTransport();