@cohortapp/agent-sdk 2.17.0 → 2.18.5

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/.claude/settings.json +18 -0
  2. package/.env.example +18 -5
  3. package/README.md +1 -0
  4. package/bin/maestro.mjs +62 -0
  5. package/docs/guides/billing-console-keys.md +60 -0
  6. package/docs/guides/front-door-session.md +54 -9
  7. package/docs/guides/mac-mini.md +20 -25
  8. package/docs/guides/setup-wizard.md +1 -1
  9. package/docs/runbooks/fleet-rollout.md +156 -0
  10. package/docs/runbooks/mac-mini-bootstrap.md +12 -14
  11. package/lib/action-executor.js +19 -3
  12. package/lib/budget-guard.mjs +279 -3
  13. package/lib/channels/base-adapter.mjs +3 -1
  14. package/lib/channels/contract.mjs +2 -1
  15. package/lib/channels/inbox-item.mjs +8 -0
  16. package/lib/claude-bin.mjs +5 -6
  17. package/lib/cli/doctor-checks.mjs +141 -10
  18. package/lib/cli/global-setup-extras.mjs +5 -1
  19. package/lib/cli/inbox.mjs +100 -15
  20. package/lib/cli/seat-auth.mjs +463 -0
  21. package/lib/cli/session.mjs +80 -12
  22. package/lib/collective/capture-slots.mjs +234 -0
  23. package/lib/collective/capture.mjs +8 -6
  24. package/lib/collective/config.mjs +2 -0
  25. package/lib/collective/global-config.mjs +63 -1
  26. package/lib/collective/loop-guard.mjs +155 -0
  27. package/lib/collective/presence.mjs +142 -5
  28. package/lib/comms/send-gate.mjs +559 -1
  29. package/lib/diagnostics/alerts.mjs +49 -0
  30. package/lib/diagnostics/cadence-output-freshness.mjs +288 -0
  31. package/lib/engine/agents/definitions.mjs +343 -0
  32. package/lib/engine/agents/persist.mjs +275 -0
  33. package/lib/engine/agents/runtime.mjs +748 -0
  34. package/lib/engine/agents/usage.mjs +95 -0
  35. package/lib/engine/auth-status.mjs +139 -0
  36. package/lib/engine/budget.mjs +194 -0
  37. package/lib/engine/cli.mjs +1204 -0
  38. package/lib/engine/commands/index.mjs +269 -0
  39. package/lib/engine/context/budget.mjs +219 -0
  40. package/lib/engine/context/cache.mjs +125 -0
  41. package/lib/engine/context/child-env.mjs +215 -0
  42. package/lib/engine/context/compaction.mjs +342 -0
  43. package/lib/engine/context/images.mjs +90 -0
  44. package/lib/engine/context/instructions.mjs +327 -0
  45. package/lib/engine/context/lazy-instructions.mjs +169 -0
  46. package/lib/engine/context/manager.mjs +182 -0
  47. package/lib/engine/context/real-path.mjs +91 -0
  48. package/lib/engine/context/secret-values.mjs +163 -0
  49. package/lib/engine/context/settings.mjs +274 -0
  50. package/lib/engine/context/stream-input.mjs +159 -0
  51. package/lib/engine/guard.mjs +152 -0
  52. package/lib/engine/hooks.mjs +713 -0
  53. package/lib/engine/loop.mjs +560 -0
  54. package/lib/engine/mcp/client.mjs +254 -0
  55. package/lib/engine/mcp/config.mjs +301 -0
  56. package/lib/engine/mcp/http.mjs +201 -0
  57. package/lib/engine/mcp/index.mjs +146 -0
  58. package/lib/engine/mcp/jsonrpc.mjs +147 -0
  59. package/lib/engine/mcp/naming.mjs +66 -0
  60. package/lib/engine/mcp/resources.mjs +89 -0
  61. package/lib/engine/mcp/results.mjs +133 -0
  62. package/lib/engine/mcp/stdio.mjs +137 -0
  63. package/lib/engine/mcp/supervisor.mjs +116 -0
  64. package/lib/engine/messages.mjs +104 -0
  65. package/lib/engine/output/json.mjs +164 -0
  66. package/lib/engine/output/stream-json.mjs +266 -0
  67. package/lib/engine/permissions.mjs +845 -0
  68. package/lib/engine/process-identity.mjs +164 -0
  69. package/lib/engine/process-tree.mjs +551 -0
  70. package/lib/engine/prompt.mjs +60 -0
  71. package/lib/engine/session/store.mjs +299 -0
  72. package/lib/engine/session-runtime/args.mjs +97 -0
  73. package/lib/engine/session-runtime/host.mjs +143 -0
  74. package/lib/engine/session-runtime/inbox.mjs +122 -0
  75. package/lib/engine/session-runtime/notifications.mjs +129 -0
  76. package/lib/engine/session-runtime/registry.mjs +328 -0
  77. package/lib/engine/session-runtime/runner.mjs +344 -0
  78. package/lib/engine/session-runtime/socket.mjs +212 -0
  79. package/lib/engine/session-runtime/wakeup.mjs +115 -0
  80. package/lib/engine/skills/index.mjs +321 -0
  81. package/lib/engine/tools/bash-background.mjs +533 -0
  82. package/lib/engine/tools/bash.mjs +216 -0
  83. package/lib/engine/tools/edit.mjs +97 -0
  84. package/lib/engine/tools/glob.mjs +81 -0
  85. package/lib/engine/tools/grep.mjs +224 -0
  86. package/lib/engine/tools/index.mjs +84 -0
  87. package/lib/engine/tools/list-agents.mjs +32 -0
  88. package/lib/engine/tools/ls.mjs +127 -0
  89. package/lib/engine/tools/monitor.mjs +82 -0
  90. package/lib/engine/tools/notebook-edit.mjs +218 -0
  91. package/lib/engine/tools/read.mjs +103 -0
  92. package/lib/engine/tools/schedule-wakeup.mjs +45 -0
  93. package/lib/engine/tools/schema.mjs +144 -0
  94. package/lib/engine/tools/send-message.mjs +77 -0
  95. package/lib/engine/tools/session.mjs +70 -0
  96. package/lib/engine/tools/todo.mjs +144 -0
  97. package/lib/engine/tools/toolsearch.mjs +217 -0
  98. package/lib/engine/tools/walk.mjs +193 -0
  99. package/lib/engine/tools/web-switch.mjs +31 -0
  100. package/lib/engine/tools/webfetch-html.mjs +387 -0
  101. package/lib/engine/tools/webfetch-net.mjs +340 -0
  102. package/lib/engine/tools/webfetch.mjs +198 -0
  103. package/lib/engine/tools/websearch.mjs +91 -0
  104. package/lib/engine/tools/workflow.mjs +95 -0
  105. package/lib/engine/tools/write.mjs +76 -0
  106. package/lib/engine/tui/line-editor.mjs +137 -0
  107. package/lib/engine/tui/render.mjs +86 -0
  108. package/lib/engine/tui/tui.mjs +274 -0
  109. package/lib/engine/wire/anthropic-messages.mjs +263 -0
  110. package/lib/engine/wire/effort.mjs +36 -0
  111. package/lib/engine/wire/errors.mjs +496 -0
  112. package/lib/engine/wire/http.mjs +441 -0
  113. package/lib/engine/wire/index.mjs +76 -0
  114. package/lib/engine/wire/openai-chat.mjs +332 -0
  115. package/lib/engine/wire/prompt-cache.mjs +79 -0
  116. package/lib/engine/wire/search.mjs +140 -0
  117. package/lib/engine/wire/sse.mjs +114 -0
  118. package/lib/engine/wire/stall.mjs +349 -0
  119. package/lib/engine/wire/token-provider.mjs +175 -0
  120. package/lib/engine/wire/usage.mjs +192 -0
  121. package/lib/engine/workflow/host.mjs +524 -0
  122. package/lib/engine/workflow/journal.mjs +188 -0
  123. package/lib/engine/workflow/json-schema.mjs +171 -0
  124. package/lib/engine/workflow/meta.mjs +329 -0
  125. package/lib/engine/workflow/notifications.mjs +52 -0
  126. package/lib/engine/workflow/runtime.mjs +447 -0
  127. package/lib/engine/workflow/sandbox.mjs +534 -0
  128. package/lib/engine/workflow/worker.mjs +141 -0
  129. package/lib/engine/workflow/worktree.mjs +74 -0
  130. package/lib/execution/disposition.mjs +1 -1
  131. package/lib/execution/intake.mjs +10 -0
  132. package/lib/execution/surface-policy.mjs +15 -0
  133. package/lib/learning/curator.mjs +8 -6
  134. package/lib/learning/reflect.mjs +8 -6
  135. package/lib/model-router/catalog/cohort.yaml +137 -0
  136. package/lib/model-router/catalog.mjs +118 -1
  137. package/lib/model-router/failover.mjs +67 -16
  138. package/lib/model-router/llm-task.mjs +39 -3
  139. package/lib/model-router/resolve.mjs +89 -3
  140. package/lib/model-router/spawn.mjs +46 -47
  141. package/lib/model-router/taxonomy.mjs +126 -4
  142. package/lib/org/cost-sync.mjs +141 -11
  143. package/lib/org/inbound/broadcast.mjs +289 -0
  144. package/lib/org/inbound/collective.mjs +375 -0
  145. package/lib/org/inbound/directedness.mjs +96 -8
  146. package/lib/org/inbound/facts.mjs +78 -2
  147. package/lib/org/inbound/project.mjs +22 -0
  148. package/lib/org/inbound/surfaces.mjs +14 -0
  149. package/lib/org/llm-token.mjs +879 -0
  150. package/lib/org/mesh.mjs +61 -0
  151. package/lib/org/messaging.mjs +3 -1
  152. package/lib/org/protocol.checksum +1 -1
  153. package/lib/org/protocol.mjs +15 -0
  154. package/lib/org/quota.mjs +520 -0
  155. package/lib/org/tool-surface.mjs +104 -16
  156. package/lib/org/ui-parity.mjs +16 -1
  157. package/lib/org/work-ledger.mjs +37 -6
  158. package/lib/rate-guard.mjs +114 -1
  159. package/lib/resource-governor.mjs +41 -6
  160. package/lib/runtime/adapter.mjs +833 -0
  161. package/lib/runtime/child-env.mjs +191 -0
  162. package/lib/runtime/legacy-shell-guard.mjs +97 -0
  163. package/lib/runtime/seat-engine.mjs +162 -0
  164. package/lib/session/ask-ledger.mjs +271 -0
  165. package/lib/session/current-work.mjs +676 -0
  166. package/lib/session/feed-core.mjs +40 -3
  167. package/lib/session/launch-args.mjs +56 -4
  168. package/lib/session/status-summary.mjs +26 -9
  169. package/lib/session/upgrade-notice.mjs +42 -0
  170. package/lib/setup/claude-probe.mjs +117 -13
  171. package/lib/setup/enrich.mjs +13 -10
  172. package/lib/setup/sections/model.mjs +39 -13
  173. package/lib/telemetry/collect.mjs +229 -11
  174. package/lib/upgrade/ignored-drift.mjs +105 -0
  175. package/lib/voice/post-call-brief.mjs +30 -17
  176. package/package.json +13 -3
  177. package/plugins/maestro-skills/skills/board-work.md +5 -0
  178. package/plugins/maestro-skills/skills/inbound-triage.md +56 -15
  179. package/plugins/maestro-skills/skills/main-session.md +18 -7
  180. package/scaffold/config/collective.yaml +7 -0
  181. package/scripts/ci/check-durable-write-seam.mjs +3 -1
  182. package/scripts/ci/check-tarball-fidelity.mjs +126 -2
  183. package/scripts/ci/run-tests.mjs +47 -19
  184. package/scripts/cohort-llm/api-key-helper.mjs +92 -0
  185. package/scripts/collective/hook-runner.mjs +142 -19
  186. package/scripts/continuous-monitor.sh +13 -0
  187. package/scripts/cost/track-claude-usage.mjs +15 -0
  188. package/scripts/daemon/agent-daemon.mjs +408 -20
  189. package/scripts/daemon/assurance.mjs +48 -12
  190. package/scripts/daemon/cadence-consumer.mjs +218 -68
  191. package/scripts/daemon/cadence-handlers.mjs +73 -4
  192. package/scripts/daemon/classifier.mjs +75 -26
  193. package/scripts/daemon/context-compiler.mjs +51 -37
  194. package/scripts/daemon/deliver.mjs +30 -1
  195. package/scripts/daemon/dispatcher.mjs +595 -149
  196. package/scripts/daemon/health.mjs +14 -1
  197. package/scripts/daemon/maestro-daemon.mjs +11 -0
  198. package/scripts/daemon/prompt-builder.mjs +24 -0
  199. package/scripts/daemon/responder.mjs +246 -79
  200. package/scripts/daemon/sdk-version.mjs +98 -16
  201. package/scripts/eval/probe-gateway.mjs +635 -0
  202. package/scripts/eval/replay/extract.mjs +270 -0
  203. package/scripts/eval/replay/grade.mjs +260 -0
  204. package/scripts/eval/replay/lib/config.mjs +50 -0
  205. package/scripts/eval/replay/lib/effects.mjs +65 -0
  206. package/scripts/eval/replay/lib/fixture.mjs +188 -0
  207. package/scripts/eval/replay/lib/judge.mjs +72 -0
  208. package/scripts/eval/replay/lib/redact.mjs +136 -0
  209. package/scripts/eval/replay/lib/sandbox.mjs +170 -0
  210. package/scripts/eval/replay/lib/schema-check.mjs +63 -0
  211. package/scripts/eval/replay/lib/transcript.mjs +76 -0
  212. package/scripts/eval/replay/mcp-replay-stub.mjs +101 -0
  213. package/scripts/eval/replay/report.mjs +185 -0
  214. package/scripts/eval/replay/run.mjs +404 -0
  215. package/scripts/fleet/rollout.mjs +1151 -0
  216. package/scripts/hooks/pre-send-audit.sh +36 -245
  217. package/scripts/hooks/pre-write-yaml-validate.mjs +275 -0
  218. package/scripts/hooks/validate-state-yaml.sh +190 -0
  219. package/scripts/huddle/huddle-llm.mjs +361 -0
  220. package/scripts/huddle/huddle-server.mjs +46 -121
  221. package/scripts/local-triggers/autoupdate.sh +465 -81
  222. package/scripts/local-triggers/run-trigger.sh +13 -0
  223. package/scripts/maintenance/pin-integrity.mjs +364 -0
  224. package/scripts/poll-slack-events.sh +41 -9
  225. package/scripts/poller/slack-socket-mode.mjs +28 -3
  226. package/scripts/session/supervisor.mjs +80 -13
  227. package/scripts/spawn-session.sh +13 -0
  228. package/bin/maestro.test.mjs +0 -1574
  229. package/lib/action-executor.test.mjs +0 -871
  230. package/lib/archetype.test.mjs +0 -132
  231. package/lib/assurance/plan-note.test.mjs +0 -234
  232. package/lib/assurance/room-budget.test.mjs +0 -486
  233. package/lib/assurance/tier.test.mjs +0 -174
  234. package/lib/autonomy.test.mjs +0 -66
  235. package/lib/backlog.test.mjs +0 -302
  236. package/lib/backup/policy.test.mjs +0 -305
  237. package/lib/budget-escalate.test.mjs +0 -232
  238. package/lib/budget-guard.envelope.test.mjs +0 -476
  239. package/lib/budget-guard.test.mjs +0 -427
  240. package/lib/cadence-bus-requeue.test.mjs +0 -83
  241. package/lib/cadence-bus-schedule.test.mjs +0 -194
  242. package/lib/cadence-bus.test.mjs +0 -720
  243. package/lib/cadences.test.mjs +0 -230
  244. package/lib/capability/inventory.test.mjs +0 -232
  245. package/lib/capability.test.mjs +0 -78
  246. package/lib/channels/base-adapter.test.mjs +0 -590
  247. package/lib/channels/channels.test.mjs +0 -371
  248. package/lib/channels/contract.test.mjs +0 -162
  249. package/lib/channels/inbox-item.test.mjs +0 -368
  250. package/lib/channels/orgmail/adapter.test.mjs +0 -448
  251. package/lib/channels/pairing.test.mjs +0 -270
  252. package/lib/channels/repeat-suppressor.test.mjs +0 -134
  253. package/lib/channels/slack-adapter.test.mjs +0 -212
  254. package/lib/channels/telegram-adapter.test.mjs +0 -306
  255. package/lib/channels/voice/adapter.test.mjs +0 -278
  256. package/lib/channels/whatsapp/adapter-baileys.test.mjs +0 -359
  257. package/lib/channels/whatsapp/baileys-typing.test.mjs +0 -154
  258. package/lib/charter.test.mjs +0 -89
  259. package/lib/claude-bin.test.mjs +0 -131
  260. package/lib/cli/board.test.mjs +0 -227
  261. package/lib/cli/design.test.mjs +0 -270
  262. package/lib/cli/doctor-checks.test.mjs +0 -336
  263. package/lib/cli/global-setup-extras.test.mjs +0 -462
  264. package/lib/cli/inbox.test.mjs +0 -230
  265. package/lib/cli/session-ack.test.mjs +0 -63
  266. package/lib/cli/session.test.mjs +0 -613
  267. package/lib/collective/capture.test.mjs +0 -121
  268. package/lib/collective/cards.test.mjs +0 -114
  269. package/lib/collective/config.test.mjs +0 -123
  270. package/lib/collective/global-config.test.mjs +0 -220
  271. package/lib/collective/global-skills.test.mjs +0 -126
  272. package/lib/collective/presence.test.mjs +0 -95
  273. package/lib/collective/recall.test.mjs +0 -116
  274. package/lib/collective/vendor-skills.test.mjs +0 -306
  275. package/lib/comms/send-gate.test.mjs +0 -770
  276. package/lib/comms.test.mjs +0 -41
  277. package/lib/context/budget.test.mjs +0 -252
  278. package/lib/context/history-scope.test.mjs +0 -79
  279. package/lib/cost/ledger-row.test.mjs +0 -183
  280. package/lib/design/design-md.test.mjs +0 -318
  281. package/lib/design/fixtures/DESIGN.golden.md +0 -238
  282. package/lib/design/fixtures/PRODUCT.golden.md +0 -67
  283. package/lib/design/fixtures/foundation.json +0 -133
  284. package/lib/design/refresh-gate.test.mjs +0 -144
  285. package/lib/design/write.test.mjs +0 -241
  286. package/lib/diagnostics/alerts.test.mjs +0 -318
  287. package/lib/diagnostics/backup-freshness.test.mjs +0 -185
  288. package/lib/diagnostics/counters.test.mjs +0 -206
  289. package/lib/diagnostics/events.test.mjs +0 -290
  290. package/lib/diagnostics/otel.test.mjs +0 -196
  291. package/lib/diagnostics/trace.test.mjs +0 -251
  292. package/lib/env-compat.test.mjs +0 -104
  293. package/lib/execution/disposition.test.mjs +0 -553
  294. package/lib/execution/drive.test.mjs +0 -270
  295. package/lib/execution/effects.test.mjs +0 -344
  296. package/lib/execution/intake.test.mjs +0 -389
  297. package/lib/execution/journal.test.mjs +0 -261
  298. package/lib/execution/match.test.mjs +0 -235
  299. package/lib/execution/pipeline.test.mjs +0 -392
  300. package/lib/execution/route.test.mjs +0 -186
  301. package/lib/execution/surface-policy.test.mjs +0 -162
  302. package/lib/fs-atomic.test.mjs +0 -72
  303. package/lib/fs-ownership.test.mjs +0 -158
  304. package/lib/goals/admission.test.mjs +0 -164
  305. package/lib/goals/classify.test.mjs +0 -167
  306. package/lib/goals/collaborate.test.mjs +0 -336
  307. package/lib/goals/gaps.test.mjs +0 -284
  308. package/lib/goals/loop.test.mjs +0 -845
  309. package/lib/hooks/bus.test.mjs +0 -387
  310. package/lib/identity/persona.test.mjs +0 -142
  311. package/lib/kpi-sensors.test.mjs +0 -278
  312. package/lib/kpi.test.mjs +0 -244
  313. package/lib/learning/config.test.mjs +0 -75
  314. package/lib/learning/counters.test.mjs +0 -69
  315. package/lib/learning/curator-consolidate.test.mjs +0 -238
  316. package/lib/learning/curator.test.mjs +0 -106
  317. package/lib/learning/reflect.test.mjs +0 -0
  318. package/lib/learning/session-index.test.mjs +0 -125
  319. package/lib/learning/skill-writer.test.mjs +0 -210
  320. package/lib/mandate/audit.test.mjs +0 -195
  321. package/lib/mandate/contract.test.mjs +0 -185
  322. package/lib/mandate/derive.test.mjs +0 -274
  323. package/lib/mandate/model.test.mjs +0 -164
  324. package/lib/mandate/refresh.test.mjs +0 -389
  325. package/lib/mcp/server.test.mjs +0 -426
  326. package/lib/model-router/auth-profiles.test.mjs +0 -580
  327. package/lib/model-router/catalog.test.mjs +0 -385
  328. package/lib/model-router/economics.test.mjs +0 -438
  329. package/lib/model-router/failover.test.mjs +0 -439
  330. package/lib/model-router/health.test.mjs +0 -338
  331. package/lib/model-router/integration-coverage.test.mjs +0 -831
  332. package/lib/model-router/integration.test.mjs +0 -564
  333. package/lib/model-router/ledger.test.mjs +0 -415
  334. package/lib/model-router/llm-task.test.mjs +0 -392
  335. package/lib/model-router/org-credentials.test.mjs +0 -265
  336. package/lib/model-router/pricing-refresh.test.mjs +0 -286
  337. package/lib/model-router/reconcile.test.mjs +0 -316
  338. package/lib/model-router/repair.test.mjs +0 -180
  339. package/lib/model-router/spawn.test.mjs +0 -446
  340. package/lib/model-router/taxonomy.test.mjs +0 -410
  341. package/lib/model-router.test.mjs +0 -1207
  342. package/lib/org/activity.test.mjs +0 -134
  343. package/lib/org/approvals.test.mjs +0 -216
  344. package/lib/org/awareness.test.mjs +0 -159
  345. package/lib/org/board-mine-cache.test.mjs +0 -53
  346. package/lib/org/board.test.mjs +0 -187
  347. package/lib/org/bootstrap-context.test.mjs +0 -153
  348. package/lib/org/client.test.mjs +0 -1206
  349. package/lib/org/cohort-client.test.mjs +0 -126
  350. package/lib/org/cost-sync.test.mjs +0 -153
  351. package/lib/org/doctor.test.mjs +0 -346
  352. package/lib/org/engagement-ledger.test.mjs +0 -112
  353. package/lib/org/engagement.test.mjs +0 -739
  354. package/lib/org/handoff.test.mjs +0 -269
  355. package/lib/org/inbound/directedness.test.mjs +0 -668
  356. package/lib/org/inbound/facts.test.mjs +0 -471
  357. package/lib/org/inbound/hydrate.test.mjs +0 -908
  358. package/lib/org/inbound/index.test.mjs +0 -429
  359. package/lib/org/inbound/project.test.mjs +0 -287
  360. package/lib/org/integration-tools.test.mjs +0 -160
  361. package/lib/org/keys.test.mjs +0 -92
  362. package/lib/org/knowledge.test.mjs +0 -326
  363. package/lib/org/leases.test.mjs +0 -235
  364. package/lib/org/mesh-directives.test.mjs +0 -110
  365. package/lib/org/mesh-integration.test.mjs +0 -127
  366. package/lib/org/mesh.test.mjs +0 -400
  367. package/lib/org/messaging.test.mjs +0 -471
  368. package/lib/org/param-contract.test.mjs +0 -477
  369. package/lib/org/policy.test.mjs +0 -237
  370. package/lib/org/protocol.checksum.test.mjs +0 -90
  371. package/lib/org/protocol.test.mjs +0 -323
  372. package/lib/org/push.test.mjs +0 -792
  373. package/lib/org/registry.test.mjs +0 -100
  374. package/lib/org/resource-tools.test.mjs +0 -361
  375. package/lib/org/tool-access.test.mjs +0 -144
  376. package/lib/org/tool-surface-integration.test.mjs +0 -120
  377. package/lib/org/tool-surface.test.mjs +0 -1268
  378. package/lib/org/typing.test.mjs +0 -291
  379. package/lib/org/ui-parity.test.mjs +0 -560
  380. package/lib/org/verify.test.mjs +0 -194
  381. package/lib/org/work-ledger.test.mjs +0 -273
  382. package/lib/plan/adoption-e2e.test.mjs +0 -366
  383. package/lib/plan/budget-enforcement.test.mjs +0 -400
  384. package/lib/plan/compile.test.mjs +0 -382
  385. package/lib/plan/emit.test.mjs +0 -269
  386. package/lib/plan/explain.test.mjs +0 -188
  387. package/lib/prompts/parallelism.test.mjs +0 -177
  388. package/lib/rag/rag.test.mjs +0 -505
  389. package/lib/rate-guard.test.mjs +0 -272
  390. package/lib/reactive-gate.test.mjs +0 -57
  391. package/lib/render.test.mjs +0 -68
  392. package/lib/resource-governor.test.mjs +0 -488
  393. package/lib/scheduling/dynamic-jobs.test.mjs +0 -344
  394. package/lib/scheduling/jitter.test.mjs +0 -140
  395. package/lib/secrets/broker.test.mjs +0 -280
  396. package/lib/secrets/providers.test.mjs +0 -274
  397. package/lib/security/audit-engine.test.mjs +0 -424
  398. package/lib/security/coerce-args.test.mjs +0 -281
  399. package/lib/security/dangerous-tools.test.mjs +0 -68
  400. package/lib/security/external-content.test.mjs +0 -84
  401. package/lib/security/redact.test.mjs +0 -441
  402. package/lib/security/secret-equal.test.mjs +0 -55
  403. package/lib/session/config.test.mjs +0 -92
  404. package/lib/session/feed-core.test.mjs +0 -198
  405. package/lib/session/first-run.test.mjs +0 -121
  406. package/lib/session/frontdoor.test.mjs +0 -205
  407. package/lib/session/handoffs.test.mjs +0 -183
  408. package/lib/session/identity.test.mjs +0 -180
  409. package/lib/session/inbox-claims.test.mjs +0 -286
  410. package/lib/session/launch-args.test.mjs +0 -157
  411. package/lib/session/liveness.test.mjs +0 -100
  412. package/lib/session/status-summary.test.mjs +0 -118
  413. package/lib/session-permissions.test.mjs +0 -120
  414. package/lib/setup/claude-probe.test.mjs +0 -187
  415. package/lib/setup/completeness.test.mjs +0 -110
  416. package/lib/setup/context-pack.test.mjs +0 -89
  417. package/lib/setup/enrich.test.mjs +0 -115
  418. package/lib/setup/enroll-from-cohort.test.mjs +0 -300
  419. package/lib/setup/integration.test.mjs +0 -162
  420. package/lib/setup/io.test.mjs +0 -77
  421. package/lib/setup/runner.test.mjs +0 -132
  422. package/lib/setup/sections/identity.test.mjs +0 -234
  423. package/lib/setup/sections/inventory.test.mjs +0 -198
  424. package/lib/setup/sections/learning.test.mjs +0 -81
  425. package/lib/setup/sections/mandate.test.mjs +0 -388
  426. package/lib/setup/sections/messaging.test.mjs +0 -127
  427. package/lib/setup/sections/model.test.mjs +0 -240
  428. package/lib/setup/sections/org.test.mjs +0 -346
  429. package/lib/setup/sections/orgmail.test.mjs +0 -118
  430. package/lib/setup/sections/recovery.test.mjs +0 -98
  431. package/lib/setup/sections/subagents.test.mjs +0 -429
  432. package/lib/setup/sections/verify.test.mjs +0 -175
  433. package/lib/setup/sot.test.mjs +0 -81
  434. package/lib/setup/state.test.mjs +0 -115
  435. package/lib/singleton.test.mjs +0 -151
  436. package/lib/subagents/cli.test.mjs +0 -389
  437. package/lib/subagents/client.test.mjs +0 -309
  438. package/lib/subagents/gap.test.mjs +0 -234
  439. package/lib/subagents/lock.test.mjs +0 -248
  440. package/lib/subagents/manifest.test.mjs +0 -175
  441. package/lib/subagents/refs.test.mjs +0 -204
  442. package/lib/subagents/resolve.test.mjs +0 -422
  443. package/lib/subagents/schema.test.mjs +0 -328
  444. package/lib/telemetry/alerts.test.mjs +0 -109
  445. package/lib/telemetry/collect.test.mjs +0 -1274
  446. package/lib/tool-definitions-integration.test.mjs +0 -83
  447. package/lib/tool-definitions.test.mjs +0 -437
  448. package/lib/upgrade/global-refresh.test.mjs +0 -65
  449. package/lib/upgrade/launchd-reconcile.test.mjs +0 -272
  450. package/lib/upgrade/post-steps.test.mjs +0 -200
  451. package/lib/upgrade/verify.test.mjs +0 -164
  452. package/lib/util/fetch-timeout.test.mjs +0 -202
  453. package/lib/util/reconnect.test.mjs +0 -369
  454. package/lib/util/unhandled.test.mjs +0 -216
  455. package/lib/voice/outbound.test.mjs +0 -69
  456. package/lib/voice/session-rotation.test.mjs +0 -114
  457. package/lib/voice/stt.test.mjs +0 -226
  458. package/lib/voice/voice.test.mjs +0 -990
  459. package/scripts/cadence/enqueue-cadence-tick.test.mjs +0 -187
  460. package/scripts/ci/check-docs-accuracy.test.mjs +0 -409
  461. package/scripts/ci/check-durable-write-seam.test.mjs +0 -90
  462. package/scripts/ci/check-no-build-artifacts.test.mjs +0 -71
  463. package/scripts/ci/check-no-residual-identity.test.mjs +0 -202
  464. package/scripts/ci/check-skill-packs.test.mjs +0 -495
  465. package/scripts/ci/check-subagent-frontmatter.test.mjs +0 -124
  466. package/scripts/ci/check.test.mjs +0 -194
  467. package/scripts/ci/conformance-org-api.test.mjs +0 -425
  468. package/scripts/cloud-relay/voice/relay-identity.test.mjs +0 -96
  469. package/scripts/collective/hook-runner.test.mjs +0 -173
  470. package/scripts/cost/fleet-digest.test.mjs +0 -207
  471. package/scripts/cost/track-claude-usage-pricing.test.mjs +0 -183
  472. package/scripts/cost/track-claude-usage.test.mjs +0 -148
  473. package/scripts/daemon/agent-daemon-board-mine.test.mjs +0 -96
  474. package/scripts/daemon/agent-daemon-design.test.mjs +0 -238
  475. package/scripts/daemon/agent-daemon-frontdoor.test.mjs +0 -60
  476. package/scripts/daemon/agent-daemon.test.mjs +0 -995
  477. package/scripts/daemon/assurance-e2e.test.mjs +0 -613
  478. package/scripts/daemon/assurance.test.mjs +0 -1791
  479. package/scripts/daemon/board-mirror.test.mjs +0 -165
  480. package/scripts/daemon/cadence-consumer-frontdoor.test.mjs +0 -393
  481. package/scripts/daemon/cadence-consumer-governance.test.mjs +0 -276
  482. package/scripts/daemon/cadence-consumer.test.mjs +0 -776
  483. package/scripts/daemon/cadence-handlers.test.mjs +0 -837
  484. package/scripts/daemon/classifier-identity.test.mjs +0 -137
  485. package/scripts/daemon/classifier.test.mjs +0 -266
  486. package/scripts/daemon/classify-kind.test.mjs +0 -40
  487. package/scripts/daemon/context-compiler.test.mjs +0 -406
  488. package/scripts/daemon/deliver.test.mjs +0 -564
  489. package/scripts/daemon/dispatcher-cooldown.test.mjs +0 -122
  490. package/scripts/daemon/dispatcher-governance.test.mjs +0 -1013
  491. package/scripts/daemon/dispatcher-resume.test.mjs +0 -166
  492. package/scripts/daemon/dispatcher-session-continuity.test.mjs +0 -365
  493. package/scripts/daemon/execution-ladder.test.mjs +0 -470
  494. package/scripts/daemon/goal-steward-cadence.test.mjs +0 -312
  495. package/scripts/daemon/inbox-deferral-session.test.mjs +0 -49
  496. package/scripts/daemon/inbox-deferral.test.mjs +0 -336
  497. package/scripts/daemon/inbox-wake.test.mjs +0 -199
  498. package/scripts/daemon/integration.test.mjs +0 -149
  499. package/scripts/daemon/lib/self-echo.test.mjs +0 -153
  500. package/scripts/daemon/lib/session-router.test.mjs +0 -554
  501. package/scripts/daemon/prompt-builder-preamble.test.mjs +0 -210
  502. package/scripts/daemon/prompt-builder.test.mjs +0 -556
  503. package/scripts/daemon/responder-cost.test.mjs +0 -68
  504. package/scripts/daemon/responder-history.test.mjs +0 -221
  505. package/scripts/daemon/sdk-version.test.mjs +0 -31
  506. package/scripts/daemon/session-lock.test.mjs +0 -252
  507. package/scripts/daemon/session-outcomes.test.mjs +0 -533
  508. package/scripts/daemon/typing-registry.test.mjs +0 -102
  509. package/scripts/hooks/pre-send-audit.test.mjs +0 -354
  510. package/scripts/huddle/huddle-prompt.test.mjs +0 -176
  511. package/scripts/local-triggers/autoupdate.test.mjs +0 -518
  512. package/scripts/local-triggers/generate-plists.test.mjs +0 -456
  513. package/scripts/media-generation/brand-clause.test.mjs +0 -135
  514. package/scripts/org/send-orgmail.first-contact.test.mjs +0 -102
  515. package/scripts/poller/inbox-privilege-injection.test.mjs +0 -167
  516. package/scripts/poller/inbox-scan-poller.test.mjs +0 -295
  517. package/scripts/poller/lib/cloud-relay-dedup.test.mjs +0 -133
  518. package/scripts/poller/slack-socket-mode.test.mjs +0 -805
  519. package/scripts/poller-launchd/install.test.mjs +0 -243
  520. package/scripts/restore-from-backup.test.mjs +0 -181
  521. package/scripts/session/feed.test.mjs +0 -196
  522. package/scripts/session/supervisor-sh.test.mjs +0 -218
  523. package/scripts/session/supervisor.test.mjs +0 -482
  524. package/scripts/setup/configure-macos.test.mjs +0 -306
  525. package/scripts/setup/gen-subagent-manifest.test.mjs +0 -124
  526. package/scripts/setup/generate-agent-package-json.test.mjs +0 -143
  527. package/scripts/setup/generate-capability.test.mjs +0 -134
  528. package/scripts/setup/init-agent.test.mjs +0 -370
  529. package/scripts/setup/init-skill-marketplace.test.mjs +0 -193
  530. package/scripts/vendor/sync-skill-packs.test.mjs +0 -103
  531. package/scripts/watchdog/memory-watchdog.test.mjs +0 -64
@@ -1,990 +0,0 @@
1
- /**
2
- * voice.test.mjs — node:test coverage for the voice subsystem.
3
- *
4
- * Tests are pure-Node: no real WebSocket, no real OpenAI. We mock the
5
- * provider where the real implementation needs the network.
6
- */
7
-
8
- import { test } from "node:test";
9
- import assert from "node:assert/strict";
10
- import { EventEmitter } from "node:events";
11
-
12
- import {
13
- VoiceProvider,
14
- VOICE_EVENTS,
15
- createProvider,
16
- buildSessionConfig,
17
- } from "./index.mjs";
18
-
19
- import {
20
- shouldRotate,
21
- rotateSessionIfStale,
22
- makeSummary,
23
- SESSION_ROTATION_DEFAULTS,
24
- } from "./session-rotation.mjs";
25
-
26
- import {
27
- actionsToRealtimeTools,
28
- registerToolBridge,
29
- loadActionClassification,
30
- redactAuditValue,
31
- } from "./tool-bridge.mjs";
32
-
33
- import {
34
- sendVoiceMessage,
35
- placeOutboundCall,
36
- } from "./outbound.mjs";
37
-
38
- import {
39
- buildMediaStreamsBridge,
40
- buildSipInboundHandler,
41
- } from "./twilio-sip-bridge.mjs";
42
-
43
- import { createOpenAIRealtimeProvider } from "./openai-realtime.mjs";
44
-
45
- // ---------------------------------------------------------------------------
46
- // buildSessionConfig
47
- // ---------------------------------------------------------------------------
48
-
49
- test("buildSessionConfig fills defaults: gpt-realtime-2, cedar, PCM16, server_vad", () => {
50
- const cfg = buildSessionConfig({}, { name: "Ravi", role: "VP AI" });
51
- assert.equal(cfg.type, "realtime");
52
- assert.equal(cfg.model, "gpt-realtime-2");
53
- assert.equal(cfg.voice, "cedar");
54
- assert.deepEqual(cfg.output_modalities, ["audio"]);
55
- assert.equal(cfg.input_audio_format, "pcm16");
56
- assert.equal(cfg.output_audio_format, "pcm16");
57
- assert.equal(cfg.input_audio_transcription.model, "gpt-realtime-whisper");
58
- assert.equal(cfg.turn_detection.type, "server_vad");
59
- assert.match(cfg.instructions, /Ravi.*VP AI/);
60
- });
61
-
62
- test("buildSessionConfig allows full override", () => {
63
- const cfg = buildSessionConfig({
64
- model: "gpt-realtime-translate",
65
- voice: "marin",
66
- instructions: "You are a translator.",
67
- turn_detection: { type: "semantic_vad", eagerness: "high" },
68
- tools: [{ type: "function", name: "send_slack_message", parameters: {} }],
69
- });
70
- assert.equal(cfg.model, "gpt-realtime-translate");
71
- assert.equal(cfg.voice, "marin");
72
- assert.equal(cfg.instructions, "You are a translator.");
73
- assert.equal(cfg.turn_detection.type, "semantic_vad");
74
- assert.equal(cfg.tools[0].name, "send_slack_message");
75
- });
76
-
77
- // ---------------------------------------------------------------------------
78
- // createProvider — factory dispatch (without actually connecting)
79
- // ---------------------------------------------------------------------------
80
-
81
- test("createProvider returns an OpenAIRealtimeProvider for openai-realtime", () => {
82
- const p = createProvider("openai-realtime", { apiKey: "fake" });
83
- assert.ok(p instanceof VoiceProvider);
84
- assert.equal(p.transport, "ws");
85
- assert.equal(p.model, "gpt-realtime-2");
86
- });
87
-
88
- test("createProvider rejects unknown / unbuilt providers", () => {
89
- assert.throws(() => createProvider("gemini-live"), /gemini-live/);
90
- assert.throws(() => createProvider("claude-voice"), /claude-voice/);
91
- assert.throws(() => createProvider("does-not-exist"), /unknown voice provider/);
92
- });
93
-
94
- // ---------------------------------------------------------------------------
95
- // session-rotation
96
- // ---------------------------------------------------------------------------
97
-
98
- test("shouldRotate returns false on a fresh session", () => {
99
- const decision = shouldRotate({ turns: 0, started_at: Date.now(), recent_latencies_ms: [] });
100
- assert.equal(decision.rotate, false);
101
- });
102
-
103
- test("shouldRotate triggers on max_turns", () => {
104
- const decision = shouldRotate({ turns: 12, started_at: Date.now() });
105
- assert.equal(decision.rotate, true);
106
- assert.equal(decision.reason, "max_turns");
107
- });
108
-
109
- test("shouldRotate triggers on max_duration", () => {
110
- const decision = shouldRotate({
111
- turns: 2,
112
- started_at: Date.now() - SESSION_ROTATION_DEFAULTS.max_duration_ms - 1000,
113
- });
114
- assert.equal(decision.rotate, true);
115
- assert.equal(decision.reason, "max_duration");
116
- });
117
-
118
- test("shouldRotate triggers on p95 latency drift", () => {
119
- const decision = shouldRotate({
120
- turns: 3,
121
- started_at: Date.now(),
122
- recent_latencies_ms: [400, 500, 600, 2500, 2800],
123
- });
124
- assert.equal(decision.rotate, true);
125
- assert.equal(decision.reason, "latency_drift");
126
- });
127
-
128
- test("shouldRotate respects custom thresholds", () => {
129
- const decision = shouldRotate(
130
- { turns: 5, started_at: Date.now() },
131
- { max_turns: 3 }
132
- );
133
- assert.equal(decision.rotate, true);
134
- assert.equal(decision.reason, "max_turns");
135
- });
136
-
137
- test("makeSummary keeps recent exchanges and tool activity", () => {
138
- const transcript = [
139
- { role: "user", text: "Hello" },
140
- { role: "assistant", text: "Hi Ravi, how can I help?" },
141
- { role: "user", text: "Send Alex a message that the deal is approved" },
142
- { role: "assistant", text: "Confirmed. Sending now." },
143
- { tool: { name: "send_slack_message", args: { channel: "@alex", text: "deal approved" } } },
144
- { role: "assistant", text: "Sent." },
145
- ];
146
- const summary = makeSummary(transcript);
147
- assert.match(summary, /Session rotated/);
148
- assert.match(summary, /Send Alex/);
149
- assert.match(summary, /send_slack_message/);
150
- assert.match(summary, /Continue the conversation/);
151
- });
152
-
153
- test("makeSummary copes with empty transcript", () => {
154
- assert.match(makeSummary([]), /no prior context/i);
155
- assert.match(makeSummary(null), /no prior context/i);
156
- });
157
-
158
- test("rotateSessionIfStale skips when not stale", async () => {
159
- const provider = { close: () => {}, connect: async () => {}, sendText: () => {} };
160
- const result = await rotateSessionIfStale(provider, { turns: 1, started_at: Date.now() }, {
161
- createNewProvider: () => { throw new Error("should not be called"); },
162
- });
163
- assert.equal(result.rotated, false);
164
- assert.equal(result.provider, provider);
165
- });
166
-
167
- test("rotateSessionIfStale spins up a new provider and re-seeds with summary", async () => {
168
- const oldClosed = [];
169
- const oldProvider = {
170
- sessionConfig: { type: "realtime", model: "gpt-realtime-2" },
171
- close: (reason) => oldClosed.push(reason),
172
- };
173
- let newConnect = null;
174
- let newText = null;
175
- const newProvider = {
176
- state: "idle",
177
- connect: async (cfg) => { newConnect = cfg; newProvider.state = "connected"; },
178
- sendText: (t) => { newText = t; },
179
- close: () => {},
180
- };
181
- const result = await rotateSessionIfStale(
182
- oldProvider,
183
- {
184
- turns: 15,
185
- started_at: Date.now(),
186
- sessionConfig: oldProvider.sessionConfig,
187
- transcript: [{ role: "user", text: "ping" }, { role: "assistant", text: "pong" }],
188
- },
189
- { createNewProvider: () => newProvider }
190
- );
191
- assert.equal(result.rotated, true);
192
- assert.equal(result.provider, newProvider);
193
- assert.equal(result.reason, "max_turns");
194
- assert.deepEqual(newConnect, oldProvider.sessionConfig);
195
- assert.match(newText, /pong|Session rotated/);
196
- assert.equal(oldClosed.length, 1);
197
- assert.match(oldClosed[0], /rotated/);
198
- });
199
-
200
- // M10 — rotation keeps the old provider when the new session fails to come up.
201
- test("rotateSessionIfStale keeps old provider and reports rotated:false when next.connect rejects", async () => {
202
- const oldClosed = [];
203
- const oldProvider = {
204
- state: "connected",
205
- sessionConfig: { type: "realtime", model: "gpt-realtime-2" },
206
- close: (reason) => oldClosed.push(reason),
207
- sendText: () => { throw new Error("old provider sendText must not be touched"); },
208
- };
209
- let newSendTextCalled = false;
210
- let newClosed = null;
211
- const failingProvider = {
212
- state: "idle",
213
- connect: async () => { throw new Error("upstream refused"); },
214
- sendText: () => { newSendTextCalled = true; },
215
- close: (reason) => { newClosed = reason; },
216
- };
217
- const result = await rotateSessionIfStale(
218
- oldProvider,
219
- {
220
- turns: 99,
221
- started_at: Date.now(),
222
- sessionConfig: oldProvider.sessionConfig,
223
- transcript: [{ role: "user", text: "hi" }],
224
- },
225
- { createNewProvider: () => failingProvider, confirmTimeoutMs: 200 },
226
- );
227
- assert.equal(result.rotated, false, "must not rotate when bring-up fails");
228
- assert.equal(result.provider, oldProvider, "must keep serving the old provider");
229
- assert.match(result.error || "", /upstream refused/);
230
- assert.equal(oldClosed.length, 0, "old provider must NOT be closed on failed rotation");
231
- assert.equal(newSendTextCalled, false, "must not seed a session that never came up");
232
- assert.match(newClosed || "", /rotation_failed/, "half-open new provider must be torn down");
233
- });
234
-
235
- // M10 — a new provider that resolves connect() but then drops before
236
- // confirming live must NOT cause us to cut over.
237
- test("rotateSessionIfStale does not cut over when new session drops before confirmed live", async () => {
238
- const { EventEmitter } = await import("node:events");
239
- const oldClosed = [];
240
- const oldProvider = {
241
- state: "connected",
242
- sessionConfig: { type: "realtime" },
243
- close: (r) => oldClosed.push(r),
244
- };
245
- const next = new EventEmitter();
246
- next.state = "idle";
247
- next.connect = async () => { /* resolves but never becomes healthy */ };
248
- next.sendText = () => { throw new Error("should not seed a dead session"); };
249
- let nextClosed = null;
250
- next.close = (r) => { nextClosed = r; };
251
- // Emit CLOSED shortly after connect resolves to simulate an immediate drop.
252
- setImmediate(() => next.emit(VOICE_EVENTS.CLOSED, { reason: "upstream gone" }));
253
-
254
- const result = await rotateSessionIfStale(
255
- oldProvider,
256
- { turns: 99, started_at: Date.now(), sessionConfig: oldProvider.sessionConfig, transcript: [] },
257
- { createNewProvider: () => next, confirmTimeoutMs: 500 },
258
- );
259
- assert.equal(result.rotated, false);
260
- assert.equal(result.provider, oldProvider);
261
- assert.equal(oldClosed.length, 0);
262
- assert.match(nextClosed || "", /rotation_failed/);
263
- });
264
-
265
- // ---------------------------------------------------------------------------
266
- // twilio-sip-bridge — media streams (M11) + native SIP webhook (L17)
267
- // ---------------------------------------------------------------------------
268
-
269
- test("buildMediaStreamsBridge: failing internal connect does NOT throw unhandled + frames drop safely (M11)", async () => {
270
- // Capture any unhandled rejection for the duration of this test.
271
- const unhandled = [];
272
- const onUnhandled = (err) => unhandled.push(err);
273
- process.on("unhandledRejection", onUnhandled);
274
-
275
- const bridge = buildMediaStreamsBridge({ apiKey: "fake" });
276
- // The real module created a provider with a real (lazy) WS connect that
277
- // will reject because there's no network/key. Force a deterministic
278
- // rejection by replacing the provider's socket path: easiest is to assert
279
- // the bridge exposes the safety surface and that ready rejects cleanly.
280
- assert.equal(typeof bridge.isConnected, "function");
281
- assert.equal(typeof bridge.lastError, "function");
282
-
283
- // ready must reject (no real upstream) but must be already-handled.
284
- let readyRejected = false;
285
- try { await bridge.ready; } catch { readyRejected = true; }
286
- assert.equal(readyRejected, true, "ready should reject without a real upstream");
287
- assert.equal(bridge.isConnected(), false, "bridge must report not-connected");
288
- assert.ok(bridge.lastError(), "bridge must record the connect error");
289
-
290
- // Forwarding a media frame on a never-connected provider must be a no-op
291
- // (no throw), not forwarded into a dead provider.
292
- assert.doesNotThrow(() => bridge.onTwilioFrame(JSON.stringify({
293
- event: "media", media: { payload: "AAAA" },
294
- })));
295
-
296
- // Let any microtasks settle, then assert no unhandled rejection escaped.
297
- await new Promise((r) => setImmediate(r));
298
- process.removeListener("unhandledRejection", onUnhandled);
299
- assert.equal(unhandled.length, 0, "internal connect rejection must not be unhandled");
300
-
301
- try { bridge.close(); } catch { /* */ }
302
- });
303
-
304
- test("buildMediaStreamsBridge: connected provider forwards frames; closed provider drops them (M11)", async () => {
305
- const bridge = buildMediaStreamsBridge({ apiKey: "fake" });
306
- // Simulate a successful connect by flipping the provider live + connected.
307
- const appends = [];
308
- bridge.provider.appendAudio = (b64) => appends.push(b64);
309
- bridge.provider.commitTurn = () => appends.push("__commit__");
310
- bridge.provider.state = "connected";
311
- bridge.provider.emit(VOICE_EVENTS.CONNECTED, {}); // sets connected=true
312
-
313
- bridge.onTwilioFrame(JSON.stringify({ event: "media", media: { payload: "ZZZ" } }));
314
- assert.deepEqual(appends, ["ZZZ"]);
315
-
316
- // Now mark the provider closed — further frames must drop.
317
- bridge.provider.state = "closed";
318
- bridge.onTwilioFrame(JSON.stringify({ event: "media", media: { payload: "YYY" } }));
319
- assert.deepEqual(appends, ["ZZZ"], "frames must drop once provider is closed");
320
-
321
- // Swallow the (unrelated) ready rejection from the fake upstream.
322
- bridge.ready.catch(() => {});
323
- });
324
-
325
- test("buildSipInboundHandler: failed event-WS attach tears down provider + detach (L17)", async () => {
326
- // We can't easily inject the provider the handler creates, so we assert the
327
- // observable contract: the handler responds 200 and never throws even when
328
- // the internal connect rejects, and detach is invoked via CLOSED teardown.
329
- let detachCalls = 0;
330
- const handler = buildSipInboundHandler({
331
- apiKey: "fake",
332
- acceptedByRelay: true, // skip the /accept fetch so no network is needed
333
- sessionConfig: async () => ({ type: "realtime" }),
334
- attachBridges: () => () => { detachCalls += 1; },
335
- });
336
-
337
- const req = { body: { type: "realtime.call.incoming", data: { call: { id: "call_123" } } } };
338
- let status = null;
339
- let payload = null;
340
- const res = {
341
- status: (s) => { status = s; return res; },
342
- json: (b) => { payload = b; },
343
- };
344
-
345
- await assert.doesNotReject(handler(req, res));
346
- assert.equal(status, 200, "webhook must still 200 even if event-WS attach fails");
347
- assert.equal(payload.ok, true);
348
- assert.equal(payload.call_id, "call_123");
349
-
350
- // The real provider's connect will reject (fake key/no network); give the
351
- // microtask + teardown time to run, then assert detach fired.
352
- await new Promise((r) => setTimeout(r, 50));
353
- assert.ok(detachCalls >= 1, "detach must be invoked when the connect fails (no leak)");
354
- });
355
-
356
- // ---------------------------------------------------------------------------
357
- // openai-realtime — client vs upstream close + bounded reconnect (H4)
358
- // ---------------------------------------------------------------------------
359
-
360
- // A minimal fake WebSocket: EventEmitter-ish with the .on/.send/.close the
361
- // provider's non-addEventListener path uses.
362
- function makeFakeSocket() {
363
- const handlers = {};
364
- return {
365
- on(ev, fn) { (handlers[ev] ||= []).push(fn); },
366
- once(ev, fn) { (handlers[ev] ||= []).push(fn); },
367
- send() { /* swallow */ },
368
- close() { this._emit("close", 1000, "client"); },
369
- _emit(ev, ...args) { for (const fn of (handlers[ev] || [])) fn(...args); },
370
- _handlers: handlers,
371
- };
372
- }
373
-
374
- // The provider creates the socket inside an async _connectWebSocket().then(),
375
- // so the socket factory hasn't run synchronously after connect() returns. Wait
376
- // (via microtasks) until at least `n` sockets exist before driving events.
377
- async function waitForSocket(sockets, n, tries = 50) {
378
- while (sockets.length < n && tries-- > 0) {
379
- await new Promise((r) => setImmediate(r));
380
- }
381
- if (sockets.length < n) throw new Error(`waitForSocket: expected ${n}, got ${sockets.length}`);
382
- return sockets[n - 1];
383
- }
384
-
385
- test("openai-realtime: client close() does NOT trigger a reconnect (H4)", async () => {
386
- let ctorCalls = 0;
387
- const sockets = [];
388
- const provider = createOpenAIRealtimeProvider({
389
- apiKey: "fake",
390
- wsCtor: () => { ctorCalls += 1; const s = makeFakeSocket(); sockets.push(s); return s; },
391
- });
392
- // Drive connect: the socket is created asynchronously, so wait for it then
393
- // fire "open" to resolve the connect handshake.
394
- const connecting = provider.connect({ type: "realtime" });
395
- (await waitForSocket(sockets, 1))._emit("open");
396
- await connecting;
397
- assert.equal(provider.state, "connected");
398
- assert.equal(ctorCalls, 1);
399
-
400
- const closes = [];
401
- provider.on(VOICE_EVENTS.CLOSED, (info) => closes.push(info));
402
- provider.close("done");
403
- // Now fire the underlying socket close as a consequence of client close().
404
- sockets[0]._emit("close", 1000, "client");
405
-
406
- await new Promise((r) => setImmediate(r));
407
- assert.equal(ctorCalls, 1, "client close() must not reopen the socket");
408
- assert.equal(provider.state, "closed");
409
- assert.ok(closes.length >= 1, "client close emits CLOSED");
410
- });
411
-
412
- test("openai-realtime: upstream drop attempts bounded reconnect, then fails deterministically (H4)", async () => {
413
- let ctorCalls = 0;
414
- const sockets = [];
415
- // Use a synchronous fake timer so backoff fires immediately.
416
- const timers = [];
417
- const fakeSetTimeout = (fn) => { timers.push(fn); return { _t: true, unref() {} }; };
418
- const fakeClearTimeout = () => {};
419
-
420
- const provider = createOpenAIRealtimeProvider({
421
- apiKey: "fake",
422
- maxReconnectAttempts: 2,
423
- reconnectBaseDelayMs: 1,
424
- setTimeout: fakeSetTimeout,
425
- clearTimeout: fakeClearTimeout,
426
- // Every reconnect attempt's new socket immediately errors so reconnect
427
- // fails and we exhaust the budget deterministically.
428
- wsCtor: () => {
429
- ctorCalls += 1;
430
- const s = makeFakeSocket();
431
- sockets.push(s);
432
- return s;
433
- },
434
- });
435
-
436
- const connecting = provider.connect({ type: "realtime", model: "gpt-realtime-2" });
437
- (await waitForSocket(sockets, 1))._emit("open"); // initial connect succeeds
438
- await connecting;
439
- assert.equal(provider.state, "connected");
440
- assert.equal(ctorCalls, 1);
441
-
442
- const errors = [];
443
- const closes = [];
444
- provider.on(VOICE_EVENTS.ERROR, (e) => errors.push(e));
445
- provider.on(VOICE_EVENTS.CLOSED, (i) => closes.push(i));
446
-
447
- // Simulate an UNEXPECTED upstream drop (not client-initiated).
448
- sockets[0]._emit("close", 1006, "upstream gone");
449
- assert.equal(provider.state, "reconnecting", "upstream drop must enter reconnecting, not closed");
450
-
451
- // Drain the scheduled reconnect attempts. Each attempt opens a new fake
452
- // socket; we make each reconnect fail by emitting 'error' before 'open'.
453
- let guard = 0;
454
- while (timers.length && guard++ < 10) {
455
- const fn = timers.shift();
456
- const before = sockets.length;
457
- fn(); // runs _attemptReconnect → _connectWebSocket (creates a socket)
458
- await new Promise((r) => setImmediate(r));
459
- // Fail the newly created socket's connect handshake.
460
- if (sockets.length > before) {
461
- sockets[sockets.length - 1]._emit("error", new Error("reconnect refused"));
462
- await new Promise((r) => setImmediate(r));
463
- }
464
- }
465
-
466
- assert.ok(ctorCalls >= 2, "must have attempted at least one reconnect");
467
- assert.equal(provider.state, "closed", "exhausted reconnect must end closed");
468
- assert.ok(closes.length >= 1, "must emit CLOSED on exhaustion (not silent)");
469
- assert.match(
470
- String(closes[closes.length - 1].reason || ""),
471
- /upstream_drop_reconnect_exhausted/,
472
- "CLOSED reason must signal exhausted reconnect",
473
- );
474
- assert.ok(errors.length >= 1, "must surface errors during reconnect");
475
- });
476
-
477
- test("openai-realtime: upstream drop reconnect succeeds and re-sends session config (H4)", async () => {
478
- let ctorCalls = 0;
479
- const sockets = [];
480
- const sent = [];
481
- const timers = [];
482
- const fakeSetTimeout = (fn) => { timers.push(fn); return { unref() {} }; };
483
-
484
- const provider = createOpenAIRealtimeProvider({
485
- apiKey: "fake",
486
- maxReconnectAttempts: 3,
487
- reconnectBaseDelayMs: 1,
488
- setTimeout: fakeSetTimeout,
489
- clearTimeout: () => {},
490
- wsCtor: () => {
491
- ctorCalls += 1;
492
- const s = makeFakeSocket();
493
- s.send = (data) => sent.push(data);
494
- sockets.push(s);
495
- return s;
496
- },
497
- });
498
-
499
- const sessionCfg = { type: "realtime", model: "gpt-realtime-2", voice: "cedar" };
500
- const connecting = provider.connect(sessionCfg);
501
- (await waitForSocket(sockets, 1))._emit("open");
502
- await connecting;
503
- sent.length = 0; // ignore the initial session.update
504
-
505
- // The provider emits VOICE_EVENTS.ERROR (== "error") during reconnect; an
506
- // EventEmitter with no "error" listener throws on emit, so register one.
507
- const errors = [];
508
- provider.on(VOICE_EVENTS.ERROR, (e) => errors.push(e));
509
-
510
- // Upstream drop.
511
- sockets[0]._emit("close", 1006, "blip");
512
- assert.equal(provider.state, "reconnecting");
513
-
514
- // Run the scheduled reconnect; let the new socket "open" successfully.
515
- assert.equal(timers.length, 1);
516
- timers.shift()();
517
- await new Promise((r) => setImmediate(r));
518
- // The reconnect created a fresh socket; fire its open.
519
- sockets[sockets.length - 1]._emit("open");
520
- await new Promise((r) => setImmediate(r));
521
-
522
- assert.equal(provider.state, "connected", "successful reconnect returns to connected");
523
- assert.ok(ctorCalls >= 2, "reconnect opened a new socket");
524
- // The stored session config must be re-sent via session.update.
525
- const sessionUpdates = sent
526
- .map((d) => { try { return JSON.parse(d); } catch { return null; } })
527
- .filter((m) => m && m.type === "session.update");
528
- assert.ok(sessionUpdates.length >= 1, "must re-send session.update after reconnect");
529
- assert.deepEqual(sessionUpdates[0].session, sessionCfg);
530
-
531
- provider.close("test-done");
532
- });
533
-
534
- // ---------------------------------------------------------------------------
535
- // tool-bridge
536
- // ---------------------------------------------------------------------------
537
-
538
- test("loadActionClassification normalises both root-shape and actions-shape", () => {
539
- // We can't write YAML without js-yaml, so test the normaliser directly
540
- // via the in-memory shape.
541
- const out = loadActionClassification("/tmp/nonexistent-agent-root");
542
- // No file → empty object.
543
- assert.deepEqual(out, {});
544
- });
545
-
546
- test("actionsToRealtimeTools filters via include / exclude / classification", async () => {
547
- // We mock the dynamic import by setting up a minimal classification.
548
- // Because tool-definitions.js is real and exported, the call should
549
- // succeed and return only tools that exist in include[].
550
- let tools;
551
- try {
552
- tools = await actionsToRealtimeTools({
553
- include: [],
554
- exclude: [],
555
- accessLevel: "voice",
556
- });
557
- } catch (err) {
558
- // If the framework's tool-definitions.js doesn't define "voice" yet,
559
- // we expect an empty array, not a crash.
560
- if (/getToolsForAccessLevel/.test(err.message)) tools = [];
561
- else throw err;
562
- }
563
- assert.ok(Array.isArray(tools), "actionsToRealtimeTools must return an array");
564
- });
565
-
566
- test("registerToolBridge calls executor and replies via sendToolResult", async () => {
567
- const calls = [];
568
- const provider = new EventEmitter();
569
- provider.sendToolResult = (callId, output) => calls.push({ callId, output });
570
- const teardown = registerToolBridge(provider, {
571
- executor: async (name, args) => ({ ok: true, echoed: { name, args } }),
572
- });
573
-
574
- provider.emit("tool.call", {
575
- call_id: "c1",
576
- name: "send_slack_message",
577
- arguments: { channel: "@alex", text: "hi" },
578
- });
579
- // Allow the async handler to flush.
580
- await new Promise((r) => setImmediate(r));
581
-
582
- assert.equal(calls.length, 1);
583
- assert.equal(calls[0].callId, "c1");
584
- assert.equal(calls[0].output.ok, true);
585
- assert.equal(calls[0].output.echoed.name, "send_slack_message");
586
- teardown();
587
- // After teardown, the bridge no longer responds.
588
- provider.emit("tool.call", { call_id: "c2", name: "x" });
589
- await new Promise((r) => setImmediate(r));
590
- assert.equal(calls.length, 1);
591
- });
592
-
593
- test("registerToolBridge enforces allow-list", async () => {
594
- const calls = [];
595
- const provider = new EventEmitter();
596
- provider.sendToolResult = (callId, output) => calls.push({ callId, output });
597
- registerToolBridge(provider, {
598
- allow: ["send_slack_message"],
599
- executor: async () => ({ should_not_run: true }),
600
- });
601
- provider.emit("tool.call", { call_id: "c1", name: "wire_transfer", arguments: { amount: 50000 } });
602
- await new Promise((r) => setImmediate(r));
603
- assert.equal(calls.length, 1);
604
- assert.equal(calls[0].output.ok, false);
605
- assert.equal(calls[0].output.error, "tool_not_allowed");
606
- });
607
-
608
- test("registerToolBridge calls audit hook for both success and error paths", async () => {
609
- const auditEntries = [];
610
- const provider = new EventEmitter();
611
- provider.sendToolResult = () => {};
612
- registerToolBridge(provider, {
613
- executor: async (name) => {
614
- if (name === "fails") throw new Error("kaboom");
615
- return { ok: true };
616
- },
617
- audit: (entry) => auditEntries.push(entry),
618
- });
619
- provider.emit("tool.call", { call_id: "c1", name: "succeeds", arguments: {} });
620
- provider.emit("tool.call", { call_id: "c2", name: "fails", arguments: {} });
621
- await new Promise((r) => setImmediate(r));
622
- assert.equal(auditEntries.length, 2);
623
- assert.equal(auditEntries[0].error, null);
624
- assert.equal(auditEntries[1].error, "kaboom");
625
- });
626
-
627
- // ---------------------------------------------------------------------------
628
- // VOICE_EVENTS constants
629
- // ---------------------------------------------------------------------------
630
-
631
- test("VOICE_EVENTS surface is frozen and complete", () => {
632
- assert.ok(Object.isFrozen(VOICE_EVENTS));
633
- for (const k of ["AUDIO_DELTA", "TRANSCRIPT_DELTA", "TOOL_CALL", "TURN_DONE", "USER_SPEECH_STARTED", "ERROR", "CLOSED"]) {
634
- assert.ok(VOICE_EVENTS[k], `missing event: ${k}`);
635
- }
636
- });
637
-
638
- // ---------------------------------------------------------------------------
639
- // L12 — openai-realtime backpressure / readyState on _send + appendAudio
640
- // ---------------------------------------------------------------------------
641
-
642
- // A fake socket that lets a test drive readyState + bufferedAmount and records
643
- // everything written. (makeFakeSocket above has no numeric readyState; this one
644
- // does, exactly so the L12 guard can observe it.)
645
- function makeBackpressureSocket() {
646
- return {
647
- sent: [],
648
- listeners: {},
649
- readyState: 1, // OPEN
650
- bufferedAmount: 0,
651
- addEventListener(type, fn) { (this.listeners[type] ||= []).push(fn); },
652
- send(data) { this.sent.push(data); },
653
- close() { this.closed = true; },
654
- fire(type, evt) { (this.listeners[type] || []).forEach((fn) => fn(evt)); },
655
- };
656
- }
657
-
658
- async function connectBackpressureProvider(overrides = {}) {
659
- const sockets = [];
660
- const provider = createOpenAIRealtimeProvider({
661
- apiKey: "sk-test",
662
- wsCtor: () => { const s = makeBackpressureSocket(); sockets.push(s); return s; },
663
- ...overrides,
664
- });
665
- const connectP = provider.connect({ voice: "cedar" });
666
- const sock = await waitForSocket(sockets, 1);
667
- sock.fire("open");
668
- await connectP;
669
- return { provider, socket: sockets[sockets.length - 1] };
670
- }
671
-
672
- test("openai-realtime: appendAudio forwards a frame when the socket is OPEN and drained (L12)", async () => {
673
- const { provider, socket } = await connectBackpressureProvider();
674
- const before = socket.sent.length; // session.update from connect()
675
- provider.appendAudio("AAAA");
676
- assert.equal(socket.sent.length, before + 1);
677
- const last = JSON.parse(socket.sent[socket.sent.length - 1]);
678
- assert.equal(last.type, "input_audio_buffer.append");
679
- assert.equal(provider.droppedAudioFrames, 0);
680
- });
681
-
682
- test("openai-realtime: appendAudio drops frames under bufferedAmount backpressure but keeps the socket alive (L12)", async () => {
683
- const { provider, socket } = await connectBackpressureProvider({ maxBufferedBytes: 100 });
684
- const before = socket.sent.length;
685
- socket.bufferedAmount = 1000; // over threshold → backpressured
686
- provider.appendAudio("AAAA");
687
- provider.appendAudio("BBBB");
688
- assert.equal(socket.sent.length, before, "no audio frames written while backpressured");
689
- assert.equal(provider.droppedAudioFrames, 2);
690
- // Buffer drains → audio flows again (normal case keeps working).
691
- socket.bufferedAmount = 0;
692
- provider.appendAudio("CCCC");
693
- assert.equal(socket.sent.length, before + 1);
694
- assert.equal(provider.droppedAudioFrames, 2);
695
- });
696
-
697
- test("openai-realtime: _send / appendAudio skip a non-OPEN socket instead of throwing (L12)", async () => {
698
- const { provider, socket } = await connectBackpressureProvider();
699
- const before = socket.sent.length;
700
- socket.readyState = 0; // CONNECTING — not OPEN
701
- socket.send = () => { throw new Error("should not be called on a non-open socket"); };
702
- provider.appendAudio("AAAA"); // audio path
703
- provider.sendText("hi"); // control path via _send
704
- assert.equal(socket.sent.length, before);
705
- assert.equal(provider.droppedAudioFrames, 1);
706
- // Restore an open, working socket → control frames flow again.
707
- socket.readyState = 1;
708
- socket.send = (d) => socket.sent.push(d);
709
- provider.sendText("now");
710
- assert.ok(socket.sent.length > before);
711
- });
712
-
713
- // ---------------------------------------------------------------------------
714
- // L11/L20 — tool-bridge audit redaction
715
- // ---------------------------------------------------------------------------
716
-
717
- function makeAuditProvider() {
718
- const provider = new EventEmitter();
719
- provider.sendToolResult = () => {};
720
- return provider;
721
- }
722
-
723
- test("tool-bridge: registerToolBridge audit is RAW by default (no redaction) (L11)", async () => {
724
- const audits = [];
725
- const provider = makeAuditProvider();
726
- const teardown = registerToolBridge(provider, {
727
- executor: async () => ({ ok: true, body: "secret message body" }),
728
- audit: (e) => audits.push(e),
729
- });
730
- provider.emit("tool.call", {
731
- call_id: "c1",
732
- name: "send_message",
733
- arguments: { to: "+15551234567", token: "sk-live-abcdef", body: "hello there" },
734
- });
735
- await new Promise((r) => setImmediate(r));
736
- assert.equal(audits.length, 1);
737
- assert.equal(audits[0].args.token, "sk-live-abcdef");
738
- assert.equal(audits[0].args.body, "hello there");
739
- assert.equal(audits[0].result.body, "secret message body");
740
- teardown();
741
- });
742
-
743
- test("tool-bridge: redactAudit masks sensitive fields + URL creds, preserves structure (L11)", async () => {
744
- const audits = [];
745
- const provider = makeAuditProvider();
746
- const teardown = registerToolBridge(provider, {
747
- redactAudit: true,
748
- executor: async () => ({ ok: true, link: "https://api.example.com/x?api_key=zzz" }),
749
- audit: (e) => audits.push(e),
750
- });
751
- provider.emit("tool.call", {
752
- call_id: "c2",
753
- name: "send_message",
754
- arguments: { to: "+15551234567", token: "sk-live-abcdef", body: "hello" },
755
- });
756
- await new Promise((r) => setImmediate(r));
757
- assert.equal(audits.length, 1);
758
- assert.equal(audits[0].args.token, "***");
759
- assert.equal(audits[0].args.body, "hello");
760
- assert.equal(audits[0].args.to, "+15551234567");
761
- assert.ok(audits[0].result.link.includes("api_key=***"));
762
- assert.ok(!audits[0].result.link.includes("zzz"));
763
- assert.equal(audits[0].name, "send_message");
764
- teardown();
765
- });
766
-
767
- test("tool-bridge: auditAllowlist keeps only listed top-level fields (L11)", async () => {
768
- const audits = [];
769
- const provider = makeAuditProvider();
770
- const teardown = registerToolBridge(provider, {
771
- auditAllowlist: ["to"],
772
- executor: async () => ({ ok: true, body: "should be dropped" }),
773
- audit: (e) => audits.push(e),
774
- });
775
- provider.emit("tool.call", {
776
- call_id: "c3",
777
- name: "send_message",
778
- arguments: { to: "+15551234567", body: "private body", amount: 50000 },
779
- });
780
- await new Promise((r) => setImmediate(r));
781
- assert.equal(audits.length, 1);
782
- assert.equal(audits[0].args.to, "+15551234567");
783
- assert.ok(!("body" in audits[0].args));
784
- assert.ok(!("amount" in audits[0].args));
785
- assert.ok(!("body" in audits[0].result));
786
- teardown();
787
- });
788
-
789
- test("tool-bridge: custom opts.redact wins and never breaks auditing (L11)", async () => {
790
- const audits = [];
791
- const provider = makeAuditProvider();
792
- let firstCall = true;
793
- const teardown = registerToolBridge(provider, {
794
- executor: async () => ({ ok: true }),
795
- redact: (entry) => {
796
- if (firstCall) { firstCall = false; throw new Error("redactor blew up"); }
797
- return { ...entry, args: { redacted: true } };
798
- },
799
- audit: (e) => audits.push(e),
800
- });
801
- provider.emit("tool.call", { call_id: "r1", name: "t", arguments: { secret: "x" } });
802
- await new Promise((r) => setImmediate(r));
803
- provider.emit("tool.call", { call_id: "r2", name: "t", arguments: { secret: "y" } });
804
- await new Promise((r) => setImmediate(r));
805
- assert.equal(audits.length, 2);
806
- // First: redactor threw → fell back to the RAW entry (auditing preserved).
807
- assert.equal(audits[0].args.secret, "x");
808
- // Second: custom redactor applied.
809
- assert.deepEqual(audits[1].args, { redacted: true });
810
- teardown();
811
- });
812
-
813
- test("tool-bridge: redactAuditValue is pure, cycle-safe, and truncates long strings (L11)", () => {
814
- const long = "a".repeat(1000);
815
- const out = redactAuditValue({ password: "p", note: long, nested: { token: "t", ok: 1 } });
816
- assert.equal(out.password, "***");
817
- assert.equal(out.nested.token, "***");
818
- assert.equal(out.nested.ok, 1);
819
- assert.ok(out.note.length < long.length, "long string truncated");
820
- const cyc = { a: 1 };
821
- cyc.self = cyc;
822
- const safe = redactAuditValue(cyc);
823
- assert.equal(safe.a, 1);
824
- });
825
-
826
- // ---------------------------------------------------------------------------
827
- // L13 (text coercion) + L19 (context_delivered) — outbound dispatcher.
828
- //
829
- // These tests stub global.fetch + process.env. node:test runs top-level tests
830
- // concurrently, so a module-level FIFO lock serialises every stubbed section so
831
- // two of them never overlap (one would otherwise restore the real fetch while
832
- // another is mid-flight). No other test in this file touches global.fetch.
833
- // ---------------------------------------------------------------------------
834
-
835
- let _fetchStubLock = Promise.resolve();
836
- function withFetchStubLock(fn) {
837
- const run = _fetchStubLock.then(fn, fn);
838
- // Keep the chain alive but swallow errors so one failure doesn't poison the
839
- // lock for later tests; the awaited `run` still rejects to its own caller.
840
- _fetchStubLock = run.then(() => {}, () => {});
841
- return run;
842
- }
843
-
844
- // Stub global.fetch so sendVoiceMessage runs fully offline (TTS → slack upload
845
- // flow → twilio call all resolve to canned responses).
846
- function withStubbedVoiceFetch(run) {
847
- return withFetchStubLock(() => {
848
- const realFetch = global.fetch;
849
- const env = {
850
- OPENAI_API_KEY: process.env.OPENAI_API_KEY,
851
- SLACK_BOT_TOKEN: process.env.SLACK_BOT_TOKEN,
852
- TWILIO_ACCOUNT_SID: process.env.TWILIO_ACCOUNT_SID,
853
- TWILIO_AUTH_TOKEN: process.env.TWILIO_AUTH_TOKEN,
854
- TWILIO_FROM_NUMBER: process.env.TWILIO_FROM_NUMBER,
855
- };
856
- process.env.OPENAI_API_KEY = "sk-test";
857
- process.env.SLACK_BOT_TOKEN = "xoxb-test";
858
- process.env.TWILIO_ACCOUNT_SID = "ACtest";
859
- process.env.TWILIO_AUTH_TOKEN = "tok";
860
- process.env.TWILIO_FROM_NUMBER = "+15550000000";
861
-
862
- const okJson = (obj) => ({ ok: true, status: 200, json: async () => obj, text: async () => JSON.stringify(obj) });
863
- global.fetch = async (url) => {
864
- const u = String(url);
865
- if (u.includes("/v1/audio/speech")) {
866
- return { ok: true, status: 200, arrayBuffer: async () => new Uint8Array([1, 2, 3]).buffer };
867
- }
868
- if (u.includes("files.getUploadURLExternal")) {
869
- return okJson({ ok: true, upload_url: "https://files.slack.test/upload", file_id: "F1" });
870
- }
871
- if (u.includes("files.slack.test/upload")) return { ok: true, status: 200 };
872
- if (u.includes("files.completeUploadExternal")) {
873
- return okJson({ ok: true, files: [{ permalink: "https://slack.test/f1" }] });
874
- }
875
- if (u.includes("/Calls.json")) return okJson({ sid: "CA1", status: "queued" });
876
- return okJson({ ok: true });
877
- };
878
-
879
- const restore = () => {
880
- global.fetch = realFetch;
881
- for (const [k, v] of Object.entries(env)) {
882
- if (v === undefined) delete process.env[k]; else process.env[k] = v;
883
- }
884
- };
885
- return Promise.resolve().then(run).finally(restore);
886
- });
887
- }
888
-
889
- function withStubbedOutboundFetch(opts, run) {
890
- return withFetchStubLock(() => {
891
- const realFetch = global.fetch;
892
- const env = {
893
- TWILIO_ACCOUNT_SID: process.env.TWILIO_ACCOUNT_SID,
894
- TWILIO_AUTH_TOKEN: process.env.TWILIO_AUTH_TOKEN,
895
- TWILIO_FROM_NUMBER: process.env.TWILIO_FROM_NUMBER,
896
- VOICE_RELAY_URL: process.env.VOICE_RELAY_URL,
897
- OPENAI_SIP_URI: process.env.OPENAI_SIP_URI,
898
- };
899
- process.env.TWILIO_ACCOUNT_SID = "ACtest";
900
- process.env.TWILIO_AUTH_TOKEN = "tok";
901
- process.env.TWILIO_FROM_NUMBER = "+15550000000";
902
- if (opts.relayUrl == null) delete process.env.VOICE_RELAY_URL;
903
- else process.env.VOICE_RELAY_URL = opts.relayUrl;
904
- if (opts.sipUri) process.env.OPENAI_SIP_URI = opts.sipUri;
905
- else delete process.env.OPENAI_SIP_URI;
906
-
907
- const calls = [];
908
- global.fetch = async (url, init) => {
909
- const u = String(url);
910
- calls.push({ url: u, method: init?.method });
911
- if (u.includes("/Calls/") && u.endsWith(".json")) {
912
- // cancel endpoint
913
- return { ok: true, status: 200, json: async () => ({ sid: "CA1", status: "completed" }), text: async () => "{}" };
914
- }
915
- if (u.includes("/Calls.json")) {
916
- return { ok: true, status: 200, json: async () => ({ sid: "CA1", status: "queued" }), text: async () => "{}" };
917
- }
918
- if (u.includes("/twilio/queue-outbound")) {
919
- return opts.queueOk
920
- ? { ok: true, status: 200, text: async () => "ok" }
921
- : { ok: false, status: 500, text: async () => "relay boom" };
922
- }
923
- return { ok: true, status: 200, json: async () => ({}), text: async () => "{}" };
924
- };
925
- const restore = () => {
926
- global.fetch = realFetch;
927
- for (const [k, v] of Object.entries(env)) {
928
- if (v === undefined) delete process.env[k]; else process.env[k] = v;
929
- }
930
- };
931
- return Promise.resolve().then(() => run(calls)).finally(restore);
932
- });
933
- }
934
-
935
- // L13: a non-string text (number) must flow through the delivery helpers'
936
- // String(text||"") coercion without throwing. The PSTN path routes the coerced
937
- // text into escapeXml() (the <Say> TwiML body) and slugify() — the call sites
938
- // that would throw on a non-string; deliverViaSlack shares the identical
939
- // coercion at its top.
940
- test("L13: sendVoiceMessage(pstn) tolerates non-string text via String(text||\"\") coercion", async () => {
941
- await withStubbedVoiceFetch(async () => {
942
- const r = await sendVoiceMessage({ transport: "pstn", to: "+15551234567", text: 67890 });
943
- assert.equal(r.transport, "pstn");
944
- assert.equal(r.message_id, "CA1");
945
- });
946
- });
947
-
948
- test("L19: placeOutboundCall reports context_delivered:true when relay queue succeeds", async () => {
949
- await withStubbedOutboundFetch({ relayUrl: "https://relay.test", queueOk: true }, async () => {
950
- const r = await placeOutboundCall({ to: "+15551234567", brief: "say hi", agentRoot: "/tmp/nope-agent" });
951
- assert.equal(r.transport, "media_streams");
952
- assert.equal(r.context_delivered, true);
953
- assert.equal(r.twilio_call_sid, "CA1");
954
- });
955
- });
956
-
957
- test("L19: placeOutboundCall reports context_delivered:false when relay queue fails (call still proceeds)", async () => {
958
- await withStubbedOutboundFetch({ relayUrl: "https://relay.test", queueOk: false }, async (calls) => {
959
- const r = await placeOutboundCall({ to: "+15551234567", brief: "say hi", agentRoot: "/tmp/nope-agent" });
960
- assert.equal(r.context_delivered, false);
961
- assert.equal(r.twilio_call_sid, "CA1");
962
- assert.ok(!calls.some((c) => c.url.includes("/Calls/CA1")), "no cancel call by default");
963
- });
964
- });
965
-
966
- test("L19: placeOutboundCall(cancelOnContextFail) cancels the dialed call when context fails", async () => {
967
- await withStubbedOutboundFetch({ relayUrl: "https://relay.test", queueOk: false }, async (calls) => {
968
- const r = await placeOutboundCall({
969
- to: "+15551234567",
970
- brief: "say hi",
971
- agentRoot: "/tmp/nope-agent",
972
- cancelOnContextFail: true,
973
- });
974
- assert.equal(r.context_delivered, false);
975
- assert.ok(calls.some((c) => c.url.includes("/Calls/CA1")), "cancel endpoint was hit");
976
- });
977
- });
978
-
979
- test("L19: placeOutboundCall(sip) reports context_delivered:true (no relay pre-registration)", async () => {
980
- await withStubbedOutboundFetch({ relayUrl: null, sipUri: "sip:proj@sip.openai.com", queueOk: true }, async () => {
981
- const r = await placeOutboundCall({
982
- to: "+15551234567",
983
- brief: "say hi",
984
- agentRoot: "/tmp/nope-agent",
985
- transport: "sip",
986
- });
987
- assert.equal(r.transport, "sip");
988
- assert.equal(r.context_delivered, true);
989
- });
990
- });