mixdog 1.4.0 → 1.4.2

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 (493) hide show
  1. package/package.json +3 -2
  2. package/scripts/build-shipped-history.mjs +115 -33
  3. package/scripts/check-voice-runtime-inputs.mjs +25 -0
  4. package/scripts/gate-local.mjs +183 -63
  5. package/scripts/latest-guard.mjs +21 -9
  6. package/scripts/lib/gate-scheduler.mjs +138 -32
  7. package/scripts/lib/gate-timing-reporter.mjs +16 -0
  8. package/scripts/lib/isolated-test-env.mjs +10 -5
  9. package/scripts/lib/run-node-tests.mjs +91 -66
  10. package/scripts/lib/scoped-temp.d.mts +16 -0
  11. package/scripts/lib/scoped-temp.mjs +124 -0
  12. package/scripts/lib/stale-temp.mjs +44 -0
  13. package/scripts/lib/test-failure-records.mjs +14 -1
  14. package/scripts/lib/test-failure-summary.mjs +16 -4
  15. package/scripts/lib/test-spawn-ledger.mjs +12 -3
  16. package/scripts/post-release-check.mjs +1 -6
  17. package/scripts/pptx-kit-index.mjs +17 -5
  18. package/scripts/suite-health.mjs +115 -24
  19. package/scripts/test-data-dir.mjs +10 -7
  20. package/scripts/test.mjs +9 -14
  21. package/src/agents/advisor/AGENT.md +4 -4
  22. package/src/agents/advisor/agent.json +1 -1
  23. package/src/agents/explore/AGENT.md +22 -0
  24. package/src/agents/explore/agent.json +6 -0
  25. package/src/app.mjs +4 -0
  26. package/src/cli.mjs +7 -0
  27. package/src/defaults/agents.json +7 -0
  28. package/src/defaults/shipped-history.json +23 -2
  29. package/src/defaults/skills/browser-use/SKILL.md +10 -5
  30. package/src/defaults/skills/code-tidy/SKILL.md +71 -102
  31. package/src/defaults/skills/code-tidy/references/agent-cleanup.md +66 -114
  32. package/src/defaults/skills/code-tidy/references/cleanup-report.md +19 -35
  33. package/src/defaults/skills/code-tidy/references/dead-code.md +3 -9
  34. package/src/defaults/skills/code-tidy/references/test-suite-slop.md +16 -27
  35. package/src/defaults/skills/computer-use/SKILL.md +16 -4
  36. package/src/defaults/skills/goal-management/SKILL.md +1 -1
  37. package/src/defaults/skills/setup/references/actions.md +12 -6
  38. package/src/defaults/skills/setup/references/surfaces.md +2 -2
  39. package/src/defaults/skills/setup-guide/SKILL.md +5 -2
  40. package/src/defaults/skills/setup-guide/model-recommendations.json +13 -0
  41. package/src/defaults/skills/skill-creator/SKILL.md +85 -190
  42. package/src/defaults/skills/skill-creator/references/design.md +70 -162
  43. package/src/defaults/skills/skill-creator/references/evaluation.md +33 -92
  44. package/src/defaults/skills/test-suite/SKILL.md +194 -0
  45. package/src/defaults/skills/test-suite/references/case-management.md +51 -0
  46. package/src/defaults/skills/test-suite/references/flaky-policy.md +39 -0
  47. package/src/defaults/skills/test-suite/references/reliability.md +49 -0
  48. package/src/defaults/skills/test-suite/references/suite-design.md +78 -0
  49. package/src/defaults/skills/test-suite/scripts/inventory.mjs +335 -0
  50. package/src/defaults/skills/visualize/SKILL.md +6 -2
  51. package/src/lib/rules-builder.cjs +35 -42
  52. package/src/output-styles/common.md +2 -2
  53. package/src/output-styles/simple.md +1 -1
  54. package/src/rules/agent/AGENT.md +5 -4
  55. package/src/rules/lead/LEAD.md +12 -7
  56. package/src/rules/shared/10-tool-workflow.md +3 -1
  57. package/src/rules/shared/20-research.md +3 -6
  58. package/src/rules/shared/40-editing.md +1 -0
  59. package/src/rules/shared/45-destructive.md +0 -2
  60. package/src/rules/shared/50-execution.md +2 -0
  61. package/src/rules/shared/60-verification.md +10 -9
  62. package/src/rules/shared/70-delivery.md +8 -9
  63. package/src/runtime/agent/orchestrator/agent-runtime/agent-dispatch/abort-link.mjs +5 -1
  64. package/src/runtime/agent/orchestrator/agent-runtime/agent-dispatch.mjs +10 -1
  65. package/src/runtime/agent/orchestrator/agent-runtime/agent-progress-watchdog.mjs +156 -24
  66. package/src/runtime/agent/orchestrator/agent-runtime/cache-strategy.mjs +13 -0
  67. package/src/runtime/agent/orchestrator/agent-runtime/maintenance-route.mjs +4 -1
  68. package/src/runtime/agent/orchestrator/cache-break-trace.mjs +2 -0
  69. package/src/runtime/agent/orchestrator/config.mjs +12 -7
  70. package/src/runtime/agent/orchestrator/context/deferred-tools.mjs +8 -8
  71. package/src/runtime/agent/orchestrator/context/role-instructions.mjs +5 -26
  72. package/src/runtime/agent/orchestrator/context/skill-catalog.mjs +3 -1
  73. package/src/runtime/agent/orchestrator/internal-agents.mjs +3 -14
  74. package/src/runtime/agent/orchestrator/mcp/agent-connectors.mjs +122 -12
  75. package/src/runtime/agent/orchestrator/mcp/child-tree.mjs +5 -3
  76. package/src/runtime/agent/orchestrator/mcp/client-config.mjs +13 -2
  77. package/src/runtime/agent/orchestrator/mcp/client-transport.mjs +152 -58
  78. package/src/runtime/agent/orchestrator/mcp/client.mjs +51 -18
  79. package/src/runtime/agent/orchestrator/mcp/oauth-login.mjs +88 -54
  80. package/src/runtime/agent/orchestrator/mcp/oauth.mjs +42 -26
  81. package/src/runtime/agent/orchestrator/providers/account-pool.mjs +54 -8
  82. package/src/runtime/agent/orchestrator/providers/anthropic-api-recovery.mjs +1 -1
  83. package/src/runtime/agent/orchestrator/providers/anthropic-api-request.mjs +37 -31
  84. package/src/runtime/agent/orchestrator/providers/anthropic-api-transport.mjs +8 -2
  85. package/src/runtime/agent/orchestrator/providers/anthropic-max-tokens-recovery.mjs +6 -2
  86. package/src/runtime/agent/orchestrator/providers/anthropic-messages.mjs +2 -2
  87. package/src/runtime/agent/orchestrator/providers/anthropic-oauth-client-version.mjs +1 -1
  88. package/src/runtime/agent/orchestrator/providers/anthropic-oauth-credentials.mjs +31 -21
  89. package/src/runtime/agent/orchestrator/providers/anthropic-oauth-request/initial-status.mjs +3 -1
  90. package/src/runtime/agent/orchestrator/providers/anthropic-oauth.mjs +14 -3
  91. package/src/runtime/agent/orchestrator/providers/anthropic-sse.mjs +6 -0
  92. package/src/runtime/agent/orchestrator/providers/anthropic-turn-result.mjs +2 -2
  93. package/src/runtime/agent/orchestrator/providers/antigravity-oauth-login.mjs +3 -1
  94. package/src/runtime/agent/orchestrator/providers/antigravity-oauth-tokens.mjs +2 -2
  95. package/src/runtime/agent/orchestrator/providers/codex-client-meta.mjs +1 -1
  96. package/src/runtime/agent/orchestrator/providers/command-code-oauth-login.mjs +1 -10
  97. package/src/runtime/agent/orchestrator/providers/command-code-oauth.mjs +1 -1
  98. package/src/runtime/agent/orchestrator/providers/cursor.mjs +3 -0
  99. package/src/runtime/agent/orchestrator/providers/custom-provider-config.mjs +40 -0
  100. package/src/runtime/agent/orchestrator/providers/custom-provider-keys.mjs +34 -0
  101. package/src/runtime/agent/orchestrator/providers/custom-provider.mjs +3 -0
  102. package/src/runtime/agent/orchestrator/providers/devin-auth.mjs +14 -7
  103. package/src/runtime/agent/orchestrator/providers/devin-wire-transport.mjs +3 -2
  104. package/src/runtime/agent/orchestrator/providers/devin.mjs +3 -0
  105. package/src/runtime/agent/orchestrator/providers/gemini-response.mjs +2 -2
  106. package/src/runtime/agent/orchestrator/providers/gemini-stream.mjs +4 -1
  107. package/src/runtime/agent/orchestrator/providers/grok-oauth-login.mjs +248 -41
  108. package/src/runtime/agent/orchestrator/providers/lib/anthropic-prefix-trace.mjs +76 -11
  109. package/src/runtime/agent/orchestrator/providers/lib/anthropic-request-utils.mjs +45 -6
  110. package/src/runtime/agent/orchestrator/providers/lib/first-output-window.mjs +58 -0
  111. package/src/runtime/agent/orchestrator/providers/lib/listen-on.mjs +14 -0
  112. package/src/runtime/agent/orchestrator/providers/lib/oauth-page.mjs +0 -18
  113. package/src/runtime/agent/orchestrator/providers/lib/oauth-token-utils.mjs +138 -6
  114. package/src/runtime/agent/orchestrator/providers/mimo-oauth-login.mjs +1 -10
  115. package/src/runtime/agent/orchestrator/providers/mimo-oauth.mjs +1 -1
  116. package/src/runtime/agent/orchestrator/providers/model-cache.mjs +100 -33
  117. package/src/runtime/agent/orchestrator/providers/muse-code-oauth.mjs +1 -1
  118. package/src/runtime/agent/orchestrator/providers/oauth-secret-fields.fixtures.mjs +45 -0
  119. package/src/runtime/agent/orchestrator/providers/openai-compat-chat-send.mjs +1 -0
  120. package/src/runtime/agent/orchestrator/providers/openai-compat-chat-stream/chunk-events.mjs +9 -2
  121. package/src/runtime/agent/orchestrator/providers/openai-compat-chat-stream/stream-state.mjs +7 -0
  122. package/src/runtime/agent/orchestrator/providers/openai-compat-chat-stream.mjs +14 -3
  123. package/src/runtime/agent/orchestrator/providers/openai-compat-responses-events.mjs +4 -2
  124. package/src/runtime/agent/orchestrator/providers/openai-compat-responses.mjs +1 -0
  125. package/src/runtime/agent/orchestrator/providers/openai-compat-stream-common.mjs +5 -3
  126. package/src/runtime/agent/orchestrator/providers/openai-compat-stream.mjs +16 -3
  127. package/src/runtime/agent/orchestrator/providers/openai-compat-xai-send.mjs +1 -0
  128. package/src/runtime/agent/orchestrator/providers/openai-http-sse-response-state/response-events/output-items.mjs +5 -2
  129. package/src/runtime/agent/orchestrator/providers/openai-http-sse-response-state/response-events.mjs +13 -3
  130. package/src/runtime/agent/orchestrator/providers/openai-http-sse-response-state.mjs +13 -2
  131. package/src/runtime/agent/orchestrator/providers/openai-http-sse-watchdogs.mjs +81 -42
  132. package/src/runtime/agent/orchestrator/providers/openai-oauth-http-sse.mjs +8 -0
  133. package/src/runtime/agent/orchestrator/providers/openai-oauth-login.mjs +160 -31
  134. package/src/runtime/agent/orchestrator/providers/openai-ws-stream/event-switch.mjs +22 -12
  135. package/src/runtime/agent/orchestrator/providers/openai-ws-stream.mjs +7 -1
  136. package/src/runtime/agent/orchestrator/providers/openai-ws-watchdogs.mjs +49 -22
  137. package/src/runtime/agent/orchestrator/providers/opencode-go-oauth.mjs +1 -1
  138. package/src/runtime/agent/orchestrator/providers/opencode-go.mjs +3 -1
  139. package/src/runtime/agent/orchestrator/providers/registry.mjs +45 -2
  140. package/src/runtime/agent/orchestrator/providers/vertex-ai-auth.mjs +622 -0
  141. package/src/runtime/agent/orchestrator/providers/vertex-ai-maas.mjs +185 -0
  142. package/src/runtime/agent/orchestrator/providers/vertex-ai-models.mjs +445 -0
  143. package/src/runtime/agent/orchestrator/providers/vertex-ai.mjs +567 -0
  144. package/src/runtime/agent/orchestrator/runtime-core/ask-user-tool-defs.mjs +41 -13
  145. package/src/runtime/agent/orchestrator/runtime-core/builtin-features.mjs +2 -0
  146. package/src/runtime/agent/orchestrator/runtime-core/orchestration.mjs +8 -6
  147. package/src/runtime/agent/orchestrator/runtime-core/session-text.mjs +7 -3
  148. package/src/runtime/agent/orchestrator/runtime-core/tool-catalog-data.mjs +3 -0
  149. package/src/runtime/agent/orchestrator/runtime-core/tool-defs.mjs +6 -1
  150. package/src/runtime/agent/orchestrator/runtime-core/workflow/context.mjs +14 -5
  151. package/src/runtime/agent/orchestrator/runtime-core/workflow-ids.mjs +1 -0
  152. package/src/runtime/agent/orchestrator/runtime-core/workflow.mjs +5 -2
  153. package/src/runtime/agent/orchestrator/session/agent-room.d.mts +30 -5
  154. package/src/runtime/agent/orchestrator/session/agent-room.mjs +171 -37
  155. package/src/runtime/agent/orchestrator/session/cache/scoped-cache.mjs +1 -3
  156. package/src/runtime/agent/orchestrator/session/cache-warm.mjs +102 -12
  157. package/src/runtime/agent/orchestrator/session/catalog-db/schema.mjs +4 -1
  158. package/src/runtime/agent/orchestrator/session/compact/execution-tail.mjs +1 -8
  159. package/src/runtime/agent/orchestrator/session/compact/messages.mjs +23 -0
  160. package/src/runtime/agent/orchestrator/session/compact/observation-supersession.mjs +103 -23
  161. package/src/runtime/agent/orchestrator/session/compact/runner.mjs +160 -36
  162. package/src/runtime/agent/orchestrator/session/context-utils.mjs +13 -1
  163. package/src/runtime/agent/orchestrator/session/conversation-import/claude.mjs +164 -23
  164. package/src/runtime/agent/orchestrator/session/conversation-import/codex.mjs +139 -19
  165. package/src/runtime/agent/orchestrator/session/conversation-import/convert.mjs +38 -7
  166. package/src/runtime/agent/orchestrator/session/conversation-import/imported-session.mjs +3 -0
  167. package/src/runtime/agent/orchestrator/session/conversation-import/turns.mjs +100 -22
  168. package/src/runtime/agent/orchestrator/session/eager-dispatch.mjs +4 -3
  169. package/src/runtime/agent/orchestrator/session/human-gate/requests.mjs +36 -6
  170. package/src/runtime/agent/orchestrator/session/loop/compact-policy.mjs +33 -3
  171. package/src/runtime/agent/orchestrator/session/loop/fresh-context.mjs +9 -2
  172. package/src/runtime/agent/orchestrator/session/loop/pre-dispatch-deny.mjs +1 -1
  173. package/src/runtime/agent/orchestrator/session/loop/provider-tool-exclusions.mjs +13 -5
  174. package/src/runtime/agent/orchestrator/session/loop/route-fallback.mjs +14 -0
  175. package/src/runtime/agent/orchestrator/session/loop/send-phase.mjs +13 -1
  176. package/src/runtime/agent/orchestrator/session/loop/tool-exec/before-hook.mjs +23 -4
  177. package/src/runtime/agent/orchestrator/session/loop/tool-exec/dispatch.mjs +2 -0
  178. package/src/runtime/agent/orchestrator/session/loop/tool-exec.mjs +23 -1
  179. package/src/runtime/agent/orchestrator/session/loop/tool-exposure-migration.mjs +39 -21
  180. package/src/runtime/agent/orchestrator/session/loop/turn-limits.mjs +13 -8
  181. package/src/runtime/agent/orchestrator/session/manager/ask-session.mjs +50 -28
  182. package/src/runtime/agent/orchestrator/session/manager/ask-turn-loop-options.mjs +3 -3
  183. package/src/runtime/agent/orchestrator/session/manager/ask-turn-settle.mjs +3 -1
  184. package/src/runtime/agent/orchestrator/session/manager/owner-route-fallbacks.mjs +2 -2
  185. package/src/runtime/agent/orchestrator/session/manager/prompt-utils.mjs +1 -0
  186. package/src/runtime/agent/orchestrator/session/manager/route-fallback-chain.mjs +2 -1
  187. package/src/runtime/agent/orchestrator/session/manager/rules-cache.mjs +30 -13
  188. package/src/runtime/agent/orchestrator/session/manager/runtime-liveness.mjs +63 -6
  189. package/src/runtime/agent/orchestrator/session/manager/session-close.mjs +7 -0
  190. package/src/runtime/agent/orchestrator/session/manager/session-crud.mjs +15 -0
  191. package/src/runtime/agent/orchestrator/session/manager/session-lifecycle.mjs +35 -13
  192. package/src/runtime/agent/orchestrator/session/manager/session-prompt-composition.mjs +24 -14
  193. package/src/runtime/agent/orchestrator/session/manager/session-scratch-environment.mjs +70 -0
  194. package/src/runtime/agent/orchestrator/session/manager/session-tool-surface.mjs +0 -3
  195. package/src/runtime/agent/orchestrator/session/manager/tool-resolution.mjs +10 -6
  196. package/src/runtime/agent/orchestrator/session/manager/turn-checkpoint-context.mjs +4 -0
  197. package/src/runtime/agent/orchestrator/session/manager/turn-checkpoint.mjs +3 -0
  198. package/src/runtime/agent/orchestrator/session/manager/turn-interruption.mjs +56 -29
  199. package/src/runtime/agent/orchestrator/session/manager/turn-reap.mjs +125 -0
  200. package/src/runtime/agent/orchestrator/session/mixy-name.mjs +11 -5
  201. package/src/runtime/agent/orchestrator/session/pre-send-compact.mjs +5 -1
  202. package/src/runtime/agent/orchestrator/session/prompt-cache-touch-store.mjs +30 -7
  203. package/src/runtime/agent/orchestrator/session/restart-prefix-parity.fixture.mjs +154 -0
  204. package/src/runtime/agent/orchestrator/session/store/session-delete.mjs +7 -0
  205. package/src/runtime/agent/orchestrator/session/store-summary-catalog.mjs +4 -0
  206. package/src/runtime/agent/orchestrator/session/store-summary-fields.mjs +15 -0
  207. package/src/runtime/agent/orchestrator/session/store-summary-index.mjs +37 -8
  208. package/src/runtime/agent/orchestrator/session/store-summary-reader.mjs +252 -39
  209. package/src/runtime/agent/orchestrator/session/store-transcript-cache.mjs +163 -64
  210. package/src/runtime/agent/orchestrator/session/store-transcript-projection.mjs +164 -4
  211. package/src/runtime/agent/orchestrator/session/store-transcript-worker.mjs +142 -18
  212. package/src/runtime/agent/orchestrator/session/transcript-restore/restore.mjs +61 -2
  213. package/src/runtime/agent/orchestrator/stall-policy.mjs +23 -0
  214. package/src/runtime/agent/orchestrator/tools/builtin/bash-tool/completed-result.mjs +6 -2
  215. package/src/runtime/agent/orchestrator/tools/builtin/bash-tool/invocation-plan.mjs +2 -2
  216. package/src/runtime/agent/orchestrator/tools/builtin/bash-tool/spawn-env.mjs +4 -2
  217. package/src/runtime/agent/orchestrator/tools/builtin/bash-tool.mjs +6 -1
  218. package/src/runtime/agent/orchestrator/tools/builtin/builtin-tools.mjs +46 -20
  219. package/src/runtime/agent/orchestrator/tools/builtin/cache-layers.mjs +7 -1
  220. package/src/runtime/agent/orchestrator/tools/builtin/git-command-tool.mjs +67 -31
  221. package/src/runtime/agent/orchestrator/tools/builtin/git-worktree-tool.mjs +25 -13
  222. package/src/runtime/agent/orchestrator/tools/builtin/lib/scoped-search-flight.mjs +9 -5
  223. package/src/runtime/agent/orchestrator/tools/builtin/lib/shell-job-records.mjs +58 -20
  224. package/src/runtime/agent/orchestrator/tools/builtin/read-single-stream.mjs +7 -1
  225. package/src/runtime/agent/orchestrator/tools/builtin/read-streaming.mjs +6 -3
  226. package/src/runtime/agent/orchestrator/tools/builtin/read-tool/batch-dispatch.mjs +1 -1
  227. package/src/runtime/agent/orchestrator/tools/builtin/read-tool/batch-publication.mjs +23 -12
  228. package/src/runtime/agent/orchestrator/tools/builtin/read-tool/batch-snapshot.mjs +6 -1
  229. package/src/runtime/agent/orchestrator/tools/builtin/read-tool.mjs +1 -8
  230. package/src/runtime/agent/orchestrator/tools/builtin/runtime-capabilities.mjs +20 -15
  231. package/src/runtime/agent/orchestrator/tools/builtin/shell-jobs.mjs +96 -20
  232. package/src/runtime/agent/orchestrator/tools/builtin/task-tool.mjs +59 -10
  233. package/src/runtime/agent/orchestrator/tools/code-graph/dispatch/federation.mjs +3 -1
  234. package/src/runtime/agent/orchestrator/tools/code-graph-tool-defs.mjs +1 -1
  235. package/src/runtime/agent/orchestrator/tools/graph-manifest.json +13 -13
  236. package/src/runtime/agent/orchestrator/tools/lib/isolated-test-env.mjs +4 -3
  237. package/src/runtime/agent/orchestrator/tools/lib/native-spawn-client.mjs +99 -2
  238. package/src/runtime/agent/orchestrator/tools/lib/owned-shell-trees.mjs +2 -0
  239. package/src/runtime/agent/orchestrator/tools/lib/shell-descendants.mjs +103 -13
  240. package/src/runtime/agent/orchestrator/tools/lib/shell-run-background/promote-job.mjs +3 -1
  241. package/src/runtime/agent/orchestrator/tools/lib/shell-run-settle.mjs +49 -15
  242. package/src/runtime/agent/orchestrator/tools/lib/shell-run-spawn.mjs +45 -27
  243. package/src/runtime/agent/orchestrator/tools/lib/shell-run-state.mjs +34 -10
  244. package/src/runtime/agent/orchestrator/tools/lib/shell-warm-standby.mjs +28 -4
  245. package/src/runtime/agent/orchestrator/tools/lib/wait-until-fixture.mjs +26 -0
  246. package/src/runtime/agent/orchestrator/tools/shell-command.mjs +7 -2
  247. package/src/runtime/agent/orchestrator/tools/spawn-manifest.json +13 -13
  248. package/src/runtime/channels/lib/webhook/signature.mjs +4 -1
  249. package/src/runtime/channels/lib/whisper-port.mjs +29 -11
  250. package/src/runtime/channels/lib/whisper-server.mjs +10 -1
  251. package/src/runtime/computer-bridge/action-schema.mjs +2 -2
  252. package/src/runtime/computer-bridge/core-actions.mjs +2 -2
  253. package/src/runtime/computer-bridge/error-recovery.mjs +5 -4
  254. package/src/runtime/computer-bridge/linux-action-capabilities.mjs +24 -5
  255. package/src/runtime/computer-bridge/linux-readiness.d.mts +7 -2
  256. package/src/runtime/connectors/connector-accounts-mcp.mjs +236 -103
  257. package/src/runtime/connectors/gmail-app-password.mjs +3 -3
  258. package/src/runtime/explore/explorer.mjs +93 -0
  259. package/src/runtime/explore/tool-defs.mjs +35 -0
  260. package/src/runtime/explore/tool.mjs +123 -0
  261. package/src/runtime/local-provider/server-process.mjs +2 -1
  262. package/src/runtime/media/adapters/gemini-video.mjs +4 -1
  263. package/src/runtime/media/adapters/xai-media.mjs +2 -1
  264. package/src/runtime/memory/index.mjs +4 -0
  265. package/src/runtime/memory/lib/embedding-provider.mjs +4 -1
  266. package/src/runtime/memory/lib/embedding-worker.mjs +10 -3
  267. package/src/runtime/memory/lib/memory-action-handlers/cycle-backfill-action.mjs +1 -7
  268. package/src/runtime/memory/lib/memory-chunk-quality.mjs +1 -6
  269. package/src/runtime/office/authoring/pdf-author-action.mjs +1 -6
  270. package/src/runtime/office/design/design-art-direction.mjs +29 -27
  271. package/src/runtime/office/pdf/pdf-writer.mjs +6 -1
  272. package/src/runtime/office/portable/portable-snapshot-docx.mjs +7 -1
  273. package/src/runtime/office/portable/portable-snapshot-shared.mjs +6 -1
  274. package/src/runtime/office/quality/assurance-rendered.mjs +9 -2
  275. package/src/runtime/office/quality/assurance-structure-docx.mjs +4 -2
  276. package/src/runtime/office/quality/design-review.mjs +1 -5
  277. package/src/runtime/office/quality/document-brief.mjs +1 -5
  278. package/src/runtime/office/quality/forced-break-pages.mjs +9 -6
  279. package/src/runtime/office/quality/quality-pipeline.mjs +1 -1
  280. package/src/runtime/shared/agent-route-config.mjs +17 -2
  281. package/src/runtime/shared/atomic-file.mjs +103 -2
  282. package/src/runtime/shared/background-tasks.mjs +15 -6
  283. package/src/runtime/shared/bot-owned-work.mjs +56 -0
  284. package/src/runtime/shared/connector-accounts.mjs +5 -5
  285. package/src/runtime/shared/connector-catalog.d.mts +11 -4
  286. package/src/runtime/shared/connector-catalog.mjs +60 -52
  287. package/src/runtime/shared/custom-provider-keys.mjs +20 -0
  288. package/src/runtime/shared/defaults-separation.mjs +1 -4
  289. package/src/runtime/shared/fetch-safe-listen.d.mts +16 -0
  290. package/src/runtime/shared/fetch-safe-listen.mjs +50 -0
  291. package/src/runtime/shared/file-has-data.mjs +26 -2
  292. package/src/runtime/shared/file-lock.mjs +13 -15
  293. package/src/runtime/shared/git-launch.d.mts +9 -0
  294. package/src/runtime/shared/git-launch.mjs +213 -0
  295. package/src/runtime/shared/git-runner-worker.mjs +2 -1
  296. package/src/runtime/shared/handoff-artifacts.d.mts +2 -1
  297. package/src/runtime/shared/handoff-artifacts.mjs +18 -8
  298. package/src/runtime/shared/idle-auto-clear-gate.mjs +29 -7
  299. package/src/runtime/shared/llm/cost.mjs +11 -2
  300. package/src/runtime/shared/llm/http-agent.mjs +313 -29
  301. package/src/runtime/shared/llm/model-catalog-projection.mjs +3 -2
  302. package/src/runtime/shared/llm/model-catalog.mjs +46 -6
  303. package/src/runtime/shared/llm/provider-catalog-registry.mjs +3 -0
  304. package/src/runtime/shared/llm/system-proxy.mjs +452 -0
  305. package/src/runtime/shared/loopback-listener.mjs +25 -2
  306. package/src/runtime/shared/model-route-chain.d.mts +7 -2
  307. package/src/runtime/shared/model-route-chain.mjs +22 -4
  308. package/src/runtime/shared/open-url.mjs +10 -0
  309. package/src/runtime/shared/provider-accounts.mjs +52 -2
  310. package/src/runtime/shared/session-activity-signal.mjs +14 -0
  311. package/src/runtime/shared/session-scratch.mjs +37 -0
  312. package/src/runtime/shared/staged-install-worker.mjs +5 -0
  313. package/src/runtime/shared/staged-update.mjs +47 -2
  314. package/src/runtime/shared/tool-card-model/agent-surface.mjs +1 -3
  315. package/src/runtime/shared/tool-card-model/card-status.mjs +15 -2
  316. package/src/runtime/shared/tool-result-summary.mjs +1 -1
  317. package/src/runtime/shared/tool-surface.mjs +113 -36
  318. package/src/runtime/shared/tool-work-units.mjs +6 -0
  319. package/src/runtime/shared/turn-snapshot-store.mjs +13 -6
  320. package/src/runtime/shared/turn-worktree-snapshot.mjs +414 -54
  321. package/src/runtime/shared/worktrees/activity-gate.mjs +215 -318
  322. package/src/runtime/shared/worktrees/activity-ledger-worker.mjs +56 -0
  323. package/src/runtime/shared/worktrees/activity-ledger.mjs +391 -0
  324. package/src/runtime/shared/worktrees/branch-management.mjs +9 -3
  325. package/src/runtime/shared/worktrees/contract.mjs +4 -1
  326. package/src/runtime/shared/worktrees/git.mjs +72 -0
  327. package/src/runtime/shared/worktrees/manager.mjs +285 -168
  328. package/src/runtime/shared/worktrees/test-support.mjs +6 -10
  329. package/src/runtime/tidy/install.mjs +95 -15
  330. package/src/runtime/tidy/languages.mjs +17 -15
  331. package/src/runtime/tidy/process.mjs +7 -4
  332. package/src/runtime/tidy/resolve.mjs +19 -16
  333. package/src/runtime/tidy/runners/biome.mjs +3 -3
  334. package/src/runtime/tidy/tool.mjs +1 -1
  335. package/src/runtime/tidy/worktree.mjs +10 -6
  336. package/src/runtime/visualize-bridge/client.mjs +6 -1
  337. package/src/runtime/visualize-bridge/tool-defs.mjs +7 -2
  338. package/src/runtime/web-search/index.mjs +1 -1
  339. package/src/session-runtime/agent-home-delivery.mjs +41 -0
  340. package/src/session-runtime/agent-task-sessions.mjs +458 -312
  341. package/src/session-runtime/agent-tool-routing.mjs +8 -41
  342. package/src/session-runtime/boot/tools.mjs +7 -1
  343. package/src/session-runtime/bot-status.mjs +107 -101
  344. package/src/session-runtime/bot-target.mjs +38 -0
  345. package/src/session-runtime/channel-config-api.mjs +6 -1
  346. package/src/session-runtime/connector-merge-migration.mjs +18 -15
  347. package/src/session-runtime/conversation-import/codex-titles.mjs +88 -0
  348. package/src/session-runtime/conversation-import/discovery.mjs +401 -36
  349. package/src/session-runtime/conversation-import/service.mjs +35 -8
  350. package/src/session-runtime/handoff-attachments.mjs +82 -31
  351. package/src/session-runtime/held-requests.mjs +3 -1
  352. package/src/session-runtime/internal-tool-executor/ask-user-tool.mjs +12 -13
  353. package/src/session-runtime/internal-tool-executor/bridge-tools.mjs +1 -0
  354. package/src/session-runtime/internal-tool-executor/feature-tools.mjs +2 -0
  355. package/src/session-runtime/internal-tool-executor/knowledge-tools.mjs +8 -0
  356. package/src/session-runtime/internal-tool-executor/reaction-tool.mjs +4 -1
  357. package/src/session-runtime/internal-tool-executor/workspace-tools.mjs +145 -112
  358. package/src/session-runtime/lifecycle/cold-heir.mjs +11 -6
  359. package/src/session-runtime/lifecycle/session-catalog.mjs +9 -1
  360. package/src/session-runtime/lifecycle/teardown/session-close.mjs +6 -1
  361. package/src/session-runtime/lifecycle/teardown.mjs +1 -1
  362. package/src/session-runtime/mcp-glue/server-catalog.mjs +16 -10
  363. package/src/session-runtime/mcp-glue/server-input.mjs +4 -1
  364. package/src/session-runtime/mixy-heartbeat.mjs +1 -1
  365. package/src/session-runtime/model-route/set-route.mjs +11 -2
  366. package/src/session-runtime/provider-auth/login.mjs +2 -2
  367. package/src/session-runtime/provider-catalog-cache.mjs +82 -36
  368. package/src/session-runtime/provider-models/catalog-load.mjs +23 -6
  369. package/src/session-runtime/provider-models.mjs +4 -2
  370. package/src/session-runtime/resource-mcp-api.mjs +98 -35
  371. package/src/session-runtime/resource-mcp-connector-accounts.mjs +44 -31
  372. package/src/session-runtime/resource-mcp-secrets.mjs +28 -11
  373. package/src/session-runtime/resource-mcp-servers.mjs +5 -4
  374. package/src/session-runtime/resource-recall-api.mjs +6 -1
  375. package/src/session-runtime/runtime-feature-gates.mjs +5 -1
  376. package/src/session-runtime/services/agent-tool/execute.mjs +14 -9
  377. package/src/session-runtime/services/agent-tool/job-views/agent-list.mjs +20 -4
  378. package/src/session-runtime/services/agent-tool/model-select.mjs +48 -7
  379. package/src/session-runtime/services/agent-tool/render.mjs +71 -17
  380. package/src/session-runtime/services/agent-tool/send-flow.mjs +10 -2
  381. package/src/session-runtime/services/agent-tool/spawn-flow/spawn-prep.mjs +8 -3
  382. package/src/session-runtime/services/agent-tool/spawn-flow/spawn-run.mjs +4 -1
  383. package/src/session-runtime/services/agent-tool/spawn-preset.mjs +6 -2
  384. package/src/session-runtime/services/agent-tool/tool-def.mjs +9 -9
  385. package/src/session-runtime/services/agent-watchdog-registry.mjs +32 -4
  386. package/src/session-runtime/services/channel-worker/daemon-spawn.mjs +2 -0
  387. package/src/session-runtime/services/daemon-candidate.mjs +4 -1
  388. package/src/session-runtime/services/memory-runtime-proxy/daemon-spawn.mjs +4 -0
  389. package/src/session-runtime/services/plugin-admin.mjs +10 -6
  390. package/src/session-runtime/services/provider-admin.mjs +283 -11
  391. package/src/session-runtime/session-turn-api.mjs +2 -0
  392. package/src/session-runtime/settings-builtin-tools-api.mjs +4 -1
  393. package/src/session-runtime/settings-system-api.mjs +1 -1
  394. package/src/session-runtime/setup-tool/agent-settings-actions.mjs +13 -3
  395. package/src/session-runtime/setup-tool/connector-widen-approval.mjs +96 -0
  396. package/src/session-runtime/setup-tool/executor.mjs +6 -2
  397. package/src/session-runtime/setup-tool/tool-defs.mjs +2 -1
  398. package/src/session-runtime/tool-policy/policy-stage.mjs +1 -0
  399. package/src/session-runtime/turn/agent-ops.mjs +23 -0
  400. package/src/session-runtime/workflow-agents-api/agent-connectors.mjs +49 -11
  401. package/src/session-runtime/workflow-agents-api/agent-editor.mjs +5 -1
  402. package/src/session-runtime/workflow-agents-api/agent-route.mjs +25 -5
  403. package/src/session-runtime/workflow-agents-api/onboarding.mjs +3 -3
  404. package/src/session-runtime/workspace/activity-guards.mjs +176 -0
  405. package/src/session-runtime/workspace/session-view.mjs +149 -0
  406. package/src/session-runtime/workspace/side-checkouts.mjs +203 -0
  407. package/src/session-runtime/workspace/transition-runner.mjs +188 -0
  408. package/src/session-runtime/workspace/transitions.mjs +108 -1041
  409. package/src/session-runtime/workspace/workspace-merge.mjs +132 -0
  410. package/src/session-runtime/workspace/worktree-intents.mjs +242 -0
  411. package/src/session-runtime/workspace/worktree-maintenance.mjs +80 -0
  412. package/src/session-runtime/workspace/worktree-setup.mjs +85 -0
  413. package/src/session-runtime/workspace/worktree-tool.mjs +73 -56
  414. package/src/standalone/daemon-desktop-runtime.mjs +2 -0
  415. package/src/standalone/daemon-session-control.mjs +169 -138
  416. package/src/standalone/daemon.mjs +7 -0
  417. package/src/standalone/desktop-service-registry.mjs +9 -0
  418. package/src/standalone/local-session-runtime.mjs +5 -1
  419. package/src/standalone/session-client/daemon-unavailable.mjs +3 -0
  420. package/src/standalone/session-client.mjs +5 -1
  421. package/src/standalone/session-frame-stream.mjs +83 -11
  422. package/src/standalone/session-protocol.mjs +4 -0
  423. package/src/standalone/session-service/agent-tree/agent-turns.mjs +16 -12
  424. package/src/standalone/session-service/agent-tree.mjs +45 -9
  425. package/src/standalone/session-service/projection/transcript-window.mjs +700 -64
  426. package/src/standalone/session-service/session-calls/session-action.mjs +10 -3
  427. package/src/standalone/session-service/session-calls/session-views.mjs +160 -104
  428. package/src/standalone/session-service/stored-reader.mjs +127 -40
  429. package/src/standalone/session-transport/client-registry/client-grace.mjs +12 -9
  430. package/src/tui/App.jsx +154 -164
  431. package/src/tui/app/app-view/floating-panel.jsx +10 -4
  432. package/src/tui/app/app-view/text-entry-labels.mjs +1 -0
  433. package/src/tui/app/clipboard.mjs +21 -10
  434. package/src/tui/app/model-picker/route-selection/fast-parameters.mjs +1 -3
  435. package/src/tui/app/model-picker/route-selection.mjs +5 -6
  436. package/src/tui/app/prompt-handlers/use-prompt-history-nav.mjs +1 -1
  437. package/src/tui/app/prompt-handlers/use-prompt-interrupt.mjs +3 -0
  438. package/src/tui/app/prompt-submit/provider-prompts.mjs +3 -1
  439. package/src/tui/app/provider-setup/api-key-actions.mjs +31 -1
  440. package/src/tui/app/provider-setup/oauth-actions.mjs +58 -21
  441. package/src/tui/app/provider-setup/provider-items.mjs +8 -2
  442. package/src/tui/app/provider-setup-picker.mjs +29 -18
  443. package/src/tui/app/shell-layout/row-budgets.mjs +12 -10
  444. package/src/tui/app/slash-commands.mjs +1 -0
  445. package/src/tui/app/slash-dispatch/session-commands.mjs +46 -0
  446. package/src/tui/app/slash-dispatch.mjs +1 -1
  447. package/src/tui/app/use-btw-panel.mjs +29 -0
  448. package/src/tui/app/use-context-panel-refresh.mjs +31 -0
  449. package/src/tui/app/use-model-catalog-cache.mjs +13 -10
  450. package/src/tui/app/use-mouse-input.mjs +11 -0
  451. package/src/tui/app/use-onboarding-start.mjs +8 -3
  452. package/src/tui/app/use-panel-transition.mjs +10 -1
  453. package/src/tui/app/use-pasted-buffers.mjs +28 -20
  454. package/src/tui/app/use-prompt-draft-flow.mjs +7 -0
  455. package/src/tui/app/use-prompt-layout-rows.mjs +3 -3
  456. package/src/tui/app/use-prompt-queue-history.mjs +3 -2
  457. package/src/tui/app/use-selection-focus.mjs +11 -2
  458. package/src/tui/app/use-selection-geometry.mjs +18 -9
  459. package/src/tui/app/use-selection-paint.mjs +4 -4
  460. package/src/tui/app/use-selection-stitch.mjs +3 -3
  461. package/src/tui/app/use-slash-palette.mjs +62 -0
  462. package/src/tui/app/use-terminal-chrome.mjs +2 -2
  463. package/src/tui/app/use-transcript-activity.mjs +47 -32
  464. package/src/tui/app/use-transcript-follow.mjs +12 -4
  465. package/src/tui/app/use-transcript-scroll.mjs +46 -17
  466. package/src/tui/app/use-transcript-swap-reset.mjs +27 -0
  467. package/src/tui/app/use-transcript-window/geometry.mjs +19 -5
  468. package/src/tui/app/use-transcript-window/instance-state.mjs +4 -0
  469. package/src/tui/app/use-transcript-window/selection-shift.mjs +5 -1
  470. package/src/tui/app/use-transcript-window.mjs +21 -11
  471. package/src/tui/app/use-tui-ready.mjs +18 -0
  472. package/src/tui/app/use-welcome-prompt-hint.mjs +5 -0
  473. package/src/tui/app/use-workflow-tab-cycle.mjs +5 -3
  474. package/src/tui/components/Picker.jsx +27 -3
  475. package/src/tui/components/QuestionPanel.jsx +13 -4
  476. package/src/tui/components/SignInUrl.jsx +68 -0
  477. package/src/tui/components/TextEntryPanel.jsx +76 -46
  478. package/src/tui/components/sign-in-url-layout.mjs +24 -0
  479. package/src/tui/dist/index.mjs +1963 -1361
  480. package/src/tui/session/goal-turn-state.mjs +6 -2
  481. package/src/tui/session/session-api/controls.mjs +4 -0
  482. package/src/tui/session/session-api/extensions.mjs +8 -0
  483. package/src/tui/session/session-api/intake/abort.mjs +2 -1
  484. package/src/tui/session/session-api/intake.mjs +2 -0
  485. package/src/tui/session/session-api/integrations.mjs +2 -2
  486. package/src/tui/session/session-api/routes-agent-definitions.mjs +1 -0
  487. package/src/tui/session/session-api/settings.mjs +2 -2
  488. package/src/tui/session/session-flow/queue/take-entries.mjs +11 -0
  489. package/src/tui/session/transcript-spill/spill-writer.mjs +15 -0
  490. package/src/tui/session/transcript-spill.mjs +92 -4
  491. package/src/tui/session/transcript-store.mjs +2 -0
  492. package/src/ui/statusline-agents.mjs +1 -3
  493. package/src/defaults/skills/skill-creator/references/source-review.md +0 -94
@@ -7,6 +7,7 @@ import {
7
7
  PROVIDER_SSE_IDLE_WATCHDOG_ENABLED,
8
8
  PROVIDER_SEMANTIC_IDLE_TIMEOUT_MS,
9
9
  createTimeoutSignal,
10
+ providerFirstOutputTimeoutMs,
10
11
  } from '../stall-policy.mjs';
11
12
  import {
12
13
  closeCompatStream,
@@ -23,6 +24,7 @@ import {
23
24
  parseCompletedToolCallArgumentsJson,
24
25
  } from './lib/openai-tool-args.mjs';
25
26
  import { handleCompatResponsesStreamEvent } from './openai-compat-responses-events.mjs';
27
+ import { streamFirstOutputWindow } from './lib/first-output-window.mjs';
26
28
  import {
27
29
  attachPartialState,
28
30
  createResponsesLeakRelay,
@@ -56,6 +58,7 @@ export async function consumeCompatResponsesStream(
56
58
  responseOutputText,
57
59
  knownToolNames,
58
60
  semanticIdleTimeoutMs,
61
+ sessionId = null,
59
62
  } = {}
60
63
  ) {
61
64
  try {
@@ -68,13 +71,23 @@ export async function consumeCompatResponsesStream(
68
71
  const idleEnabled = idleOverrideEnabled || PROVIDER_SSE_IDLE_WATCHDOG_ENABLED;
69
72
  // Per-event (last-event-relative) SEMANTIC idle — see the Chat path note.
70
73
  const idleMs = idleOverrideEnabled ? Number(semanticIdleTimeoutMs) : PROVIDER_SEMANTIC_IDLE_TIMEOUT_MS;
74
+ // Until the first semantic output the logical request's first-output window
75
+ // bounds the stream; a request that already had output runs under the
76
+ // semantic idle from the stream's opening.
77
+ const firstOutput = streamFirstOutputWindow({
78
+ sessionId,
79
+ onStreamDelta,
80
+ timeoutMs: providerFirstOutputTimeoutMs(idleMs),
81
+ });
71
82
  const state = createResponsesStreamState();
83
+ if (firstOutput.outputSeen) state.semanticIdleDeadlineAt = Date.now() + idleMs;
72
84
  const reportProgress = (kind) => {
73
85
  if (kind !== 'transport') state.semanticIdleDeadlineAt = Date.now() + idleMs;
74
86
  try {
75
87
  onStreamDelta?.(kind);
76
88
  } catch {}
77
89
  };
90
+ const reportLifecycle = (kind) => reportProgress(state.semanticIdleDeadlineAt > 0 ? kind : 'transport');
78
91
  let sawFirstEvent = false;
79
92
  const { relayLeakText, flushLeak, leakedCalls } = createResponsesLeakRelay({
80
93
  state,
@@ -88,6 +101,7 @@ export async function consumeCompatResponsesStream(
88
101
  parseResponsesToolCalls,
89
102
  responseOutputText,
90
103
  onStreamDelta: reportProgress,
104
+ onLifecycle: reportLifecycle,
91
105
  onToolCall,
92
106
  onTextDelta,
93
107
  onStreamItemStart,
@@ -98,9 +112,8 @@ export async function consumeCompatResponsesStream(
98
112
  while (true) {
99
113
  const { value: event, done } = await nextAsyncWithWatchdog(iterator, {
100
114
  signal: sawFirstEvent ? signal : firstByteTimeout.signal,
101
- idleMs,
102
- idleDeadlineAt: state.semanticIdleDeadlineAt,
103
- idleEnabled: sawFirstEvent && idleEnabled && state.semanticIdleDeadlineAt > 0,
115
+ ...firstOutput.idleWatch(state.semanticIdleDeadlineAt, idleMs),
116
+ idleEnabled: sawFirstEvent && idleEnabled,
104
117
  idleLabel: `${label} SSE idle`,
105
118
  streamLabel: label,
106
119
  // Unsafe-to-retry once any tool call (native or recovered-leaked)
@@ -131,6 +131,7 @@ export async function sendXaiResponses(provider, messages, useModel, tools, opts
131
131
  return await consumeCompatResponsesStream(stream, {
132
132
  signal: attemptSignal,
133
133
  label: 'xai:responses',
134
+ sessionId: opts.sessionId,
134
135
  onStreamDelta: opts.onStreamDelta,
135
136
  onToolCall: opts.onToolCall,
136
137
  onTextDelta: opts.onTextDelta,
@@ -15,7 +15,7 @@ function outputItemKind(item) {
15
15
  return 'semantic';
16
16
  }
17
17
 
18
- export function createOutputItemEvents({ state, items, meaningful }) {
18
+ export function createOutputItemEvents({ state, items, meaningful, lifecycle }) {
19
19
  const { toolTracker } = state;
20
20
 
21
21
  const onOutputItemAdded = (item) => {
@@ -52,7 +52,10 @@ export function createOutputItemEvents({ state, items, meaningful }) {
52
52
  toolTracker.mark(item);
53
53
  state.toolInFlight = true;
54
54
  }
55
- meaningful(state.toolInFlight ? 'tool' : 'semantic');
55
+ // A tool call starting is model output; an empty reasoning or message
56
+ // item is lifecycle (the silent thinking follows it).
57
+ if (state.toolInFlight) meaningful('tool');
58
+ else lifecycle('semantic');
56
59
  };
57
60
 
58
61
  const onToolInputDelta = (itemId) => {
@@ -7,18 +7,28 @@ import { createOutputItemEvents } from './response-events/output-items.mjs';
7
7
  import { createTerminalFrameEvents } from './response-events/terminal-frames.mjs';
8
8
  import { reportStreamItemStart, responsesItemStart } from '../lib/send-callbacks.mjs';
9
9
 
10
- export function createResponseEvents({ state, items, text, outcome, meaningful, onServerEvent, onStreamItemStart }) {
11
- const output = createOutputItemEvents({ state, items, meaningful });
10
+ export function createResponseEvents({
11
+ state,
12
+ items,
13
+ text,
14
+ outcome,
15
+ meaningful,
16
+ lifecycle,
17
+ onServerEvent,
18
+ onStreamItemStart,
19
+ }) {
20
+ const output = createOutputItemEvents({ state, items, meaningful, lifecycle });
12
21
  const terminal = createTerminalFrameEvents({ state, items, text, outcome, meaningful });
13
22
 
14
23
  const handleEvent = (event) => {
15
24
  if (!event || typeof event.type !== 'string') return;
16
25
  onServerEvent();
17
26
  switch (event.type) {
27
+ // The server's ack is metadata, not model output: it satisfies only the
28
+ // first-server-event deadline (onServerEvent above).
18
29
  case 'response.created':
19
30
  if (event.response?.model) state.model = event.response.model;
20
31
  if (event.response?.id) state.responseId = event.response.id;
21
- meaningful('semantic');
22
32
  break;
23
33
  case 'response.output_text.delta':
24
34
  text.relayLeakText(event.delta || '');
@@ -24,7 +24,8 @@ import { createResponseEvents } from './openai-http-sse-response-state/response-
24
24
  * @param {(call: object) => void} [deps.onToolCall]
25
25
  * @param {(text: string) => void} [deps.onTextDelta]
26
26
  * @param {(kind: string) => void} deps.meaningful semantic progress (re-arms the idle watchdog)
27
- * @param {() => void} deps.onServerEvent first-event → semantic-idle handover
27
+ * @param {(kind: string) => void} [deps.lifecycle] item lifecycle without output: progress only after semantic output
28
+ * @param {() => void} deps.onServerEvent any parsed server event (satisfies the first-server-event deadline)
28
29
  * @param {(detail: object) => void} [deps.onStreamItemStart] a tool call or phased message started
29
30
  */
30
31
  export function createHttpSseResponseState({
@@ -33,6 +34,7 @@ export function createHttpSseResponseState({
33
34
  onTextDelta,
34
35
  onStreamItemStart = null,
35
36
  meaningful,
37
+ lifecycle = () => {},
36
38
  onServerEvent,
37
39
  label,
38
40
  }) {
@@ -40,7 +42,16 @@ export function createHttpSseResponseState({
40
42
  const outcome = createResponseOutcome({ state });
41
43
  const items = createResponseItems({ state, onToolCall });
42
44
  const text = createTextRelay({ state, body, onTextDelta, meaningful, emitToolCall: items.emitToolCall });
43
- const events = createResponseEvents({ state, items, text, outcome, meaningful, onServerEvent, onStreamItemStart });
45
+ const events = createResponseEvents({
46
+ state,
47
+ items,
48
+ text,
49
+ outcome,
50
+ meaningful,
51
+ lifecycle,
52
+ onServerEvent,
53
+ onStreamItemStart,
54
+ });
44
55
 
45
56
  return {
46
57
  handleEvent: events.handleEvent,
@@ -1,7 +1,15 @@
1
1
  /**
2
2
  * openai-http-sse-watchdogs.mjs — liveness gates of one HTTP/SSE fallback
3
3
  * stream: the total/external abort relay, the fixed first-server-event
4
- * deadline, the SEMANTIC idle watchdog, and the cancellable reader.read().
4
+ * deadline, the first-OUTPUT window, the SEMANTIC idle watchdog, and the
5
+ * cancellable reader.read().
6
+ *
7
+ * Until the model's first semantic output (reasoning, text, a tool call) only
8
+ * the first-server-event deadline and the first-output window run: server
9
+ * metadata (response.created / in_progress, an empty reasoning or message
10
+ * item) and keepalives neither end that phase nor start the semantic-idle
11
+ * clock, so a model may think silently longer than the idle window. From the
12
+ * first semantic output on, the semantic idle owns the stream.
5
13
  *
6
14
  * After headerTimeout.cleanup() the in-flight fetch no longer carries a live
7
15
  * signal, so a totalTimeout / external abort that fires during a pending
@@ -17,8 +25,10 @@ import {
17
25
  PROVIDER_FIRST_BYTE_TIMEOUT_MS,
18
26
  PROVIDER_SEMANTIC_IDLE_TIMEOUT_MS,
19
27
  PROVIDER_SSE_IDLE_WATCHDOG_ENABLED,
28
+ providerFirstOutputTimeoutMs,
20
29
  streamStalledError,
21
30
  } from '../stall-policy.mjs';
31
+ import { streamFirstOutputWindow } from './lib/first-output-window.mjs';
22
32
 
23
33
  function positiveOverride(value) {
24
34
  const ms = Number(value);
@@ -31,8 +41,18 @@ function positiveOverride(value) {
31
41
  * @param {ReadableStreamDefaultReader} deps.reader
32
42
  * @param {{ signal?: AbortSignal, cleanup(): void }} deps.totalTimeout
33
43
  * @param {() => object} deps.stallPartial streamed partial state attached to a semantic-idle stall
44
+ * @param {string|null} [deps.sessionId] the session whose logical request this stream serves
45
+ * @param {Function} [deps.onStreamDelta] the stream's progress callback; without it the stream is a fork of the request
34
46
  */
35
- export function createHttpSseWatchdogs({ opts, reader, totalTimeout, stallPartial, label: LABEL }) {
47
+ export function createHttpSseWatchdogs({
48
+ opts,
49
+ reader,
50
+ totalTimeout,
51
+ stallPartial,
52
+ label: LABEL,
53
+ sessionId = null,
54
+ onStreamDelta,
55
+ }) {
36
56
  let abortReason = null;
37
57
  let pendingReadReject = null;
38
58
  const rejectPendingRead = (err) => {
@@ -58,9 +78,46 @@ export function createHttpSseWatchdogs({ opts, reader, totalTimeout, stallPartia
58
78
  else totalTimeout.signal.addEventListener('abort', onTotalAbort, { once: true });
59
79
  }
60
80
 
61
- // Initial wait is governed only by the fixed first-server-event policy.
62
- // Semantic idle begins after a parsed server event, so a lower
63
- // semantic-idle override cannot shorten this first-event wait.
81
+ // SEMANTIC idle watchdog: reset ONLY on meaningful() (text/reasoning/tool
82
+ // deltas), never on raw bytes/keepalive frames, so a stream that emits some
83
+ // deltas then goes silent trips a short, named terminal failure instead of
84
+ // hanging until the 30-min agent watchdog. Disablable via the shared env.
85
+ let semanticIdleTimer = null;
86
+ const semanticIdleOverrideMs = positiveOverride(opts?._semanticIdleTimeoutMs);
87
+ const semanticIdleMs = semanticIdleOverrideMs || PROVIDER_SEMANTIC_IDLE_TIMEOUT_MS;
88
+ const semanticIdleEnabled = semanticIdleOverrideMs > 0 || PROVIDER_SSE_IDLE_WATCHDOG_ENABLED;
89
+ // FIRST-OUTPUT window of the logical request this stream serves, retired by
90
+ // the first semantic output. Metadata-only streams (repeated
91
+ // response.in_progress, keepalive/ping frames, unknown event types) cannot
92
+ // refresh it, so a wedge that never produces a token still ends here.
93
+ const firstOutputOverrideMs = positiveOverride(opts?._firstOutputTimeoutMs);
94
+ const firstOutput = streamFirstOutputWindow({
95
+ sessionId,
96
+ onStreamDelta,
97
+ timeoutMs: firstOutputOverrideMs || providerFirstOutputTimeoutMs(semanticIdleMs),
98
+ });
99
+ const firstOutputEnabled = firstOutputOverrideMs > 0 || semanticIdleEnabled;
100
+
101
+ // A stalled stream fails with the named stall error, carrying the streamed
102
+ // partial state so the agent loop can accept a wedged FINAL no-tool summary
103
+ // as a successful partial-final instead of dropping the result.
104
+ // pendingToolUse gates out any mid-flight tool call.
105
+ const abortStalled = (timeoutMs) => {
106
+ const partial = stallPartial();
107
+ const err = streamStalledError(LABEL, timeoutMs, { emittedToolCall: partial.emittedToolCall });
108
+ try {
109
+ err.partialContent = partial.content;
110
+ err.partialToolCalls = partial.toolCalls;
111
+ err.pendingToolUse = partial.pendingToolUse;
112
+ err.partialModel = partial.model;
113
+ } catch {
114
+ /* best-effort enrichment */
115
+ }
116
+ abortStream(err);
117
+ };
118
+
119
+ // Initial wait for any server event is governed by the fixed
120
+ // first-server-event policy; a lower semantic-idle override cannot shorten it.
64
121
  let firstServerEventTimer = null;
65
122
  const firstServerEventMs = positiveOverride(opts?._firstServerEventTimeoutMs) || PROVIDER_FIRST_BYTE_TIMEOUT_MS;
66
123
  const clearFirstServerEvent = () => {
@@ -82,15 +139,15 @@ export function createHttpSseWatchdogs({ opts, reader, totalTimeout, stallPartia
82
139
  firstServerEventTimer.unref?.();
83
140
  } catch {}
84
141
  };
142
+ // Until the stream's first output the request's first-output window bounds
143
+ // it. A request that already had output has none: its stream runs under the
144
+ // semantic idle from its first server event (noteServerEvent).
145
+ const armFirstOutput = () => {
146
+ if (!firstOutput.outputSeen && firstOutputEnabled && firstOutput.timeoutMs > 0) {
147
+ firstOutput.arm(() => abortStalled(firstOutput.timeoutMs));
148
+ }
149
+ };
85
150
 
86
- // SEMANTIC idle watchdog: reset ONLY on meaningful() (text/reasoning/tool
87
- // deltas), never on raw bytes/keepalive frames, so a stream that emits some
88
- // deltas then goes silent trips a short, named terminal failure instead of
89
- // hanging until the 30-min agent watchdog. Disablable via the shared env.
90
- let semanticIdleTimer = null;
91
- const semanticIdleOverrideMs = positiveOverride(opts?._semanticIdleTimeoutMs);
92
- const semanticIdleMs = semanticIdleOverrideMs || PROVIDER_SEMANTIC_IDLE_TIMEOUT_MS;
93
- const semanticIdleEnabled = semanticIdleOverrideMs > 0 || PROVIDER_SSE_IDLE_WATCHDOG_ENABLED;
94
151
  const clearSemanticIdle = () => {
95
152
  if (semanticIdleTimer) {
96
153
  clearTimeout(semanticIdleTimer);
@@ -100,43 +157,22 @@ export function createHttpSseWatchdogs({ opts, reader, totalTimeout, stallPartia
100
157
  const armSemanticIdle = () => {
101
158
  if (!semanticIdleEnabled || !(semanticIdleMs > 0)) return;
102
159
  clearSemanticIdle();
103
- semanticIdleTimer = setTimeout(() => {
104
- const partial = stallPartial();
105
- const err = streamStalledError(LABEL, semanticIdleMs, { emittedToolCall: partial.emittedToolCall });
106
- // Partial-final recovery: attach the streamed partial state so the
107
- // agent loop can accept a wedged FINAL no-tool summary as a successful
108
- // partial-final instead of dropping the result. pendingToolUse gates
109
- // out any mid-flight tool call.
110
- try {
111
- err.partialContent = partial.content;
112
- err.partialToolCalls = partial.toolCalls;
113
- err.pendingToolUse = partial.pendingToolUse;
114
- err.partialModel = partial.model;
115
- } catch {
116
- /* best-effort enrichment */
117
- }
118
- abortStream(err);
119
- }, semanticIdleMs);
160
+ semanticIdleTimer = setTimeout(() => abortStalled(semanticIdleMs), semanticIdleMs);
120
161
  try {
121
162
  semanticIdleTimer.unref?.();
122
163
  } catch {}
123
164
  };
124
- // One-shot latch for the first-server-event → semantic-idle handover. Once
125
- // the FIRST real SSE server event arrives, the fixed initial deadline is
126
- // satisfied and semantic-idle ownership begins. Arming on every parsed event
127
- // let a metadata-only stream (repeated response.in_progress, keepalive/ping
128
- // frames, unknown event types) refresh the watchdog forever without
129
- // producing a single token. Only meaningful progress re-arms it from then on.
130
- let semanticIdleArmed = false;
165
+ // A parsed server event satisfies the first-server-event deadline and, for a
166
+ // request that already had output, starts the semantic idle (once: only
167
+ // output re-arms it).
131
168
  const noteServerEvent = () => {
132
169
  clearFirstServerEvent();
133
- if (!semanticIdleArmed) {
134
- semanticIdleArmed = true;
135
- armSemanticIdle();
136
- }
170
+ if (firstOutput.outputSeen && !semanticIdleTimer) armSemanticIdle();
137
171
  };
172
+ // Semantic output: the first one ends the first-output phase; every one
173
+ // re-arms the semantic idle.
138
174
  const noteMeaningful = () => {
139
- semanticIdleArmed = true;
175
+ firstOutput.noteOutput();
140
176
  armSemanticIdle();
141
177
  };
142
178
 
@@ -151,6 +187,7 @@ export function createHttpSseWatchdogs({ opts, reader, totalTimeout, stallPartia
151
187
  const dispose = () => {
152
188
  pendingReadReject = null;
153
189
  clearFirstServerEvent();
190
+ firstOutput.clear();
154
191
  clearSemanticIdle();
155
192
  try {
156
193
  reader.releaseLock?.();
@@ -165,9 +202,11 @@ export function createHttpSseWatchdogs({ opts, reader, totalTimeout, stallPartia
165
202
  return {
166
203
  abortReason: () => abortReason,
167
204
  armFirstServerEvent,
205
+ armFirstOutput,
168
206
  clearSemanticIdle,
169
207
  noteServerEvent,
170
208
  noteMeaningful,
209
+ semanticSeen: () => firstOutput.outputSeen,
171
210
  read,
172
211
  dispose,
173
212
  };
@@ -183,6 +183,8 @@ export async function sendViaHttpSse({
183
183
  totalTimeout,
184
184
  stallPartial: () => state.stallPartial(),
185
185
  label,
186
+ sessionId: opts?.sessionId,
187
+ onStreamDelta,
186
188
  });
187
189
  const meaningful = (kind = 'semantic') => {
188
190
  if (ttftMs == null) ttftMs = Date.now() - sseStartedAt;
@@ -191,12 +193,17 @@ export async function sendViaHttpSse({
191
193
  onStreamDelta?.(kind);
192
194
  } catch {}
193
195
  };
196
+ // An empty reasoning or message item added: progress only after output.
197
+ const lifecycle = (kind = 'semantic') => {
198
+ if (watchdogs.semanticSeen()) meaningful(kind);
199
+ };
194
200
  const state = createHttpSseResponseState({
195
201
  body,
196
202
  onToolCall,
197
203
  onTextDelta,
198
204
  onStreamItemStart: typeof opts?.onStreamItemStart === 'function' ? opts.onStreamItemStart : null,
199
205
  meaningful,
206
+ lifecycle,
200
207
  onServerEvent: watchdogs.noteServerEvent,
201
208
  label,
202
209
  });
@@ -210,6 +217,7 @@ export async function sendViaHttpSse({
210
217
  let buffer = '';
211
218
  try {
212
219
  watchdogs.armFirstServerEvent();
220
+ watchdogs.armFirstOutput();
213
221
  while (true) {
214
222
  if (totalTimeout.signal?.aborted) {
215
223
  watchdogs.clearSemanticIdle();
@@ -12,9 +12,11 @@ import { createServer } from 'node:http';
12
12
  import { randomBytes } from 'node:crypto';
13
13
  import { createOAuthPkce, parseOAuthCodeInput } from './lib/oauth-pkce.mjs';
14
14
  import { OAUTH_PAGE_CONTENT_TYPE, oauthErrorHtml, oauthSuccessHtml } from './lib/oauth-page.mjs';
15
+ import { oauthFailureReason, oauthHttpError, oauthRequestError, oauthResponseJson } from './lib/oauth-token-utils.mjs';
15
16
  import { openLoginUrl } from './lib/open-login-url.mjs';
17
+ import { sleepWithAbort } from './retry-backoff.mjs';
16
18
 
17
- const TOKEN_URL = 'https://auth.openai.com/oauth/token';
19
+ const DEFAULT_ISSUER = 'https://auth.openai.com';
18
20
  const AUTHORIZE_URL = 'https://auth.openai.com/oauth/authorize';
19
21
  const CODEX_OAUTH_SCOPE = 'openid profile email offline_access api.connectors.read api.connectors.invoke';
20
22
  const CALLBACK_HOST = '127.0.0.1';
@@ -23,14 +25,9 @@ const CALLBACK_PATH = '/auth/callback';
23
25
  const REDIRECT_URI = `http://localhost:${CALLBACK_PORT}${CALLBACK_PATH}`;
24
26
  const LOGIN_TIMEOUT_MS = 5 * 60_000;
25
27
  const TOKEN_TIMEOUT_MS = 30_000;
26
-
27
- function _scrubOAuthLoginBody(text) {
28
- return String(text || '')
29
- .replace(/"access_token"\s*:\s*"[^"]+"/g, '"access_token":"[REDACTED]"')
30
- .replace(/"refresh_token"\s*:\s*"[^"]+"/g, '"refresh_token":"[REDACTED]"')
31
- .replace(/"id_token"\s*:\s*"[^"]+"/g, '"id_token":"[REDACTED]"')
32
- .replace(/[A-Za-z0-9_-]{32,}\.[A-Za-z0-9._-]+/g, '[REDACTED]');
33
- }
28
+ // Codex device-code login: the user has 15 minutes to enter the code.
29
+ const DEVICE_LOGIN_TIMEOUT_MS = 15 * 60_000;
30
+ const DEFAULT_DEVICE_INTERVAL_S = 5;
34
31
 
35
32
  /**
36
33
  * @param {object} deps
@@ -40,34 +37,59 @@ function _scrubOAuthLoginBody(text) {
40
37
  * @param {(...tokens:string[])=>(object|null)} deps.identityFromTokens
41
38
  * @param {(token:string)=>number} deps.expiryFromAccessToken
42
39
  * @param {(tokens:object)=>void} deps.saveTokens
40
+ * @param {string} [deps.issuer] auth server base URL (tests point it at a fake server)
41
+ * @param {(ms:number, signal?:AbortSignal)=>Promise<void>} [deps.sleep] device-poll wait (tests inject a fast one)
42
+ * @param {()=>number} [deps.now]
43
+ * @param {number} [deps.deviceTimeoutMs] device-code login deadline (tests shorten it)
44
+ * @param {number} [deps.requestTimeoutMs] deadline of the device-code start request (tests shorten it)
43
45
  */
44
46
  export function createOpenAIOAuthLogin(deps) {
45
- const { clientId, originator, extractAccountId, identityFromTokens, expiryFromAccessToken, saveTokens } = deps;
47
+ const {
48
+ clientId,
49
+ originator,
50
+ extractAccountId,
51
+ identityFromTokens,
52
+ expiryFromAccessToken,
53
+ saveTokens,
54
+ issuer = DEFAULT_ISSUER,
55
+ sleep = sleepWithAbort,
56
+ now = Date.now,
57
+ deviceTimeoutMs = DEVICE_LOGIN_TIMEOUT_MS,
58
+ requestTimeoutMs = TOKEN_TIMEOUT_MS,
59
+ } = deps;
60
+ const issuerBase = issuer.replace(/\/+$/, '');
61
+ const tokenUrl = `${issuerBase}/oauth/token`;
62
+ const deviceApiBase = `${issuerBase}/api/accounts`;
46
63
 
47
- async function exchangeAuthorizationCode({ pkce, code, signal = null }) {
64
+ async function exchangeAuthorizationCode({ pkce, code, redirectUri = REDIRECT_URI, signal = null }) {
48
65
  signal?.throwIfAborted();
49
66
  const cleanCode = String(code || '').trim();
50
67
  if (!cleanCode) throw new Error('[openai-oauth] authorization code is required');
51
- const tokenRes = await fetch(TOKEN_URL, {
52
- method: 'POST',
53
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
54
- body: new URLSearchParams({
55
- grant_type: 'authorization_code',
56
- code: cleanCode,
57
- redirect_uri: REDIRECT_URI,
58
- client_id: clientId,
59
- code_verifier: pkce.verifier,
60
- }),
61
- redirect: 'error',
62
- signal: signal
63
- ? AbortSignal.any([signal, AbortSignal.timeout(TOKEN_TIMEOUT_MS)])
64
- : AbortSignal.timeout(TOKEN_TIMEOUT_MS),
65
- });
68
+ let tokenRes;
69
+ try {
70
+ tokenRes = await fetch(tokenUrl, {
71
+ method: 'POST',
72
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
73
+ body: new URLSearchParams({
74
+ grant_type: 'authorization_code',
75
+ code: cleanCode,
76
+ redirect_uri: redirectUri,
77
+ client_id: clientId,
78
+ code_verifier: pkce.verifier,
79
+ }),
80
+ redirect: 'error',
81
+ signal: signal
82
+ ? AbortSignal.any([signal, AbortSignal.timeout(TOKEN_TIMEOUT_MS)])
83
+ : AbortSignal.timeout(TOKEN_TIMEOUT_MS),
84
+ });
85
+ } catch (err) {
86
+ throw oauthRequestError('[openai-oauth] token exchange', err);
87
+ }
66
88
  if (!tokenRes.ok) {
67
89
  const text = await tokenRes.text().catch(() => '');
68
- throw new Error(`[openai-oauth] token exchange ${tokenRes.status}: ${_scrubOAuthLoginBody(text).slice(0, 500)}`);
90
+ throw oauthHttpError('[openai-oauth] token exchange', tokenRes.status, text, [cleanCode, pkce.verifier]);
69
91
  }
70
- const json = await tokenRes.json();
92
+ const json = await oauthResponseJson(tokenRes, '[openai-oauth] token exchange');
71
93
  if (!json.access_token || !json.refresh_token) {
72
94
  throw new Error('[openai-oauth] token exchange response missing access_token or refresh_token');
73
95
  }
@@ -87,7 +109,114 @@ export function createOpenAIOAuthLogin(deps) {
87
109
  return tokens;
88
110
  }
89
111
 
112
+ const postJson = (path, body, signal) =>
113
+ fetch(`${deviceApiBase}${path}`, {
114
+ method: 'POST',
115
+ headers: { 'Content-Type': 'application/json' },
116
+ body: JSON.stringify(body),
117
+ redirect: 'error',
118
+ signal,
119
+ });
120
+
121
+ // Codex device-code flow (`codex login --device-auth`): the user enters a
122
+ // short code at the verification URL on any machine; this host polls until
123
+ // the server hands back an authorization code, then exchanges it with the
124
+ // deviceauth redirect URI. Resolves null when the server has no device flow.
125
+ async function beginDeviceLogin() {
126
+ // No login deadline or cancel handle exists yet, so the start request
127
+ // carries its own timeout; it also bounds reading the response body.
128
+ const startSignal = AbortSignal.timeout(requestTimeoutMs);
129
+ const res = await postJson('/deviceauth/usercode', { client_id: clientId }, startSignal);
130
+ if (res.status === 404) return null;
131
+ if (!res.ok) throw new Error(`[openai-oauth] device code request failed with status ${res.status}`);
132
+ const started = await res.json();
133
+ const userCode = started.user_code || started.usercode;
134
+ const deviceAuthId = started.device_auth_id;
135
+ if (!userCode || !deviceAuthId)
136
+ throw new Error('[openai-oauth] device code response missing user_code or device_auth_id');
137
+ const interval = Number(String(started.interval ?? '').trim());
138
+ const intervalMs = (Number.isFinite(interval) && interval > 0 ? interval : DEFAULT_DEVICE_INTERVAL_S) * 1000;
139
+ const url = `${issuerBase}/codex/device`;
140
+
141
+ const controller = new AbortController();
142
+ const { signal } = controller;
143
+ const timedOut = () => new Error('[openai-oauth] device auth timed out after 15 minutes');
144
+ // One poll, aborted at the login deadline so a stalled request cannot
145
+ // outlive it. A reply that arrives in time is honoured whatever the clock
146
+ // says afterwards (the user did authorize).
147
+ const pollOnce = async (left) => {
148
+ const deadlineController = new AbortController();
149
+ const timer = setTimeout(() => deadlineController.abort(), left);
150
+ try {
151
+ const poll = await postJson(
152
+ '/deviceauth/token',
153
+ { device_auth_id: deviceAuthId, user_code: userCode },
154
+ AbortSignal.any([signal, deadlineController.signal])
155
+ );
156
+ if (poll.ok) return { granted: await poll.json() };
157
+ // 403/404: the user has not approved the code yet.
158
+ if (poll.status !== 403 && poll.status !== 404) {
159
+ throw new Error(`[openai-oauth] device auth failed with status ${poll.status}`);
160
+ }
161
+ return { granted: null };
162
+ } catch (err) {
163
+ if (!signal.aborted && deadlineController.signal.aborted) throw timedOut();
164
+ throw err;
165
+ } finally {
166
+ clearTimeout(timer);
167
+ }
168
+ };
169
+ const pollForCode = async () => {
170
+ const deadline = now() + deviceTimeoutMs;
171
+ for (;;) {
172
+ const left = deadline - now();
173
+ if (left <= 0) throw timedOut();
174
+ const { granted } = await pollOnce(left);
175
+ if (granted) return granted;
176
+ await sleep(Math.min(intervalMs, Math.max(0, deadline - now())), signal);
177
+ }
178
+ };
179
+ const waitForCallback = (async () => {
180
+ try {
181
+ const granted = await pollForCode();
182
+ return await exchangeAuthorizationCode({
183
+ pkce: { verifier: granted.code_verifier },
184
+ code: granted.authorization_code,
185
+ redirectUri: `${issuerBase}/deviceauth/callback`,
186
+ signal,
187
+ });
188
+ } catch (err) {
189
+ // A cancelled login settles empty, as the browser flow does.
190
+ if (signal.aborted) return null;
191
+ throw err;
192
+ }
193
+ })();
194
+ // A cancelled or expired login may reject before a host attaches a listener.
195
+ waitForCallback.catch(() => {});
196
+ process.stderr.write(
197
+ `\n[openai-oauth] To log in to ChatGPT (OpenAI OAuth), open:\n${url}\nand enter this code: ${userCode}\n\n`
198
+ );
199
+ return {
200
+ provider: 'openai-oauth',
201
+ url,
202
+ userCode,
203
+ waitForCallback,
204
+ cancel: () => controller.abort(),
205
+ };
206
+ }
207
+
208
+ // Without a browser on this host (headless/SSH) the device-code flow is used;
209
+ // like Codex, a server that has none (404) falls back to the browser flow.
90
210
  async function beginOAuthLogin({ openBrowser = true } = {}) {
211
+ if (!openBrowser) {
212
+ const device = await beginDeviceLogin();
213
+ if (device) return device;
214
+ process.stderr.write('\n[openai-oauth] Device code login is not enabled; falling back to browser login.\n');
215
+ }
216
+ return await beginBrowserLogin({ openBrowser });
217
+ }
218
+
219
+ async function beginBrowserLogin({ openBrowser }) {
91
220
  const pkce = createOAuthPkce(64);
92
221
  const state = randomBytes(16).toString('hex');
93
222
  const url = new URL(AUTHORIZE_URL);
@@ -161,10 +290,10 @@ export function createOpenAIOAuthLogin(deps) {
161
290
  // written; do not leave a keep-alive connection bound to it.
162
291
  res.writeHead(200, { 'Content-Type': OAUTH_PAGE_CONTENT_TYPE, Connection: 'close' });
163
292
  res.end(oauthSuccessHtml('OpenAI'));
164
- } catch {
165
- // The shared exchange reports its error through waitForCallback.
293
+ } catch (err) {
294
+ // The shared exchange also reports its error through waitForCallback.
166
295
  res.writeHead(500, { 'Content-Type': OAUTH_PAGE_CONTENT_TYPE, Connection: 'close' });
167
- res.end(oauthErrorHtml('OpenAI could not complete the token exchange.'));
296
+ res.end(oauthErrorHtml(oauthFailureReason('OpenAI could not complete the token exchange.', err)));
168
297
  }
169
298
  });
170
299
  timeout = setTimeout(() => finish(null), LOGIN_TIMEOUT_MS);