mixdog 0.9.2 → 0.9.3

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 (154) hide show
  1. package/package.json +2 -1
  2. package/scripts/anthropic-maxtokens-test.mjs +119 -0
  3. package/scripts/build-tui.mjs +13 -1
  4. package/scripts/explore-bench.mjs +124 -0
  5. package/scripts/hook-bus-test.mjs +191 -0
  6. package/scripts/path-suffix-test.mjs +57 -0
  7. package/scripts/recall-bench.mjs +207 -0
  8. package/scripts/tool-smoke.mjs +7 -4
  9. package/src/agents/debugger/AGENT.md +2 -2
  10. package/src/agents/heavy-worker/AGENT.md +20 -11
  11. package/src/agents/reviewer/AGENT.md +2 -2
  12. package/src/agents/worker/AGENT.md +17 -11
  13. package/src/mixdog-session-runtime.mjs +424 -1812
  14. package/src/repl.mjs +5 -5
  15. package/src/rules/agent/30-explorer.md +8 -11
  16. package/src/rules/lead/lead-tool.md +9 -5
  17. package/src/rules/shared/01-tool.md +11 -5
  18. package/src/runtime/agent/orchestrator/context/collect.mjs +51 -0
  19. package/src/runtime/agent/orchestrator/mcp/client.mjs +6 -2
  20. package/src/runtime/agent/orchestrator/providers/anthropic-effort.mjs +1 -1
  21. package/src/runtime/agent/orchestrator/providers/anthropic-max-tokens.mjs +93 -0
  22. package/src/runtime/agent/orchestrator/providers/anthropic-oauth.mjs +22 -68
  23. package/src/runtime/agent/orchestrator/providers/anthropic.mjs +46 -7
  24. package/src/runtime/agent/orchestrator/providers/api-usage.mjs +1 -13
  25. package/src/runtime/agent/orchestrator/providers/gemini.mjs +1 -1
  26. package/src/runtime/agent/orchestrator/providers/grok-oauth.mjs +1 -1
  27. package/src/runtime/agent/orchestrator/providers/lib/usage-primitives.mjs +32 -0
  28. package/src/runtime/agent/orchestrator/providers/oauth-usage.mjs +54 -20
  29. package/src/runtime/agent/orchestrator/providers/openai-compat-stream.mjs +19 -12
  30. package/src/runtime/agent/orchestrator/providers/openai-compat.mjs +7 -5
  31. package/src/runtime/agent/orchestrator/providers/openai-oauth-ws.mjs +33 -23
  32. package/src/runtime/agent/orchestrator/providers/openai-oauth.mjs +31 -14
  33. package/src/runtime/agent/orchestrator/providers/opencode-go-usage.mjs +38 -12
  34. package/src/runtime/agent/orchestrator/providers/retry-classifier.mjs +7 -8
  35. package/src/runtime/agent/orchestrator/session/loop/compact-debug.mjs +28 -0
  36. package/src/runtime/agent/orchestrator/session/loop/compact-policy.mjs +262 -0
  37. package/src/runtime/agent/orchestrator/session/loop/context-overflow.mjs +38 -0
  38. package/src/runtime/agent/orchestrator/session/loop/env.mjs +14 -0
  39. package/src/runtime/agent/orchestrator/session/loop/hidden-agents.mjs +21 -0
  40. package/src/runtime/agent/orchestrator/session/loop/pre-dispatch-deny.mjs +49 -0
  41. package/src/runtime/agent/orchestrator/session/loop/steering.mjs +63 -0
  42. package/src/runtime/agent/orchestrator/session/loop/stored-tool-args.mjs +100 -0
  43. package/src/runtime/agent/orchestrator/session/loop/tool-classify.mjs +52 -0
  44. package/src/runtime/agent/orchestrator/session/loop/tool-helpers.mjs +218 -0
  45. package/src/runtime/agent/orchestrator/session/loop/transcript-repair.mjs +101 -0
  46. package/src/runtime/agent/orchestrator/session/loop/usage.mjs +35 -0
  47. package/src/runtime/agent/orchestrator/session/loop.mjs +169 -918
  48. package/src/runtime/agent/orchestrator/session/manager/context-meta.mjs +227 -0
  49. package/src/runtime/agent/orchestrator/session/manager/pending-messages.mjs +235 -0
  50. package/src/runtime/agent/orchestrator/session/manager/prompt-utils.mjs +137 -0
  51. package/src/runtime/agent/orchestrator/session/manager/rules-cache.mjs +155 -0
  52. package/src/runtime/agent/orchestrator/session/manager/tool-resolution.mjs +303 -0
  53. package/src/runtime/agent/orchestrator/session/manager.mjs +65 -1032
  54. package/src/runtime/agent/orchestrator/stall-policy.mjs +3 -3
  55. package/src/runtime/agent/orchestrator/tools/builtin/builtin-tools.mjs +2 -2
  56. package/src/runtime/agent/orchestrator/tools/builtin/external-tool-adapters.mjs +241 -0
  57. package/src/runtime/agent/orchestrator/tools/builtin/external-tool-adapters.test.mjs +162 -0
  58. package/src/runtime/agent/orchestrator/tools/builtin/fuzzy-match.mjs +1 -1
  59. package/src/runtime/agent/orchestrator/tools/builtin/path-diagnostics.mjs +42 -2
  60. package/src/runtime/agent/orchestrator/tools/builtin/read-formatting.mjs +1 -1
  61. package/src/runtime/agent/orchestrator/tools/builtin/read-single-tool.mjs +11 -4
  62. package/src/runtime/agent/orchestrator/tools/builtin/search-tool.mjs +5 -0
  63. package/src/runtime/agent/orchestrator/tools/builtin/shell-jobs.mjs +50 -39
  64. package/src/runtime/agent/orchestrator/tools/builtin.mjs +11 -0
  65. package/src/runtime/agent/orchestrator/tools/code-graph/build.mjs +303 -0
  66. package/src/runtime/agent/orchestrator/tools/code-graph/constants.mjs +43 -0
  67. package/src/runtime/agent/orchestrator/tools/code-graph/disk-cache.mjs +382 -0
  68. package/src/runtime/agent/orchestrator/tools/code-graph/dispatch.mjs +497 -0
  69. package/src/runtime/agent/orchestrator/tools/code-graph/graph-binary.mjs +295 -0
  70. package/src/runtime/agent/orchestrator/tools/code-graph/graph-model.mjs +158 -0
  71. package/src/runtime/agent/orchestrator/tools/code-graph/lang-predicates.mjs +128 -0
  72. package/src/runtime/agent/orchestrator/tools/code-graph/memory-cache.mjs +66 -0
  73. package/src/runtime/agent/orchestrator/tools/code-graph/project-root.mjs +44 -0
  74. package/src/runtime/agent/orchestrator/tools/code-graph/search.mjs +1192 -0
  75. package/src/runtime/agent/orchestrator/tools/code-graph/source-access.mjs +81 -0
  76. package/src/runtime/agent/orchestrator/tools/code-graph/span.mjs +19 -0
  77. package/src/runtime/agent/orchestrator/tools/code-graph/symbol-index.mjs +280 -0
  78. package/src/runtime/agent/orchestrator/tools/code-graph/text-mask.mjs +347 -0
  79. package/src/runtime/agent/orchestrator/tools/code-graph.mjs +36 -4277
  80. package/src/runtime/agent/orchestrator/tools/patch.mjs +3 -3
  81. package/src/runtime/agent/orchestrator/tools/progress-message.mjs +1 -2
  82. package/src/runtime/agent/orchestrator/tools/shell-command.mjs +1 -2
  83. package/src/runtime/agent/orchestrator/tools/shell-snapshot.mjs +2 -4
  84. package/src/runtime/channels/index.mjs +14 -233
  85. package/src/runtime/channels/lib/boot-profile.mjs +23 -0
  86. package/src/runtime/channels/lib/crash-log.mjs +106 -0
  87. package/src/runtime/channels/lib/index-drop-trace.mjs +72 -0
  88. package/src/runtime/channels/lib/output-forwarder.mjs +8 -0
  89. package/src/runtime/channels/lib/telegram-format.mjs +19 -22
  90. package/src/runtime/channels/lib/whisper-language.mjs +42 -0
  91. package/src/runtime/memory/index.mjs +314 -359
  92. package/src/runtime/memory/lib/core-memory-store.mjs +351 -1
  93. package/src/runtime/memory/lib/cycle-signatures.mjs +34 -0
  94. package/src/runtime/memory/lib/http-wire.mjs +57 -0
  95. package/src/runtime/memory/lib/memory-cycle2.mjs +56 -3
  96. package/src/runtime/memory/lib/memory-recall-scope-filter.mjs +24 -0
  97. package/src/runtime/memory/lib/memory-retrievers.mjs +8 -0
  98. package/src/runtime/memory/lib/memory.mjs +20 -0
  99. package/src/runtime/memory/lib/promotion-fingerprint.mjs +50 -0
  100. package/src/runtime/memory/lib/recall-format.mjs +183 -0
  101. package/src/runtime/memory/tool-defs.mjs +4 -4
  102. package/src/runtime/shared/abort-controller.mjs +1 -1
  103. package/src/runtime/shared/background-tasks.mjs +2 -3
  104. package/src/runtime/shared/buffered-appender.mjs +149 -0
  105. package/src/runtime/shared/task-notification-envelope.mjs +98 -0
  106. package/src/runtime/shared/task-notification-envelope.test.mjs +107 -0
  107. package/src/runtime/shared/tool-execution-contract.mjs +2 -2
  108. package/src/runtime/shared/transcript-writer.mjs +29 -2
  109. package/src/session-runtime/config-helpers.mjs +209 -0
  110. package/src/session-runtime/effort.mjs +128 -0
  111. package/src/session-runtime/fs-utils.mjs +10 -0
  112. package/src/session-runtime/model-capabilities.mjs +130 -0
  113. package/src/session-runtime/output-styles.mjs +124 -0
  114. package/src/session-runtime/plugin-mcp.mjs +114 -0
  115. package/src/session-runtime/session-text.mjs +100 -0
  116. package/src/session-runtime/statusline-route.mjs +35 -0
  117. package/src/session-runtime/tool-catalog.mjs +720 -0
  118. package/src/session-runtime/workflow.mjs +358 -0
  119. package/src/standalone/agent-tool.mjs +49 -10
  120. package/src/standalone/channel-worker.mjs +3 -2
  121. package/src/standalone/explore-tool.mjs +10 -3
  122. package/src/standalone/hook-bus.mjs +165 -8
  123. package/src/standalone/opencode-go-login.mjs +121 -0
  124. package/src/standalone/provider-admin.mjs +14 -3
  125. package/src/tui/App.jsx +884 -143
  126. package/src/tui/components/PromptInput.jsx +272 -15
  127. package/src/tui/components/ToolExecution.jsx +20 -10
  128. package/src/tui/components/tool-output-format.mjs +2 -2
  129. package/src/tui/dist/index.mjs +1771 -1947
  130. package/src/tui/engine/agent-envelope.mjs +296 -0
  131. package/src/tui/engine/boot-profile.mjs +21 -0
  132. package/src/tui/engine/labels.mjs +67 -0
  133. package/src/tui/engine/notice-text.mjs +112 -0
  134. package/src/tui/engine/queue-helpers.mjs +161 -0
  135. package/src/tui/engine/session-stats.mjs +46 -0
  136. package/src/tui/engine/tool-call-fields.mjs +23 -0
  137. package/src/tui/engine/tool-result-text.mjs +126 -0
  138. package/src/tui/engine.mjs +311 -851
  139. package/src/tui/input-editing.mjs +58 -8
  140. package/src/tui/input-editing.selection.test.mjs +75 -0
  141. package/src/tui/keyboard-protocol.mjs +2 -2
  142. package/src/tui/lib/voice-recorder.mjs +35 -19
  143. package/src/tui/markdown/format-token.mjs +7 -8
  144. package/src/tui/markdown/format-token.test.mjs +3 -3
  145. package/src/tui/paste-attachments.mjs +38 -0
  146. package/src/tui/paste-fix.test.mjs +119 -0
  147. package/src/tui/themes/base.mjs +2 -2
  148. package/src/tui/themes/kanagawa.mjs +4 -4
  149. package/src/tui/themes/teal.mjs +4 -5
  150. package/src/tui/themes/utils.mjs +1 -1
  151. package/src/ui/statusline.mjs +49 -0
  152. package/src/workflows/default/WORKFLOW.md +16 -9
  153. package/src/workflows/sequential/WORKFLOW.md +16 -11
  154. package/src/workflows/solo/WORKFLOW.md +5 -1
@@ -0,0 +1,218 @@
1
+ // Miscellaneous tool helpers extracted from loop.mjs: eager-dispatch check,
2
+ // message-array change detect, tool-kind classification, skills, hook overrides,
3
+ // native tool-search payload parsing, bash-session routing, and approval.
4
+ import { isMcpTool } from '../../mcp/client.mjs';
5
+ import { isBuiltinTool } from '../../tools/builtin.mjs';
6
+ import { isInternalTool } from '../../internal-tools.mjs';
7
+ import { collectSkillsCached, loadSkillResource, buildSkillToolEnvelope } from '../../context/collect.mjs';
8
+ import { isAgentOwner } from '../../agent-owner.mjs';
9
+
10
+ // Eager-dispatch: tools with readOnlyHint:true in their declaration are safe
11
+ // to execute during SSE parsing so tool work overlaps with the rest of the
12
+ // stream. Writes, bash, MCP and skills stay serial after send() returns.
13
+ export function isEagerDispatchable(name, tools) {
14
+ if (!Array.isArray(tools)) return false;
15
+ const def = tools.find(t => t?.name === name);
16
+ return def?.annotations?.readOnlyHint === true;
17
+ }
18
+ export function messagesArrayChanged(before, after) {
19
+ if (!Array.isArray(before) || !Array.isArray(after)) return before !== after;
20
+ if (before.length !== after.length) return true;
21
+ for (let i = 0; i < before.length; i += 1) {
22
+ if (before[i] !== after[i]) return true;
23
+ }
24
+ return false;
25
+ }
26
+
27
+ const SKILL_TOOL_NAMES = new Set(['Skill', 'skills_list', 'skill_view']);
28
+ const SPECIAL_TOOL_NAMES = new Set(['bash_session', 'apply_patch', 'code_graph']);
29
+ const BASH_SESSION_HEADER_RE = /\[session: ([^\]\r\n]+)\]/;
30
+
31
+ export function getToolKind(name) {
32
+ if (SKILL_TOOL_NAMES.has(name)) return 'skill';
33
+ if (SPECIAL_TOOL_NAMES.has(name)) return 'builtin';
34
+ if (isMcpTool(name)) return 'mcp';
35
+ if (isInternalTool(name)) return 'internal';
36
+ if (isBuiltinTool(name)) return 'builtin';
37
+ return 'builtin';
38
+ }
39
+ export function buildSkillsListResponse(cwd) {
40
+ const skills = collectSkillsCached(cwd);
41
+ const entries = skills.map(s => ({ name: s.name, description: s.description || '' }));
42
+ return JSON.stringify({ skills: entries });
43
+ }
44
+ export function viewSkill(cwd, name) {
45
+ if (!name) return 'Error: skill name is required';
46
+ const res = loadSkillResource(name, cwd);
47
+ if (!res) return `Error: skill "${name}" not found`;
48
+ // Return the general tool envelope: the model-visible tool_result is the
49
+ // short stub (`Loaded skill: <name>`) and the full SKILL.md body is
50
+ // delivered ONCE as a separate injected role:'user' message (newMessages).
51
+ return buildSkillToolEnvelope(name, res.content, res.dir);
52
+ }
53
+
54
+ /** Normalize PostToolUse hook override values (legacy MCP text envelopes only). */
55
+ export function normalizeHookUpdatedToolOutput(value) {
56
+ if (typeof value === 'string') return value;
57
+ if (value == null) return '';
58
+ if (typeof value === 'object' && Array.isArray(value.content)) {
59
+ const hasNonText = value.content.some((c) => c && typeof c === 'object' && c.type && c.type !== 'text');
60
+ if (hasNonText) return value;
61
+ return value.content
62
+ .map((c) => (c?.type === 'text' ? c.text || '' : JSON.stringify(c)))
63
+ .join('\n');
64
+ }
65
+ return value;
66
+ }
67
+
68
+ export function resolveToolResultAfterHook(originalResult, hookResult) {
69
+ if (!hookResult || typeof hookResult !== 'object' || hookResult.updatedToolOutput === undefined) {
70
+ return originalResult;
71
+ }
72
+ const updated = normalizeHookUpdatedToolOutput(hookResult.updatedToolOutput);
73
+ return updated === undefined ? originalResult : updated;
74
+ }
75
+
76
+ export function parseNativeToolSearchPayload(toolName, result) {
77
+ if (toolName !== 'tool_search' || typeof result !== 'string') return null;
78
+ try {
79
+ const parsed = JSON.parse(result);
80
+ const native = parsed?.nativeToolSearch;
81
+ if (!native || typeof native !== 'object') return null;
82
+ const rawToolReferences = Array.isArray(native.toolReferences) ? native.toolReferences : [];
83
+ const toolReferences = rawToolReferences
84
+ .filter((name) => typeof name === 'string')
85
+ .map((name) => name.trim())
86
+ .filter(Boolean);
87
+ const rawOpenaiTools = Array.isArray(native.openaiTools) ? native.openaiTools : [];
88
+ const openaiTools = rawOpenaiTools.filter((tool) => (
89
+ tool
90
+ && typeof tool === 'object'
91
+ && !Array.isArray(tool)
92
+ && typeof tool.name === 'string'
93
+ && tool.name.trim()
94
+ && (tool.type === undefined || typeof tool.type === 'string')
95
+ ));
96
+ if (!toolReferences.length && !openaiTools.length) return null;
97
+ const baseSummary = typeof native.summary === 'string' && native.summary
98
+ ? native.summary
99
+ : `Loaded deferred tools: ${toolReferences.join(', ') || openaiTools.map((tool) => tool.name).filter(Boolean).join(', ')}`;
100
+ const selectedTools = parsed?.selected?.tools;
101
+ const missing = Array.isArray(selectedTools?.missing)
102
+ ? selectedTools.missing.map((name) => String(name || '').trim()).filter(Boolean)
103
+ : [];
104
+ const blocked = Array.isArray(selectedTools?.blocked)
105
+ ? selectedTools.blocked
106
+ .map((entry) => {
107
+ if (entry && typeof entry === 'object') {
108
+ const name = String(entry.name || '').trim();
109
+ if (!name) return '';
110
+ const reason = String(entry.reason || '').trim();
111
+ return reason ? `${name} (${reason})` : name;
112
+ }
113
+ return String(entry || '').trim();
114
+ })
115
+ .filter(Boolean)
116
+ : [];
117
+ const extraLines = [];
118
+ if (missing.length) extraLines.push(`missing: ${missing.join(', ')}`);
119
+ if (blocked.length) extraLines.push(`blocked: ${blocked.join(', ')}`);
120
+ const summary = extraLines.length ? `${baseSummary}\n${extraLines.join('; ')}` : baseSummary;
121
+ return {
122
+ toolReferences,
123
+ openaiTools,
124
+ summary,
125
+ };
126
+ } catch {
127
+ return null;
128
+ }
129
+ }
130
+ export function extractBashSessionId(result) {
131
+ if (typeof result !== 'string') return null;
132
+ const match = BASH_SESSION_HEADER_RE.exec(result);
133
+ return match ? match[1] : null;
134
+ }
135
+
136
+ export function buildAgentBashSessionArgs(args, sessionRef) {
137
+ if (!isAgentOwner(sessionRef)) return null;
138
+ // run_in_background is a detached one-shot job, incompatible with the
139
+ // persistent bash session. Fall through to the background-job path
140
+ // (executeBuiltinTool -> startBackgroundShellJob) so the worker gets a
141
+ // task_id that task control can resolve — otherwise the persistent
142
+ // session returns a [session: ...] header and task control reports "task not found".
143
+ if (args?.run_in_background === true) return null;
144
+ const routedArgs = { ...(args || {}) };
145
+ const explicitSessionId = typeof routedArgs.session_id === 'string' && routedArgs.session_id.trim()
146
+ ? routedArgs.session_id.trim()
147
+ : null;
148
+ const wantsPersistent = routedArgs.persistent === true || !!explicitSessionId;
149
+ if (!wantsPersistent) return null;
150
+ if (!explicitSessionId && sessionRef?.implicitBashSessionId) {
151
+ routedArgs.session_id = sessionRef.implicitBashSessionId;
152
+ } else if (explicitSessionId) {
153
+ routedArgs.session_id = explicitSessionId;
154
+ }
155
+ delete routedArgs.persistent;
156
+ return routedArgs;
157
+ }
158
+
159
+ export function formatMissingToolApprovalUiDenial(toolName, askReason) {
160
+ const reason = String(askReason || 'approval requested by hook').trim();
161
+ const name = String(toolName || 'tool');
162
+ return `Error: tool "${name}" denied by hook: approval required but no approval UI is available${reason ? ` (${reason})` : ''}`;
163
+ }
164
+
165
+ /**
166
+ * Resolve PreToolUse `{ action: 'ask' }` against an optional approval callback.
167
+ * Returns `{ denial }` when the tool must not run; otherwise `{ approval }`.
168
+ */
169
+ export async function resolvePreToolAskApproval({
170
+ toolName,
171
+ args,
172
+ cwd,
173
+ sessionId,
174
+ toolCallId,
175
+ askReason,
176
+ toolApprovalHook,
177
+ }) {
178
+ const name = String(toolName || 'tool');
179
+ const reason = String(askReason || 'approval requested by hook').trim();
180
+ if (typeof toolApprovalHook !== 'function') {
181
+ return { denial: formatMissingToolApprovalUiDenial(name, reason) };
182
+ }
183
+ let approval;
184
+ try {
185
+ approval = await toolApprovalHook({
186
+ name,
187
+ args,
188
+ cwd,
189
+ sessionId,
190
+ toolCallId: toolCallId || null,
191
+ reason,
192
+ });
193
+ } catch (error) {
194
+ const detail = error?.message || String(error || 'approval failed');
195
+ return { denial: `Error: tool "${name}" denied by hook: ${detail}` };
196
+ }
197
+ if (!approvalGranted(approval)) {
198
+ const detail = approvalReason(approval, reason || 'not approved');
199
+ return { denial: `Error: tool "${name}" denied by hook: ${detail}` };
200
+ }
201
+ return { approval };
202
+ }
203
+
204
+ export function approvalGranted(value) {
205
+ if (value === true) return true;
206
+ if (!value || typeof value !== 'object') return false;
207
+ if (value.approved === true || value.allow === true || value.allowed === true) return true;
208
+ const decision = String(value.decision || value.action || value.result || '').trim().toLowerCase();
209
+ return decision === 'approve' || decision === 'approved' || decision === 'allow' || decision === 'yes';
210
+ }
211
+
212
+ export function approvalReason(value, fallback = '') {
213
+ if (value && typeof value === 'object') {
214
+ const reason = String(value.reason || value.message || '').trim();
215
+ if (reason) return reason;
216
+ }
217
+ return fallback;
218
+ }
@@ -0,0 +1,101 @@
1
+ // Pre-provider transcript pairing repair, extracted from loop.mjs.
2
+ // Anthropic 400-rejects when an assistant message ends with tool_use blocks and
3
+ // the next message isn't tool results for those exact ids. abort/timeout/error
4
+ // races in the loop body can leave a dangling assistant tool_use at the tail;
5
+ // strip any trailing/orphaned tool_use|tool_result so provider.send sees a
6
+ // valid transcript instead of leaking the 400 to the user.
7
+ import { sanitizeToolPairs } from '../context-utils.mjs';
8
+
9
+ // Transcript pairing guard. Anthropic 400-rejects when an assistant message
10
+ // ends with tool_use blocks and the next message isn't tool results for
11
+ // those exact ids. abort/timeout/error race in the loop body can leave a
12
+ // dangling assistant tool_use at the tail (e.g. the structure_probe loop
13
+ // running 12 deep then aborting between push-assistant and push-tool).
14
+ // Strip any trailing assistant tool_use that has no matching tool result
15
+ // so provider.send sees a valid transcript instead of leaking the 400 to
16
+ // the user. Repair runs every iteration but is a no-op on healthy paths.
17
+ function _ensureTranscriptPairing(msgs, sessionId) {
18
+ // Walk backwards to find the last assistant message that emitted
19
+ // tool_use, then validate that every id has a matching tool result
20
+ // inside the CONTIGUOUS tool-message block immediately following it.
21
+ // Earlier guard splice'd the entire tail — which silently deleted any
22
+ // user prompt appended after the dangling assistant by manager.mjs:
23
+ // when the guard fired with shape
24
+ // [..., assistant{a,b}, tool{a}, user{new prompt}]
25
+ // the splice removed user{new prompt} along with the orphan suffix.
26
+ // Fix: remove only assistant + the contiguous tool block; preserve
27
+ // anything past it (user / system / next assistant) untouched.
28
+ let popped = 0;
29
+ while (msgs.length > 0) {
30
+ let lastAssistantIdx = -1;
31
+ for (let i = msgs.length - 1; i >= 0; i--) {
32
+ const m = msgs[i];
33
+ if (m?.role === 'assistant' && Array.isArray(m.toolCalls) && m.toolCalls.length > 0) {
34
+ lastAssistantIdx = i;
35
+ break;
36
+ }
37
+ }
38
+ if (lastAssistantIdx === -1) break;
39
+ // Collect the contiguous tool messages directly after this assistant.
40
+ // Anything past that block is unrelated (next user prompt, system
41
+ // marker, etc.) and must survive the repair.
42
+ let toolBlockEnd = lastAssistantIdx + 1;
43
+ while (toolBlockEnd < msgs.length && msgs[toolBlockEnd]?.role === 'tool') {
44
+ toolBlockEnd += 1;
45
+ }
46
+ const toolBlock = msgs.slice(lastAssistantIdx + 1, toolBlockEnd);
47
+ const ids = msgs[lastAssistantIdx].toolCalls.map(c => c.id);
48
+ const matched = ids.every(id => toolBlock.some(m => m.toolCallId === id));
49
+ if (matched) break;
50
+ const removed = toolBlockEnd - lastAssistantIdx;
51
+ msgs.splice(lastAssistantIdx, removed);
52
+ popped += removed;
53
+ }
54
+ // Second sweep — catch dangling tool results that survived the
55
+ // contiguous-block splice. Anthropic strict spec requires every
56
+ // tool result to sit in a contiguous block right after the
57
+ // assistant whose toolCalls produced it; a `[..., assistant{a,b},
58
+ // tool{a}, user, tool{b}]` shape leaves tool{b} orphaned even
59
+ // after assistant + tool{a} are repaired by the loop above.
60
+ // Walk back from each tool message to the nearest non-tool
61
+ // ancestor; if it is not an assistant whose toolCalls include
62
+ // this id, drop the orphan.
63
+ for (let i = msgs.length - 1; i >= 0; i--) {
64
+ const m = msgs[i];
65
+ if (m?.role !== 'tool') continue;
66
+ if (!m.toolCallId) {
67
+ msgs.splice(i, 1);
68
+ popped += 1;
69
+ continue;
70
+ }
71
+ let prevIdx = i - 1;
72
+ while (prevIdx >= 0 && msgs[prevIdx]?.role === 'tool') prevIdx--;
73
+ const anchor = prevIdx >= 0 ? msgs[prevIdx] : null;
74
+ const anchorOk = anchor?.role === 'assistant'
75
+ && Array.isArray(anchor.toolCalls)
76
+ && anchor.toolCalls.some(c => c.id === m.toolCallId);
77
+ if (!anchorOk) {
78
+ msgs.splice(i, 1);
79
+ popped += 1;
80
+ }
81
+ }
82
+ if (popped > 0 && sessionId) {
83
+ try { process.stderr.write(`[transcript-repair] sess=${sessionId} popped=${popped} dangling assistant tool_use\n`); } catch {}
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Pre-provider transcript repair for the agent loop. Reattach valid tool
89
+ * results (non-destructive) before any destructive orphan pairing cleanup.
90
+ * Mutates `messages` in place to preserve the session array reference.
91
+ */
92
+ export function repairTranscriptBeforeProviderSend(messages, sessionId = null) {
93
+ if (!Array.isArray(messages)) return messages;
94
+ const sanitized = sanitizeToolPairs(messages);
95
+ if (sanitized !== messages) {
96
+ messages.length = 0;
97
+ messages.push(...sanitized);
98
+ }
99
+ _ensureTranscriptPairing(messages, sessionId);
100
+ return messages;
101
+ }
@@ -0,0 +1,35 @@
1
+ // Usage accumulation helpers extracted from loop.mjs.
2
+ // Normalize a provider usage payload into the canonical token/cost shape and
3
+ // fold successive deltas into a running total across loop iterations.
4
+
5
+ export function normalizeUsage(usage) {
6
+ if (!usage) return null;
7
+ const costUsd = Number(usage.costUsd);
8
+ return {
9
+ inputTokens: usage.inputTokens || 0,
10
+ outputTokens: usage.outputTokens || 0,
11
+ cachedTokens: usage.cachedTokens || 0,
12
+ cacheWriteTokens: usage.cacheWriteTokens || 0,
13
+ promptTokens: usage.promptTokens || 0,
14
+ ...(Number.isFinite(costUsd) ? { costUsd } : {}),
15
+ raw: usage.raw,
16
+ };
17
+ }
18
+
19
+ export function addUsage(total, usage) {
20
+ const delta = normalizeUsage(usage);
21
+ if (!delta) return total;
22
+ if (!total) return { ...delta };
23
+ const next = {
24
+ ...total,
25
+ inputTokens: (total.inputTokens || 0) + delta.inputTokens,
26
+ outputTokens: (total.outputTokens || 0) + delta.outputTokens,
27
+ cachedTokens: (total.cachedTokens || 0) + delta.cachedTokens,
28
+ cacheWriteTokens: (total.cacheWriteTokens || 0) + delta.cacheWriteTokens,
29
+ promptTokens: (total.promptTokens || 0) + delta.promptTokens,
30
+ };
31
+ if (delta.costUsd != null || total.costUsd != null) {
32
+ next.costUsd = (total.costUsd || 0) + (delta.costUsd || 0);
33
+ }
34
+ return next;
35
+ }