@oyasmi/pipiclaw 0.9.4 → 0.9.5-beta.3

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 (531) hide show
  1. package/README.en.md +35 -31
  2. package/README.md +34 -30
  3. package/dist/agent/builtin-commands.d.ts +7 -2
  4. package/dist/agent/builtin-commands.js +19 -23
  5. package/dist/agent/channel-runner.d.ts +23 -35
  6. package/dist/agent/channel-runner.js +150 -89
  7. package/dist/agent/maintenance-context.d.ts +8 -5
  8. package/dist/agent/maintenance-context.js +30 -15
  9. package/dist/agent/prompt/manifest.js +1 -1
  10. package/dist/agent/prompt/resources.d.ts +1 -1
  11. package/dist/agent/prompt/resources.js +1 -1
  12. package/dist/agent/prompt/sections.js +11 -9
  13. package/dist/agent/prompt/types.d.ts +1 -1
  14. package/dist/agent/runner-factory.d.ts +6 -6
  15. package/dist/agent/runner-factory.js +7 -8
  16. package/dist/agent/session/command-extension.js +11 -0
  17. package/dist/agent/session/compaction-input.d.ts +6 -0
  18. package/dist/agent/session/compaction-input.js +75 -0
  19. package/dist/agent/session/compaction-snapshot.d.ts +30 -0
  20. package/dist/agent/session/compaction-snapshot.js +154 -0
  21. package/dist/agent/session/compaction-summary.d.ts +39 -0
  22. package/dist/agent/session/compaction-summary.js +162 -0
  23. package/dist/agent/session/compaction.d.ts +35 -0
  24. package/dist/agent/session/compaction.js +294 -0
  25. package/dist/agent/session/context-input.d.ts +15 -0
  26. package/dist/agent/session/context-input.js +82 -0
  27. package/dist/agent/session/context-snapshot.d.ts +11 -0
  28. package/dist/agent/session/context-snapshot.js +72 -0
  29. package/dist/agent/session/event-guards.d.ts +2 -0
  30. package/dist/agent/session/event-guards.js +4 -0
  31. package/dist/agent/session/execution-trace.d.ts +14 -0
  32. package/dist/agent/session/execution-trace.js +57 -0
  33. package/dist/agent/session/request-tools.d.ts +3 -0
  34. package/dist/agent/session/request-tools.js +20 -0
  35. package/dist/agent/session/session-adapter.d.ts +2 -1
  36. package/dist/agent/session/session-adapter.js +6 -3
  37. package/dist/agent/session/session-events.d.ts +4 -8
  38. package/dist/agent/session/session-events.js +80 -70
  39. package/dist/agent/session/session-host.d.ts +39 -61
  40. package/dist/agent/session/session-host.js +122 -124
  41. package/dist/agent/session/settings-diagnostics.d.ts +5 -0
  42. package/dist/agent/session/settings-diagnostics.js +21 -0
  43. package/dist/agent/status-render.js +5 -2
  44. package/dist/{runtime → agent}/stop-watchdog.d.ts +3 -1
  45. package/dist/{runtime → agent}/stop-watchdog.js +7 -3
  46. package/dist/agent/turn/progress-formatter.d.ts +1 -3
  47. package/dist/agent/turn/progress-formatter.js +3 -22
  48. package/dist/agent/turn/task-digest.d.ts +5 -4
  49. package/dist/agent/turn/task-digest.js +37 -34
  50. package/dist/agent/turn/turn-context.d.ts +12 -8
  51. package/dist/agent/turn/turn-context.js +27 -19
  52. package/dist/agent/turn/turn-finish.d.ts +18 -6
  53. package/dist/agent/turn/turn-finish.js +52 -77
  54. package/dist/agent/turn/turn-input.d.ts +2 -2
  55. package/dist/agent/turn/turn-input.js +4 -3
  56. package/dist/agent/turn/turn-output.d.ts +19 -0
  57. package/dist/agent/turn/turn-output.js +41 -0
  58. package/dist/agent/turn/turn-pipeline.d.ts +15 -10
  59. package/dist/agent/turn/turn-pipeline.js +86 -59
  60. package/dist/agent/turn/turn-prompt.d.ts +1 -1
  61. package/dist/agent/turn/turn-recovery.d.ts +11 -10
  62. package/dist/agent/turn/turn-recovery.js +14 -29
  63. package/dist/agent/types.d.ts +93 -24
  64. package/dist/agent/types.js +5 -1
  65. package/dist/app/auth-command.js +1 -1
  66. package/dist/app/home.js +34 -19
  67. package/dist/channel/active-session-store.d.ts +14 -12
  68. package/dist/channel/active-session-store.js +29 -25
  69. package/dist/channel/attachments.d.ts +25 -0
  70. package/dist/channel/attachments.js +56 -0
  71. package/dist/channel/channel-context.d.ts +87 -96
  72. package/dist/channel/channel-context.js +1 -66
  73. package/dist/channel/channel-event.d.ts +49 -47
  74. package/dist/channel/channel-event.js +6 -11
  75. package/dist/channel/channel-id.d.ts +22 -0
  76. package/dist/channel/channel-id.js +13 -0
  77. package/dist/channel/channel-index.d.ts +17 -34
  78. package/dist/channel/channel-index.js +41 -80
  79. package/dist/channel/config.d.ts +10 -0
  80. package/dist/channel/config.js +55 -0
  81. package/dist/channel/ingress.d.ts +93 -0
  82. package/dist/channel/ingress.js +5 -0
  83. package/dist/channel/store.d.ts +14 -16
  84. package/dist/channel/store.js +21 -25
  85. package/dist/channel/transport.d.ts +99 -0
  86. package/dist/channel/turn-context.d.ts +23 -0
  87. package/dist/channel/turn-context.js +1 -0
  88. package/dist/commands/catalog.d.ts +4 -7
  89. package/dist/commands/catalog.js +48 -49
  90. package/dist/commands/router.d.ts +28 -14
  91. package/dist/commands/router.js +30 -27
  92. package/dist/config/settings.d.ts +8 -14
  93. package/dist/config/settings.js +0 -7
  94. package/dist/config/tools.d.ts +2 -2
  95. package/dist/config/tools.js +2 -2
  96. package/dist/desk/bindings.d.ts +6 -0
  97. package/dist/desk/bindings.js +105 -0
  98. package/dist/desk/commands.d.ts +81 -0
  99. package/dist/desk/commands.js +145 -0
  100. package/dist/desk/default.d.ts +4 -0
  101. package/dist/desk/default.js +11 -0
  102. package/dist/desk/paths.d.ts +41 -0
  103. package/dist/desk/paths.js +81 -0
  104. package/dist/desk/registry.d.ts +17 -0
  105. package/dist/desk/registry.js +191 -0
  106. package/dist/desk/startup-error.d.ts +4 -0
  107. package/dist/desk/startup-error.js +7 -0
  108. package/dist/desk/types.d.ts +72 -0
  109. package/dist/desk/types.js +7 -0
  110. package/dist/dingtalk/bot.d.ts +20 -35
  111. package/dist/dingtalk/bot.js +25 -204
  112. package/dist/dingtalk/cards.d.ts +7 -0
  113. package/dist/dingtalk/cards.js +32 -2
  114. package/dist/dingtalk/channel-ids.d.ts +15 -0
  115. package/dist/dingtalk/channel-ids.js +39 -0
  116. package/dist/dingtalk/config.d.ts +6 -3
  117. package/dist/dingtalk/config.js +13 -25
  118. package/dist/dingtalk/connection.d.ts +1 -0
  119. package/dist/dingtalk/connection.js +5 -4
  120. package/dist/dingtalk/conversation-meta.d.ts +10 -5
  121. package/dist/dingtalk/conversation-meta.js +72 -50
  122. package/dist/dingtalk/delivery.d.ts +34 -14
  123. package/dist/dingtalk/delivery.js +332 -190
  124. package/dist/dingtalk/inbound-media.d.ts +2 -18
  125. package/dist/dingtalk/inbound-media.js +0 -53
  126. package/dist/dingtalk/inbound.d.ts +10 -11
  127. package/dist/dingtalk/inbound.js +12 -19
  128. package/dist/dingtalk/media.d.ts +9 -11
  129. package/dist/dingtalk/media.js +18 -31
  130. package/dist/dingtalk/progress.d.ts +57 -0
  131. package/dist/dingtalk/progress.js +199 -0
  132. package/dist/dingtalk/response-mode.d.ts +13 -0
  133. package/dist/dingtalk/response-mode.js +31 -0
  134. package/dist/dingtalk/transport.d.ts +47 -0
  135. package/dist/dingtalk/transport.js +71 -0
  136. package/dist/events/commands.d.ts +7 -2
  137. package/dist/events/commands.js +40 -22
  138. package/dist/events/pre-action-error.d.ts +10 -0
  139. package/dist/events/pre-action-error.js +10 -0
  140. package/dist/events/types.d.ts +20 -2
  141. package/dist/events/watcher.d.ts +14 -7
  142. package/dist/events/watcher.js +49 -26
  143. package/dist/file-store.d.ts +4 -0
  144. package/dist/file-store.js +6 -1
  145. package/dist/index.d.ts +4 -2
  146. package/dist/jobs/completion-observer.d.ts +20 -0
  147. package/dist/jobs/completion-observer.js +107 -0
  148. package/dist/jobs/completion-signal.d.ts +9 -0
  149. package/dist/jobs/completion-signal.js +32 -0
  150. package/dist/jobs/completion-wake.d.ts +14 -0
  151. package/dist/jobs/completion-wake.js +25 -0
  152. package/dist/jobs/manager.d.ts +29 -42
  153. package/dist/jobs/manager.js +130 -236
  154. package/dist/jobs/probe.d.ts +3 -0
  155. package/dist/jobs/probe.js +42 -0
  156. package/dist/jobs/record.d.ts +5 -6
  157. package/dist/jobs/record.js +2 -0
  158. package/dist/jobs/runtime.d.ts +28 -0
  159. package/dist/jobs/runtime.js +69 -0
  160. package/dist/log.d.ts +0 -1
  161. package/dist/log.js +1 -1
  162. package/dist/main.js +10 -3
  163. package/dist/memory/boundary-work.d.ts +19 -0
  164. package/dist/memory/boundary-work.js +204 -0
  165. package/dist/memory/commands.d.ts +4 -3
  166. package/dist/memory/commands.js +20 -17
  167. package/dist/memory/desk-memory-queue.d.ts +18 -0
  168. package/dist/memory/desk-memory-queue.js +33 -0
  169. package/dist/memory/index-budget.d.ts +3 -3
  170. package/dist/memory/index-budget.js +21 -18
  171. package/dist/memory/journal.d.ts +6 -6
  172. package/dist/memory/journal.js +16 -15
  173. package/dist/memory/lifecycle.d.ts +17 -28
  174. package/dist/memory/lifecycle.js +87 -147
  175. package/dist/memory/maintenance-state.d.ts +14 -15
  176. package/dist/memory/maintenance-state.js +43 -42
  177. package/dist/memory/reflect-job.d.ts +5 -10
  178. package/dist/memory/reflect-job.js +29 -44
  179. package/dist/memory/reflect.d.ts +6 -1
  180. package/dist/memory/reflect.js +44 -16
  181. package/dist/memory/render.d.ts +1 -1
  182. package/dist/memory/render.js +2 -2
  183. package/dist/memory/review-log.d.ts +17 -4
  184. package/dist/memory/review-log.js +54 -5
  185. package/dist/memory/scheduler.d.ts +12 -19
  186. package/dist/memory/scheduler.js +28 -64
  187. package/dist/memory/search.js +7 -4
  188. package/dist/memory/session-corpus.d.ts +4 -1
  189. package/dist/memory/session-corpus.js +70 -29
  190. package/dist/memory/session-search.d.ts +11 -3
  191. package/dist/memory/session-search.js +14 -11
  192. package/dist/memory/sidecar-worker.d.ts +1 -0
  193. package/dist/memory/sidecar-worker.js +57 -76
  194. package/dist/memory/source-window.d.ts +18 -7
  195. package/dist/memory/source-window.js +59 -29
  196. package/dist/memory/store.d.ts +14 -12
  197. package/dist/memory/store.js +89 -57
  198. package/dist/paths.d.ts +2 -0
  199. package/dist/paths.js +2 -0
  200. package/dist/playbooks/agent-delegation.md +23 -17
  201. package/dist/playbooks/background-jobs.md +7 -5
  202. package/dist/playbooks/event-scheduling.md +9 -7
  203. package/dist/playbooks/memory-and-learning.md +18 -14
  204. package/dist/playbooks/outbound-media.md +3 -3
  205. package/dist/playbooks/runtime-orientation.md +39 -23
  206. package/dist/playbooks/task-lead.md +57 -34
  207. package/dist/runtime/bootstrap.d.ts +45 -35
  208. package/dist/runtime/bootstrap.js +372 -167
  209. package/dist/runtime/channel-queue.d.ts +25 -0
  210. package/dist/{dingtalk → runtime}/channel-queue.js +25 -10
  211. package/dist/runtime/daemon-lock.d.ts +12 -0
  212. package/dist/runtime/daemon-lock.js +28 -0
  213. package/dist/runtime/desk-runtime.d.ts +131 -0
  214. package/dist/runtime/desk-runtime.js +402 -0
  215. package/dist/runtime/durable-dispatch.d.ts +18 -5
  216. package/dist/runtime/durable-dispatch.js +85 -14
  217. package/dist/runtime/inbound-images.d.ts +32 -10
  218. package/dist/runtime/inbound-images.js +95 -21
  219. package/dist/runtime/ingress-busy.d.ts +25 -0
  220. package/dist/runtime/ingress-busy.js +178 -0
  221. package/dist/runtime/ingress-commands.d.ts +7 -0
  222. package/dist/runtime/ingress-commands.js +170 -0
  223. package/dist/runtime/ingress-deps.d.ts +59 -0
  224. package/dist/runtime/ingress-deps.js +1 -0
  225. package/dist/runtime/ingress.d.ts +22 -0
  226. package/dist/runtime/ingress.js +386 -0
  227. package/dist/runtime/request-execution.d.ts +19 -0
  228. package/dist/runtime/request-execution.js +88 -0
  229. package/dist/runtime/shutdown.d.ts +14 -6
  230. package/dist/runtime/shutdown.js +11 -5
  231. package/dist/runtime/task-close.d.ts +4 -0
  232. package/dist/runtime/task-close.js +102 -0
  233. package/dist/runtime/task-control.d.ts +34 -0
  234. package/dist/runtime/task-control.js +225 -0
  235. package/dist/runtime/task-input.d.ts +13 -0
  236. package/dist/runtime/task-input.js +129 -0
  237. package/dist/runtime/task-lane-types.d.ts +123 -0
  238. package/dist/runtime/task-lane-types.js +14 -0
  239. package/dist/runtime/task-lane.d.ts +99 -0
  240. package/dist/runtime/task-lane.js +703 -0
  241. package/dist/runtime/task-pending.d.ts +8 -0
  242. package/dist/runtime/task-pending.js +40 -0
  243. package/dist/runtime/task-spawn.d.ts +8 -8
  244. package/dist/runtime/task-spawn.js +10 -9
  245. package/dist/runtime/task-step.d.ts +32 -0
  246. package/dist/runtime/task-step.js +276 -0
  247. package/dist/runtime/transports.d.ts +32 -0
  248. package/dist/runtime/transports.js +101 -0
  249. package/dist/runtime/turn-run.d.ts +20 -23
  250. package/dist/runtime/turn-run.js +252 -159
  251. package/dist/runtime/wake-coalescing.d.ts +12 -6
  252. package/dist/runtime/wake-coalescing.js +12 -4
  253. package/dist/security/config.js +5 -10
  254. package/dist/security/logger.js +1 -1
  255. package/dist/security/path-guard.js +7 -63
  256. package/dist/security/types.d.ts +27 -30
  257. package/dist/security/types.js +0 -1
  258. package/dist/shared/atomic-file.d.ts +2 -0
  259. package/dist/shared/atomic-file.js +14 -1
  260. package/dist/shared/file-lock.d.ts +35 -0
  261. package/dist/shared/file-lock.js +195 -0
  262. package/dist/shared/format.d.ts +0 -6
  263. package/dist/shared/format.js +0 -17
  264. package/dist/shared/host-process.d.ts +2 -0
  265. package/dist/shared/host-process.js +16 -1
  266. package/dist/shared/jsonl-appender.d.ts +5 -0
  267. package/dist/shared/jsonl-appender.js +25 -2
  268. package/dist/shared/with-timeout.d.ts +2 -0
  269. package/dist/shared/with-timeout.js +21 -0
  270. package/dist/skills/catalog.d.ts +9 -0
  271. package/dist/skills/catalog.js +34 -0
  272. package/dist/skills/commands.d.ts +3 -12
  273. package/dist/skills/commands.js +36 -22
  274. package/dist/skills/loader.d.ts +2 -31
  275. package/dist/skills/loader.js +101 -68
  276. package/dist/skills/roots.d.ts +12 -0
  277. package/dist/skills/roots.js +18 -0
  278. package/dist/skills/types.d.ts +24 -0
  279. package/dist/skills/types.js +1 -0
  280. package/dist/subagents/completion-wake.d.ts +11 -2
  281. package/dist/subagents/completion-wake.js +21 -18
  282. package/dist/subagents/discovery.d.ts +1 -1
  283. package/dist/subagents/discovery.js +10 -16
  284. package/dist/subagents/dispatch.d.ts +0 -10
  285. package/dist/subagents/dispatch.js +18 -44
  286. package/dist/subagents/external/cursor-cli.d.ts +2 -0
  287. package/dist/subagents/external/cursor-cli.js +256 -0
  288. package/dist/subagents/external/dispatch.js +1 -1
  289. package/dist/subagents/external/harness.d.ts +5 -5
  290. package/dist/subagents/external/reconciliation.d.ts +7 -0
  291. package/dist/subagents/external/reconciliation.js +105 -0
  292. package/dist/subagents/external/recovery.d.ts +20 -0
  293. package/dist/subagents/external/recovery.js +71 -0
  294. package/dist/subagents/external/registry.js +2 -0
  295. package/dist/subagents/external/role-warnings.d.ts +17 -0
  296. package/dist/subagents/external/role-warnings.js +42 -0
  297. package/dist/subagents/external/run.d.ts +1 -1
  298. package/dist/subagents/external/run.js +21 -25
  299. package/dist/subagents/format.d.ts +1 -1
  300. package/dist/subagents/format.js +1 -1
  301. package/dist/subagents/grace.d.ts +2 -2
  302. package/dist/subagents/grace.js +3 -3
  303. package/dist/subagents/internal/run.js +8 -6
  304. package/dist/subagents/internal/worker.js +37 -16
  305. package/dist/subagents/result.js +2 -3
  306. package/dist/subagents/run-archive.d.ts +11 -0
  307. package/dist/subagents/run-archive.js +49 -0
  308. package/dist/subagents/run-record.d.ts +13 -15
  309. package/dist/subagents/run-record.js +5 -5
  310. package/dist/subagents/run-registry.d.ts +5 -3
  311. package/dist/subagents/run-registry.js +22 -45
  312. package/dist/subagents/runs.d.ts +51 -54
  313. package/dist/subagents/runs.js +178 -304
  314. package/dist/subagents/task-envelope.js +9 -11
  315. package/dist/subagents/task-settlement.d.ts +3 -0
  316. package/dist/subagents/task-settlement.js +20 -0
  317. package/dist/subagents/types.d.ts +7 -7
  318. package/dist/subagents/workspace-summary.js +5 -1
  319. package/dist/tasks/archive.d.ts +11 -0
  320. package/dist/tasks/archive.js +141 -0
  321. package/dist/tasks/board.d.ts +5 -12
  322. package/dist/tasks/board.js +4 -30
  323. package/dist/tasks/bound-work.d.ts +13 -7
  324. package/dist/tasks/bound-work.js +41 -28
  325. package/dist/tasks/brief.d.ts +39 -15
  326. package/dist/tasks/brief.js +131 -73
  327. package/dist/tasks/budget.d.ts +3 -3
  328. package/dist/tasks/budget.js +9 -4
  329. package/dist/tasks/commands.d.ts +24 -10
  330. package/dist/tasks/commands.js +225 -131
  331. package/dist/tasks/completion.d.ts +12 -0
  332. package/dist/tasks/completion.js +35 -0
  333. package/dist/tasks/contract.d.ts +8 -19
  334. package/dist/tasks/contract.js +41 -45
  335. package/dist/tasks/control.d.ts +138 -0
  336. package/dist/tasks/control.js +1 -0
  337. package/dist/tasks/create.d.ts +4 -2
  338. package/dist/tasks/create.js +13 -7
  339. package/dist/tasks/delivery.d.ts +24 -0
  340. package/dist/tasks/delivery.js +221 -0
  341. package/dist/tasks/file-mutation.d.ts +5 -0
  342. package/dist/tasks/file-mutation.js +38 -0
  343. package/dist/tasks/frontmatter.d.ts +46 -27
  344. package/dist/tasks/frontmatter.js +90 -47
  345. package/dist/tasks/input-receipts.d.ts +7 -0
  346. package/dist/tasks/input-receipts.js +60 -0
  347. package/dist/tasks/loop-log.d.ts +150 -37
  348. package/dist/tasks/loop-log.js +250 -42
  349. package/dist/tasks/mutation-lock.d.ts +7 -5
  350. package/dist/tasks/mutation-lock.js +32 -9
  351. package/dist/tasks/receipts.d.ts +19 -0
  352. package/dist/tasks/receipts.js +48 -0
  353. package/dist/tasks/session-path.d.ts +3 -3
  354. package/dist/tasks/session-path.js +5 -5
  355. package/dist/tasks/state.d.ts +93 -0
  356. package/dist/tasks/state.js +156 -0
  357. package/dist/tasks/store.d.ts +86 -54
  358. package/dist/tasks/store.js +256 -156
  359. package/dist/tools/bash.d.ts +8 -10
  360. package/dist/tools/bash.js +27 -40
  361. package/dist/tools/contract/details.d.ts +6 -6
  362. package/dist/tools/contract/details.js +6 -6
  363. package/dist/tools/contract/execution-trace.d.ts +4 -0
  364. package/dist/tools/contract/execution-trace.js +23 -0
  365. package/dist/tools/contract/names.d.ts +7 -0
  366. package/dist/tools/contract/names.js +22 -0
  367. package/dist/tools/contract/presentation.js +6 -2
  368. package/dist/tools/edit.d.ts +1 -0
  369. package/dist/tools/edit.js +46 -43
  370. package/dist/tools/event-manage.d.ts +3 -1
  371. package/dist/tools/event-manage.js +34 -33
  372. package/dist/tools/glob.js +5 -5
  373. package/dist/tools/grep.js +2 -2
  374. package/dist/tools/index.d.ts +17 -20
  375. package/dist/tools/index.js +28 -22
  376. package/dist/tools/job.d.ts +4 -2
  377. package/dist/tools/job.js +11 -8
  378. package/dist/tools/memory-manage.d.ts +5 -3
  379. package/dist/tools/memory-manage.js +32 -25
  380. package/dist/tools/read.js +1 -1
  381. package/dist/tools/registry.d.ts +19 -19
  382. package/dist/tools/registry.js +65 -34
  383. package/dist/tools/send-media.d.ts +2 -2
  384. package/dist/tools/send-media.js +3 -3
  385. package/dist/tools/session-search.d.ts +3 -1
  386. package/dist/tools/session-search.js +8 -6
  387. package/dist/tools/skill.d.ts +2 -2
  388. package/dist/tools/skill.js +24 -10
  389. package/dist/tools/subagent-manage.d.ts +2 -8
  390. package/dist/tools/subagent-manage.js +26 -19
  391. package/dist/tools/subagent.d.ts +0 -2
  392. package/dist/tools/subagent.js +3 -8
  393. package/dist/tools/task-manage/control-tools.d.ts +4 -0
  394. package/dist/tools/task-manage/control-tools.js +65 -0
  395. package/dist/tools/task-manage/create.js +3 -2
  396. package/dist/tools/task-manage/factory.d.ts +12 -6
  397. package/dist/tools/task-manage/factory.js +73 -58
  398. package/dist/tools/task-manage/lifecycle.d.ts +7 -12
  399. package/dist/tools/task-manage/lifecycle.js +119 -65
  400. package/dist/tools/task-manage/log-view.js +10 -7
  401. package/dist/tools/task-manage/schema.d.ts +21 -26
  402. package/dist/tools/task-manage/schema.js +29 -35
  403. package/dist/tools/task-manage/shared.d.ts +8 -39
  404. package/dist/tools/task-manage/shared.js +20 -69
  405. package/dist/tools/task-manage/step-tools.d.ts +5 -0
  406. package/dist/tools/task-manage/step-tools.js +103 -0
  407. package/dist/tools/task-manage/types.d.ts +33 -21
  408. package/dist/tools/web-cache.d.ts +3 -3
  409. package/dist/tools/web-cache.js +12 -12
  410. package/dist/tools/web-fetch.d.ts +2 -2
  411. package/dist/tools/web-fetch.js +7 -7
  412. package/dist/tools/write-content.d.ts +1 -0
  413. package/dist/tools/write-content.js +7 -2
  414. package/dist/tools/write.d.ts +1 -0
  415. package/dist/tools/write.js +1 -0
  416. package/dist/tui/cli.d.ts +17 -5
  417. package/dist/tui/cli.js +90 -27
  418. package/dist/tui/client.d.ts +26 -0
  419. package/dist/tui/client.js +157 -0
  420. package/dist/tui/colors.d.ts +0 -1
  421. package/dist/tui/colors.js +0 -1
  422. package/dist/tui/commands.d.ts +10 -51
  423. package/dist/tui/commands.js +16 -39
  424. package/dist/tui/frontend.d.ts +2 -2
  425. package/dist/tui/frontend.js +2 -2
  426. package/dist/tui/pitui-frontend.d.ts +0 -2
  427. package/dist/tui/pitui-frontend.js +1 -6
  428. package/dist/tui/render.d.ts +62 -0
  429. package/dist/tui/render.js +123 -0
  430. package/dist/tui/session.d.ts +92 -0
  431. package/dist/tui/session.js +317 -0
  432. package/dist/usage/ledger.d.ts +9 -4
  433. package/dist/usage/ledger.js +2 -0
  434. package/dist/usage/render.d.ts +6 -1
  435. package/dist/usage/render.js +20 -15
  436. package/dist/web/search-providers.js +0 -33
  437. package/dist/webapi/auth.d.ts +13 -0
  438. package/dist/webapi/auth.js +29 -0
  439. package/dist/webapi/config.d.ts +29 -0
  440. package/dist/webapi/config.js +100 -0
  441. package/dist/webapi/errors.d.ts +39 -0
  442. package/dist/webapi/errors.js +32 -0
  443. package/dist/webapi/http.d.ts +25 -0
  444. package/dist/webapi/http.js +4 -0
  445. package/dist/webapi/ids.d.ts +9 -0
  446. package/dist/webapi/ids.js +20 -0
  447. package/dist/webapi/input.d.ts +17 -0
  448. package/dist/webapi/input.js +229 -0
  449. package/dist/webapi/items.d.ts +37 -0
  450. package/dist/webapi/items.js +48 -0
  451. package/dist/webapi/key-command.d.ts +2 -0
  452. package/dist/webapi/key-command.js +110 -0
  453. package/dist/webapi/limits.d.ts +47 -0
  454. package/dist/webapi/limits.js +48 -0
  455. package/dist/webapi/request-policy.d.ts +17 -0
  456. package/dist/webapi/request-policy.js +160 -0
  457. package/dist/webapi/response-record.d.ts +68 -0
  458. package/dist/webapi/response-record.js +58 -0
  459. package/dist/webapi/response-state.d.ts +90 -0
  460. package/dist/webapi/response-state.js +347 -0
  461. package/dist/webapi/routes/conversations.d.ts +8 -0
  462. package/dist/webapi/routes/conversations.js +80 -0
  463. package/dist/webapi/routes/models.d.ts +3 -0
  464. package/dist/webapi/routes/models.js +12 -0
  465. package/dist/webapi/routes/responses.d.ts +8 -0
  466. package/dist/webapi/routes/responses.js +118 -0
  467. package/dist/webapi/routes/websocket.d.ts +9 -0
  468. package/dist/webapi/routes/websocket.js +328 -0
  469. package/dist/webapi/server.d.ts +24 -0
  470. package/dist/webapi/server.js +229 -0
  471. package/dist/webapi/service.d.ts +130 -0
  472. package/dist/webapi/service.js +588 -0
  473. package/dist/webapi/store.d.ts +46 -0
  474. package/dist/webapi/store.js +245 -0
  475. package/dist/webapi/stream.d.ts +13 -0
  476. package/dist/webapi/stream.js +76 -0
  477. package/dist/webapi/transport.d.ts +43 -0
  478. package/dist/webapi/transport.js +100 -0
  479. package/examples/sub-agents/README.md +23 -16
  480. package/examples/sub-agents/agents/claude-high.md +1 -1
  481. package/examples/sub-agents/agents/claude-main.md +1 -1
  482. package/examples/sub-agents/agents/codex-flash.md +1 -1
  483. package/examples/sub-agents/agents/codex-high.md +1 -1
  484. package/examples/sub-agents/agents/codex-main.md +4 -4
  485. package/examples/sub-agents/agents/cursor-high.md +22 -0
  486. package/examples/sub-agents/agents/cursor-main.md +22 -0
  487. package/examples/sub-agents/agents/glm-flash.md +1 -1
  488. package/examples/sub-agents/agents/glm-high.md +2 -2
  489. package/examples/sub-agents/agents/scout.md +30 -0
  490. package/package.json +13 -7
  491. package/dist/channel/channel-paths.d.ts +0 -16
  492. package/dist/channel/channel-paths.js +0 -53
  493. package/dist/channel/commands.d.ts +0 -32
  494. package/dist/channel/commands.js +0 -109
  495. package/dist/channel/project-scope-store.d.ts +0 -51
  496. package/dist/channel/project-scope-store.js +0 -112
  497. package/dist/dingtalk/channel-queue.d.ts +0 -19
  498. package/dist/dingtalk/handler.d.ts +0 -90
  499. package/dist/memory/channel-maintenance-queue.d.ts +0 -5
  500. package/dist/memory/channel-maintenance-queue.js +0 -8
  501. package/dist/runtime/task-driver.d.ts +0 -100
  502. package/dist/runtime/task-driver.js +0 -417
  503. package/dist/runtime/task-migration.d.ts +0 -30
  504. package/dist/runtime/task-migration.js +0 -465
  505. package/dist/runtime/task-wake.d.ts +0 -46
  506. package/dist/runtime/task-wake.js +0 -32
  507. package/dist/runtime/turn-handler.d.ts +0 -47
  508. package/dist/runtime/turn-handler.js +0 -318
  509. package/dist/security/project-scope.d.ts +0 -45
  510. package/dist/security/project-scope.js +0 -105
  511. package/dist/shared/wake-claim.d.ts +0 -23
  512. package/dist/shared/wake-claim.js +0 -26
  513. package/dist/skills/validation.d.ts +0 -8
  514. package/dist/skills/validation.js +0 -91
  515. package/dist/skills/workspace.d.ts +0 -33
  516. package/dist/skills/workspace.js +0 -116
  517. package/dist/tasks/steer.d.ts +0 -8
  518. package/dist/tasks/steer.js +0 -79
  519. package/dist/tasks/ticket.d.ts +0 -71
  520. package/dist/tasks/ticket.js +0 -138
  521. package/dist/tools/task-manage/step-end.d.ts +0 -11
  522. package/dist/tools/task-manage/step-end.js +0 -117
  523. package/dist/tui/app.d.ts +0 -16
  524. package/dist/tui/app.js +0 -166
  525. package/dist/tui/terminal-context.d.ts +0 -27
  526. package/dist/tui/terminal-context.js +0 -84
  527. package/dist/tui/terminal-media-sender.d.ts +0 -9
  528. package/dist/tui/terminal-media-sender.js +0 -15
  529. package/dist/tui/turn-controller.d.ts +0 -64
  530. package/dist/tui/turn-controller.js +0 -311
  531. /package/dist/{dingtalk/handler.js → channel/transport.js} +0 -0
@@ -0,0 +1,328 @@
1
+ import * as log from "../../log.js";
2
+ import { errorMessage } from "../../shared/text-utils.js";
3
+ import { badRequest, serverError, WebApiError, wsErrorEnvelope } from "../errors.js";
4
+ import { channelIdOf, isStreamId, newId } from "../ids.js";
5
+ import { parseInput } from "../input.js";
6
+ import { MAX_PENDING_STEERS, MAX_WS_INFLIGHT_RESPONSES, MAX_WS_PENDING_BYTES, MAX_WS_PENDING_REQUESTS, MAX_WS_STREAMS, } from "../limits.js";
7
+ import { validateCreateRequest } from "../request-policy.js";
8
+ const DEFAULT_LANE = "";
9
+ /** Close a connection whose client reads so slowly that this much is waiting to be written. */
10
+ const MAX_BUFFERED_BYTES = 32 * 1024 * 1024;
11
+ class Connection {
12
+ constructor(socket, principal, service, maxMs) {
13
+ this.socket = socket;
14
+ this.principal = principal;
15
+ this.service = service;
16
+ /** Responses created on this connection (and their successors): the only ones it may steer. */
17
+ this.responses = new Map();
18
+ /** Each lane runs its responses one after another. */
19
+ this.lanes = new Map();
20
+ this.inflight = 0;
21
+ /** Requests accepted but not yet started, and the bytes they hold. */
22
+ this.pendingRequests = 0;
23
+ this.pendingBytes = 0;
24
+ this.waiting = [];
25
+ this.closed = false;
26
+ this.successorWatchers = new Map();
27
+ /** The lane each response (and each successor) is on, so a late successor lands on the right one. */
28
+ this.laneOf = new Map();
29
+ this.timer = setTimeout(() => this.limitReached(), maxMs);
30
+ this.timer.unref?.();
31
+ socket.on("message", (data) => {
32
+ void this.onMessage(data).catch((error) => {
33
+ log.logWarn("webapi.ws.handler_failed", "WebSocket message handler failed", {
34
+ reason: errorMessage(error),
35
+ });
36
+ this.sendError(serverError());
37
+ });
38
+ });
39
+ socket.on("close", () => this.onClose());
40
+ socket.on("error", () => this.onClose());
41
+ }
42
+ // ---- wire ------------------------------------------------------------------------------
43
+ send(message, streamId) {
44
+ if (this.closed || this.socket.readyState !== this.socket.OPEN)
45
+ return;
46
+ const body = streamId ? { ...message, stream_id: streamId } : message;
47
+ this.socket.send(JSON.stringify(body));
48
+ if (this.socket.bufferedAmount > MAX_BUFFERED_BYTES) {
49
+ log.logWarn("webapi.ws.slow_client", "WebSocket closed: the client is not reading");
50
+ this.socket.close(1013, "client too slow");
51
+ }
52
+ }
53
+ sendError(error, streamId) {
54
+ if (this.closed || this.socket.readyState !== this.socket.OPEN)
55
+ return;
56
+ this.socket.send(JSON.stringify(wsErrorEnvelope(error, streamId)));
57
+ }
58
+ limitReached() {
59
+ this.sendError(new WebApiError(400, "invalid_request_error", "websocket_connection_limit_reached", "This WebSocket connection reached its 60 minute limit; open a new connection to continue."));
60
+ this.socket.close(1000, "connection limit reached");
61
+ }
62
+ onClose() {
63
+ if (this.closed)
64
+ return;
65
+ this.closed = true;
66
+ clearTimeout(this.timer);
67
+ // Whatever this connection was waiting for or running goes with it (D19).
68
+ for (const live of this.responses.values()) {
69
+ if (!live.terminal)
70
+ void this.service.cancel(live);
71
+ }
72
+ for (const release of this.waiting.splice(0))
73
+ release();
74
+ }
75
+ // ---- messages --------------------------------------------------------------------------
76
+ async onMessage(data) {
77
+ let event;
78
+ try {
79
+ const parsed = JSON.parse(data.toString());
80
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
81
+ throw new Error("not an object");
82
+ event = parsed;
83
+ }
84
+ catch {
85
+ this.sendError(badRequest("invalid_json", "A WebSocket message must be a JSON object."));
86
+ return;
87
+ }
88
+ const streamId = typeof event.stream_id === "string" ? event.stream_id : undefined;
89
+ try {
90
+ switch (event.type) {
91
+ case "response.create":
92
+ await this.create(event, Buffer.byteLength(data.toString()));
93
+ return;
94
+ case "response.steer":
95
+ await this.steer(event);
96
+ return;
97
+ default:
98
+ throw badRequest("invalid_value", "Only `response.create` and `response.steer` events are accepted.", "type");
99
+ }
100
+ }
101
+ catch (error) {
102
+ if (error instanceof WebApiError)
103
+ this.sendError(error, streamId);
104
+ else
105
+ throw error;
106
+ }
107
+ }
108
+ // ---- response.create -------------------------------------------------------------------
109
+ laneFor(event) {
110
+ const streamId = event.stream_id;
111
+ if (streamId === undefined || streamId === null)
112
+ return DEFAULT_LANE;
113
+ if (!isStreamId(streamId)) {
114
+ throw new WebApiError(400, "invalid_request_error", "invalid_stream_id", "`stream_id` must be 1–64 letters, digits, `-` or `_`.", "stream_id");
115
+ }
116
+ if (!this.lanes.has(streamId) &&
117
+ [...this.lanes.keys()].filter((id) => id !== DEFAULT_LANE).length >= MAX_WS_STREAMS) {
118
+ throw new WebApiError(400, "invalid_request_error", "websocket_stream_limit_reached", `A connection may use at most ${MAX_WS_STREAMS} named streams.`, "stream_id");
119
+ }
120
+ return streamId;
121
+ }
122
+ async create(event, rawBytes) {
123
+ const lane = this.laneFor(event);
124
+ const { type: _type, stream_id: _streamId, ...fields } = event;
125
+ const request = validateCreateRequest(fields, "websocket");
126
+ const input = parseInput(request.input);
127
+ const streamId = lane === DEFAULT_LANE ? undefined : lane;
128
+ // A request waiting for its lane holds its whole input; without a bound a client could queue
129
+ // any amount behind one slow response.
130
+ if (this.pendingRequests >= MAX_WS_PENDING_REQUESTS || this.pendingBytes + rawBytes > MAX_WS_PENDING_BYTES) {
131
+ throw new WebApiError(429, "rate_limit_error", "websocket_backlog_full", "Too many requests are waiting on this connection; wait for some to finish.");
132
+ }
133
+ this.pendingRequests++;
134
+ this.pendingBytes += rawBytes;
135
+ let started = false;
136
+ const start = () => {
137
+ if (started)
138
+ return;
139
+ started = true;
140
+ this.pendingRequests--;
141
+ this.pendingBytes -= rawBytes;
142
+ };
143
+ // Each lane is a chain: a response starts when the one before it on the lane has ended.
144
+ const previous = this.lanes.get(lane) ?? Promise.resolve();
145
+ const run = previous.then(async () => {
146
+ if (this.closed)
147
+ return start();
148
+ await this.acquire();
149
+ start();
150
+ try {
151
+ if (this.closed)
152
+ return;
153
+ const live = await this.service.create(this.principal, request, input);
154
+ this.responses.set(live.id, live);
155
+ this.laneOf.set(live.id, streamId);
156
+ await this.follow(live, streamId);
157
+ }
158
+ catch (error) {
159
+ if (error instanceof WebApiError)
160
+ this.sendError(error, streamId);
161
+ else {
162
+ log.logWarn("webapi.ws.create_failed", "WebSocket response.create failed", {
163
+ reason: errorMessage(error),
164
+ });
165
+ this.sendError(serverError(), streamId);
166
+ }
167
+ }
168
+ finally {
169
+ this.release();
170
+ }
171
+ });
172
+ this.lanes.set(lane, run);
173
+ }
174
+ /** Forward `live`'s events, and its successors', until the chain of responses ends. */
175
+ async follow(first, streamId) {
176
+ let current = first;
177
+ while (current) {
178
+ const live = current;
179
+ current = await this.forward(live, streamId);
180
+ }
181
+ }
182
+ /** Send one response's events; resolves with its successor when it ended because it was steered. */
183
+ forward(live, streamId) {
184
+ return new Promise((resolve) => {
185
+ let successor;
186
+ this.successorWatchers.set(live.id, (next) => {
187
+ successor = next;
188
+ });
189
+ live.subscribe(0, {
190
+ onEvent: (logged) => this.send(logged, streamId),
191
+ onEnd: () => {
192
+ // The successor of a steered response is made in the same tick the response ends.
193
+ queueMicrotask(() => {
194
+ this.successorWatchers.delete(live.id);
195
+ resolve(successor);
196
+ });
197
+ },
198
+ });
199
+ });
200
+ }
201
+ async acquire() {
202
+ while (this.inflight >= MAX_WS_INFLIGHT_RESPONSES && !this.closed) {
203
+ await new Promise((resolve) => this.waiting.push(resolve));
204
+ }
205
+ this.inflight++;
206
+ }
207
+ release() {
208
+ this.inflight--;
209
+ this.waiting.shift()?.();
210
+ }
211
+ // ---- response.steer --------------------------------------------------------------------
212
+ steerFailed(code, message, target, steerId) {
213
+ this.send({
214
+ type: "response.steer.failed",
215
+ sequence_number: target?.logLength ?? 0,
216
+ error: { type: "invalid_request_error", code, message },
217
+ steer: { ...(steerId ? { id: steerId } : {}), input: null },
218
+ });
219
+ }
220
+ async steer(event) {
221
+ const targetId = event.previous_response_id;
222
+ const target = typeof targetId === "string" ? this.responses.get(targetId) : undefined;
223
+ if (!target) {
224
+ this.steerFailed("response_not_found", "That response is not on this connection.", undefined);
225
+ return;
226
+ }
227
+ if (target.terminal) {
228
+ this.steerFailed("response_already_completed", "That response has already ended.", target);
229
+ return;
230
+ }
231
+ if (target.record.request_scoped) {
232
+ this.steerFailed("response_not_active", "Steering needs a persistent conversation; create the response with `conversation`.", target);
233
+ return;
234
+ }
235
+ if (target.status !== "in_progress") {
236
+ this.steerFailed("response_not_active", "That response is not running yet.", target);
237
+ return;
238
+ }
239
+ let input;
240
+ try {
241
+ input = parseInput(event.input);
242
+ }
243
+ catch (error) {
244
+ this.steerFailed("invalid_input", error instanceof WebApiError ? error.message : "The input is not valid.", target);
245
+ return;
246
+ }
247
+ if (input.context.some((message) => message.role !== "user")) {
248
+ // It joins the running turn as the user's words; another role cannot be said that way.
249
+ this.steerFailed("invalid_input", "A steering input is user messages only.", target);
250
+ return;
251
+ }
252
+ if (this.service.pendingSteersOf(target.id).length >= MAX_PENDING_STEERS) {
253
+ this.steerFailed("too_many_pending_steers", "Too many steering inputs are waiting for this response.", target);
254
+ return;
255
+ }
256
+ const steer = {
257
+ steerId: newId("steer"),
258
+ successorId: newId("resp"),
259
+ targetId: target.id,
260
+ conversationId: target.record.conversation_id,
261
+ principal: this.principal,
262
+ input,
263
+ onSuccessor: (successor) => {
264
+ const follows = successor.record.previous_response_id;
265
+ this.adopt((follows !== null ? this.responses.get(follows) : undefined) ?? target, successor);
266
+ },
267
+ };
268
+ this.service.registerSteer(steer);
269
+ let result;
270
+ try {
271
+ result = await this.service.ingress.steer(channelIdOf(target.record.conversation_id), {
272
+ channelId: channelIdOf(target.record.conversation_id),
273
+ user: this.principal.name,
274
+ userName: this.principal.name,
275
+ text: input.text,
276
+ ...(input.attachments.length > 0 ? { attachments: input.attachments } : {}),
277
+ ref: steer.successorId,
278
+ ts: String(Date.now()),
279
+ ...(this.principal.desks ? { allowedDesks: this.principal.desks } : {}),
280
+ });
281
+ }
282
+ catch (error) {
283
+ this.service.forgetSteer(steer.successorId);
284
+ throw error;
285
+ }
286
+ if (result.kind === "rejected") {
287
+ this.service.forgetSteer(steer.successorId);
288
+ this.steerFailed(result.code, "The running turn could not take this input.", target, steer.steerId);
289
+ return;
290
+ }
291
+ this.send({
292
+ type: "response.steer.accepted",
293
+ sequence_number: target.logLength,
294
+ steer: { id: steer.steerId, previous_response_id: target.id },
295
+ });
296
+ }
297
+ /** A steering input became a response: forward it where the response it follows was going. */
298
+ adopt(target, successor) {
299
+ this.responses.set(successor.id, successor);
300
+ this.laneOf.set(successor.id, this.laneOf.get(target.id));
301
+ const watcher = this.successorWatchers.get(target.id);
302
+ if (watcher) {
303
+ watcher(successor);
304
+ return;
305
+ }
306
+ // The response it follows has already been forwarded to its end: start a new forwarding.
307
+ void this.follow(successor, this.laneOf.get(target.id));
308
+ }
309
+ }
310
+ export function registerWebSocketRoute(app, context) {
311
+ const { service, maxWebSocketMs } = context;
312
+ app.route({
313
+ method: "GET",
314
+ url: "/v1/responses",
315
+ handler: async (_request, reply) => reply.status(426).send({
316
+ error: {
317
+ message: "This endpoint is for WebSocket connections; upgrade the request.",
318
+ type: "invalid_request_error",
319
+ param: null,
320
+ code: "upgrade_required",
321
+ },
322
+ }),
323
+ wsHandler: (socket, request) => {
324
+ context.auditHijacked(request, 101);
325
+ new Connection(socket, request.principal, service, maxWebSocketMs);
326
+ },
327
+ });
328
+ }
@@ -0,0 +1,24 @@
1
+ import { type FastifyInstance } from "fastify";
2
+ import type { SecurityLogEvent } from "../security/types.js";
3
+ import type { WebApiConfig } from "./config.js";
4
+ import { type Listener } from "./http.js";
5
+ import type { WebApiService } from "./service.js";
6
+ export interface ServerDeps {
7
+ config: WebApiConfig;
8
+ service: WebApiService;
9
+ /** Where the local socket is created; its directory is made private. */
10
+ socketPath: string;
11
+ audit: (event: SecurityLogEvent) => void;
12
+ maxWebSocketMs?: number;
13
+ }
14
+ export declare class WebApiServer {
15
+ private readonly deps;
16
+ private readonly apps;
17
+ constructor(deps: ServerDeps);
18
+ /** Create `app` for the instance under test without listening (route-level tests use `inject`). */
19
+ static build(listener: Listener, deps: ServerDeps): Promise<FastifyInstance>;
20
+ /** Opens every listener or none: a failure after the first one closes what was already open. */
21
+ start(): Promise<void>;
22
+ private listen;
23
+ stop(): Promise<void>;
24
+ }
@@ -0,0 +1,229 @@
1
+ /**
2
+ * The Web API's HTTP servers (spec 061, D24): Fastify, on the local socket and — when configured —
3
+ * on TCP. Two instances share one route set (so a request knows which listener it came in on, which
4
+ * decides whether a key and a Host check apply); everything that guards the door lives in the
5
+ * `onRequest` hook, which runs before the body is read (INV-6).
6
+ */
7
+ import { chmod, mkdir, readFile, rm } from "node:fs/promises";
8
+ import { dirname } from "node:path";
9
+ import rateLimit from "@fastify/rate-limit";
10
+ import websocket from "@fastify/websocket";
11
+ import Fastify from "fastify";
12
+ import * as log from "../log.js";
13
+ import { errorMessage } from "../shared/text-utils.js";
14
+ import { authenticate, LOCAL_PRINCIPAL } from "./auth.js";
15
+ import { badRequest, forbidden, notFound, serverError, tooManyRequests, unauthorized, WebApiError } from "./errors.js";
16
+ import { sendError } from "./http.js";
17
+ import { KEEP_ALIVE_TIMEOUT_MS, MAX_BODY_BYTES, MAX_CONNECTIONS, MAX_WS_CONNECTION_MS, RATE_LIMIT_PER_MINUTE, REQUEST_TIMEOUT_MS, } from "./limits.js";
18
+ import { registerConversationRoutes } from "./routes/conversations.js";
19
+ import { registerModelRoutes } from "./routes/models.js";
20
+ import { registerResponseRoutes } from "./routes/responses.js";
21
+ import { registerWebSocketRoute } from "./routes/websocket.js";
22
+ /** Hosts a loopback TCP listener answers to: a rebinding page cannot make a browser send these. */
23
+ function allowedHosts(config) {
24
+ const tcp = config.tcp;
25
+ if (!tcp?.loopback)
26
+ return new Set();
27
+ const hosts = new Set([`127.0.0.1:${tcp.port}`, `localhost:${tcp.port}`, `[::1]:${tcp.port}`]);
28
+ hosts.add(`${tcp.host.includes(":") ? `[${tcp.host}]` : tcp.host}:${tcp.port}`);
29
+ return hosts;
30
+ }
31
+ function paramOf(error) {
32
+ const first = error.validation?.[0];
33
+ if (!first)
34
+ return null;
35
+ const extra = first.params?.additionalProperty;
36
+ const path = first.instancePath.replace(/^\//, "").replace(/\//g, ".");
37
+ return extra ? (path ? `${path}.${extra}` : extra) : path || null;
38
+ }
39
+ /** Whatever Fastify or a route throws, in the API's own error format. */
40
+ function toWebApiError(error) {
41
+ if (error instanceof WebApiError)
42
+ return error;
43
+ const failure = error;
44
+ if (failure.validation) {
45
+ const param = paramOf(failure);
46
+ return badRequest(failure.validation[0]?.keyword === "additionalProperties" ? "unknown_parameter" : "invalid_value", param ? `Invalid \`${param}\`.` : "The request is not valid.", param ?? undefined);
47
+ }
48
+ switch (failure.code) {
49
+ case "FST_ERR_CTP_BODY_TOO_LARGE":
50
+ return new WebApiError(413, "invalid_request_error", "request_too_large", "The request body is too large.");
51
+ case "FST_ERR_CTP_INVALID_MEDIA_TYPE":
52
+ return new WebApiError(415, "invalid_request_error", "unsupported_media_type", "Send the body as application/json.");
53
+ case "FST_ERR_CTP_EMPTY_JSON_BODY":
54
+ return badRequest("invalid_json", "The request body is empty; send a JSON object.");
55
+ case "FST_ERR_CTP_INVALID_CONTENT_LENGTH":
56
+ case "FST_ERR_CTP_INVALID_JSON_BODY":
57
+ return badRequest("invalid_json", "The request body is not valid JSON.");
58
+ }
59
+ if (error instanceof SyntaxError || failure.statusCode === 400) {
60
+ return badRequest("invalid_json", "The request body is not valid JSON.");
61
+ }
62
+ log.logWarn("webapi.request.failed", "Request failed", { reason: errorMessage(error) });
63
+ return serverError();
64
+ }
65
+ async function buildApp(listener, deps, https) {
66
+ const app = Fastify({
67
+ logger: false,
68
+ ...(https ? { https } : {}),
69
+ bodyLimit: MAX_BODY_BYTES,
70
+ requestTimeout: REQUEST_TIMEOUT_MS,
71
+ connectionTimeout: 0,
72
+ keepAliveTimeout: KEEP_ALIVE_TIMEOUT_MS,
73
+ onProtoPoisoning: "error",
74
+ onConstructorPoisoning: "error",
75
+ trustProxy: false,
76
+ ajv: { customOptions: { removeAdditional: false, coerceTypes: "array", useDefaults: true, allErrors: false } },
77
+ });
78
+ app.server.maxConnections = MAX_CONNECTIONS;
79
+ // JSON only: Fastify would otherwise also accept text/plain bodies.
80
+ app.removeContentTypeParser("text/plain");
81
+ app.decorateRequest("principal", undefined);
82
+ app.addHook("onRequest", async (request, reply) => {
83
+ if (request.headers.origin === undefined)
84
+ return;
85
+ // Write to raw so hijacked SSE responses retain these headers too. Register before
86
+ // rate limiting and authentication so browsers can read their error responses.
87
+ reply.raw.setHeader("access-control-allow-origin", "*");
88
+ reply.raw.setHeader("access-control-expose-headers", "Retry-After");
89
+ });
90
+ if (listener === "tcp") {
91
+ // Counted per key, after the key check and before the body is read. Not per address: behind a
92
+ // reverse proxy every caller has the proxy's address, so one busy key would lock out the rest.
93
+ // A request without a valid key is refused before it gets here; flooding is the proxy's to limit.
94
+ await app.register(rateLimit, {
95
+ max: RATE_LIMIT_PER_MINUTE,
96
+ timeWindow: "1 minute",
97
+ hook: "preParsing",
98
+ keyGenerator: (request) => request.principal.name,
99
+ errorResponseBuilder: (_request, context) => tooManyRequests("Too many requests with this key.", Math.ceil(context.ttl / 1000)),
100
+ });
101
+ }
102
+ const hosts = allowedHosts(deps.config);
103
+ const remoteOf = (request) => (listener === "socket" ? "socket" : request.ip);
104
+ const refuse = (request, reply, reason, error) => {
105
+ deps.audit({
106
+ type: "webapi-auth",
107
+ tool: "webapi",
108
+ listener,
109
+ reason,
110
+ remote: remoteOf(request),
111
+ method: request.method,
112
+ path: request.url.split("?")[0] ?? "",
113
+ });
114
+ return sendError(reply, error);
115
+ };
116
+ app.addHook("onRequest", async (request, reply) => {
117
+ if (listener === "tcp" && hosts.size > 0 && !hosts.has(String(request.headers.host ?? "").toLowerCase())) {
118
+ return refuse(request, reply, "host", forbidden("host_not_allowed", "The Host header is not one this server answers to."));
119
+ }
120
+ if (request.method === "OPTIONS" &&
121
+ request.headers.origin !== undefined &&
122
+ request.headers["access-control-request-method"] !== undefined) {
123
+ // Preflight carries no bearer key; only the subsequent API request is authenticated.
124
+ reply.header("access-control-allow-methods", "GET, POST, DELETE, OPTIONS");
125
+ reply.header("vary", "Access-Control-Request-Headers");
126
+ const headers = request.headers["access-control-request-headers"];
127
+ if (headers)
128
+ reply.header("access-control-allow-headers", headers);
129
+ return reply.code(204).send();
130
+ }
131
+ if (listener === "socket") {
132
+ request.principal = LOCAL_PRINCIPAL;
133
+ return;
134
+ }
135
+ const header = request.headers.authorization;
136
+ const principal = authenticate(header, deps.config.keys);
137
+ if (!principal)
138
+ return refuse(request, reply, header ? "invalid_key" : "missing_key", unauthorized());
139
+ request.principal = principal;
140
+ });
141
+ const audit = (request, status) => deps.audit({
142
+ type: "webapi-request",
143
+ tool: "webapi",
144
+ listener,
145
+ principal: request.principal?.name ?? "-",
146
+ method: request.method,
147
+ path: request.url.split("?")[0] ?? "",
148
+ status,
149
+ ...(request.auditConversationId ? { conversationId: request.auditConversationId } : {}),
150
+ });
151
+ app.addHook("onResponse", async (request, reply) => audit(request, reply.statusCode));
152
+ app.setErrorHandler((error, _request, reply) => sendError(reply, toWebApiError(error)));
153
+ app.setNotFoundHandler((_request, reply) => sendError(reply, notFound("The requested endpoint", "not_found")));
154
+ await app.register(websocket, { options: { maxPayload: MAX_BODY_BYTES } });
155
+ const context = {
156
+ service: deps.service,
157
+ listener,
158
+ maxWebSocketMs: deps.maxWebSocketMs ?? MAX_WS_CONNECTION_MS,
159
+ auditHijacked: (request, status) => audit(request, status),
160
+ };
161
+ registerModelRoutes(app);
162
+ registerConversationRoutes(app, context);
163
+ registerResponseRoutes(app, context);
164
+ registerWebSocketRoute(app, context);
165
+ await app.ready();
166
+ return app;
167
+ }
168
+ export class WebApiServer {
169
+ constructor(deps) {
170
+ this.deps = deps;
171
+ this.apps = [];
172
+ }
173
+ /** Create `app` for the instance under test without listening (route-level tests use `inject`). */
174
+ static build(listener, deps) {
175
+ return buildApp(listener, deps, undefined);
176
+ }
177
+ /** Opens every listener or none: a failure after the first one closes what was already open. */
178
+ async start() {
179
+ try {
180
+ await this.listen();
181
+ }
182
+ catch (error) {
183
+ await this.stop().catch(() => undefined);
184
+ throw error;
185
+ }
186
+ }
187
+ async listen() {
188
+ const { config, socketPath } = this.deps;
189
+ if (config.socket) {
190
+ const app = await buildApp("socket", this.deps, undefined);
191
+ this.apps.push(app);
192
+ await mkdir(dirname(socketPath), { recursive: true, mode: 0o700 });
193
+ await chmod(dirname(socketPath), 0o700);
194
+ // A stale socket file is safe to remove: the daemon lock says no other runtime owns this home.
195
+ await rm(socketPath, { force: true });
196
+ await app.listen({ path: socketPath });
197
+ await chmod(socketPath, 0o600);
198
+ log.logInfoEvent("webapi.listening", "Web API listening on the local socket", {
199
+ fields: { socket: socketPath },
200
+ });
201
+ }
202
+ if (config.tcp) {
203
+ const https = config.tls
204
+ ? { cert: await readFile(config.tls.cert), key: await readFile(config.tls.key) }
205
+ : undefined;
206
+ const app = await buildApp("tcp", this.deps, https);
207
+ this.apps.push(app);
208
+ await app.listen({ host: config.tcp.host, port: config.tcp.port });
209
+ log.logInfoEvent("webapi.listening", "Web API listening on TCP", {
210
+ fields: { host: config.tcp.host, port: config.tcp.port, tls: Boolean(https) },
211
+ });
212
+ if (!https && !config.tcp.loopback) {
213
+ // Allowed for a TLS-terminating proxy or a trusted LAN, but a key is shell access and
214
+ // crosses this network in the clear: the operator should see that every start.
215
+ log.logWarn("webapi.tcp.plaintext", "Web API serves a non-loopback address without TLS", {
216
+ fields: { host: config.tcp.host, port: config.tcp.port },
217
+ });
218
+ }
219
+ }
220
+ }
221
+ async stop() {
222
+ // Open connections (a running stream, a WebSocket) must not hold shutdown up.
223
+ await Promise.all(this.apps.splice(0).map(async (app) => {
224
+ app.server.closeAllConnections?.();
225
+ await app.close();
226
+ }));
227
+ await rm(this.deps.socketPath, { force: true });
228
+ }
229
+ }