mixdog 1.2.1 → 1.2.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 (233) hide show
  1. package/package.json +1 -1
  2. package/scripts/gate-local.mjs +19 -3
  3. package/scripts/model-catalog-audit.mjs +1 -15
  4. package/src/agents/reviewer/AGENT.md +3 -3
  5. package/src/agents/reviewer/agent.json +1 -1
  6. package/src/defaults/shipped-history.json +1 -0
  7. package/src/repl/slash-commands.mjs +16 -1
  8. package/src/runtime/agent/orchestrator/agent-runtime/agent-progress-watchdog.mjs +29 -4
  9. package/src/runtime/agent/orchestrator/agent-runtime/cache-strategy.mjs +10 -0
  10. package/src/runtime/agent/orchestrator/mcp/client-config.mjs +36 -7
  11. package/src/runtime/agent/orchestrator/mcp/client-handshake.mjs +49 -10
  12. package/src/runtime/agent/orchestrator/mcp/client-transport.mjs +40 -3
  13. package/src/runtime/agent/orchestrator/mcp/client.mjs +230 -96
  14. package/src/runtime/agent/orchestrator/mcp/oauth-callback.mjs +103 -0
  15. package/src/runtime/agent/orchestrator/mcp/oauth-credentials.mjs +150 -0
  16. package/src/runtime/agent/orchestrator/mcp/oauth-login.mjs +111 -0
  17. package/src/runtime/agent/orchestrator/mcp/oauth-probe.mjs +87 -0
  18. package/src/runtime/agent/orchestrator/mcp/oauth-provider.mjs +95 -0
  19. package/src/runtime/agent/orchestrator/mcp/oauth-request.mjs +122 -0
  20. package/src/runtime/agent/orchestrator/mcp/oauth-shared.mjs +9 -0
  21. package/src/runtime/agent/orchestrator/mcp/oauth.mjs +229 -0
  22. package/src/runtime/agent/orchestrator/providers/account-pool.mjs +188 -29
  23. package/src/runtime/agent/orchestrator/providers/anthropic-api-recovery.mjs +2 -1
  24. package/src/runtime/agent/orchestrator/providers/anthropic-api-transport.mjs +94 -31
  25. package/src/runtime/agent/orchestrator/providers/anthropic-error-contract.mjs +96 -0
  26. package/src/runtime/agent/orchestrator/providers/anthropic-fast-mode.mjs +39 -18
  27. package/src/runtime/agent/orchestrator/providers/anthropic-max-tokens-recovery.mjs +55 -0
  28. package/src/runtime/agent/orchestrator/providers/anthropic-max-tokens.mjs +25 -21
  29. package/src/runtime/agent/orchestrator/providers/anthropic-messages.mjs +3 -1
  30. package/src/runtime/agent/orchestrator/providers/anthropic-midstream-recovery.mjs +18 -4
  31. package/src/runtime/agent/orchestrator/providers/anthropic-model-resolve.mjs +13 -1
  32. package/src/runtime/agent/orchestrator/providers/anthropic-oauth-client-version.mjs +1 -1
  33. package/src/runtime/agent/orchestrator/providers/anthropic-oauth-midstream.mjs +10 -1
  34. package/src/runtime/agent/orchestrator/providers/anthropic-oauth-recovery.mjs +23 -9
  35. package/src/runtime/agent/orchestrator/providers/anthropic-oauth-request/initial-status.mjs +46 -20
  36. package/src/runtime/agent/orchestrator/providers/anthropic-oauth-request.mjs +14 -9
  37. package/src/runtime/agent/orchestrator/providers/anthropic-oauth.mjs +73 -35
  38. package/src/runtime/agent/orchestrator/providers/anthropic-overload-fallback.mjs +69 -0
  39. package/src/runtime/agent/orchestrator/providers/anthropic-server-fallback.mjs +4 -0
  40. package/src/runtime/agent/orchestrator/providers/anthropic-sse.mjs +8 -1
  41. package/src/runtime/agent/orchestrator/providers/anthropic.mjs +34 -7
  42. package/src/runtime/agent/orchestrator/providers/antigravity-oauth-catalog.mjs +30 -9
  43. package/src/runtime/agent/orchestrator/providers/antigravity-oauth.mjs +7 -0
  44. package/src/runtime/agent/orchestrator/providers/antigravity-request.mjs +30 -14
  45. package/src/runtime/agent/orchestrator/providers/antigravity-response.mjs +2 -1
  46. package/src/runtime/agent/orchestrator/providers/antigravity-retry-policy.mjs +93 -0
  47. package/src/runtime/agent/orchestrator/providers/antigravity-transport.mjs +82 -9
  48. package/src/runtime/agent/orchestrator/providers/command-code-oauth.mjs +3 -0
  49. package/src/runtime/agent/orchestrator/providers/cursor-auth.mjs +38 -5
  50. package/src/runtime/agent/orchestrator/providers/cursor-client-version.mjs +1 -1
  51. package/src/runtime/agent/orchestrator/providers/cursor-wire-guards.mjs +97 -2
  52. package/src/runtime/agent/orchestrator/providers/cursor-wire-stream-bridge.mjs +102 -23
  53. package/src/runtime/agent/orchestrator/providers/cursor-wire-transport.mjs +103 -33
  54. package/src/runtime/agent/orchestrator/providers/cursor-wire.mjs +29 -6
  55. package/src/runtime/agent/orchestrator/providers/cursor.mjs +18 -1
  56. package/src/runtime/agent/orchestrator/providers/effort-configuration.mjs +77 -17
  57. package/src/runtime/agent/orchestrator/providers/gemini-cache-policy.mjs +1 -1
  58. package/src/runtime/agent/orchestrator/providers/gemini-cache.mjs +29 -8
  59. package/src/runtime/agent/orchestrator/providers/gemini-error-contract.mjs +191 -0
  60. package/src/runtime/agent/orchestrator/providers/gemini-family.mjs +9 -0
  61. package/src/runtime/agent/orchestrator/providers/gemini-history-signatures.mjs +9 -4
  62. package/src/runtime/agent/orchestrator/providers/gemini-response.mjs +3 -1
  63. package/src/runtime/agent/orchestrator/providers/gemini-retry-policy.mjs +180 -0
  64. package/src/runtime/agent/orchestrator/providers/gemini-schema.mjs +21 -82
  65. package/src/runtime/agent/orchestrator/providers/gemini-sdk-request.mjs +4 -1
  66. package/src/runtime/agent/orchestrator/providers/gemini-stream.mjs +71 -12
  67. package/src/runtime/agent/orchestrator/providers/gemini-thinking.mjs +21 -20
  68. package/src/runtime/agent/orchestrator/providers/gemini.mjs +56 -23
  69. package/src/runtime/agent/orchestrator/providers/grok-oauth-tokens.mjs +3 -0
  70. package/src/runtime/agent/orchestrator/providers/grok-oauth.mjs +68 -19
  71. package/src/runtime/agent/orchestrator/providers/mimo-oauth.mjs +3 -0
  72. package/src/runtime/agent/orchestrator/providers/model-list-sanitize.mjs +2 -1
  73. package/src/runtime/agent/orchestrator/providers/muse-code-oauth.mjs +4 -9
  74. package/src/runtime/agent/orchestrator/providers/openai-compat-chat-send.mjs +4 -2
  75. package/src/runtime/agent/orchestrator/providers/openai-compat-chat-stream/stream-result.mjs +22 -0
  76. package/src/runtime/agent/orchestrator/providers/openai-compat-chat-stream.mjs +1 -0
  77. package/src/runtime/agent/orchestrator/providers/openai-compat-error-contract.mjs +50 -0
  78. package/src/runtime/agent/orchestrator/providers/openai-compat-response-normalization.mjs +23 -0
  79. package/src/runtime/agent/orchestrator/providers/openai-compat-responses-events.mjs +16 -8
  80. package/src/runtime/agent/orchestrator/providers/openai-compat-responses-state.mjs +3 -2
  81. package/src/runtime/agent/orchestrator/providers/openai-compat-responses.mjs +94 -13
  82. package/src/runtime/agent/orchestrator/providers/openai-compat-retry-profile.mjs +193 -0
  83. package/src/runtime/agent/orchestrator/providers/openai-compat-stream-common.mjs +66 -2
  84. package/src/runtime/agent/orchestrator/providers/openai-compat-stream.mjs +2 -1
  85. package/src/runtime/agent/orchestrator/providers/openai-compat-wire.mjs +6 -0
  86. package/src/runtime/agent/orchestrator/providers/openai-compat-xai-send.mjs +4 -2
  87. package/src/runtime/agent/orchestrator/providers/openai-compat-xai.mjs +23 -14
  88. package/src/runtime/agent/orchestrator/providers/openai-compat.mjs +17 -3
  89. package/src/runtime/agent/orchestrator/providers/openai-direct-request.mjs +42 -25
  90. package/src/runtime/agent/orchestrator/providers/openai-error-contract.mjs +274 -0
  91. package/src/runtime/agent/orchestrator/providers/openai-http-sse-request.mjs +72 -32
  92. package/src/runtime/agent/orchestrator/providers/openai-http-sse-response-state/response-events/terminal-frames.mjs +18 -11
  93. package/src/runtime/agent/orchestrator/providers/openai-http-sse-response-state/response-outcome.mjs +1 -2
  94. package/src/runtime/agent/orchestrator/providers/openai-http-sse-response-state/response-stamps.mjs +2 -2
  95. package/src/runtime/agent/orchestrator/providers/openai-http-sse-response-state/response-state.mjs +2 -3
  96. package/src/runtime/agent/orchestrator/providers/openai-http-sse-response-state.mjs +2 -2
  97. package/src/runtime/agent/orchestrator/providers/openai-http-sse-watchdogs.mjs +1 -3
  98. package/src/runtime/agent/orchestrator/providers/openai-oauth-dispatch.mjs +34 -3
  99. package/src/runtime/agent/orchestrator/providers/openai-oauth-http-sse.mjs +5 -1
  100. package/src/runtime/agent/orchestrator/providers/openai-oauth-tokens.mjs +22 -2
  101. package/src/runtime/agent/orchestrator/providers/openai-oauth.mjs +5 -0
  102. package/src/runtime/agent/orchestrator/providers/openai-responses-input.mjs +5 -9
  103. package/src/runtime/agent/orchestrator/providers/openai-retry-policy.mjs +9 -0
  104. package/src/runtime/agent/orchestrator/providers/openai-ws-handshake.mjs +16 -8
  105. package/src/runtime/agent/orchestrator/providers/openai-ws-send-attempts/attempt-context.mjs +1 -2
  106. package/src/runtime/agent/orchestrator/providers/openai-ws-send-attempts/policy.mjs +25 -14
  107. package/src/runtime/agent/orchestrator/providers/openai-ws-terminal.mjs +18 -11
  108. package/src/runtime/agent/orchestrator/providers/openai-ws.mjs +31 -20
  109. package/src/runtime/agent/orchestrator/providers/provider-error-kind.mjs +581 -0
  110. package/src/runtime/agent/orchestrator/providers/retry-backoff.mjs +46 -7
  111. package/src/runtime/agent/orchestrator/providers/retry-classification.mjs +118 -219
  112. package/src/runtime/agent/orchestrator/providers/retry-classifier.mjs +2 -0
  113. package/src/runtime/agent/orchestrator/providers/retry-executor.mjs +148 -45
  114. package/src/runtime/agent/orchestrator/providers/retry-midstream.mjs +81 -16
  115. package/src/runtime/agent/orchestrator/runtime-core/config-helpers.mjs +3 -0
  116. package/src/runtime/agent/orchestrator/runtime-core/goal-reminder.mjs +0 -18
  117. package/src/runtime/agent/orchestrator/runtime-core/model-capabilities.mjs +57 -28
  118. package/src/runtime/agent/orchestrator/runtime-core/orchestration.mjs +19 -16
  119. package/src/runtime/agent/orchestrator/runtime-core/plugin-mcp.mjs +1 -97
  120. package/src/runtime/agent/orchestrator/session/catalog-db/schema.mjs +3 -1
  121. package/src/runtime/agent/orchestrator/session/loop/send-phase.mjs +4 -0
  122. package/src/runtime/agent/orchestrator/session/loop/step-auto-effort.mjs +102 -18
  123. package/src/runtime/agent/orchestrator/session/loop/tool-phase.mjs +3 -1
  124. package/src/runtime/agent/orchestrator/session/manager/ask-queue.mjs +30 -2
  125. package/src/runtime/agent/orchestrator/session/manager/ask-session.mjs +11 -2
  126. package/src/runtime/agent/orchestrator/session/manager/ask-turn-execute.mjs +41 -21
  127. package/src/runtime/agent/orchestrator/session/manager/pending-message-entry.mjs +5 -10
  128. package/src/runtime/agent/orchestrator/session/manager/session-close.mjs +1 -1
  129. package/src/runtime/agent/orchestrator/session/manager/turn-interruption.mjs +18 -7
  130. package/src/runtime/agent/orchestrator/session/send-with-recovery.mjs +155 -29
  131. package/src/runtime/agent/orchestrator/session/store/save-worker.mjs +6 -3
  132. package/src/runtime/agent/orchestrator/session/store/write-guards.mjs +16 -0
  133. package/src/runtime/agent/orchestrator/session/store-agent-worker-rows.mjs +22 -10
  134. package/src/runtime/agent/orchestrator/session/store-summary-catalog.mjs +2 -0
  135. package/src/runtime/agent/orchestrator/session/store-summary-fields.mjs +5 -0
  136. package/src/runtime/agent/orchestrator/session/store-summary-index.mjs +3 -0
  137. package/src/runtime/agent/orchestrator/session/transcript-restore/restore.mjs +20 -1
  138. package/src/runtime/agent/orchestrator/tools/builtin/arg-guard.mjs +2 -2
  139. package/src/runtime/agent/orchestrator/tools/builtin/bash-tool/deadline-plan.mjs +12 -15
  140. package/src/runtime/agent/orchestrator/tools/builtin/builtin-tools.mjs +5 -5
  141. package/src/runtime/memory/lib/pg/process.mjs +34 -24
  142. package/src/runtime/memory/lib/pg/supervisor.mjs +16 -13
  143. package/src/runtime/office/README.md +1 -1
  144. package/src/runtime/office/shared/values.mjs +0 -5
  145. package/src/runtime/shared/background-tasks.mjs +92 -14
  146. package/src/runtime/shared/err-text.mjs +25 -0
  147. package/src/runtime/shared/error-presentation.mjs +159 -19
  148. package/src/runtime/shared/llm/anthropic-betas.mjs +4 -3
  149. package/src/runtime/shared/llm/anthropic-effort.mjs +123 -134
  150. package/src/runtime/shared/llm/anthropic-thinking-contract.mjs +50 -14
  151. package/src/runtime/shared/llm/model-catalog.mjs +53 -40
  152. package/src/runtime/shared/llm/openai-daybreak.mjs +4 -16
  153. package/src/runtime/shared/llm/provider-catalog-registry.mjs +11 -0
  154. package/src/runtime/shared/llm/provider-model-identities.mjs +13 -4
  155. package/src/runtime/shared/llm/usage-rollup.mjs +0 -1
  156. package/src/runtime/shared/model-display.mjs +13 -0
  157. package/src/runtime/shared/quota-resume-store.mjs +11 -0
  158. package/src/runtime/shared/session-baseline-store.mjs +960 -0
  159. package/src/runtime/shared/statusline/statusline-format.mjs +4 -4
  160. package/src/runtime/shared/task-notification-envelope.mjs +2 -2
  161. package/src/runtime/shared/turn-changes.mjs +447 -219
  162. package/src/runtime/shared/turn-snapshot-store.mjs +182 -1
  163. package/src/runtime/shared/turn-snapshot.mjs +170 -48
  164. package/src/runtime/shared/turn-worktree-snapshot.mjs +135 -46
  165. package/src/runtime/shared/worktrees/contract.mjs +0 -24
  166. package/src/runtime/shared/worktrees/test-support.mjs +19 -4
  167. package/src/session-runtime/boot/apis.mjs +6 -0
  168. package/src/session-runtime/boot/infrastructure.mjs +6 -0
  169. package/src/session-runtime/lifecycle/session-catalog.mjs +2 -0
  170. package/src/session-runtime/lifecycle/teardown.mjs +1 -1
  171. package/src/session-runtime/mcp-glue/connect.mjs +29 -9
  172. package/src/session-runtime/mcp-glue/server-catalog.mjs +20 -3
  173. package/src/session-runtime/mcp-glue.mjs +3 -0
  174. package/src/session-runtime/mcp-oauth-login.mjs +174 -0
  175. package/src/session-runtime/model-route/model-switch-target.mjs +34 -0
  176. package/src/session-runtime/model-route/set-route.mjs +83 -15
  177. package/src/session-runtime/model-route/web-search-route.mjs +1 -1
  178. package/src/session-runtime/native-web-search/routes.mjs +22 -3
  179. package/src/session-runtime/provider-models/model-meta.mjs +12 -3
  180. package/src/session-runtime/quick-model-rows/web-search-rows.mjs +13 -8
  181. package/src/session-runtime/quick-web-search-models.mjs +13 -38
  182. package/src/session-runtime/resource-extension-sync.mjs +4 -0
  183. package/src/session-runtime/resource-mcp-api.mjs +98 -2
  184. package/src/session-runtime/runtime-review-api.mjs +13 -0
  185. package/src/session-runtime/services/agent-tool/job-task-reconcile.mjs +13 -1
  186. package/src/session-runtime/services/agent-tool/job-views/agent-list.mjs +7 -2
  187. package/src/session-runtime/services/agent-tool/send-flow.mjs +22 -4
  188. package/src/session-runtime/services/agent-tool/spawn-flow/job-start.mjs +2 -0
  189. package/src/session-runtime/services/agent-tool/spawn-flow/spawn-run.mjs +22 -5
  190. package/src/session-runtime/services/agent-tool/worker-index/row-liveness.mjs +8 -1
  191. package/src/session-runtime/services/agent-tool/worker-index/row-shape.mjs +2 -2
  192. package/src/session-runtime/services/agent-tool/worker-rows.mjs +17 -0
  193. package/src/session-runtime/settings-compaction-api.mjs +1 -0
  194. package/src/standalone/daemon-drain-policy.mjs +8 -0
  195. package/src/standalone/daemon-telemetry.mjs +55 -0
  196. package/src/standalone/daemon.mjs +3 -7
  197. package/src/standalone/session-protocol.mjs +7 -0
  198. package/src/standalone/session-service/agent-tree/agent-cancel.mjs +33 -2
  199. package/src/standalone/session-service/agent-tree/agent-turns.mjs +26 -10
  200. package/src/standalone/session-service/agent-tree.mjs +12 -0
  201. package/src/standalone/session-service/quota-resume.mjs +8 -0
  202. package/src/standalone/session-service/retention/busy.mjs +15 -1
  203. package/src/standalone/session-service-api.mjs +5 -0
  204. package/src/standalone/session-service.mjs +1 -0
  205. package/src/tui/app/app-view.jsx +1 -0
  206. package/src/tui/app/create-app-pickers.mjs +4 -0
  207. package/src/tui/app/extension-pickers/mcp-login.mjs +107 -0
  208. package/src/tui/app/extension-pickers/mcp-servers-picker.mjs +2 -1
  209. package/src/tui/app/extension-pickers.mjs +2 -1
  210. package/src/tui/app/model-options.mjs +11 -16
  211. package/src/tui/app/slash-commands.mjs +7 -2
  212. package/src/tui/app/slash-dispatch/panel-commands.mjs +16 -1
  213. package/src/tui/components/StatusLine.jsx +2 -0
  214. package/src/tui/components/status-line/local-line.mjs +5 -2
  215. package/src/tui/components/status-line/use-statusline-text.mjs +7 -1
  216. package/src/tui/dist/index.mjs +816 -43
  217. package/src/tui/session/quota-resume.mjs +46 -14
  218. package/src/tui/session/session-api/commands.mjs +33 -24
  219. package/src/tui/session/session-api/extensions.mjs +22 -0
  220. package/src/tui/session/session-api/integrations.mjs +7 -0
  221. package/src/tui/session/session-api/lifecycle.mjs +5 -1
  222. package/src/tui/session/session-api/routes.mjs +71 -7
  223. package/src/tui/session/session-api/settings.mjs +5 -14
  224. package/src/tui/session/session-flow/drain.mjs +7 -1
  225. package/src/tui/session/session-flow/failed-turn-rewind.mjs +10 -4
  226. package/src/tui/session/turn.mjs +38 -15
  227. package/src/tui/statusline-ansi-bridge.mjs +1 -1
  228. package/src/ui/statusline-agents.mjs +15 -4
  229. package/src/ui/statusline.mjs +7 -3
  230. package/src/ui/streaming-markdown-heal.mjs +34 -3
  231. package/src/vendor/statusline/src/gateway/claude-current.mjs +14 -4
  232. package/src/runtime/memory/lib/memory-session-merge.mjs +0 -32
  233. package/src/runtime/shared/llm/usage-session-history.mjs +0 -266
@@ -11,6 +11,7 @@
11
11
  import {
12
12
  cancelQuotaResumeEntry,
13
13
  forgetQuotaSuspendedGoal,
14
+ isAgentOnlySession,
14
15
  noteQuotaSuspendedGoal,
15
16
  publicQuotaResume,
16
17
  quotaAutoResumeEnabled,
@@ -73,6 +74,20 @@ export function latestQuotaFailure(items) {
73
74
  return null;
74
75
  }
75
76
 
77
+ /** The turn key of the failed turndone that ends the transcript, when no
78
+ * later turn has begun; '' otherwise. */
79
+ export function latestFailedTurnKey(items) {
80
+ const transcript = Array.isArray(items) ? items : [];
81
+ for (let index = transcript.length - 1; index >= 0; index -= 1) {
82
+ const item = transcript[index];
83
+ if (item?.kind === 'user' || item?.archived === true) return '';
84
+ if (item?.kind !== 'turndone') continue;
85
+ if (String(item.status || '').toLowerCase() !== 'failed') return '';
86
+ return transcriptTurnKeys(transcript)[index] || '';
87
+ }
88
+ return '';
89
+ }
90
+
76
91
  /** What retrying the turn submits: its prompt when it produced no output, the
77
92
  * continuation instruction when it did, null when the prompt carried no text
78
93
  * (a media/attachment-only prompt cannot be replayed). */
@@ -125,6 +140,8 @@ export function createQuotaResumeLane(bag) {
125
140
  routeProvider: String(runtime.sessionProvider ?? runtime.provider ?? ''),
126
141
  routeModel: String(runtime.sessionModel ?? runtime.model ?? ''),
127
142
  });
143
+ // A delegated agent child never owns a resume: the Lead decides its retries.
144
+ const agentOnly = () => isAgentOnlySession({ id: currentId(), ...runtime.session });
128
145
  const queueResume = (sessionId, failure) =>
129
146
  scheduleQuotaResumeEntry({ sessionId, turnKey: failure.turnKey, ...failure.quota, ...sessionRoute() });
130
147
 
@@ -141,6 +158,21 @@ export function createQuotaResumeLane(bag) {
141
158
  forgetQuotaSuspendedGoal(sessionId);
142
159
  };
143
160
 
161
+ // Anything running, settling, closing or queued owns the session first.
162
+ const retryBlocked = () => {
163
+ const state = getState();
164
+ return (
165
+ flags.disposed ||
166
+ settlement !== null ||
167
+ (flags.admission || 'open') !== 'open' ||
168
+ state.busy ||
169
+ state.commandBusy ||
170
+ flags.autoClearRunning ||
171
+ flags.draining ||
172
+ pending.length > 0
173
+ );
174
+ };
175
+
144
176
  /** The one retry operation. `automatic` is the scheduler's resume: it
145
177
  * enqueues directly, because the hours it waited must not trigger the idle
146
178
  * auto-clear a user submission starts. */
@@ -166,7 +198,7 @@ export function createQuotaResumeLane(bag) {
166
198
  settlement = null;
167
199
  if (!id || !failure) return null;
168
200
  settlement = { sessionId: id, turnKey: failure.turnKey, epoch: cancelEpoch };
169
- if (failure.quota.resetAt === null || !quotaAutoResumeEnabled()) return null;
201
+ if (failure.quota.resetAt === null || !quotaAutoResumeEnabled() || agentOnly()) return null;
170
202
  return queueResume(id, failure);
171
203
  },
172
204
 
@@ -188,6 +220,7 @@ export function createQuotaResumeLane(bag) {
188
220
  /** Explicit request to auto-resume the latest quota-failed turn. */
189
221
  scheduleQuotaResume(sessionId) {
190
222
  requireAddressed(sessionId);
223
+ if (agentOnly()) throw new Error('agent sessions do not auto-resume; the Lead decides retries');
191
224
  const failure = latestQuotaFailure(getState().items);
192
225
  if (!failure || failure.quota.resetAt === null) {
193
226
  throw new Error('latest turn did not fail on exhausted provider quota with a known reset time');
@@ -207,9 +240,15 @@ export function createQuotaResumeLane(bag) {
207
240
  if (sessionId) cancelFor(String(sessionId));
208
241
  },
209
242
 
243
+ /** A deferred retry request (the desktop's switch-model flow): checked
244
+ * against the session's own state when it arrives, so it runs only while
245
+ * `turnKey` is still the latest failed turn and nothing is running,
246
+ * settling or queued. False when refused. */
210
247
  async retryFailedTurn(sessionId, turnKey) {
211
248
  requireAddressed(sessionId);
212
- return (await retryFailedTurn(String(turnKey || ''))) === true;
249
+ const key = String(turnKey || '');
250
+ if (!key || retryBlocked() || latestFailedTurnKey(getState().items) !== key) return false;
251
+ return (await retryFailedTurn(key)) === true;
213
252
  },
214
253
 
215
254
  /** Scheduler fire for the entry of `generation`, after a usable reading.
@@ -219,19 +258,12 @@ export function createQuotaResumeLane(bag) {
219
258
  const id = currentId();
220
259
  const entry = quotaResumeEntry(id);
221
260
  if (!id || !entry || entry.generation !== generation) return 'stale';
222
- const state = getState();
223
- if (
224
- flags.disposed ||
225
- settlement !== null ||
226
- (flags.admission || 'open') !== 'open' ||
227
- state.busy ||
228
- state.commandBusy ||
229
- flags.autoClearRunning ||
230
- flags.draining ||
231
- pending.length > 0
232
- ) {
233
- return 'busy';
261
+ if (agentOnly()) {
262
+ cancelQuotaResumeEntry(id, { generation });
263
+ return 'agent-session';
234
264
  }
265
+ const state = getState();
266
+ if (retryBlocked()) return 'busy';
235
267
  const failure = latestQuotaFailure(state.items);
236
268
  if (!failure || failure.turnKey !== entry.turnKey) {
237
269
  cancelQuotaResumeEntry(id, { generation });
@@ -92,34 +92,43 @@ export function createSessionCommandsApi(bag) {
92
92
  };
93
93
  };
94
94
 
95
+ // The compaction pass itself, under a lock its caller holds. `quiet` (the
96
+ // model switch's pre-compaction) asks the compactor to skip a pass that
97
+ // would not reduce anything and then adds no row for it.
98
+ async function runCompaction(startedAt, { quiet = false } = {}) {
99
+ // Give Ink one event-loop turn to paint the compacting spinner before
100
+ // runtime.compact() starts synchronous session/transcript work (same
101
+ // yield as the auto-clear path; without it /compact looks frozen with
102
+ // no spinner until the compact already finished).
103
+ await new Promise((resolve) => setTimeout(resolve, 0));
104
+ const result = await runtime.compact({ recoverAgent: true, ...(quiet ? { requireReduction: true } : {}) });
105
+ const compactChanged = Boolean(result && !result.error && result.changed !== false);
106
+ syncContextStats({
107
+ allowEstimated: true,
108
+ invalidateExact: compactChanged,
109
+ });
110
+ set({ ...routeState(), stats: { ...getState().stats } });
111
+ if (compactChanged) {
112
+ // The compacted rows stay visible (archived) above the divider.
113
+ const { items } = archiveItemsForCompaction(getState().items, compactDoneItem(result, startedAt), null, {
114
+ archived: compactionArchivedRows(result),
115
+ });
116
+ set({ items: replaceItems(items, { preserveSpill: true }) });
117
+ } else if (!quiet || result?.error) {
118
+ pushItem(compactDoneItem(result, startedAt));
119
+ }
120
+ return result;
121
+ }
122
+
123
+ // An in-place model switch compacts first on the current model (routes.mjs
124
+ // holds the command lock and shows the compacting status meanwhile).
125
+ bag.compactBeforeModelSwitch = () => runCompaction(Date.now(), { quiet: true });
126
+
95
127
  async function compactCommand() {
96
128
  if (getState().commandBusy) return null;
97
129
  if (getState().busy) return scheduleCompactForTurnEnd(compactCommand);
98
130
  try {
99
- return await withCommandStatus('Compacting conversation', 'compacting', async (startedAt) => {
100
- // Give Ink one event-loop turn to paint the compacting spinner before
101
- // runtime.compact() starts synchronous session/transcript work (same
102
- // yield as the auto-clear path; without it /compact looks frozen with
103
- // no spinner until the compact already finished).
104
- await new Promise((resolve) => setTimeout(resolve, 0));
105
- const result = await runtime.compact({ recoverAgent: true });
106
- const compactChanged = Boolean(result && !result.error && result.changed !== false);
107
- syncContextStats({
108
- allowEstimated: true,
109
- invalidateExact: compactChanged,
110
- });
111
- set({ ...routeState(), stats: { ...getState().stats } });
112
- if (compactChanged) {
113
- // The compacted rows stay visible (archived) above the divider.
114
- const { items } = archiveItemsForCompaction(getState().items, compactDoneItem(result, startedAt), null, {
115
- archived: compactionArchivedRows(result),
116
- });
117
- set({ items: replaceItems(items, { preserveSpill: true }) });
118
- } else {
119
- pushItem(compactDoneItem(result, startedAt));
120
- }
121
- return result;
122
- });
131
+ return await withCommandStatus('Compacting conversation', 'compacting', (startedAt) => runCompaction(startedAt));
123
132
  } finally {
124
133
  // A command reply reads the published snapshot, not the draft. Commit
125
134
  // completion before the awaiting service constructs that reply.
@@ -28,6 +28,13 @@ export function createSessionExtensionsApi(bag) {
28
28
  { busyError: 'Another command is still running; try again when it finishes.' }
29
29
  );
30
30
  const pluginLabel = (result, plugin) => result?.plugin?.title || result?.plugin?.name || plugin?.name || plugin;
31
+ // MCP OAuth sign-in methods the runtime must implement (no silent fallback).
32
+ const mcpOAuth =
33
+ (name) =>
34
+ (...args) => {
35
+ if (typeof runtime[name] !== 'function') throw new Error('MCP sign-in is unavailable');
36
+ return runtime[name](...args);
37
+ };
31
38
 
32
39
  return {
33
40
  mcpStatus: () => {
@@ -55,6 +62,19 @@ export function createSessionExtensionsApi(bag) {
55
62
  (name) => runtime.removeMcpServer?.(name),
56
63
  (_status, name) => [`mcp removed: ${name}`]
57
64
  ),
65
+ // Explicit OAuth sign-in: no command lock, the flow runs on the server's
66
+ // own connect lane and the caller polls its status. The caller (TUI app)
67
+ // owns the sign-in completion notice; the store never posts one.
68
+ beginMcpOAuthLogin: async (name, options) => {
69
+ const result = await mcpOAuth('beginMcpOAuthLogin')(name, options);
70
+ if (result?.state === 'pending') pushNotice(`mcp sign-in started: ${name}`, 'info');
71
+ return result;
72
+ },
73
+ getMcpOAuthLoginStatus: mcpOAuth('getMcpOAuthLoginStatus'),
74
+ cancelMcpOAuthLogin: mcpOAuth('cancelMcpOAuthLogin'),
75
+ completeMcpOAuthLogin: mcpOAuth('completeMcpOAuthLogin'),
76
+ signOutMcpServer: lockedChange(mcpOAuth('signOutMcpServer'), (_status, name) => [`mcp signed out: ${name}`]),
77
+ probeMcpServerAuth: mcpOAuth('probeMcpServerAuth'),
58
78
  setMcpServerEnabled: async (name, enabled) => {
59
79
  // No global commandBusy: the runtime adopts config synchronously and
60
80
  // serializes the heavy connect/close/recreate per server name, so rapid
@@ -70,6 +90,8 @@ export function createSessionExtensionsApi(bag) {
70
90
  const row = status?.servers?.find((s) => s.name === name);
71
91
  if (enabled && row && (row.status === 'failed' || row.error)) {
72
92
  pushNotice(`mcp enable failed: ${name}${row.error ? ` — ${row.error}` : ''}`, 'error');
93
+ } else if (enabled && row?.authRequired) {
94
+ pushNotice(`mcp enabled: ${name} — sign-in required`, 'warn');
73
95
  } else {
74
96
  pushNotice(`mcp ${enabled ? 'enabled' : 'disabled'}: ${name}`, 'info');
75
97
  }
@@ -78,6 +78,13 @@ export function createSessionIntegrationsApi(bag, { oauthFlows }) {
78
78
  revision
79
79
  );
80
80
  },
81
+ clearSessionChangeHistory: async () => {
82
+ // A queued or running prompt/command may still be about to record changes.
83
+ if (getState().busy || getState().commandBusy) {
84
+ throw new Error('Change history cannot be deleted while this session is running a turn');
85
+ }
86
+ return await requireRuntimeMethod('clearSessionChangeHistory', 'Change history deletion is unavailable')();
87
+ },
81
88
  getOnboardingStatus: () => {
82
89
  return runtime.getOnboardingStatus?.() || { completed: true, workflowRoutes: {} };
83
90
  },
@@ -8,6 +8,7 @@ import { createSessionResetActions } from './lifecycle/session-reset.mjs';
8
8
  import { createInheritanceActions } from './lifecycle/inheritance.mjs';
9
9
  import { createResumeAction } from './lifecycle/resume.mjs';
10
10
  import { createDisposeAction } from './lifecycle/dispose.mjs';
11
+ import { publishModelSwitch } from './routes.mjs';
11
12
 
12
13
  export function createSessionLifecycleApi(bag, { restoreTranscriptItems, oauthFlows }) {
13
14
  const { runtime, pushNotice, removeNotice, setProgressHint, finishToolApproval } = bag;
@@ -85,9 +86,12 @@ export function createSessionLifecycleApi(bag, { restoreTranscriptItems, oauthFl
85
86
  bag.supersedeQuotaResume?.(sessionId);
86
87
  bag.set({ commandBusy: true });
87
88
  try {
88
- await runtime.continueSessionInModel(sessionId, route);
89
+ const result = await runtime.continueSessionInModel(sessionId, route);
89
90
  bag.set({ ...bag.routeState(), stats: { ...bag.getState().stats } });
90
91
  bag.syncContextStats?.({ allowEstimated: true });
92
+ // The same live divider as a picker switch; IPC and remote callers
93
+ // see it through the published snapshot.
94
+ publishModelSwitch(bag, result?.modelSwitch);
91
95
  return true;
92
96
  } finally {
93
97
  bag.set({ commandBusy: false });
@@ -3,6 +3,9 @@
3
3
  * the serialized optimistic setRoute, web-search route, workflows, agent
4
4
  * definitions, output style and orchestration mode.
5
5
  */
6
+ import { modelSwitchItem } from '../../../runtime/agent/orchestrator/session/transcript-restore/restore.mjs';
7
+ import { selectedModel, switchesSessionModel } from '../../../session-runtime/model-route/model-switch-target.mjs';
8
+ import { latestQuotaFailure } from '../quota-resume.mjs';
6
9
  import { createApiHelpers } from './shared.mjs';
7
10
 
8
11
  // Optimistic route preview: the requested provider/model/effort/fast are
@@ -47,6 +50,12 @@ function optimisticRoutePatch(requested = {}, current = {}) {
47
50
  return patch;
48
51
  }
49
52
 
53
+ /** The live divider of an in-place model switch (restored from message meta
54
+ * after a reload); every switch path publishes it the same way. */
55
+ export function publishModelSwitch(bag, modelSwitch) {
56
+ if (modelSwitch) bag.pushItem(modelSwitchItem(bag.nextId(), modelSwitch));
57
+ }
58
+
50
59
  export function createSessionRouteApi(bag) {
51
60
  const {
52
61
  runtime,
@@ -68,32 +77,84 @@ export function createSessionRouteApi(bag) {
68
77
  let routeWrite = null;
69
78
  let routeSequence = 0;
70
79
 
80
+ // A preset selector previews as the preset's model, never as its id.
81
+ const previewedRequest = (routeOpts) => {
82
+ if (routeOpts.provider || !routeOpts.model) return routeOpts;
83
+ const target = selectedModel(runtime, routeOpts, '', '');
84
+ return target.provider ? { ...routeOpts, ...target } : routeOpts;
85
+ };
86
+
87
+ // Auto-compact on model change (default on): compact on the CURRENT model,
88
+ // whose cache and window still hold the history, before the switch. A model
89
+ // stopped on its quota cannot run it; the next turn's auto-compaction on the
90
+ // new model fits the history instead. A failure never blocks the switch.
91
+ const compactBeforeModelSwitch = async () => {
92
+ if (runtime.getCompactionSettings?.()?.onModelChange === false) return;
93
+ if (latestQuotaFailure(getState().items)) return;
94
+ if (typeof bag.compactBeforeModelSwitch !== 'function') return;
95
+ set({
96
+ commandStatus: { active: true, verb: 'Compacting conversation', startedAt: Date.now(), mode: 'compacting' },
97
+ });
98
+ flushEmitImmediate();
99
+ try {
100
+ await bag.compactBeforeModelSwitch();
101
+ } catch {
102
+ /* the switch goes ahead; next-turn auto-compaction fits the window */
103
+ } finally {
104
+ set({ commandStatus: null });
105
+ }
106
+ };
107
+
71
108
  const setRoute = async (opts) => {
72
109
  if (getState().commandBusy && !routeWrite) return false;
110
+ const routeOpts = opts && typeof opts === 'object' ? opts : {};
111
+ // Every user model choice on this surface (composer picker, /model,
112
+ // presets, the TUI picker) switches the conversation itself in place.
113
+ const switchesModel = switchesSessionModel(runtime, routeOpts);
114
+ // A running turn keeps the route it started on.
115
+ if (switchesModel && getState().busy) {
116
+ throw new Error('The model cannot change while a response is running. Try again when it finishes.');
117
+ }
73
118
  // Any route change supersedes waiting for the old route's quota reset.
74
119
  bag.supersedeQuotaResume?.(getState().sessionId);
75
120
  const token = ++routeSequence;
76
121
  const previousWrite = routeWrite;
77
- const routeOpts = opts && typeof opts === 'object' ? opts : {};
78
- const preview = optimisticRoutePatch(routeOpts, getState());
122
+ const preview = optimisticRoutePatch(previewedRequest(routeOpts), getState());
79
123
  // Preview immediately, serialize persistence without dropping a later
80
124
  // click. Earlier completions cannot replace the newest visible choice.
81
- set({ commandBusy: true, ...(preview || {}) });
125
+ // A model switch previews once its pre-compaction (which republishes the
126
+ // current route) is done.
127
+ set({ commandBusy: true, ...(switchesModel ? {} : preview || {}) });
82
128
  flushEmitImmediate();
83
129
  const write = (async () => {
84
130
  if (previousWrite) await previousWrite.catch(() => {});
85
131
  const previousRoute = routeState();
86
132
  try {
87
- // Explicit addressing initializes an empty session in place; the
88
- // runtime continues to own established-session route policy.
133
+ // Explicit addressing applies the route to this session: an empty
134
+ // one is initialized in place. Either way an established
135
+ // conversation follows the user's choice in place.
89
136
  const applyToCurrentSession = routeOpts.applyToCurrentSession === true;
90
137
  const keepMainModel = routeOpts.keepMainModel === true;
91
138
  const { applyToCurrentSession: _drop, keepMainModel: _keep, ...nextRoute } = routeOpts;
92
- const resolvedRoute = await runtime.setRoute(nextRoute, { applyToCurrentSession, keepMainModel });
139
+ if (switchesModel) {
140
+ // The destination must be accepted before the history is compacted.
141
+ await runtime.setRoute(nextRoute, { validateOnly: true });
142
+ await compactBeforeModelSwitch();
143
+ if (token === routeSequence && preview) {
144
+ set(preview);
145
+ flushEmitImmediate();
146
+ }
147
+ }
148
+ const resolvedRoute = await runtime.setRoute(nextRoute, {
149
+ applyToCurrentSession,
150
+ keepMainModel,
151
+ switchEstablished: true,
152
+ });
93
153
  if (token === routeSequence) {
94
- if (applyToCurrentSession) syncContextStats({ allowEstimated: true });
154
+ if (applyToCurrentSession || resolvedRoute?.modelSwitch) syncContextStats({ allowEstimated: true });
95
155
  publishRoute();
96
156
  }
157
+ publishModelSwitch(bag, resolvedRoute?.modelSwitch);
97
158
  return resolvedRoute;
98
159
  } catch (error) {
99
160
  if (token === routeSequence && preview) {
@@ -116,6 +177,9 @@ export function createSessionRouteApi(bag) {
116
177
  if (routeWrite === write) routeWrite = null;
117
178
  }
118
179
  };
180
+ // The settings surface's setModel (/model, presets) is the same user
181
+ // model choice and runs through this one path.
182
+ bag.setSessionRoute = setRoute;
119
183
 
120
184
  const setWebSearchRoute = async (opts) => {
121
185
  if (getState().commandBusy) return null;
@@ -28,20 +28,11 @@ export function createSessionSettingsApi(bag) {
28
28
  const lockedRuntimeCall = (call) => withCommandLock(async (...args) => await call(...args));
29
29
 
30
30
  return {
31
- // Model changes apply to the NEXT session only (default setRoute behavior)
32
- // — never rewrite the live session's provider/model, which would force a
33
- // full prompt-cache rewrite mid-conversation. RPC replies read the
34
- // published snapshot, not the mutable draft: commit before the caller can
35
- // acknowledge an older route.
36
- setModel: withCommandLock(
37
- async (m) => {
38
- bag.supersedeQuotaResume?.(getState().sessionId);
39
- await runtime.setRoute({ model: m });
40
- publishRoute();
41
- return true;
42
- },
43
- { busyResult: false, onRelease: flushEmitImmediate }
44
- ),
31
+ // A model selector (/model, a preset) is the user's model choice like any
32
+ // picker selection: the route surface switches an established
33
+ // conversation in place (pre-compaction, busy refusal, divider). False
34
+ // while another command holds the lock.
35
+ setModel: async (m) => (await bag.setSessionRoute({ model: m })) !== false,
45
36
  setEffort: withCommandLock(
46
37
  async (value) => {
47
38
  await runtime.setEffort(value);
@@ -248,6 +248,12 @@ export function createDrainLoop(
248
248
  while (pending.length > 0) {
249
249
  if (flags.drainEpoch !== drainEpoch) return;
250
250
  if (admission() !== 'open') return;
251
+ // Admission is rechecked before every batch: a command that took the
252
+ // lock while the previous turn settled (an in-place model switch and
253
+ // its pre-compaction, a reset) runs before the next turn starts. The
254
+ // finally below re-enters drain(), which waits on the same gate, and
255
+ // the commandBusy release re-kicks the queue.
256
+ if (flags.autoClearRunning || getState().commandBusy) return;
251
257
  // Drain one priority/mode bucket at a time (unified command queue):
252
258
  // prompt steering stays editable and task notifications stay
253
259
  // non-editable but model-visible.
@@ -267,7 +273,7 @@ export function createDrainLoop(
267
273
  // after a long idle is compacted first; the wake runs regardless.
268
274
  if (autoClearBeforeWake && batch.every((entry) => COMPLETION_WAKE_MODES.has(entry.mode))) {
269
275
  await autoClearBeforeWake();
270
- if (flags.drainEpoch !== drainEpoch || admission() !== 'open') {
276
+ if (flags.drainEpoch !== drainEpoch || admission() !== 'open' || getState().commandBusy) {
271
277
  queue.requeueEntriesFront(batch);
272
278
  return;
273
279
  }
@@ -5,8 +5,12 @@
5
5
  // prompt, so a continuation prompt or a merged batch never removes rows.
6
6
  const TURN_CHROME_KINDS = new Set(['user', 'turndone', 'notice']);
7
7
 
8
- /** The items with the trailing failed, output-less turn removed, or null
9
- * when nothing qualifies. */
8
+ // An in-place model switch made after the stop (the quota "switch model"
9
+ // path) is not the failed turn's output and outlives its rewind.
10
+ const isModelSwitchDivider = (item) => item?.kind === 'statusdone' && item.status === 'model-switched';
11
+
12
+ /** The items with the trailing failed, output-less turn removed (a later
13
+ * model switch divider kept), or null when nothing qualifies. */
10
14
  export function rewoundFailedTurnItems(items, text) {
11
15
  const list = Array.isArray(items) ? items : [];
12
16
  const resubmitted = String(text || '').trim();
@@ -16,6 +20,8 @@ export function rewoundFailedTurnItems(items, text) {
16
20
  const tail = list.slice(start + 1);
17
21
  const failed = tail.some((item) => item?.kind === 'turndone' && String(item.status || '').toLowerCase() === 'failed');
18
22
  if (!failed) return null;
19
- if (tail.some((item) => !TURN_CHROME_KINDS.has(String(item?.kind || '')))) return null;
20
- return list.slice(0, start);
23
+ if (tail.some((item) => !TURN_CHROME_KINDS.has(String(item?.kind || '')) && !isModelSwitchDivider(item))) {
24
+ return null;
25
+ }
26
+ return [...list.slice(0, start), ...tail.filter(isModelSwitchDivider)];
21
27
  }
@@ -15,6 +15,10 @@ import { preserveGoalStateAfterTurn } from './goal-turn-state.mjs';
15
15
  export { preserveGoalStateAfterTurn } from './goal-turn-state.mjs';
16
16
  export { transcriptToolCallDisplayMode } from './turn-tool-cards.mjs';
17
17
  import { isRejected429, safeErrorDetails } from '../../runtime/shared/error-presentation.mjs';
18
+ import {
19
+ QUOTA_KINDS,
20
+ providerErrorKind,
21
+ } from '../../runtime/agent/orchestrator/providers/provider-error-kind.mjs';
18
22
  import { registerTaskWaitSteeringCheck } from '../../runtime/agent/orchestrator/session/task-wait-control.mjs';
19
23
  import { promptDisplayText, STEERING_SUPPRESSED_DISPLAY } from './queue-helpers.mjs';
20
24
  import { yieldToRenderer } from './render-timing.mjs';
@@ -47,14 +51,11 @@ import {
47
51
  startLiveTail,
48
52
  } from './turn-tool-cards.mjs';
49
53
 
50
- function isUsageLimitError(error) {
54
+ // A usage limit is exactly a spent quota, a plan-gated feature or a billing
55
+ // refusal; overloads, rate limits and server faults recover by waiting.
56
+ function isUsageLimitError(error, kind = providerErrorKind(error)) {
51
57
  if (!error || isRejected429(error)) return false;
52
- const status = Number(error?.httpStatus || error?.status || error?.response?.status || 0);
53
- if (error?.providerQuota === true || error?.quotaExceeded === true || status === 429) return true;
54
- const text = String(error?.message || error);
55
- return /\brate[_ -]?limit\b|\bquota\b|too many requests|resource exhausted|insufficient_quota|quota_exceeded/i.test(
56
- text
57
- );
58
+ return QUOTA_KINDS.has(kind.kind);
58
59
  }
59
60
 
60
61
  function turnOutcome(cancelled, failed) {
@@ -165,7 +166,7 @@ function promptRestoreFor(displayText, options, submittedIds, content = null) {
165
166
  };
166
167
  }
167
168
 
168
- function commitPromptRestore(flags, turn) {
169
+ export function commitPromptRestore(flags, turn) {
169
170
  const restore = flags.activePromptRestore;
170
171
  if (!restore) return;
171
172
  if (!turn.promptCommitted && typeof restore.onCommitted === 'function') {
@@ -389,7 +390,7 @@ function toolHandlers(ctx) {
389
390
  };
390
391
  }
391
392
 
392
- function streamHandlers(ctx) {
393
+ export function streamHandlers(ctx) {
393
394
  const { isCurrentTurn, stream } = ctx;
394
395
  return {
395
396
  onStageChange: async (stage, detail = null) => {
@@ -398,7 +399,10 @@ function streamHandlers(ctx) {
398
399
  onTextDelta: (chunk) => {
399
400
  const textChunk = String(chunk ?? '');
400
401
  if (!textChunk || !isCurrentTurn()) return;
401
- ctx.markPromptCommitted();
402
+ // Same verdict as the runtime's interruption check (finalizeInterruptedTurn
403
+ // trims): whitespace-only text is not output, so it must not commit the
404
+ // prompt — the runtime would rewind it while the host skipped the requeue.
405
+ if (textChunk.trim()) ctx.markPromptCommitted();
402
406
  appendTextDelta(stream, textChunk);
403
407
  },
404
408
  onTextReset: (reset = {}) => (isCurrentTurn() ? resetStreamedText(stream, reset) : false),
@@ -448,13 +452,30 @@ export function failTurn(ctx, error) {
448
452
  }
449
453
  turn.failed = true;
450
454
  cards.aggregates.finalizeToolHeaders();
451
- turn.usageLimited = isUsageLimitError(error);
455
+ // Presentation only: legacy untyped failure text may still name a usage limit.
456
+ const errorKind = providerErrorKind(error, { legacyQuotaWording: true });
457
+ // The UI reads this descriptor instead of re-parsing the error text.
458
+ turn.errorKind = {
459
+ kind: errorKind.kind,
460
+ code: errorKind.code,
461
+ status: errorKind.status,
462
+ retryAfterMs: errorKind.retryAfterMs,
463
+ resetAt: errorKind.resetAt,
464
+ };
465
+ turn.usageLimited = isUsageLimitError(error, errorKind);
452
466
  const exhausted = error?.quotaExhausted;
453
- if (exhausted && typeof exhausted === 'object') {
467
+ // Quota metadata: the pool's validated exhaustion, or a spent quota whose
468
+ // provider named the real reset time.
469
+ const resetKnown = errorKind.kind === 'quota_exhausted' && Number.isFinite(errorKind.resetAt);
470
+ if ((exhausted && typeof exhausted === 'object') || resetKnown) {
471
+ const source = exhausted && typeof exhausted === 'object' ? exhausted : {};
472
+ let resetAt = null;
473
+ if (Number.isFinite(source.resetAt)) resetAt = source.resetAt;
474
+ else if (Number.isFinite(errorKind.resetAt)) resetAt = errorKind.resetAt;
454
475
  turn.quota = {
455
- provider: String(exhausted.provider || turn.routeMeta?.provider || ''),
456
- model: String(exhausted.model || turn.routeMeta?.model || ''),
457
- resetAt: Number.isFinite(exhausted.resetAt) ? exhausted.resetAt : null,
476
+ provider: String(source.provider || turn.routeMeta?.provider || ''),
477
+ model: String(source.model || turn.routeMeta?.model || ''),
478
+ resetAt,
458
479
  };
459
480
  }
460
481
  turn.failureDetail = toolErrorDisplay(error, 'turn').replace(/^Error:\s*/i, '');
@@ -485,6 +506,7 @@ export function turnDoneItem({ turn, stream, cards, getState, nextId }) {
485
506
  ...(turn.failureDiagnostic ? { errorDetails: turn.failureDiagnostic } : {}),
486
507
  ...turn.routeMeta,
487
508
  ...(turn.failed && turn.quota ? { quota: turn.quota } : {}),
509
+ ...(turn.failed && turn.errorKind ? { errorKind: turn.errorKind } : {}),
488
510
  };
489
511
  }
490
512
 
@@ -564,6 +586,7 @@ async function settleTurn(ctx) {
564
586
  result: turn.askResult,
565
587
  session: runtime.session || null,
566
588
  error: turn.failureDetail || null,
589
+ errorKind: turn.failed ? turn.errorKind || null : null,
567
590
  };
568
591
  // Publish termination before optional Goal work can delay the caller.
569
592
  bag.settleSteeredSubmissions?.(turn.epoch, detail);
@@ -65,7 +65,7 @@ export function statuslineFooterIdentityChanged(args, lastArgs) {
65
65
  if (!lastArgs) return true;
66
66
  if (args.sessionId !== lastArgs.sessionId) return true;
67
67
  if (args.provider !== lastArgs.provider || args.model !== lastArgs.model) return true;
68
- if (args.effort !== lastArgs.effort || args.fast !== lastArgs.fast) return true;
68
+ if (args.effort !== lastArgs.effort || args.fast !== lastArgs.fast || args.ultra !== lastArgs.ultra) return true;
69
69
  if (args.contextWindow !== lastArgs.contextWindow || args.rawContextWindow !== lastArgs.rawContextWindow) return true;
70
70
  if (args.displayContextWindow !== lastArgs.displayContextWindow) return true;
71
71
  if (args.compactBoundaryTokens !== lastArgs.compactBoundaryTokens) return true;
@@ -25,8 +25,7 @@ let _hiddenStatuslineAgents = null;
25
25
  function normalizeAgentWorkerForStatusline(worker = {}) {
26
26
  const tag = String(worker.tag || worker.agent || worker.name || '').trim();
27
27
  if (!tag) return null;
28
- const statuses = agentStatusValues(worker);
29
- const status = isActiveAgentEntry(statuses) ? 'running' : 'idle';
28
+ const status = isActiveAgentEntry(lifecycleStatuses(worker)) ? 'running' : 'idle';
30
29
  return {
31
30
  tag,
32
31
  status,
@@ -63,11 +62,12 @@ function normalizeAgentJobForStatusline(job = {}) {
63
62
  model: job.model || null,
64
63
  };
65
64
  }
66
- if (!isActiveAgentEntry(statuses)) return null;
65
+ const lifecycle = lifecycleStatuses(job);
66
+ if (!isActiveAgentEntry(lifecycle)) return null;
67
67
  return {
68
68
  tag,
69
69
  taskId,
70
- status: isQueuedAgentEntry(statuses) ? 'queued' : 'running',
70
+ status: isQueuedAgentEntry(lifecycle) ? 'queued' : 'running',
71
71
  startedAtMs,
72
72
  agent: job.agent || null,
73
73
  stage: job.stage || job.workerStatus || job.status || null,
@@ -214,6 +214,17 @@ function agentStatusValues(value = {}) {
214
214
  .filter((status, index, values) => Boolean(status) && values.indexOf(status) === index);
215
215
  }
216
216
 
217
+ /** The statuses that decide whether an entry is working. `status` is the
218
+ * lifecycle; `stage` is the runtime phase copied in beside it, which can read
219
+ * idle/done/error mid-work, so it decides only for an entry with no status. A
220
+ * cancel in either field still counts (it keeps both in play). */
221
+ function lifecycleStatuses(value = {}) {
222
+ const statuses = agentStatusValues(value);
223
+ if (statuses.some((status) => /cancel|killed/i.test(status))) return statuses;
224
+ const status = String(value.status || '').trim();
225
+ return status ? [status] : statuses;
226
+ }
227
+
217
228
  function isTerminalAgentEntry(statuses = []) {
218
229
  return statuses.some((status) => TERMINAL_AGENT_STATUS.test(String(status || '')));
219
230
  }