mixdog 1.4.4 → 1.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/package.json +1 -2
  2. package/src/cli.mjs +5 -1
  3. package/src/defaults/shipped-history.json +26 -2
  4. package/src/defaults/skills/browser-use/SKILL.md +148 -273
  5. package/src/defaults/skills/browser-use/references/devtools.md +14 -0
  6. package/src/defaults/skills/browser-use/references/page-flows.md +66 -0
  7. package/src/defaults/skills/browser-use/references/sign-in.md +70 -0
  8. package/src/defaults/skills/code-tidy/SKILL.md +60 -84
  9. package/src/defaults/skills/code-tidy/references/agent-cleanup.md +27 -2
  10. package/src/defaults/skills/computer-use/SKILL.md +145 -240
  11. package/src/defaults/skills/computer-use/references/flows.md +35 -0
  12. package/src/defaults/skills/computer-use/references/operations.md +22 -0
  13. package/src/defaults/skills/computer-use/references/platforms.md +12 -0
  14. package/src/defaults/skills/docx/SKILL.md +23 -31
  15. package/src/defaults/skills/docx/references/native-authoring.md +26 -3
  16. package/src/defaults/skills/docx/references/redlining.md +15 -0
  17. package/src/defaults/skills/image/SKILL.md +37 -77
  18. package/src/defaults/skills/image/references/prompt-forms.md +51 -0
  19. package/src/defaults/skills/image/references/text.md +6 -0
  20. package/src/defaults/skills/local-provider/SKILL.md +75 -105
  21. package/src/defaults/skills/local-provider/references/lifecycle.md +14 -0
  22. package/src/defaults/skills/local-provider/references/maintenance.md +19 -0
  23. package/src/defaults/skills/local-provider/references/recovery.md +30 -0
  24. package/src/defaults/skills/memory-management/SKILL.md +16 -20
  25. package/src/defaults/skills/pdf/SKILL.md +21 -23
  26. package/src/defaults/skills/pdf/references/blocks.md +20 -0
  27. package/src/defaults/skills/pdf/references/forms.md +12 -0
  28. package/src/defaults/skills/pdf/references/html.md +2 -2
  29. package/src/defaults/skills/pdf/references/ocr.md +7 -0
  30. package/src/defaults/skills/pdf/references/security.md +8 -0
  31. package/src/defaults/skills/pptx/SKILL.md +30 -109
  32. package/src/defaults/skills/pptx/references/audit.md +45 -0
  33. package/src/defaults/skills/pptx/references/brief-critique.md +47 -0
  34. package/src/defaults/skills/pptx/references/editing.md +24 -0
  35. package/src/defaults/skills/pptx/references/html.md +1 -1
  36. package/src/defaults/skills/pptx/references/script.md +33 -0
  37. package/src/defaults/skills/setup/SKILL.md +34 -102
  38. package/src/defaults/skills/setup/references/actions.md +72 -13
  39. package/src/defaults/skills/setup/references/surfaces.md +23 -8
  40. package/src/defaults/skills/setup-guide/SKILL.md +28 -115
  41. package/src/defaults/skills/setup-guide/references/features.md +36 -0
  42. package/src/defaults/skills/setup-guide/references/glossary.md +38 -0
  43. package/src/defaults/skills/setup-guide/references/workflow-models.md +62 -0
  44. package/src/defaults/skills/test-suite/SKILL.md +15 -127
  45. package/src/defaults/skills/test-suite/references/case-management.md +17 -9
  46. package/src/defaults/skills/test-suite/references/diagnose.md +23 -0
  47. package/src/defaults/skills/test-suite/references/prune.md +27 -0
  48. package/src/defaults/skills/test-suite/references/write.md +44 -0
  49. package/src/defaults/skills/video/SKILL.md +28 -42
  50. package/src/defaults/skills/video/references/prompting.md +31 -0
  51. package/src/defaults/skills/visualize/SKILL.md +73 -107
  52. package/src/defaults/skills/visualize/references/craft.md +1 -2
  53. package/src/defaults/skills/visualize/references/feedback.md +36 -0
  54. package/src/defaults/skills/visualize/references/showing.md +13 -0
  55. package/src/defaults/skills/xlsx/SKILL.md +23 -50
  56. package/src/defaults/skills/xlsx/references/editing.md +15 -0
  57. package/src/defaults/skills/xlsx/references/model-conventions.md +1 -1
  58. package/src/defaults/skills/xlsx/references/recalculation.md +37 -0
  59. package/src/defaults/skills/xlsx/references/report-design.md +18 -2
  60. package/src/lib/keychain-cjs.cjs +22 -1
  61. package/src/lib/rules-builder.cjs +1 -1
  62. package/src/rules/agent/AGENT.md +3 -0
  63. package/src/rules/lead/LEAD.md +3 -1
  64. package/src/runtime/agent/orchestrator/agent-runtime/cache-strategy.mjs +8 -30
  65. package/src/runtime/agent/orchestrator/agent-runtime/title-completion.mjs +5 -0
  66. package/src/runtime/agent/orchestrator/mcp/oauth-request.mjs +21 -2
  67. package/src/runtime/agent/orchestrator/providers/account-pool.mjs +3 -0
  68. package/src/runtime/agent/orchestrator/providers/admission-scheduler.mjs +2 -2
  69. package/src/runtime/agent/orchestrator/providers/anthropic-api-transport.mjs +2 -0
  70. package/src/runtime/agent/orchestrator/providers/anthropic-message-threads.mjs +583 -0
  71. package/src/runtime/agent/orchestrator/providers/anthropic-oauth-client-version.mjs +1 -1
  72. package/src/runtime/agent/orchestrator/providers/anthropic-oauth.mjs +81 -19
  73. package/src/runtime/agent/orchestrator/providers/anthropic-sse.mjs +180 -13
  74. package/src/runtime/agent/orchestrator/providers/anthropic.mjs +56 -6
  75. package/src/runtime/agent/orchestrator/providers/cursor-wire.mjs +4 -2
  76. package/src/runtime/agent/orchestrator/providers/gemini-error-contract.mjs +6 -6
  77. package/src/runtime/agent/orchestrator/providers/gemini-model-redirect.mjs +44 -0
  78. package/src/runtime/agent/orchestrator/providers/gemini-reasoning-relay.mjs +5 -0
  79. package/src/runtime/agent/orchestrator/providers/gemini-request-body.mjs +34 -5
  80. package/src/runtime/agent/orchestrator/providers/gemini-response.mjs +10 -0
  81. package/src/runtime/agent/orchestrator/providers/gemini-schema.mjs +11 -6
  82. package/src/runtime/agent/orchestrator/providers/gemini-sdk-request.mjs +4 -100
  83. package/src/runtime/agent/orchestrator/providers/gemini-stream.mjs +3 -227
  84. package/src/runtime/agent/orchestrator/providers/gemini.mjs +226 -118
  85. package/src/runtime/agent/orchestrator/providers/lib/anthropic-request-utils.mjs +11 -1
  86. package/src/runtime/agent/orchestrator/providers/lib/claude-bridge-schema.mjs +15 -3
  87. package/src/runtime/agent/orchestrator/providers/lib/gemini-model-catalog.mjs +2 -1
  88. package/src/runtime/agent/orchestrator/providers/openai-direct-request.mjs +5 -28
  89. package/src/runtime/agent/orchestrator/providers/openai-ws-pool.mjs +50 -28
  90. package/src/runtime/agent/orchestrator/providers/openai-ws-stream/socket-handlers.mjs +14 -10
  91. package/src/runtime/agent/orchestrator/providers/openai-ws.mjs +1 -3
  92. package/src/runtime/agent/orchestrator/providers/stream-json-pool/worker-slots/slot-spawn.mjs +8 -3
  93. package/src/runtime/agent/orchestrator/providers/vertex-ai-maas.mjs +2 -2
  94. package/src/runtime/agent/orchestrator/runtime-core/config-helpers.mjs +4 -5
  95. package/src/runtime/agent/orchestrator/runtime-core/goal-tool-defs.mjs +2 -2
  96. package/src/runtime/agent/orchestrator/runtime-core/provider-request-tools.mjs +15 -8
  97. package/src/runtime/agent/orchestrator/runtime-core/session-title.mjs +1 -0
  98. package/src/runtime/agent/orchestrator/runtime-core/todo-list.mjs +9 -32
  99. package/src/runtime/agent/orchestrator/runtime-core/todo-tool-defs.mjs +4 -5
  100. package/src/runtime/agent/orchestrator/session/compact/summary-route.mjs +1 -3
  101. package/src/runtime/agent/orchestrator/session/loop/compact-policy.mjs +5 -2
  102. package/src/runtime/agent/orchestrator/session/loop/no-tool-turn/todo-check.mjs +2 -17
  103. package/src/runtime/agent/orchestrator/session/loop/usage.mjs +7 -3
  104. package/src/runtime/agent/orchestrator/session/manager/ask-turn-settle.mjs +9 -2
  105. package/src/runtime/agent/orchestrator/session/manager/session-close.mjs +26 -13
  106. package/src/runtime/agent/orchestrator/session/manager/session-lifecycle.mjs +4 -5
  107. package/src/runtime/agent/orchestrator/session/manager/usage-metrics.mjs +16 -5
  108. package/src/runtime/agent/orchestrator/session/store/lifecycle-barriers.mjs +22 -1
  109. package/src/runtime/agent/orchestrator/session/store/live-state.mjs +4 -0
  110. package/src/runtime/agent/orchestrator/tools/builtin/cache-layers.mjs +11 -9
  111. package/src/runtime/agent/orchestrator/tools/builtin/grep-formatting.mjs +2 -8
  112. package/src/runtime/agent/orchestrator/tools/builtin/lib/search-input-helpers.mjs +1 -9
  113. package/src/runtime/agent/orchestrator/tools/builtin/local-search-telemetry.mjs +2 -2
  114. package/src/runtime/agent/orchestrator/tools/builtin/native-search-client.mjs +1 -1
  115. package/src/runtime/agent/orchestrator/tools/builtin/runtime-capabilities.mjs +12 -3
  116. package/src/runtime/agent/orchestrator/tools/code-graph/ast-calls.mjs +9 -2
  117. package/src/runtime/agent/orchestrator/tools/code-graph/build.mjs +137 -7
  118. package/src/runtime/agent/orchestrator/tools/code-graph/calls-cache.mjs +43 -14
  119. package/src/runtime/agent/orchestrator/tools/code-graph/calls-sidecar-worker.mjs +33 -0
  120. package/src/runtime/agent/orchestrator/tools/code-graph/disk-cache.mjs +146 -11
  121. package/src/runtime/agent/orchestrator/tools/code-graph/dispatch.mjs +31 -24
  122. package/src/runtime/agent/orchestrator/tools/code-graph/graph-binary/spawn-jsonl.mjs +172 -25
  123. package/src/runtime/agent/orchestrator/tools/code-graph/graph-model.mjs +100 -2
  124. package/src/runtime/agent/orchestrator/tools/code-graph/main-thread-slice.mjs +18 -0
  125. package/src/runtime/agent/orchestrator/tools/code-graph/mask-pool.mjs +219 -0
  126. package/src/runtime/agent/orchestrator/tools/code-graph/mask-worker.mjs +12 -0
  127. package/src/runtime/agent/orchestrator/tools/code-graph/memory-cache.mjs +6 -1
  128. package/src/runtime/agent/orchestrator/tools/code-graph/modes/calls.mjs +9 -2
  129. package/src/runtime/agent/orchestrator/tools/code-graph/modes/dependents.mjs +5 -1
  130. package/src/runtime/agent/orchestrator/tools/code-graph/modes/structure.mjs +8 -2
  131. package/src/runtime/agent/orchestrator/tools/code-graph/modes/symbols.mjs +14 -11
  132. package/src/runtime/agent/orchestrator/tools/code-graph/search-references.mjs +41 -18
  133. package/src/runtime/agent/orchestrator/tools/code-graph/search.mjs +391 -83
  134. package/src/runtime/agent/orchestrator/tools/code-graph/symbol-index.mjs +109 -9
  135. package/src/runtime/agent/orchestrator/tools/code-graph/text-mask.mjs +73 -29
  136. package/src/runtime/agent/orchestrator/tools/code-graph-prewarm-worker.mjs +6 -5
  137. package/src/runtime/agent/orchestrator/tools/lib/native-spawn-client.mjs +7 -3
  138. package/src/runtime/channels/lib/crash-log.mjs +21 -1
  139. package/src/runtime/channels/lib/worker-main.mjs +8 -25
  140. package/src/runtime/media/jobs.mjs +5 -0
  141. package/src/runtime/media/store.mjs +146 -3
  142. package/src/runtime/office/core/office-write-ledger.mjs +2 -2
  143. package/src/runtime/shared/agent-reap-state.mjs +19 -0
  144. package/src/runtime/shared/desktop-notice-host.d.mts +13 -0
  145. package/src/runtime/shared/desktop-notice-host.mjs +87 -0
  146. package/src/runtime/shared/file-lock.mjs +2 -2
  147. package/src/runtime/shared/heap-cap.mjs +9 -11
  148. package/src/runtime/shared/llm/http-agent.mjs +11 -1
  149. package/src/runtime/shared/llm/system-proxy.mjs +100 -25
  150. package/src/runtime/shared/llm/usage-accounting.mjs +18 -7
  151. package/src/runtime/shared/llm/usage-context.mjs +2 -2
  152. package/src/runtime/shared/llm/usage-ledger-requests.mjs +10 -3
  153. package/src/runtime/shared/llm/usage-ledger.mjs +13 -1
  154. package/src/runtime/shared/provider-accounts.mjs +22 -0
  155. package/src/runtime/shared/provider-auth-binding.mjs +2 -2
  156. package/src/runtime/shared/resource-admission.mjs +2 -2
  157. package/src/runtime/shared/root-async-context.mjs +51 -0
  158. package/src/runtime/shared/run-child.mjs +18 -1
  159. package/src/runtime/shared/slow-span.mjs +2 -2
  160. package/src/runtime/shared/tool-execution-owner.mjs +2 -2
  161. package/src/runtime/shared/tool-work-units.mjs +2 -0
  162. package/src/runtime/shared/turn-snapshot-store.mjs +75 -18
  163. package/src/runtime/shared/turn-worktree-snapshot.mjs +38 -8
  164. package/src/runtime/shared/user-cwd.mjs +2 -2
  165. package/src/runtime/shared/worker-requests.mjs +3 -1
  166. package/src/runtime/shared/worktrees/lock.mjs +2 -2
  167. package/src/runtime/visualize-bridge/client.mjs +26 -4
  168. package/src/runtime/visualize-bridge/tool-defs.mjs +46 -5
  169. package/src/session-runtime/boot/apis.mjs +1 -0
  170. package/src/session-runtime/boot/begin.mjs +2 -0
  171. package/src/session-runtime/media-api.mjs +15 -0
  172. package/src/session-runtime/provider-readiness.mjs +10 -2
  173. package/src/session-runtime/runtime-core.mjs +35 -8
  174. package/src/session-runtime/runtime-review-api.mjs +3 -1
  175. package/src/session-runtime/services/agent-tool/close-flow.mjs +6 -1
  176. package/src/session-runtime/services/agent-tool/execute-resume.mjs +94 -0
  177. package/src/session-runtime/services/agent-tool/execute-send.mjs +77 -27
  178. package/src/session-runtime/services/agent-tool/execute-spawn.mjs +28 -7
  179. package/src/session-runtime/services/agent-tool/execute.mjs +6 -1
  180. package/src/session-runtime/services/agent-tool/helpers.mjs +11 -0
  181. package/src/session-runtime/services/agent-tool/job-views/job-render.mjs +13 -10
  182. package/src/session-runtime/services/agent-tool/render.mjs +2 -0
  183. package/src/session-runtime/services/agent-tool/send-flow.mjs +1 -0
  184. package/src/session-runtime/services/agent-tool/spawn-flow/spawn-prep.mjs +6 -0
  185. package/src/session-runtime/services/agent-tool/spawn-flow/spawn-run.mjs +2 -1
  186. package/src/session-runtime/services/agent-tool/tag-registry/reaped-sessions.mjs +82 -0
  187. package/src/session-runtime/services/agent-tool/tag-registry/record-facts-worker.mjs +36 -0
  188. package/src/session-runtime/services/agent-tool/tag-registry.mjs +4 -0
  189. package/src/session-runtime/services/agent-tool/terminal-reaper/row-helpers.mjs +29 -0
  190. package/src/session-runtime/services/agent-tool/terminal-reaper/scan-admission.mjs +11 -3
  191. package/src/session-runtime/services/agent-tool/terminal-reaper/stale-rows.mjs +19 -8
  192. package/src/session-runtime/services/agent-tool/terminal-reaper.mjs +5 -2
  193. package/src/session-runtime/services/agent-tool/worker-index.mjs +1 -0
  194. package/src/session-runtime/services/daemon-crash-capture/daemon-exit-record.mjs +2 -2
  195. package/src/session-runtime/session-create.mjs +5 -0
  196. package/src/session-runtime/setup-tool/settings-contract.mjs +2 -0
  197. package/src/session-runtime/usage-stats-api.mjs +3 -0
  198. package/src/session-runtime/workspace/admission-gate.mjs +25 -7
  199. package/src/session-runtime/workspace/transitions.mjs +4 -0
  200. package/src/standalone/daemon-log.mjs +28 -4
  201. package/src/standalone/daemon-owner.mjs +41 -7
  202. package/src/standalone/daemon-work-gate.mjs +139 -0
  203. package/src/standalone/daemon.mjs +80 -11
  204. package/src/standalone/desktop-service-registry.mjs +11 -4
  205. package/src/standalone/session-client.mjs +57 -5
  206. package/src/standalone/session-protocol.mjs +5 -0
  207. package/src/standalone/session-service/agent-tree/agent-cancel.mjs +17 -1
  208. package/src/standalone/session-service/agent-tree.mjs +7 -0
  209. package/src/standalone/session-service/session-calls/session-turns.mjs +12 -5
  210. package/src/standalone/session-transport/call-route.mjs +10 -4
  211. package/src/standalone/session-transport/routes.mjs +21 -0
  212. package/src/standalone/session-transport/stack.mjs +3 -1
  213. package/src/standalone/session-transport.mjs +5 -0
  214. package/src/tui/dist/index.mjs +495 -477
  215. package/src/tui/session/session-api/media.mjs +5 -0
  216. package/src/tui/session/turn.mjs +13 -0
  217. package/src/runtime/agent/orchestrator/providers/gemini-sdk-stream/cancellation.mjs +0 -71
  218. package/src/runtime/agent/orchestrator/providers/gemini-sdk-stream/reader.mjs +0 -108
@@ -29,6 +29,7 @@ import {
29
29
  _cfCookieHeader,
30
30
  } from './openai-ws-headers.mjs';
31
31
  import { clearAllCodexTurnStates, clearCodexTurnStateScope, retireCodexTurnStateOwner } from './openai-turn-state.mjs';
32
+ import { runInRootAsyncContext } from '../../../shared/root-async-context.mjs';
32
33
 
33
34
  // Human-readable transport label for handshake/acquire error messages. Shared
34
35
  // with openai-oauth-ws.mjs (stream-side errors use the same labels).
@@ -273,16 +274,20 @@ function _removeFromPool(poolKey, entry) {
273
274
  if (arr.length === 0) _wsPool.delete(poolKey);
274
275
  }
275
276
 
277
+ // Pooled sockets and their idle/liveness timers outlive the request that made
278
+ // them; created in the root context they never retain that request's session.
276
279
  function _scheduleIdleClose(poolKey, entry) {
277
280
  if (!entry) return;
278
281
  if (entry.idleTimer) clearTimeout(entry.idleTimer);
279
- entry.idleTimer = setTimeout(() => {
280
- if (entry.busy) return;
281
- try {
282
- entry.socket.close(1000, 'idle_timeout');
283
- } catch {}
284
- _removeFromPool(poolKey, entry);
285
- }, WS_IDLE_MS);
282
+ entry.idleTimer = runInRootAsyncContext(() =>
283
+ setTimeout(() => {
284
+ if (entry.busy) return;
285
+ try {
286
+ entry.socket.close(1000, 'idle_timeout');
287
+ } catch {}
288
+ _removeFromPool(poolKey, entry);
289
+ }, WS_IDLE_MS)
290
+ );
286
291
  try {
287
292
  entry.idleTimer.unref?.();
288
293
  } catch {}
@@ -369,22 +374,24 @@ function _pingProbe(entry, timeoutMs) {
369
374
  // its own inter-chunk/semantic-idle watchdogs.
370
375
  function _armLiveness(poolKey, entry) {
371
376
  _clearLiveness(entry);
372
- entry.pingTimer = setInterval(async () => {
373
- if (entry.busy || entry.closing || entry.probing) return;
374
- if (!_isOpen(entry)) {
375
- _evictDead(poolKey, entry);
376
- return;
377
- }
378
- // Recent activity ⇒ assume live, skip the probe this tick.
379
- if (Date.now() - (entry.lastAliveAt || 0) < WS_LIVENESS_STALE_MS) return;
380
- entry.probing = true;
381
- try {
382
- const alive = await _pingProbe(entry, WS_PONG_TIMEOUT_MS);
383
- if (!alive && !entry.busy) _evictDead(poolKey, entry);
384
- } finally {
385
- entry.probing = false;
386
- }
387
- }, WS_PING_INTERVAL_MS);
377
+ entry.pingTimer = runInRootAsyncContext(() =>
378
+ setInterval(async () => {
379
+ if (entry.busy || entry.closing || entry.probing) return;
380
+ if (!_isOpen(entry)) {
381
+ _evictDead(poolKey, entry);
382
+ return;
383
+ }
384
+ // Recent activity ⇒ assume live, skip the probe this tick.
385
+ if (Date.now() - (entry.lastAliveAt || 0) < WS_LIVENESS_STALE_MS) return;
386
+ entry.probing = true;
387
+ try {
388
+ const alive = await _pingProbe(entry, WS_PONG_TIMEOUT_MS);
389
+ if (!alive && !entry.busy) _evictDead(poolKey, entry);
390
+ } finally {
391
+ entry.probing = false;
392
+ }
393
+ }, WS_PING_INTERVAL_MS)
394
+ );
388
395
  try {
389
396
  entry.pingTimer.unref?.();
390
397
  } catch {}
@@ -734,7 +741,11 @@ async function _openPoolEntry({ auth, cacheKey, codexHeaders, externalSignal, co
734
741
  const tokenHash = createHash('sha256').update(String(sessionToken)).digest('hex').slice(0, 8);
735
742
  _acquireTrace(`acquire-new tokenHash=${tokenHash} elapsed=${Date.now() - acqStart}ms`);
736
743
  }
737
- const { socket } = await _openSocketImpl({ auth, sessionToken, externalSignal, cacheKey, codexHeaders });
744
+ // The socket (its TCP/TLS handle and handshake timers) is reused by later
745
+ // requests: open it in the root context, never this one's.
746
+ const { socket } = await runInRootAsyncContext(() =>
747
+ _openSocketImpl({ auth, sessionToken, externalSignal, cacheKey, codexHeaders })
748
+ );
738
749
  if (_drainComplete) {
739
750
  try {
740
751
  socket.close(1000, 'drain-complete');
@@ -922,8 +933,18 @@ export function releaseWebSocket({ entry, poolKey: callerPoolKey, keep }) {
922
933
  _releasePoolOwner(poolKey, entry);
923
934
  }
924
935
 
925
- function closeOpenaiWsPoolForSession(poolKey, reason = 'session_closed') {
936
+ function closeOpenaiWsPoolForSession(poolKey, reason = 'session_closed', { inFlightOnly = false } = {}) {
926
937
  if (!poolKey) return;
938
+ if (inFlightOnly) {
939
+ // A turn abort: only a socket mid-response is unusable. An idle one keeps
940
+ // its response chain for the next turn; the closed one's own 'close'
941
+ // handler releases its owner claim and pool slot.
942
+ const owned = [...(_wsPool.get(poolKey) || []), ...[..._unpooledSockets].filter((e) => e.poolKey === poolKey)];
943
+ for (const entry of owned) {
944
+ if (entry.busy) _shutdownEntry(entry, String(reason || 'turn_aborted'));
945
+ }
946
+ return;
947
+ }
927
948
  _clearPoolOwnerScope(poolKey);
928
949
  clearCodexTurnStateScope(poolKey);
929
950
  const closeReason = String(reason || 'session_closed');
@@ -1052,11 +1073,12 @@ export function drainOpenaiWsPool(reason = 'shutdown', { immediate = false } = {
1052
1073
  // registers the same globals), so chain whatever is already installed instead of
1053
1074
  // replacing it — import order must not decide which transport gets torn down.
1054
1075
  const _priorPoolSessionCloseHook = globalThis.__mixdogCloseProviderConnectionsForSession;
1055
- globalThis.__mixdogCloseProviderConnectionsForSession = (poolKey, reason) => {
1076
+ // `options.inFlightOnly`: a turn abort, which leaves idle connections alone.
1077
+ globalThis.__mixdogCloseProviderConnectionsForSession = (poolKey, reason, options) => {
1056
1078
  try {
1057
- _priorPoolSessionCloseHook?.(poolKey, reason);
1079
+ _priorPoolSessionCloseHook?.(poolKey, reason, options);
1058
1080
  } finally {
1059
- closeOpenaiWsPoolForSession(poolKey, reason);
1081
+ closeOpenaiWsPoolForSession(poolKey, reason, options);
1060
1082
  }
1061
1083
  };
1062
1084
  const _priorPoolDrainHook = globalThis.__mixdogDrainProviderConnections;
@@ -1,3 +1,4 @@
1
+ import { AsyncResource } from 'node:async_hooks';
1
2
  import { performance } from 'node:perf_hooks';
2
3
  import { _parseEvent } from '../openai-ws-events.mjs';
3
4
  import {
@@ -158,13 +159,20 @@ export function createSocketHandlers({
158
159
  };
159
160
  const onOpen = () => _writeWsLifecycleTrace('open');
160
161
 
162
+ // Pooled sockets are opened in the root context (openai-ws-pool.mjs), and a
163
+ // socket's events run in the context it was opened in: bind this stream's
164
+ // handlers to the context of the request that sends on it.
165
+ const socketListeners = [
166
+ ['message', AsyncResource.bind(onMessage)],
167
+ ['close', AsyncResource.bind(onClose)],
168
+ ['error', AsyncResource.bind(onError)],
169
+ ['ping', AsyncResource.bind(onPing)],
170
+ ['pong', AsyncResource.bind(onPong)],
171
+ ];
172
+
161
173
  function detach() {
162
- socket.off('message', onMessage);
163
- socket.off('close', onClose);
164
- socket.off('error', onError);
174
+ for (const [event, listener] of socketListeners) socket.off(event, listener);
165
175
  socket.off('open', onOpen);
166
- socket.off('ping', onPing);
167
- socket.off('pong', onPong);
168
176
  externalSignal?.removeEventListener('abort', onAbort);
169
177
  }
170
178
 
@@ -176,11 +184,7 @@ export function createSocketHandlers({
176
184
  }
177
185
  externalSignal.addEventListener('abort', onAbort, { once: true });
178
186
  }
179
- socket.on('message', onMessage);
180
- socket.on('close', onClose);
181
- socket.on('error', onError);
182
- socket.on('ping', onPing);
183
- socket.on('pong', onPong);
187
+ for (const [event, listener] of socketListeners) socket.on(event, listener);
184
188
  if (WS_TRACE_ENABLED) {
185
189
  socket.on('open', onOpen);
186
190
  if (socket.readyState === WebSocket.OPEN) _writeWsLifecycleTrace('open');
@@ -142,9 +142,7 @@ export class OpenAIDirectProvider {
142
142
  // Keep public response storage and model-specific cache options out of
143
143
  // the shared OAuth payload. Storage opt-out still forces full frames in
144
144
  // _computeDelta; retained output items make those frames self-contained.
145
- applyOpenAIDirectCachePolicy(body, useModel, _envFlag('MIXDOG_OAI_STORE', true), {
146
- prefixTtl: opts.promptCachePrefixTtl || null,
147
- });
145
+ applyOpenAIDirectCachePolicy(body, useModel, _envFlag('MIXDOG_OAI_STORE', true));
148
146
  // poolKey MUST be sessionId-only. Falling back to promptCacheKey would
149
147
  // let unrelated raw sessions sharing the same provider-scoped cache
150
148
  // bucket reuse each other's pooled socket and inherit lastResponseId
@@ -4,6 +4,7 @@
4
4
  * idle worker from holding the process open.
5
5
  */
6
6
  import { Worker } from 'node:worker_threads';
7
+ import { runInRootAsyncContext } from '../../../../../shared/root-async-context.mjs';
7
8
 
8
9
  // After this many consecutive worker-construction failures the pool stops
9
10
  // trying to spawn and stays inline. This is a failure latch, not a throttle:
@@ -65,9 +66,13 @@ export function createSlotSpawner({ state, WorkerImpl = Worker, isClosed, affini
65
66
  function createSlot() {
66
67
  let worker;
67
68
  try {
68
- worker = new WorkerImpl(new URL('../../stream-json-worker.mjs', import.meta.url), {
69
- execArgv: [],
70
- });
69
+ // A slot serves later streams too: spawn it outside this stream's context.
70
+ worker = runInRootAsyncContext(
71
+ () =>
72
+ new WorkerImpl(new URL('../../stream-json-worker.mjs', import.meta.url), {
73
+ execArgv: [],
74
+ })
75
+ );
71
76
  } catch {
72
77
  noteSpawnFailure();
73
78
  return null;
@@ -1,4 +1,4 @@
1
- import { AsyncLocalStorage } from 'node:async_hooks';
1
+ import { runtimeAsyncLocalStorage } from '../../../shared/root-async-context.mjs';
2
2
  import { currentUsageContext } from '../../../shared/llm/usage-context.mjs';
3
3
  import { noteErrorUsage } from './lib/note-error-usage.mjs';
4
4
  import { OpenAICompatProvider } from './openai-compat.mjs';
@@ -73,7 +73,7 @@ export function vertexErrorBody(text) {
73
73
 
74
74
  // The account one send targets ({ identity, token }), read by its engine's
75
75
  // fetch on every HTTP attempt, the engine's own retries included.
76
- const sendAccount = new AsyncLocalStorage();
76
+ const sendAccount = runtimeAsyncLocalStorage();
77
77
 
78
78
  // Each HTTP attempt carries the send's account's current token, and a
79
79
  // credential switch since the send began aborts it before anything is sent.
@@ -202,11 +202,10 @@ const AUTO_CLEAR_DEFAULT_IDLE_MS = 60 * 60 * 1000;
202
202
  // reusable. Gemini, xAI and Mistral
203
203
  // caches run ~1h, Groq's implicit cache persists ~2h, and DeepSeek's
204
204
  // implicit cache is evicted after "a few hours to a few days" (kept at 24h).
205
- // OpenAI public API (GPT-5.6+ Responses, cache-strategy.mjs): the moving tail
206
- // is written with ttl "30m" and only the Lead-class stable prefix with "12h",
207
- // so the sweep matches the 30m tail — a clear after that costs nothing extra
208
- // (the tail is cold anyway) and the cleared session restarts on the warm 12h
209
- // prefix. Earlier OpenAI models (prompt_cache_retention, typically ~30 min)
205
+ // OpenAI public API (GPT-5.6+ Responses, cache-strategy.mjs): every request
206
+ // is written with ttl "30m", so the sweep matches it — a clear after that
207
+ // costs nothing extra (the cache is cold anyway). Earlier OpenAI models
208
+ // (prompt_cache_retention, typically ~30 min)
210
209
  // are not distinguished: these call sites only know the provider.
211
210
  // OpenAI OAuth (Codex/ChatGPT login) keeps the cache of logged-in users
212
211
  // indefinitely (2026-10-20), so its built-in window is unlimited: no idle
@@ -6,7 +6,7 @@ export const GOAL_TOOL_DEFS = Object.freeze([
6
6
  name: 'goal',
7
7
  title: 'Goal',
8
8
  description:
9
- 'A durable objective the runtime keeps working on across turns until you complete or block it, with an optional time cap (an upper bound, never a minimum). Create one only for an explicit Goal request or approved multi-turn work (staged refactors, migrations, open-ended objectives); never for single-turn tasks, plans, estimates or unaccepted proposals. One Goal at a time; its steps live in todo, not here. complete only after auditing every user condition against current evidence (files, command output, tests) — never because time is low, the cap was reached or the turn is ending, and never for a smaller objective than the one stated. block only for an impasse that only the user or external state can clear. Pause, resume, stop and edits are the user’s controls.',
9
+ 'A durable objective the runtime keeps working on across turns until you complete or block it, with an optional time cap (an upper bound, never a minimum). Create one only for an explicit Goal request or approved multi-turn work (staged refactors, migrations, open-ended objectives); never for single-turn tasks, plans, estimates or unaccepted proposals. One Goal at a time; its steps live in todo, not here. complete only after auditing every user condition against current evidence — never because time is low, the cap was reached or the turn is ending, and never for a smaller objective than the one stated. block only when the same blocking condition has recurred for at least three consecutive Goal turns (first turn and continuations count) and no progress is possible without the user or a change in external state; never because the work is hard, slow, uncertain, unfinished or would benefit from clarification. A resumed Goal counts afresh; once the threshold is met, block rather than report the impasse. Pause, resume, stop and edits are the user’s controls.',
10
10
  annotations: {
11
11
  title: 'Goal',
12
12
  readOnlyHint: false,
@@ -34,7 +34,7 @@ export const GOAL_TOOL_DEFS = Object.freeze([
34
34
  type: 'string',
35
35
  minLength: 1,
36
36
  maxLength: 1_000,
37
- description: 'block: the impasse; stops the Goal.',
37
+ description: 'block: the impasse that recurred for three consecutive Goal turns; stops the Goal.',
38
38
  },
39
39
  },
40
40
  required: ['action'],
@@ -1,6 +1,6 @@
1
- import { AsyncLocalStorage } from 'node:async_hooks';
1
+ import { runtimeAsyncLocalStorage } from '../../../shared/root-async-context.mjs';
2
2
 
3
- const requestToolScope = new AsyncLocalStorage();
3
+ const requestToolScope = runtimeAsyncLocalStorage();
4
4
  const NATIVE_PREFIX_COUNT = Symbol('mixdog.providerNativeToolPrefixCount');
5
5
  const finalizedProviderRequestTools = new WeakSet();
6
6
  let requestToolScopeGeneration = 0;
@@ -49,21 +49,28 @@ export function runWithProviderRequestToolsScope(scope, callback) {
49
49
  try {
50
50
  result = callback();
51
51
  } catch (error) {
52
- store.active = false;
52
+ deactivate(store);
53
53
  throw error;
54
54
  }
55
55
  if (result && typeof result.then === 'function') {
56
- return Promise.resolve(result).finally(() => {
57
- store.active = false;
58
- });
56
+ return Promise.resolve(result).finally(() => deactivate(store));
59
57
  }
60
- store.active = false;
58
+ deactivate(store);
61
59
  return result;
62
60
  });
63
61
  }
64
62
 
63
+ // An inactive scope is never read again, but any handle, timer or listener
64
+ // created under it keeps the store: drop what pins the session.
65
+ function deactivate(store) {
66
+ store.active = false;
67
+ store.session = null;
68
+ store.messages = null;
69
+ store.requestTools = null;
70
+ }
71
+
65
72
  export function invalidateProviderRequestToolsScope(scope = requestToolScope.getStore()) {
66
- if (scope && typeof scope === 'object') scope.active = false;
73
+ if (scope && typeof scope === 'object') deactivate(scope);
67
74
  }
68
75
 
69
76
  export function scopedProviderRequestTools(session, provider, messages) {
@@ -189,6 +189,7 @@ export function createSessionTitleController(deps = {}) {
189
189
  deps.generateSessionTitle || (await import('../agent-runtime/title-completion.mjs')).generateSessionTitle;
190
190
  if (disposed) return '';
191
191
  return complete(source, {
192
+ sessionId,
192
193
  signal: abort.signal,
193
194
  locale: String(deps.systemLocale?.() || resolvedSystemLocale()),
194
195
  });
@@ -31,9 +31,9 @@ function normalizeTask(raw) {
31
31
  if (!raw || typeof raw !== 'object') return null;
32
32
  const content = oneLine(raw.content);
33
33
  if (!content) return null;
34
+ // Stored lists from when `blocked` existed load as pending.
34
35
  const status = TODO_STATUSES.includes(raw.status) ? raw.status : 'pending';
35
36
  const task = { content, status };
36
- if (status === 'blocked' && oneLine(raw.blocker)) task.blocker = oneLine(raw.blocker);
37
37
  if (oneLine(raw.note)) task.note = oneLine(raw.note);
38
38
  return task;
39
39
  }
@@ -52,7 +52,7 @@ export function todoPhases(session) {
52
52
  const allTasks = (phases) => phases.flatMap((phase) => phase.tasks);
53
53
 
54
54
  /** Exactly one in_progress while actionable work exists: several keep the
55
- * earliest, none starts the earliest pending. Blocked never starts itself. */
55
+ * earliest, none starts the earliest pending. */
56
56
  function normalizeTodoPhases(phases) {
57
57
  const tasks = allTasks(phases);
58
58
  const active = tasks.filter((task) => task.status === 'in_progress');
@@ -78,8 +78,8 @@ export function openTodoItems(session) {
78
78
  return allTasks(todoPhases(session)).filter((task) => OPEN_STATUSES.has(task.status));
79
79
  }
80
80
 
81
- /** Every item not completed or dropped (blocked included): what an agent
82
- * leaves undone when it ends. */
81
+ /** Every item not completed or dropped: what an agent leaves undone when it
82
+ * ends. */
83
83
  export function unfinishedTodoItems(session) {
84
84
  return allTasks(todoPhases(session)).filter((task) => task.status !== 'completed' && task.status !== 'abandoned');
85
85
  }
@@ -145,7 +145,7 @@ function publish(session) {
145
145
  }
146
146
  }
147
147
 
148
- const MARKS = { completed: 'x', in_progress: '>', pending: ' ', blocked: '!', abandoned: '-' };
148
+ const MARKS = { completed: 'x', in_progress: '>', pending: ' ', abandoned: '-' };
149
149
 
150
150
  function progressLabel(phases) {
151
151
  const { completed, abandoned, total } = todoCounts(phases);
@@ -159,7 +159,7 @@ function renderTodoList(phases) {
159
159
  for (const phase of phases) {
160
160
  lines.push(phase.name);
161
161
  for (const task of phase.tasks) {
162
- const detail = task.blocker ? ` — blocked: ${task.blocker}` : task.note ? ` — ${task.note}` : '';
162
+ const detail = task.note ? ` — ${task.note}` : '';
163
163
  lines.push(` [${MARKS[task.status]}] ${task.content}${detail}`);
164
164
  }
165
165
  }
@@ -171,7 +171,6 @@ function summaryLine(phases, op, content) {
171
171
  const parts = [progressLabel(phases), `${op}: ${content}`];
172
172
  const current = tasks.find((task) => task.status === 'in_progress');
173
173
  if (current) parts.push(`next: ${current.content}`);
174
- else if (tasks.some((task) => task.status === 'blocked')) parts.push('next: none (blocked items wait)');
175
174
  else parts.push('all closed');
176
175
  return parts.join(' · ');
177
176
  }
@@ -218,7 +217,6 @@ const OPS = {
218
217
  start(phases, args) {
219
218
  const { task } = findTask(phases, args.item);
220
219
  if (task.status === 'completed') throw new Error(`todo: "${task.content}" is completed and stays closed`);
221
- if (task.status === 'blocked') throw new Error(`todo: "${task.content}" is blocked; unblock it first`);
222
220
  for (const other of allTasks(phases)) if (other.status === 'in_progress') other.status = 'pending';
223
221
  task.status = 'in_progress';
224
222
  return task.content;
@@ -226,7 +224,6 @@ const OPS = {
226
224
  done(phases, args) {
227
225
  const { task } = findTask(phases, args.item);
228
226
  task.status = 'completed';
229
- delete task.blocker;
230
227
  const note = oneLine(args.note);
231
228
  if (note) task.note = note;
232
229
  return task.content;
@@ -235,23 +232,6 @@ const OPS = {
235
232
  const { task } = findTask(phases, args.item);
236
233
  if (task.status === 'completed') throw new Error(`todo: "${task.content}" is completed and stays closed`);
237
234
  task.status = 'abandoned';
238
- delete task.blocker;
239
- return task.content;
240
- },
241
- block(phases, args) {
242
- const { task } = findTask(phases, args.item);
243
- if (task.status === 'completed' || task.status === 'abandoned') {
244
- throw new Error(`todo: "${task.content}" is ${task.status}; only open items can block`);
245
- }
246
- task.status = 'blocked';
247
- task.blocker = itemText(args.reason, 'block reason');
248
- return task.content;
249
- },
250
- unblock(phases, args) {
251
- const { task } = findTask(phases, args.item);
252
- if (task.status !== 'blocked') throw new Error(`todo: "${task.content}" is not blocked`);
253
- task.status = 'pending';
254
- delete task.blocker;
255
235
  return task.content;
256
236
  },
257
237
  append(phases, args) {
@@ -312,10 +292,7 @@ export function executeTodoTool(session, args = {}) {
312
292
  export function notDoneReport(session) {
313
293
  const unfinished = unfinishedTodoItems(session);
314
294
  if (!unfinished.length) return '';
315
- return [
316
- 'Not done:',
317
- ...unfinished.map((task) => `- ${task.content}${task.blocker ? ` (blocked: ${task.blocker})` : ''}`),
318
- ].join('\n');
295
+ return ['Not done:', ...unfinished.map((task) => `- ${task.content}`)].join('\n');
319
296
  }
320
297
 
321
298
  /** The open list as a hidden reminder (after compaction, or appended to a
@@ -335,7 +312,7 @@ const LEGACY_GOAL_TASK_STATUS = {
335
312
  in_progress: 'in_progress',
336
313
  completed: 'completed',
337
314
  dropped: 'abandoned',
338
- awaiting_approval: 'blocked',
315
+ awaiting_approval: 'pending',
339
316
  };
340
317
 
341
318
  /** Move a legacy Goal record's tasks into the session's list (once; the Goal
@@ -352,7 +329,7 @@ export function adoptLegacyGoalTasks(session, legacyTasks) {
352
329
  if (!content || existing.has(content)) continue;
353
330
  existing.add(content);
354
331
  const status = LEGACY_GOAL_TASK_STATUS[oneLine(raw?.status).toLowerCase()] || 'pending';
355
- adopted.push(status === 'blocked' ? { content, status, blocker: 'awaiting user approval' } : { content, status });
332
+ adopted.push({ content, status });
356
333
  }
357
334
  if (!adopted.length) return false;
358
335
  const name = phases.length ? 'Goal' : DEFAULT_TODO_PHASE;
@@ -1,7 +1,7 @@
1
1
  // The model-facing `todo` step list. Its description is the only guidance the
2
2
  // model gets about it: nothing is added to the system prompt or rules.
3
- export const TODO_OPS = Object.freeze(['init', 'start', 'done', 'drop', 'block', 'unblock', 'append', 'rm', 'view']);
4
- export const TODO_STATUSES = Object.freeze(['pending', 'in_progress', 'completed', 'abandoned', 'blocked']);
3
+ export const TODO_OPS = Object.freeze(['init', 'start', 'done', 'drop', 'append', 'rm', 'view']);
4
+ export const TODO_STATUSES = Object.freeze(['pending', 'in_progress', 'completed', 'abandoned']);
5
5
  export const MAX_TODO_ITEMS = 50;
6
6
  export const MAX_TODO_TEXT_LENGTH = 200;
7
7
 
@@ -19,7 +19,7 @@ export const TODO_TOOL = Object.freeze({
19
19
  agentHidden: false,
20
20
  },
21
21
  description:
22
- 'The step list for this request; the Lead and each agent keep their own. Use it whenever the work has three or more steps or several asks (a delegated brief with several parts counts); skip it only for a single step or a plain answer. Create it before the first real action: init with every ask as its own item, in order, covering investigation through verification. A follow-up that adds to the request: append its asks and any steps you discover; init is for a new, unrelated request and refuses while items are open. An item is named by its outcome in 3-8 words and keeps that exact wording; it is how you refer to it — lost the wording: view, never guess. Keep it current while you work, not at the end: the moment an item is finished and its result is read, mark it done with your next call — never batch completions. The runtime keeps exactly one item in progress; done moves it to the next. Send todo beside your next real tool call; when no real call is due, call it alone rather than skip the update. Waiting on the user, an agent or a shell: block it with a reason; unblock when it can move; done only after reading the result.',
22
+ 'The step list for this request; the Lead and each agent keep their own. Use it whenever the work has three or more steps or several asks (a delegated brief with several parts counts); skip it only for a single step or a plain answer. Create it before the first real action: init with every ask as its own item, in order, covering investigation through verification. A follow-up that adds to the request: append its asks and any steps you discover; init is for a new, unrelated request and refuses while items are open. An item is named by its outcome in 3-8 words and keeps that exact wording; it is how you refer to it — lost the wording: view, never guess. Keep it current while you work, not at the end: the moment an item is finished and its result is read, mark it done with your next call — never batch completions. The runtime keeps exactly one item in progress; done moves it to the next. Send todo beside your next real tool call; when no real call is due, call it alone rather than skip the update. Mark an item done only after reading its result; an item waiting on the user, an agent or a shell stays open.',
23
23
  inputSchema: {
24
24
  type: 'object',
25
25
  properties: {
@@ -36,10 +36,9 @@ export const TODO_TOOL = Object.freeze({
36
36
  },
37
37
  description: 'init: named phases instead of items.',
38
38
  },
39
- item: { type: 'string', description: 'start/done/drop/block/unblock/rm: exact item wording.' },
39
+ item: { type: 'string', description: 'start/done/drop/rm: exact item wording.' },
40
40
  phase: { type: 'string', description: 'append: target phase (default last; new name adds one).' },
41
41
  note: { type: 'string', description: 'done: optional one-line evidence.' },
42
- reason: { type: 'string', description: 'block: what it waits on.' },
43
42
  },
44
43
  required: ['op'],
45
44
  additionalProperties: false,
@@ -21,9 +21,7 @@ const WARM_MARGIN_RATIO = 0.1;
21
21
 
22
22
  /** How long the cache a saved request wrote or read stays readable, in ms:
23
23
  * Infinity when it does not expire (openai-oauth), 0 when it is not cached.
24
- * Anthropic: the request's message-tail tier (5m / 1h); OpenAI: the 30m tail
25
- * that holds the conversation (the Lead's 12h breakpoint covers only the
26
- * stable tools/instructions prefix). */
24
+ * Anthropic: the request's message-tail tier (5m / 1h); OpenAI: 30m. */
27
25
  function requestCacheLifetimeMs(request) {
28
26
  const name = request?.provider?.name;
29
27
  if (name === 'openai-oauth') return Infinity;
@@ -319,10 +319,13 @@ export function invalidateContextUsageSnapshot(sessionRef) {
319
319
 
320
320
  function providerPressureTokens(sessionRef, usage) {
321
321
  if (!usage || typeof usage !== 'object') return 0;
322
- const input = Math.max(0, Number(usage.inputTokens) || 0);
322
+ // Billed input can repeat context (Gemini long decode); the context input
323
+ // the provider reports then replaces both billed prompt figures.
324
+ const contextInput = Math.max(0, Number(usage.contextInputTokens) || 0);
325
+ const input = contextInput || Math.max(0, Number(usage.inputTokens) || 0);
323
326
  const cachedRead = Math.max(0, Number(usage.cachedTokens) || 0);
324
327
  const cacheWrite = Math.max(0, Number(usage.cacheWriteTokens) || 0);
325
- const explicitPrompt = Math.max(0, Number(usage.promptTokens) || 0);
328
+ const explicitPrompt = contextInput || Math.max(0, Number(usage.promptTokens) || 0);
326
329
  const normalizedPrompt = providerInputExcludesCache(sessionRef?.provider) ? input + cachedRead + cacheWrite : input;
327
330
  const prompt = Math.max(explicitPrompt, normalizedPrompt);
328
331
  const output = Math.max(0, Number(usage.outputTokens) || 0);
@@ -15,13 +15,7 @@
15
15
  import { resolvePluginData } from '../../../../../shared/plugin-paths.mjs';
16
16
  import { awaitingBackgroundWork, beginUserCycle } from '../../../../../shared/background-wait.mjs';
17
17
  import { readStoredGoalSnapshot } from '../../../runtime-core/goal-storage.mjs';
18
- import {
19
- clearTodo,
20
- openTodoItems,
21
- todoAllClosed,
22
- todoPhases,
23
- unfinishedTodoItems,
24
- } from '../../../runtime-core/todo-list.mjs';
18
+ import { clearTodo, openTodoItems, todoAllClosed, todoPhases } from '../../../runtime-core/todo-list.mjs';
25
19
  import { TODO_TOOL } from '../../../runtime-core/todo-tool-defs.mjs';
26
20
  import { HIDDEN_AGENT_NAMES } from '../hidden-agents.mjs';
27
21
  import { _isMutationTool, _isShellTool } from '../tool-classify.mjs';
@@ -67,15 +61,6 @@ export function todoStartReminder(session) {
67
61
  if (HIDDEN_AGENT_NAMES.has(session.agent)) return null;
68
62
  if (!session.tools?.some((tool) => tool?.name === TODO_TOOL.name)) return null;
69
63
  if (openTodoItems(session).length) return null;
70
- // `init` refuses while any item is unfinished (blocked included), so such a
71
- // list is reconciled or appended to, never re-initialized.
72
- if (unfinishedTodoItems(session).length) {
73
- return [
74
- '<system-reminder>',
75
- 'The todo list still has blocked items. If this brief adds asks, append them; first done, drop or unblock each blocked item that this brief settles. Do not init over them. Do not mention this reminder.',
76
- '</system-reminder>',
77
- ].join('\n');
78
- }
79
64
  return [
80
65
  '<system-reminder>',
81
66
  'If this brief has three or more steps or several asks, init the todo list with every ask as its own item in the same response as your first tool call; each item the brief lists is its own todo item, never folded into one. A single step or a plain answer needs none. Do not mention this reminder.',
@@ -159,7 +144,7 @@ function openItemsReminder(open, count) {
159
144
  '<system-reminder>',
160
145
  `You ended the turn with ${open.length} open todo item(s):`,
161
146
  ...open.map((task) => `- ${task.content}`),
162
- 'Continue them, or close each with the todo tool (done, drop, or block with its reason).',
147
+ 'Continue them, or close each with the todo tool (done or drop).',
163
148
  `(Reminder ${count}/${MAX_TODO_REMINDERS})`,
164
149
  '</system-reminder>',
165
150
  ].join('\n');
@@ -69,12 +69,16 @@ export function usageDeltaEvent({
69
69
  // callers that ignore these fields keep working.
70
70
  deltaCachedRead: usage.cachedTokens || 0,
71
71
  deltaCacheWrite: usage.cacheWriteTokens || 0,
72
- contextInputTokens: usage.inputTokens ?? 0,
72
+ // A provider whose billed input repeats context (Gemini long decode)
73
+ // reports the input the context really holds; the billed figures above
74
+ // stay untouched.
75
+ contextInputTokens: usage.contextInputTokens ?? usage.inputTokens ?? 0,
73
76
  contextOutputTokens: usage.outputTokens ?? 0,
74
- contextPromptTokens: usage.promptTokens ?? 0,
75
- contextCachedReadTokens: usage.cachedTokens ?? 0,
77
+ contextPromptTokens: usage.contextInputTokens ?? usage.promptTokens ?? 0,
78
+ contextCachedReadTokens: usage.contextCachedTokens ?? usage.cachedTokens ?? 0,
76
79
  contextCacheWriteTokens: usage.cacheWriteTokens ?? 0,
77
80
  contextMeasuredTokens: measuredContextTokens(usage),
81
+ ...(usage.contextInputTokens != null ? { contextOutputInWindow: true } : {}),
78
82
  sendTools,
79
83
  ts: Date.now(),
80
84
  };
@@ -25,6 +25,7 @@ import { holdTurnUntilDurable } from './turn-durability.mjs';
25
25
  import { recordProviderContextBaseline } from '../loop/compact-policy.mjs';
26
26
  import { throwIfAborted } from '../../../../shared/abort-race.mjs';
27
27
  import { appendAssistantTurnMessage, persistProviderState, recordAskUsage } from './ask-turn-commit.mjs';
28
+ import { CLOSE_PROVENANCE_VERSION } from '../../../../shared/agent-reap-state.mjs';
28
29
 
29
30
  export function attachAssistantTranscriptCompletion(messages, completion, turnStartedAt = 0) {
30
31
  if (!Array.isArray(messages) || !completion || typeof completion !== 'object') return false;
@@ -127,8 +128,14 @@ export async function commitAskTurn({ sessionId, opened, prepared, result, rawTr
127
128
  if (runtime.prepareCloseSnapshot === prepareCloseSnapshot) {
128
129
  runtime.prepareCloseSnapshot = null;
129
130
  }
130
- session.updatedAt = Date.now();
131
- session.lastUsedAt = Date.now();
131
+ const completedAt = Date.now();
132
+ session.updatedAt = completedAt;
133
+ session.lastUsedAt = completedAt;
134
+ // Owner closes from here on are recorded on this record, and only a
135
+ // completed turn (never a rewind or other bookkeeping that moves
136
+ // lastUsedAt) lifts an earlier one (agent-reap-state.mjs).
137
+ session.closeProvenance = CLOSE_PROVENANCE_VERSION;
138
+ session.lastTurnCompletedAt = completedAt;
132
139
  applyAskTerminalUsageTotals(session, result, {
133
140
  skipTotalsIfIncremental: runtime?.usageMetricsTurnIncremental === true,
134
141
  });