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
@@ -83,7 +83,12 @@ export function createCloseFlow({ mgr, registry, views }) {
83
83
  // below is an idempotent no-op fallback once terminal.
84
84
  // Closing a runtime cancels its work; only explicit session deletion
85
85
  // may tombstone the conversation.
86
- const ok = await closeManagedSession(mgr, sessionId, 'cli-agent-close', { tombstone: false });
86
+ // An owner's close (not a process exit's) is recorded on the session itself,
87
+ // so a later reuse of its reaped tag never continues it.
88
+ const ok = await closeManagedSession(mgr, sessionId, 'cli-agent-close', {
89
+ tombstone: false,
90
+ ...(keepRow ? {} : { ownerClose: true }),
91
+ });
87
92
  if (task?.taskId) cancelBackgroundTask(task.taskId, CLOSE_REASON);
88
93
  // Drop the row only once the cancellation is DURABLY recorded: a failed
89
94
  // close that still forgot the row would leave no cancelled state behind.
@@ -0,0 +1,94 @@
1
+ import { resolve } from 'node:path';
2
+ import {
3
+ callerSessionForContext,
4
+ clean,
5
+ isExistingDirectory,
6
+ normalizeAgentName,
7
+ resolvePrompt,
8
+ terminalPidForContext,
9
+ } from './helpers.mjs';
10
+
11
+ // Continuing a reaped tag's own saved session: the prompt is appended to the
12
+ // stored transcript as one more turn (nothing earlier is rewritten), so the
13
+ // worker keeps its context and a provider's prompt cache keeps its prefix.
14
+ //
15
+ // Inputs: `registry` (resumable-session reads, tag binding, tombstones),
16
+ // `sendFlow` (the existing-session dispatch) and `defaultCwd`. Output:
17
+ // { serialized, resumeTag }; one instance is shared by `send` and `spawn`.
18
+ export function createTagResume({ registry, sendFlow, defaultCwd }) {
19
+ const inFlight = new Map(); // owner scope + tag -> tail promise
20
+
21
+ /** Runs `run` after every earlier call for this owner's `tag` settled, so
22
+ * a competing send or spawn sees the tag the first one resumed (or
23
+ * respawned) instead of resuming it a second time. */
24
+ function serialized(tag, context, run) {
25
+ const owner = callerSessionForContext(context) || `pid:${terminalPidForContext(context) || 0}`;
26
+ const key = `${owner}\0${tag}`;
27
+ const previous = inFlight.get(key) || Promise.resolve();
28
+ const current = previous.then(run, run);
29
+ const tail = current.then(
30
+ () => {},
31
+ () => {}
32
+ );
33
+ inFlight.set(key, tail);
34
+ tail.then(() => {
35
+ if (inFlight.get(key) === tail) inFlight.delete(key);
36
+ });
37
+ return current;
38
+ }
39
+
40
+ // A request naming another agent or directory asks for different work than
41
+ // the saved session did; that gets a fresh session instead.
42
+ function requestFits(session, args, callerCwd) {
43
+ const agent = clean(args.agent);
44
+ if (agent && normalizeAgentName(agent) !== normalizeAgentName(session.agent)) return false;
45
+ const cwd = clean(args.cwd);
46
+ if (!cwd) return true;
47
+ return Boolean(clean(session.cwd)) && resolve(callerCwd || defaultCwd, cwd) === resolve(clean(session.cwd));
48
+ }
49
+
50
+ // The saved working directory is gone: a fresh session may start only in a
51
+ // directory the caller names that exists, never in the missing one.
52
+ async function refuseMissingCwd(operation, tag, missingCwd, args, callerCwd) {
53
+ const named = clean(args.cwd) ? resolve(callerCwd || defaultCwd, clean(args.cwd)) : '';
54
+ if (named && (await isExistingDirectory(named))) return;
55
+ const gone = missingCwd ? `"${missingCwd}"` : '(unknown)';
56
+ throw new Error(
57
+ `agent ${operation}: tag "${tag}" cannot continue: its working directory ${gone} no longer exists` +
58
+ `${named ? ` and cwd "${named}" is not a directory` : ''}; pass an existing cwd to start a fresh session there`
59
+ );
60
+ }
61
+
62
+ /** Dispatches `args` onto `sessionId` under `tag` and returns the rendered
63
+ * result, or null when that session cannot be resumed for this caller (the
64
+ * caller then starts a fresh session). Throws when only its working
65
+ * directory is gone and the caller named no existing one. A consumed
66
+ * `tombstone` is the reap record the resume replaces. Call inside
67
+ * `serialized` for this tag. */
68
+ async function resumeTag(
69
+ tag,
70
+ sessionId,
71
+ { operation, args, callerCwd, context, notifyContext, tombstone = null, route = null }
72
+ ) {
73
+ const found = await registry.resumableTagSession(tag, sessionId, context);
74
+ if (!found) return null;
75
+ if (!found.session) {
76
+ await refuseMissingCwd(operation, tag, found.missingCwd, args, callerCwd);
77
+ return null;
78
+ }
79
+ const { session } = found;
80
+ if (!requestFits(session, args, callerCwd)) return null;
81
+ const prompt = await resolvePrompt(args, session.cwd || defaultCwd);
82
+ const prepared = { args: { ...args, tag }, session, sessionId: session.id, prompt, ...(route ? { route } : {}) };
83
+ await sendFlow.adoptCaller(prepared, notifyContext);
84
+ const result = await sendFlow.dispatchToExistingSession(prepared, notifyContext, { resumed: true });
85
+ // Only once the turn was admitted on the session: the tag resolves to it
86
+ // again (its row is stamped fresh, so nothing ages it out before the turn
87
+ // writes its own), and the reap record goes.
88
+ registry.bindTag(tag, session, { turnStartedAt: new Date().toISOString() });
89
+ if (tombstone) registry.consumeTagTombstone(tombstone);
90
+ return result;
91
+ }
92
+
93
+ return { serialized, resumeTag };
94
+ }
@@ -1,18 +1,30 @@
1
+ import { createTagResume } from './execute-resume.mjs';
1
2
  import { clean, resolvePrompt } from './helpers.mjs';
2
3
 
3
- // Tag-addressed send, including the dead-tag respawn fallback: everything the
4
- // `send` request type needs once the caller's scope is resolved.
4
+ // Tag-addressed send, including the dead-tag fallback (resume the saved
5
+ // session, else respawn): everything the `send` request type needs once the
6
+ // caller's scope is resolved.
5
7
  //
6
- // Inputs: `registry` (tag maps, worker rows, tombstones), `defaultCwd`,
7
- // `sendFlow`, `spawnFlow`, and `spawnResult` (job -> rendered tool output).
8
- // Output: { send }.
9
- export function createSendDispatch({ registry, defaultCwd, sendFlow, spawnFlow, spawnResult }) {
10
- // A retained row or reap tombstone proves that this terminal owned the tag.
11
- // Unknown tags stay errors even when the caller supplies an agent/cwd: typo
12
- // absorption requires persisted same-tag evidence. Absorption identity is
13
- // always terminal-local, even when live resolution was explicitly requested
14
- // across all terminals; a local proof wins even if another terminal also
15
- // owns this tag.
8
+ // Inputs: `registry` (tag maps, worker rows, tombstones, session records),
9
+ // `defaultCwd`, `sendFlow`, `spawnFlow`, `spawnResult` (job -> rendered tool
10
+ // output) and `tagResume` (shared with spawn). Output: { send }.
11
+ const isDeadTarget = (err) => /not found|is closed/i.test(String(err?.message || ''));
12
+
13
+ export function createSendDispatch({
14
+ registry,
15
+ defaultCwd,
16
+ sendFlow,
17
+ spawnFlow,
18
+ spawnResult,
19
+ tagResume = createTagResume({ registry, sendFlow, defaultCwd }),
20
+ }) {
21
+ // A retained row, a reap tombstone, or (once a pruned row's tombstone has
22
+ // expired or been capped out) the tag's own session record proves that this
23
+ // terminal owned the tag. Unknown tags stay errors even when the caller
24
+ // supplies an agent/cwd: typo absorption requires persisted same-tag
25
+ // evidence. Absorption identity is always terminal-local, even when live
26
+ // resolution was explicitly requested across all terminals; a local proof
27
+ // wins even if another terminal also owns this tag.
16
28
  function inheritedTagIdentity(fallbackTag, ownershipContext, args, callerCwd) {
17
29
  let row = null;
18
30
  try {
@@ -21,11 +33,19 @@ export function createSendDispatch({ registry, defaultCwd, sendFlow, spawnFlow,
21
33
  row = null;
22
34
  }
23
35
  const tombstone = registry.tagTombstoneForTag(fallbackTag, ownershipContext);
24
- if (!row && !tombstone) return null;
25
- const agent = clean(args.agent) || clean(row?.agent) || clean(tombstone?.agent);
26
- const cwd = clean(args.cwd) || clean(row?.cwd) || clean(tombstone?.cwd) || clean(callerCwd);
36
+ const record = row || tombstone ? null : registry.lastTagSession(fallbackTag, ownershipContext);
37
+ if (!row && !tombstone && !record) return null;
38
+ const agent = clean(args.agent) || clean(row?.agent) || clean(tombstone?.agent) || clean(record?.agent);
39
+ const cwd = clean(args.cwd) || clean(row?.cwd) || clean(tombstone?.cwd) || clean(record?.cwd) || clean(callerCwd);
27
40
  if (!agent || !cwd) return null;
28
- return { row, tombstone, sessionId: clean(row?.sessionId), agent, cwd };
41
+ return {
42
+ row,
43
+ tombstone,
44
+ sessionId: clean(row?.sessionId),
45
+ resumeSessionId: clean(row?.sessionId) || clean(tombstone?.sessionId) || clean(record?.id),
46
+ agent,
47
+ cwd,
48
+ };
29
49
  }
30
50
 
31
51
  // Drop this terminal's in-memory trace and remove ONLY the persisted row
@@ -38,20 +58,45 @@ export function createSendDispatch({ registry, defaultCwd, sendFlow, spawnFlow,
38
58
  if (inherited.tombstone) registry.consumeTagTombstone(inherited.tombstone);
39
59
  }
40
60
 
41
- // Dead-tag fallback: a same-scope follow-up can land after its session was
42
- // closed or deleted. Instead of bouncing an
43
- // error back to Lead (who would just re-issue the same content as a spawn),
44
- // respawn a FRESH session under the same tag with the message as its brief.
45
- // `respawned: true` in the result tells Lead the worker has no prior session
46
- // context. Only tag-addressed sends fall back; explicit sessionId sends keep
47
- // erroring (the caller pinned a specific session on purpose).
48
- async function respawnDeadTagSend(err, args, { callerCwd, context, notifyContext }) {
61
+ // Dead-tag fallback: a same-scope follow-up can land after its tag was
62
+ // reaped, or after its session was closed or deleted. A reaped tag whose
63
+ // saved session is still stored and open continues that session (`resumed`,
64
+ // prior context kept). Otherwise, instead of bouncing an error back to Lead
65
+ // (who would just re-issue the same content as a spawn), respawn a FRESH
66
+ // session under the same tag with the message as its brief; `respawned:
67
+ // true` in the result tells Lead the worker has no prior session context.
68
+ // Only tag-addressed sends fall back; explicit sessionId sends keep erroring
69
+ // (the caller pinned a specific session on purpose).
70
+ async function respawnDeadTagSend(err, args, { scopedContext, callerCwd, context, notifyContext }) {
49
71
  const fallbackTag = clean(args.tag);
50
- const isDeadTarget = /not found|is closed/i.test(String(err?.message || ''));
51
- if (!fallbackTag || fallbackTag.startsWith('sess_') || !isDeadTarget) throw err;
72
+ if (!fallbackTag || fallbackTag.startsWith('sess_') || !isDeadTarget(err)) throw err;
73
+ return tagResume.serialized(fallbackTag, context, async () => {
74
+ // A competing send or spawn of this tag may have resumed or respawned
75
+ // it while this one waited: then this is an ordinary send to it.
76
+ let prepared = null;
77
+ try {
78
+ prepared = await sendFlow.prepareSend(args, scopedContext);
79
+ } catch (retryErr) {
80
+ if (!isDeadTarget(retryErr)) throw retryErr;
81
+ }
82
+ if (prepared) return dispatchPrepared(prepared, notifyContext);
83
+ return await resumeOrRespawn(err, fallbackTag, args, { callerCwd, context, notifyContext });
84
+ });
85
+ }
86
+
87
+ async function resumeOrRespawn(err, fallbackTag, args, { callerCwd, context, notifyContext }) {
52
88
  const prompt = await resolvePrompt(args, callerCwd || defaultCwd);
53
89
  const inherited = inheritedTagIdentity(fallbackTag, context, args, callerCwd);
54
90
  if (!inherited) throw err;
91
+ const resumed = await tagResume.resumeTag(fallbackTag, inherited.resumeSessionId, {
92
+ operation: 'send',
93
+ args,
94
+ callerCwd,
95
+ context,
96
+ notifyContext,
97
+ tombstone: inherited.tombstone,
98
+ });
99
+ if (resumed) return resumed;
55
100
  consumeInheritedTag(fallbackTag, inherited);
56
101
  const spawnArgs = {
57
102
  ...args,
@@ -67,13 +112,18 @@ export function createSendDispatch({ registry, defaultCwd, sendFlow, spawnFlow,
67
112
  );
68
113
  }
69
114
 
115
+ async function dispatchPrepared(prepared, notifyContext) {
116
+ await sendFlow.adoptCaller(prepared, notifyContext);
117
+ return sendFlow.dispatchToExistingSession(prepared, notifyContext);
118
+ }
119
+
70
120
  async function send(args, { scopedContext, callerCwd, context, notifyContext }) {
71
121
  try {
72
122
  const prepared = await sendFlow.prepareSend(args, scopedContext);
73
123
  await sendFlow.adoptCaller(prepared, notifyContext);
74
124
  return sendFlow.dispatchToExistingSession(prepared, notifyContext);
75
125
  } catch (err) {
76
- return await respawnDeadTagSend(err, args, { callerCwd, context, notifyContext });
126
+ return await respawnDeadTagSend(err, args, { scopedContext, callerCwd, context, notifyContext });
77
127
  }
78
128
  }
79
129
 
@@ -1,3 +1,4 @@
1
+ import { createTagResume } from './execute-resume.mjs';
1
2
  import { clean, rowMatchesContext } from './helpers.mjs';
2
3
  import { resolveRequestedModel } from './model-select.mjs';
3
4
 
@@ -21,9 +22,10 @@ function requestedRoute(args) {
21
22
  // Spawn request dispatch: deciding what an explicitly tagged spawn means before
22
23
  // a job is started, and starting it.
23
24
  //
24
- // Inputs: `registry` (tag resolution, live sessions, tombstones),
25
- // `terminalTrace`, `sendFlow` (reuse path), `spawnFlow`, and `spawnResult`
26
- // (job -> rendered tool output). Output: { spawn }.
25
+ // Inputs: `registry` (tag resolution, live sessions, tombstones, session
26
+ // records), `terminalTrace`, `sendFlow` (reuse path), `spawnFlow`,
27
+ // `spawnResult` (job -> rendered tool output), `defaultCwd` and `tagResume`
28
+ // (shared with send). Output: { spawn }.
27
29
  export function createSpawnDispatch({
28
30
  registry,
29
31
  terminalTrace,
@@ -31,13 +33,20 @@ export function createSpawnDispatch({
31
33
  spawnFlow,
32
34
  spawnResult,
33
35
  listProviderModels = null,
36
+ defaultCwd = process.cwd(),
37
+ tagResume = createTagResume({ registry, sendFlow, defaultCwd }),
34
38
  }) {
39
+ const { resumeTag } = tagResume;
40
+
35
41
  // Explicit-tag spawn priority (auto nextTag always creates a fresh session):
36
42
  // 1) live + busy -> queue the prompt (reuse)
37
43
  // 2) live + idle -> continue existing session (reuse)
38
44
  // 3) lingering terminal trace -> reap trace and fresh spawn under same tag
39
- // 4) genuinely new tag -> fresh deferred spawn
40
- async function resolveExplicitTagSpawn(explicitTag, args, { scopedContext, context, notifyContext }) {
45
+ // 4) reaped tag (tombstone, or past it this owner's last session record)
46
+ // whose saved session can continue -> resume it; a tombstone whose
47
+ // session cannot -> fresh spawn inheriting agent/cwd (`respawned`)
48
+ // 5) genuinely new tag -> fresh deferred spawn
49
+ async function resolveExplicitTagSpawn(explicitTag, args, { scopedContext, context, notifyContext, callerCwd }) {
41
50
  let liveSessionId = null;
42
51
  try {
43
52
  liveSessionId = registry.resolveTag(explicitTag, scopedContext, {
@@ -63,9 +72,12 @@ export function createSpawnDispatch({
63
72
  terminalTrace.reapTerminalTraceForTag(explicitTag, scopedContext);
64
73
  return { spawnArgs: args, respawned: true };
65
74
  }
66
- // Tombstone inheritance never honors allTerminals/global scope.
75
+ // Tombstone inheritance and resume never honor allTerminals/global scope.
76
+ const resumeOptions = { operation: 'spawn', args, callerCwd, context, notifyContext, route: requestedRoute(args) };
67
77
  const tombstone = registry.tagTombstoneForTag(explicitTag, context);
68
78
  if (tombstone) {
79
+ const resumed = await resumeTag(explicitTag, tombstone.sessionId, { ...resumeOptions, tombstone });
80
+ if (resumed) return { reused: resumed };
69
81
  registry.consumeTagTombstone(tombstone);
70
82
  return {
71
83
  spawnArgs: {
@@ -80,6 +92,11 @@ export function createSpawnDispatch({
80
92
  .readAllTagTombstones()
81
93
  .find((row) => clean(row.tag) === explicitTag && !rowMatchesContext(row, context));
82
94
  if (foreignTombstone) throw new Error(`agent spawn: tag "${explicitTag}" belongs to another terminal`);
95
+ const record = registry.lastTagSession(explicitTag, context);
96
+ if (record) {
97
+ const resumed = await resumeTag(explicitTag, record.id, resumeOptions);
98
+ if (resumed) return { reused: resumed };
99
+ }
83
100
  return { spawnArgs: args, respawned: false };
84
101
  }
85
102
 
@@ -91,7 +108,11 @@ export function createSpawnDispatch({
91
108
  let spawnArgs = args;
92
109
  let respawned = false;
93
110
  if (explicitTag) {
94
- const plan = await resolveExplicitTagSpawn(explicitTag, args, request);
111
+ // One decision at a time per owner's tag: a spawn queued behind a send
112
+ // or spawn that resumed this tag reuses it instead of resuming it again.
113
+ const plan = await tagResume.serialized(explicitTag, request.context, () =>
114
+ resolveExplicitTagSpawn(explicitTag, args, request)
115
+ );
95
116
  if (plan.reused) return plan.reused;
96
117
  spawnArgs = plan.spawnArgs;
97
118
  respawned = plan.respawned;
@@ -1,6 +1,7 @@
1
1
  import { errorLine } from '../../../runtime/shared/err-text.mjs';
2
2
  import { createSendDispatch } from './execute-send.mjs';
3
3
  import { createSpawnDispatch } from './execute-spawn.mjs';
4
+ import { createTagResume } from './execute-resume.mjs';
4
5
  import { agentScope, clean } from './helpers.mjs';
5
6
  import { renderResult } from './render.mjs';
6
7
 
@@ -30,7 +31,9 @@ export function createAgentExecute({
30
31
  return renderResult(views.renderJob(job, true));
31
32
  }
32
33
 
33
- const { send } = createSendDispatch({ registry, defaultCwd, sendFlow, spawnFlow, spawnResult });
34
+ // Shared so a send and a spawn of one reaped tag are serialized together.
35
+ const tagResume = createTagResume({ registry, sendFlow, defaultCwd });
36
+ const { send } = createSendDispatch({ registry, defaultCwd, sendFlow, spawnFlow, spawnResult, tagResume });
34
37
  const { spawn } = createSpawnDispatch({
35
38
  registry,
36
39
  terminalTrace,
@@ -38,6 +41,8 @@ export function createAgentExecute({
38
41
  spawnFlow,
39
42
  spawnResult,
40
43
  listProviderModels,
44
+ defaultCwd,
45
+ tagResume,
41
46
  });
42
47
 
43
48
  return async function execute(args = {}, context = {}) {
@@ -1,5 +1,6 @@
1
1
  // Dependency-light helpers for the agent-tool facade.
2
2
  import { existsSync, readFileSync } from 'node:fs';
3
+ import { stat } from 'node:fs/promises';
3
4
  import { isAbsolute, join, resolve } from 'node:path';
4
5
  import {
5
6
  normalizeAgentPermissionOrNone,
@@ -67,6 +68,16 @@ export function runtimeAlive(pid) {
67
68
  }
68
69
  }
69
70
 
71
+ /** Whether `path` is an existing directory (probed without blocking). */
72
+ export async function isExistingDirectory(path) {
73
+ if (!clean(path)) return false;
74
+ try {
75
+ return (await stat(path)).isDirectory();
76
+ } catch {
77
+ return false;
78
+ }
79
+ }
80
+
70
81
  export function agentTagOf(session) {
71
82
  return clean(session?.agentTag);
72
83
  }
@@ -67,16 +67,19 @@ export function createJobRender({ progress }) {
67
67
 
68
68
  function renderJob(job, includeResult = false) {
69
69
  const meta = job.meta || {};
70
- const head = jobHead(
71
- { ...job, type: job.operation },
72
- meta,
73
- meta.respawned === true
74
- ? {
75
- respawned: true,
76
- note: 'previous session reaped — fresh session, no prior context; re-supply anchors if needed',
77
- }
78
- : {}
79
- );
70
+ let reapNote = {};
71
+ if (meta.respawned === true) {
72
+ reapNote = {
73
+ respawned: true,
74
+ note: 'previous session reaped — fresh session, no prior context; re-supply anchors if needed',
75
+ };
76
+ } else if (meta.resumed === true) {
77
+ reapNote = {
78
+ resumed: true,
79
+ note: 'previous session reaped — resumed from its saved transcript, prior context kept',
80
+ };
81
+ }
82
+ const head = jobHead({ ...job, type: job.operation }, meta, reapNote);
80
83
  const tail = includeResult && job.result !== undefined ? { result: job.result } : {};
81
84
  // Frozen terminal view: never re-read the (possibly reused) live session.
82
85
  if (isTerminalJobStatus(job.status)) {
@@ -156,6 +156,7 @@ function renderTask(value, includeDiagnostics) {
156
156
  if (value.type) lines.push(`type: ${value.type}`);
157
157
  if (value.reused) lines.push('reused: true');
158
158
  if (value.respawned) lines.push('respawned: true');
159
+ if (value.resumed) lines.push('resumed: true');
159
160
  if (value.note) lines.push(`note: ${value.note}`);
160
161
  if (value.tag || value.sessionId) lines.push(`target: ${value.tag || '-'} ${value.sessionId || ''}`.trim());
161
162
  if (!isStartAck) lines.push(...taskDiagnosticLines(value));
@@ -174,6 +175,7 @@ function renderQueued(value) {
174
175
  return [
175
176
  'agent message queued',
176
177
  value.reused ? 'reused: true' : null,
178
+ value.resumed ? 'resumed: true' : null,
177
179
  `target: ${value.tag || '-'} ${value.sessionId || ''}`.trim(),
178
180
  value.agent ? `agent: ${value.agent}` : null,
179
181
  `queueDepth: ${value.queueDepth ?? 1}`,
@@ -343,6 +343,7 @@ export function createSendFlow({
343
343
  effort: session.effort || null,
344
344
  fast: session.fast === true,
345
345
  ...(session.autoEffort === false ? { autoEffort: false } : {}),
346
+ ...(extras.resumed === true ? { resumed: true } : {}),
346
347
  },
347
348
  (job, ownerNotifyContext) => runSend(prepared, ownerNotifyContext, job),
348
349
  notifyContext
@@ -7,6 +7,7 @@
7
7
  import { presetKey, readAgentFirstResponseTimeoutMs, writeAgentStatuslineRoute } from '../helpers.mjs';
8
8
  import { resolveAgentWatchdogPolicy } from '../../../../runtime/agent/orchestrator/agent-runtime/agent-progress-watchdog.mjs';
9
9
  import { prepareAgentSession } from '../../../../runtime/agent/orchestrator/agent-runtime/session-builder.mjs';
10
+ import { prewarmGitStartupProbes } from '../../../../runtime/agent/orchestrator/tools/builtin/runtime-capabilities.mjs';
10
11
  import { getProvider } from '../../../../runtime/agent/orchestrator/providers/registry.mjs';
11
12
  import { resolveRouteContextState } from '../../../route-state.mjs';
12
13
  import { contextSelectionFromState } from '../../../../runtime/agent/orchestrator/runtime-core/route-context-state.mjs';
@@ -106,10 +107,15 @@ export function createSpawnPreparer({
106
107
  if (plan.preset.contextPercent || plan.preset.contextTokens) {
107
108
  Object.assign(sessionSpec, contextSelectionFromState(resolveRouteContextState(plan.preset, null), plan.preset));
108
109
  }
110
+ // Session creation composes the git startup line synchronously; its probes
111
+ // answer off-thread here so that composition never spawns git on the event loop.
112
+ const gitProbes = prewarmGitStartupProbes([sessionSpec.cwd]);
109
113
  if (sessionSurface?.canonical === true && typeof sessionSurface.createChild === 'function') {
114
+ await gitProbes;
110
115
  return sessionSurface.createChild({ spec: sessionSpec, prompt: plan.prompt, tag: plan.tag });
111
116
  }
112
117
  await ensureProvider(plan.config, plan.preset.provider);
118
+ await gitProbes;
113
119
  if (prepState?.timedOut) {
114
120
  throw new Error('agent spawn prep timed out before session bind');
115
121
  }
@@ -253,7 +253,8 @@ export function createSpawnRunner({
253
253
  // SubagentStop: worker finished (terminal), regardless of outcome.
254
254
  emitSubagentEvent('stop', agent, { session_id: session.id, tag, status: finalStatus });
255
255
  // Keep the durable session/tag for same-tag follow-ups, but release every
256
- // process-local provider, shell, watchdog and tool cache immediately.
256
+ // process-local shell, watchdog and tool cache immediately. Pooled
257
+ // provider connections stay for the follow-up's response chain.
257
258
  try {
258
259
  mgr.unloadSessionRuntime?.(session.id, 'agent-turn-complete');
259
260
  } catch {}
@@ -0,0 +1,82 @@
1
+ // Sessions behind a reaped tag, for an explicit reuse of that tag only (scans
2
+ // never read these). A reap drops only the index row and leaves a capped,
3
+ // expiring tombstone; the session record stays on disk and still names its
4
+ // tag and owner session, and the store's own retention deletes it in time.
5
+ // These reads let a send or explicit spawn continue that saved session, or at
6
+ // least prove the tag was this owner's, once the index no longer can.
7
+ import { sessionPath } from '../../../../runtime/agent/orchestrator/session/store/session-paths.mjs';
8
+ import { resumableAfterReap } from '../../../../runtime/shared/agent-reap-state.mjs';
9
+ import { createWorkerRequestClient } from '../../../../runtime/shared/worker-requests.mjs';
10
+ import {
11
+ agentTagOf,
12
+ callerSessionForContext,
13
+ clean,
14
+ isExistingDirectory,
15
+ sessionMatchesContext,
16
+ stampMs,
17
+ } from '../helpers.mjs';
18
+ import { isLeadPoolAgent } from '../worker-rows.mjs';
19
+
20
+ // The record is read and parsed on a worker thread (record-facts-worker.mjs),
21
+ // started on the first resume and retired when idle.
22
+ const readRecordFacts = createWorkerRequestClient(new URL('./record-facts-worker.mjs', import.meta.url), {
23
+ idleExitMs: 30_000,
24
+ });
25
+
26
+ async function storedRecordFacts(sessionId) {
27
+ let path;
28
+ try {
29
+ path = sessionPath(sessionId);
30
+ } catch {
31
+ return null;
32
+ }
33
+ return readRecordFacts({ path, sessionId });
34
+ }
35
+
36
+ export function createReapedSessions({ mgr, getLiveSession, isReleased }) {
37
+ function ownedTagSession(session, tag, context) {
38
+ return (
39
+ Boolean(clean(session?.id)) &&
40
+ agentTagOf(session) === tag &&
41
+ !isLeadPoolAgent(session.agent) &&
42
+ sessionMatchesContext(session, context)
43
+ );
44
+ }
45
+
46
+ /** The newest session record (open or closed) the caller's owner session
47
+ * ran under `tag`, or null when it never used the tag. Only an owner
48
+ * session scopes this: a terminal pid alone proves nothing durable. */
49
+ function lastTagSession(tag, context = {}) {
50
+ const value = clean(tag);
51
+ if (!value || value.startsWith('sess_') || !callerSessionForContext(context)) return null;
52
+ let newest = null;
53
+ for (const session of mgr.listSessions?.({ includeClosed: true }) || []) {
54
+ if (!ownedTagSession(session, value, context)) continue;
55
+ if (!newest || stampMs(session.createdAt) > stampMs(newest.createdAt)) newest = session;
56
+ }
57
+ return newest;
58
+ }
59
+
60
+ /** Whether `sessionId` may continue under `tag` for this owner, decided by
61
+ * its stored record (strictly parsed off the event loop; a daemon-owned
62
+ * child's live descriptor carries none of these fields): still stored, not
63
+ * closed, carrying close provenance and not closed by its owner since its
64
+ * last turn (resumableAfterReap; the index's released marker counts only
65
+ * for its TTL), and naming this tag and owner. `{ session }` when it may
66
+ * continue, `{ missingCwd }` when only its working directory is gone, else
67
+ * null. */
68
+ async function resumableTagSession(tag, sessionId, context = {}) {
69
+ const value = clean(tag);
70
+ const id = clean(sessionId);
71
+ if (!value || !id || isReleased(id)) return null;
72
+ const record = await storedRecordFacts(id);
73
+ if (!record || record.closed === true || !resumableAfterReap(record)) return null;
74
+ if (!ownedTagSession(record, value, context)) return null;
75
+ const session = getLiveSession(id);
76
+ if (!session) return null;
77
+ const cwd = clean(record.cwd);
78
+ return (await isExistingDirectory(cwd)) ? { session } : { missingCwd: cwd };
79
+ }
80
+
81
+ return { lastTagSession, resumableTagSession };
82
+ }
@@ -0,0 +1,36 @@
1
+ // Worker thread: reads one stored session record and answers the few fields a
2
+ // reaped-tag resume decides on, so a transcript of several MB is never read or
3
+ // parsed on the host's event loop. Same strict parse as the store's lifecycle
4
+ // authority: an absent, unreadable, ambiguous or foreign record answers null.
5
+ import { readFile } from 'node:fs/promises';
6
+ import { serveWorkerRequests } from '../../../../runtime/shared/worker-requests.mjs';
7
+ import {
8
+ isLifecycleUnreadable,
9
+ readTopLevelLifecycleRecord,
10
+ } from '../../../../runtime/agent/orchestrator/session/lifecycle-scan.mjs';
11
+
12
+ serveWorkerRequests(async ({ path, sessionId }) => {
13
+ let text;
14
+ try {
15
+ text = await readFile(path, 'utf8');
16
+ } catch (error) {
17
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') return null;
18
+ throw error;
19
+ }
20
+ const record = readTopLevelLifecycleRecord(text);
21
+ if (isLifecycleUnreadable(record) || record.id !== sessionId) return null;
22
+ const doc = record.doc;
23
+ return {
24
+ id: sessionId,
25
+ agentTag: doc.agentTag || null,
26
+ agent: doc.agent || null,
27
+ parentSessionId: doc.parentSessionId || null,
28
+ ownerSessionId: doc.ownerSessionId || null,
29
+ clientHostPid: doc.clientHostPid || null,
30
+ cwd: doc.cwd || '',
31
+ closed: doc.closed === true || doc.status === 'closed',
32
+ lastTurnCompletedAt: doc.lastTurnCompletedAt ?? null,
33
+ ownerClosedAt: doc.ownerClosedAt ?? null,
34
+ closeProvenance: doc.closeProvenance ?? null,
35
+ };
36
+ });
@@ -10,6 +10,7 @@ import { createTagMaps } from './tag-maps.mjs';
10
10
  import { createTerminalReaper } from './terminal-reaper.mjs';
11
11
  import { createTagLookup } from './tag-registry/tag-lookup.mjs';
12
12
  import { createTagRefresh } from './tag-registry/tag-refresh.mjs';
13
+ import { createReapedSessions } from './tag-registry/reaped-sessions.mjs';
13
14
 
14
15
  export function createTagRegistry({ dataDir, cfgMod, mgr }) {
15
16
  const tagMaps = createTagMaps();
@@ -68,6 +69,7 @@ export function createTagRegistry({ dataDir, cfgMod, mgr }) {
68
69
  }
69
70
 
70
71
  const reaper = createTerminalReaper({ cfgMod, mgr, tagMaps, index, getLiveSession });
72
+ const reaped = createReapedSessions({ mgr, getLiveSession, isReleased: index.isReleased });
71
73
 
72
74
  function wantsSessionScan(args = {}) {
73
75
  return args.recover === true || args.scanSessions === true || args.scan_sessions === true;
@@ -140,6 +142,8 @@ export function createTagRegistry({ dataDir, cfgMod, mgr }) {
140
142
  tombstoneTerminalSession: reaper.tombstoneTerminalSession,
141
143
  tagTombstoneForTag: reaper.tagTombstoneForTag,
142
144
  consumeTagTombstone: reaper.consumeTagTombstone,
145
+ lastTagSession: reaped.lastTagSession,
146
+ resumableTagSession: reaped.resumableTagSession,
143
147
  transitionStaleNonterminalRows: reaper.transitionStaleNonterminalRows,
144
148
  };
145
149
  }