@denizokcu/haze 0.9.0 → 0.11.0

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 (241) hide show
  1. package/CHANGELOG.md +133 -17
  2. package/README.md +164 -68
  3. package/SECURITY.md +22 -0
  4. package/bin/haze.js +102 -1
  5. package/dist/buildInfo.json +7 -0
  6. package/dist/cli/chat/TaskBar.d.ts +2 -1
  7. package/dist/cli/chat/TaskBar.js +7 -4
  8. package/dist/cli/chat/chatMetrics.d.ts +17 -1
  9. package/dist/cli/chat/chatMetrics.js +22 -5
  10. package/dist/cli/chat/contextReport.d.ts +11 -0
  11. package/dist/cli/chat/contextReport.js +46 -0
  12. package/dist/cli/chat/fileMentionSuggestions.d.ts +29 -0
  13. package/dist/cli/chat/fileMentionSuggestions.js +92 -0
  14. package/dist/cli/chat/inputSuggestions.d.ts +5 -0
  15. package/dist/cli/chat/inputSuggestions.js +17 -3
  16. package/dist/cli/chat/liveRegion.d.ts +25 -0
  17. package/dist/cli/chat/liveRegion.js +48 -0
  18. package/dist/cli/chat/messages.d.ts +33 -2
  19. package/dist/cli/chat/messages.js +216 -33
  20. package/dist/cli/chat/sessionLifecycle.d.ts +67 -0
  21. package/dist/cli/chat/sessionLifecycle.js +205 -0
  22. package/dist/cli/chat/sessionRecorder.js +80 -14
  23. package/dist/cli/chat/startupInfo.js +11 -4
  24. package/dist/cli/chat/tips.d.ts +21 -0
  25. package/dist/cli/chat/tips.js +43 -0
  26. package/dist/cli/chat/wizardDispatch.d.ts +64 -0
  27. package/dist/cli/chat/wizardDispatch.js +744 -0
  28. package/dist/cli/commands/chat.d.ts +6 -0
  29. package/dist/cli/commands/chat.js +373 -790
  30. package/dist/cli/commands/chatModes.d.ts +1 -1
  31. package/dist/cli/commands/chatModes.js +7 -2
  32. package/dist/cli/commands/commandHelp.js +5 -3
  33. package/dist/cli/commands/commands.d.ts +5 -2
  34. package/dist/cli/commands/commands.js +22 -18
  35. package/dist/cli/commands/doctor.d.ts +19 -0
  36. package/dist/cli/commands/doctor.js +76 -0
  37. package/dist/cli/commands/fleetCommand.d.ts +14 -0
  38. package/dist/cli/commands/fleetCommand.js +46 -0
  39. package/dist/cli/commands/formatters.d.ts +5 -0
  40. package/dist/cli/commands/formatters.js +35 -6
  41. package/dist/cli/commands/logsCommand.js +1 -7
  42. package/dist/cli/commands/modelCommand.js +1 -1
  43. package/dist/cli/commands/ndjsonSink.d.ts +23 -0
  44. package/dist/cli/commands/ndjsonSink.js +38 -0
  45. package/dist/cli/commands/providerWizard.d.ts +10 -2
  46. package/dist/cli/commands/providerWizard.js +50 -4
  47. package/dist/cli/commands/runCommand.d.ts +4 -0
  48. package/dist/cli/commands/runCommand.js +142 -16
  49. package/dist/cli/commands/sessionPicker.d.ts +9 -0
  50. package/dist/cli/commands/sessionPicker.js +29 -0
  51. package/dist/cli/commands/settingsSummary.js +6 -4
  52. package/dist/cli/commands/skillConfirmRemove.js +4 -3
  53. package/dist/cli/commands/skillWizard.d.ts +2 -0
  54. package/dist/cli/commands/skillWizard.js +16 -6
  55. package/dist/cli/commands/streaming/abortCause.d.ts +24 -0
  56. package/dist/cli/commands/streaming/abortCause.js +16 -0
  57. package/dist/cli/commands/streaming/assistantText.js +9 -2
  58. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +65 -0
  59. package/dist/cli/commands/streaming/goalCheckpoint.js +23 -0
  60. package/dist/cli/commands/streaming/goalSupervisor.d.ts +64 -0
  61. package/dist/cli/commands/streaming/goalSupervisor.js +127 -0
  62. package/dist/cli/commands/streaming/idleTimer.d.ts +26 -0
  63. package/dist/cli/commands/streaming/idleTimer.js +24 -0
  64. package/dist/cli/commands/streaming/toolCallRecovery.d.ts +2 -0
  65. package/dist/cli/commands/streaming/toolCallRecovery.js +24 -0
  66. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +31 -0
  67. package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -2
  68. package/dist/cli/commands/streaming/toolResultState.d.ts +6 -1
  69. package/dist/cli/commands/streaming/toolResultState.js +29 -7
  70. package/dist/cli/commands/streaming/turnOutcome.d.ts +17 -0
  71. package/dist/cli/commands/streaming/turnOutcome.js +27 -11
  72. package/dist/cli/commands/streaming/turnRuntime.js +6 -4
  73. package/dist/cli/commands/streaming.d.ts +82 -3
  74. package/dist/cli/commands/streaming.js +528 -91
  75. package/dist/cli/commands/wizardActions.d.ts +7 -0
  76. package/dist/cli/commands/wizardActions.js +7 -0
  77. package/dist/cli/commands/wizardPrompts.js +7 -1
  78. package/dist/cli/commands/wizardSuggestions.d.ts +8 -0
  79. package/dist/cli/commands/wizardSuggestions.js +64 -14
  80. package/dist/cli/commands/wizardTransition.d.ts +4 -0
  81. package/dist/cli/commands/wizardTransition.js +1 -2
  82. package/dist/cli/index.js +82 -22
  83. package/dist/cli/terminalTitle.d.ts +6 -0
  84. package/dist/cli/terminalTitle.js +36 -0
  85. package/dist/config/inputHistory.d.ts +3 -3
  86. package/dist/config/inputHistory.js +12 -18
  87. package/dist/config/modelDiscovery.d.ts +71 -0
  88. package/dist/config/modelDiscovery.js +214 -0
  89. package/dist/config/privateStorage.js +28 -2
  90. package/dist/config/providerAuth.d.ts +14 -0
  91. package/dist/config/providerAuth.js +49 -0
  92. package/dist/config/providerPresets.d.ts +49 -5
  93. package/dist/config/providerPresets.js +573 -73
  94. package/dist/config/providers.d.ts +2 -0
  95. package/dist/config/providers.js +9 -0
  96. package/dist/config/settings.d.ts +58 -0
  97. package/dist/config/settings.js +38 -1
  98. package/dist/config/skillSettings.d.ts +6 -13
  99. package/dist/config/skillSettings.js +20 -19
  100. package/dist/core/agent/budgets.d.ts +36 -0
  101. package/dist/core/agent/budgets.js +44 -0
  102. package/dist/core/agent/compaction.d.ts +38 -0
  103. package/dist/core/agent/compaction.js +108 -19
  104. package/dist/core/agent/completionController.d.ts +230 -0
  105. package/dist/core/agent/completionController.js +287 -0
  106. package/dist/core/agent/contextBudget.d.ts +46 -0
  107. package/dist/core/agent/contextBudget.js +89 -7
  108. package/dist/core/agent/errors.js +6 -2
  109. package/dist/core/agent/events.d.ts +86 -0
  110. package/dist/core/agent/reasoningPolicy.d.ts +31 -0
  111. package/dist/core/agent/reasoningPolicy.js +27 -0
  112. package/dist/core/agent/toolCapabilities.d.ts +27 -0
  113. package/dist/core/agent/toolCapabilities.js +58 -0
  114. package/dist/core/agent/toolExecutionBudget.d.ts +35 -0
  115. package/dist/core/agent/toolExecutionBudget.js +49 -0
  116. package/dist/core/agent/toolOutputStore.d.ts +13 -0
  117. package/dist/core/agent/toolOutputStore.js +27 -10
  118. package/dist/core/agent/toolResults.d.ts +12 -0
  119. package/dist/core/agent/toolResults.js +38 -0
  120. package/dist/core/agent/turnBudget.d.ts +35 -0
  121. package/dist/core/agent/turnBudget.js +27 -0
  122. package/dist/core/agent/turnPolicy.d.ts +11 -0
  123. package/dist/core/agent/turnPolicy.js +19 -0
  124. package/dist/core/agent/workState.d.ts +76 -1
  125. package/dist/core/agent/workState.js +120 -13
  126. package/dist/core/attachments/imageAttachments.d.ts +90 -0
  127. package/dist/core/attachments/imageAttachments.js +245 -0
  128. package/dist/core/attachments/readBlessings.d.ts +37 -0
  129. package/dist/core/attachments/readBlessings.js +79 -0
  130. package/dist/core/deadline.d.ts +33 -0
  131. package/dist/core/deadline.js +74 -0
  132. package/dist/core/goal/completionPolicy.d.ts +27 -0
  133. package/dist/core/goal/completionPolicy.js +37 -1
  134. package/dist/core/goal/requestClassifier.d.ts +0 -3
  135. package/dist/core/goal/requestClassifier.js +0 -13
  136. package/dist/core/io/boundedRead.js +76 -29
  137. package/dist/core/limits/byteBudgets.d.ts +7 -0
  138. package/dist/core/limits/byteBudgets.js +7 -0
  139. package/dist/core/limits/textBudgets.d.ts +25 -0
  140. package/dist/core/limits/textBudgets.js +25 -0
  141. package/dist/core/log/llmLog.js +7 -0
  142. package/dist/core/persistence/orderedFileWriter.d.ts +10 -0
  143. package/dist/core/persistence/orderedFileWriter.js +16 -2
  144. package/dist/core/process/backgroundRegistry.d.ts +35 -0
  145. package/dist/core/process/backgroundRegistry.js +195 -0
  146. package/dist/core/process/runBoundedProcess.d.ts +9 -0
  147. package/dist/core/process/runBoundedProcess.js +74 -29
  148. package/dist/core/safety/missingExecutable.d.ts +42 -0
  149. package/dist/core/safety/missingExecutable.js +77 -0
  150. package/dist/core/safety/urlGuard.d.ts +2 -1
  151. package/dist/core/safety/urlGuard.js +3 -2
  152. package/dist/core/session/sessionSlimming.js +47 -4
  153. package/dist/core/session/sessionStore.d.ts +74 -0
  154. package/dist/core/session/sessionStore.js +268 -18
  155. package/dist/core/subagent/contracts.d.ts +120 -0
  156. package/dist/core/subagent/contracts.js +55 -0
  157. package/dist/core/subagent/executionProfiles.d.ts +28 -0
  158. package/dist/core/subagent/executionProfiles.js +45 -0
  159. package/dist/core/subagent/subagentCoordinator.d.ts +78 -0
  160. package/dist/core/subagent/subagentCoordinator.js +164 -0
  161. package/dist/core/subagent/subagentRunner.d.ts +211 -145
  162. package/dist/core/subagent/subagentRunner.js +208 -98
  163. package/dist/core/subagent/workspaceMutationPolicy.d.ts +11 -0
  164. package/dist/core/subagent/workspaceMutationPolicy.js +52 -0
  165. package/dist/core/tasks/taskStorage.js +12 -1
  166. package/dist/llm/client.d.ts +36 -29
  167. package/dist/llm/client.js +102 -33
  168. package/dist/llm/hazeTools.d.ts +2559 -150
  169. package/dist/llm/hazeTools.js +119 -31
  170. package/dist/llm/lsp.d.ts +26 -4
  171. package/dist/llm/lsp.js +90 -14
  172. package/dist/llm/lspTools.d.ts +2366 -0
  173. package/dist/llm/lspTools.js +87 -79
  174. package/dist/llm/openaiCodex.d.ts +3 -0
  175. package/dist/llm/openaiCodex.js +47 -0
  176. package/dist/llm/openaiCodexOAuth.d.ts +54 -0
  177. package/dist/llm/openaiCodexOAuth.js +214 -0
  178. package/dist/llm/requestContext.d.ts +25 -1
  179. package/dist/llm/requestContext.js +51 -8
  180. package/dist/llm/systemPrompt.d.ts +15 -1
  181. package/dist/llm/systemPrompt.js +24 -8
  182. package/dist/llm/toolResultTypes.d.ts +8 -1
  183. package/dist/llm/tools/bashTool.d.ts +906 -32
  184. package/dist/llm/tools/bashTool.js +30 -4
  185. package/dist/llm/tools/editMatch.d.ts +14 -0
  186. package/dist/llm/tools/editMatch.js +72 -0
  187. package/dist/llm/tools/failures.d.ts +2 -0
  188. package/dist/llm/tools/failures.js +1 -0
  189. package/dist/llm/tools/fetchTool.d.ts +42 -26
  190. package/dist/llm/tools/fetchTool.js +1 -1
  191. package/dist/llm/tools/fileToolShared.d.ts +6 -4
  192. package/dist/llm/tools/fileToolShared.js +18 -23
  193. package/dist/llm/tools/gitIgnore.d.ts +49 -0
  194. package/dist/llm/tools/gitIgnore.js +129 -0
  195. package/dist/llm/tools/grepRunner.d.ts +5 -0
  196. package/dist/llm/tools/grepRunner.js +52 -71
  197. package/dist/llm/tools/outputCap.d.ts +2 -6
  198. package/dist/llm/tools/outputCap.js +2 -6
  199. package/dist/llm/tools/processTool.d.ts +1077 -0
  200. package/dist/llm/tools/processTool.js +41 -0
  201. package/dist/llm/tools/readRecovery.d.ts +10 -0
  202. package/dist/llm/tools/readRecovery.js +135 -0
  203. package/dist/llm/tools/toolContext.d.ts +9 -1
  204. package/dist/llm/tools/toolContext.js +83 -43
  205. package/dist/llm/tools/workspaceFile.d.ts +9 -1
  206. package/dist/llm/tools/workspaceFile.js +33 -4
  207. package/dist/llm/webFetch.d.ts +17 -0
  208. package/dist/llm/webFetch.js +66 -86
  209. package/dist/llm/workerContext.d.ts +18 -0
  210. package/dist/llm/workerContext.js +55 -0
  211. package/dist/skills/SkillLoader.d.ts +2 -2
  212. package/dist/skills/SkillRegistry.d.ts +3 -2
  213. package/dist/skills/SkillRegistry.js +43 -13
  214. package/dist/skills/builder/SkillBuilder.d.ts +3 -0
  215. package/dist/skills/builder/SkillBuilder.js +23 -5
  216. package/dist/skills/skillTools.js +11 -4
  217. package/dist/skills/types.d.ts +6 -1
  218. package/dist/ui/codeHighlight.d.ts +4 -0
  219. package/dist/ui/codeHighlight.js +31 -0
  220. package/dist/ui/components/Header.d.ts +1 -1
  221. package/dist/ui/components/MarkdownText.d.ts +16 -2
  222. package/dist/ui/components/MarkdownText.js +244 -34
  223. package/dist/ui/components/TextInput.d.ts +12 -2
  224. package/dist/ui/components/TextInput.js +80 -8
  225. package/dist/ui/theme.d.ts +4 -3
  226. package/dist/ui/theme.js +5 -4
  227. package/dist/utils/buildInfo.d.ts +104 -0
  228. package/dist/utils/buildInfo.js +253 -0
  229. package/dist/utils/format.d.ts +2 -0
  230. package/dist/utils/format.js +8 -0
  231. package/dist/utils/fs.d.ts +9 -1
  232. package/dist/utils/fs.js +87 -29
  233. package/dist/utils/openPath.d.ts +2 -0
  234. package/dist/utils/openPath.js +22 -0
  235. package/dist/utils/path.d.ts +2 -0
  236. package/dist/utils/path.js +5 -1
  237. package/dist/utils/utf8.d.ts +22 -0
  238. package/dist/utils/utf8.js +54 -0
  239. package/dist/utils/version.d.ts +9 -3
  240. package/dist/utils/version.js +28 -2
  241. package/package.json +24 -19
@@ -0,0 +1,65 @@
1
+ import type { CompletionReadiness, TurnExecutionState } from '../../../core/agent/completionController.js';
2
+ import type { ValidationOutcome } from '../../../core/agent/workState.js';
3
+ /**
4
+ * Bounded continuation checkpoint for a logical goal whose work is recoverably
5
+ * unfinished. Safe metadata only — reasons, counts, enums — never commands,
6
+ * content, or credentials. Carried on `TurnResult.resume` so a goal supervisor
7
+ * (or the interactive resume affordance) can continue the same logical goal in
8
+ * a fresh physical turn without replaying completed work.
9
+ */
10
+ export interface IncompleteGoalResume {
11
+ kind: 'incomplete-goal';
12
+ request: string;
13
+ reason: CompletionReadiness;
14
+ /** Logical-goal id shared across physical turns. */
15
+ goalId: string;
16
+ /** Physical turns consumed so far (including the one producing this). */
17
+ cycle: number;
18
+ stepsUsed: number;
19
+ /** Cumulative successful mutations across the logical goal. */
20
+ mutationCount: number;
21
+ taskCounts?: {
22
+ total: number;
23
+ pending: number;
24
+ inProgress: number;
25
+ completed: number;
26
+ };
27
+ validationOutcome?: ValidationOutcome;
28
+ }
29
+ /** Supervisor-level checkpoint persisted between physical turns (in memory). */
30
+ export interface GoalCheckpoint {
31
+ goalId: string;
32
+ request: string;
33
+ cycle: number;
34
+ readiness: CompletionReadiness;
35
+ taskCounts?: {
36
+ total: number;
37
+ pending: number;
38
+ inProgress: number;
39
+ completed: number;
40
+ };
41
+ mutationCount: number;
42
+ validationOutcome: ValidationOutcome;
43
+ /** Cumulative progress signature used by the no-progress guard. */
44
+ progressSignature: string;
45
+ /** Consecutive physical turns without measurable progress. */
46
+ noProgressCount: number;
47
+ }
48
+ /** Cumulative progress signature: mutations, validation outcome, task counts. */
49
+ export declare function goalCheckpointSignature(input: {
50
+ mutationCount: number;
51
+ validationOutcome: ValidationOutcome;
52
+ taskCounts?: {
53
+ pending: number;
54
+ inProgress: number;
55
+ completed: number;
56
+ total: number;
57
+ };
58
+ }): string;
59
+ /**
60
+ * Build the checkpoint payload for a `recoverable-incomplete` attempt that no
61
+ * same-turn recovery can continue. Single construction site so every path
62
+ * (voluntary final, budget boundary, tool-calls finish, exhausted recovery
63
+ * slice) yields the same bounded shape.
64
+ */
65
+ export declare function buildIncompleteGoalResume(request: string, goalId: string, cycle: number, state: Pick<TurnExecutionState, 'stepsUsed' | 'mutationCount' | 'validationOutcome' | 'taskProgress'>, reason: CompletionReadiness): IncompleteGoalResume;
@@ -0,0 +1,23 @@
1
+ /** Cumulative progress signature: mutations, validation outcome, task counts. */
2
+ export function goalCheckpointSignature(input) {
3
+ return JSON.stringify([input.mutationCount, input.validationOutcome, input.taskCounts ? [input.taskCounts.total, input.taskCounts.pending, input.taskCounts.inProgress, input.taskCounts.completed] : null]);
4
+ }
5
+ /**
6
+ * Build the checkpoint payload for a `recoverable-incomplete` attempt that no
7
+ * same-turn recovery can continue. Single construction site so every path
8
+ * (voluntary final, budget boundary, tool-calls finish, exhausted recovery
9
+ * slice) yields the same bounded shape.
10
+ */
11
+ export function buildIncompleteGoalResume(request, goalId, cycle, state, reason) {
12
+ return {
13
+ kind: 'incomplete-goal',
14
+ request,
15
+ reason,
16
+ goalId,
17
+ cycle,
18
+ stepsUsed: state.stepsUsed,
19
+ mutationCount: state.mutationCount,
20
+ ...(state.taskProgress ? { taskCounts: { total: state.taskProgress.total, pending: state.taskProgress.pending, inProgress: state.taskProgress.inProgress, completed: state.taskProgress.completed } } : {}),
21
+ ...(state.validationOutcome !== 'not_applicable' ? { validationOutcome: state.validationOutcome } : {}),
22
+ };
23
+ }
@@ -0,0 +1,64 @@
1
+ import type { ContextFile } from '../../../config/contextFiles.js';
2
+ import type { TurnCompletionEvidence } from '../../../core/agent/completionController.js';
3
+ import type { PromptSession } from '../../../llm/systemPrompt.js';
4
+ import { type StreamCallbacks, type TurnExecutionOptions } from '../streaming.js';
5
+ import { type GoalCheckpoint } from './goalCheckpoint.js';
6
+ /** Why a logical goal stopped. `completed` is the only success. */
7
+ export type GoalStopReason = 'completed' | 'no-progress' | 'goal-deadline' | 'blocked' | 'model-error' | 'model-stream-idle' | 'user-aborted';
8
+ /** Authoritative outcome of a logical goal (one or more physical turns). */
9
+ export interface GoalRunResult {
10
+ status: 'complete' | 'failed' | 'aborted';
11
+ stopReason: GoalStopReason;
12
+ /** Physical turns consumed by the logical goal. */
13
+ cycles: number;
14
+ /** Last physical turn's bounded evidence. */
15
+ evidence?: TurnCompletionEvidence;
16
+ /**
17
+ * Present only for genuinely paused goals (no-progress, deadline, idle
18
+ * stall): what an explicit resume needs. Automatic continuation has already
19
+ * been attempted; this never rides a `completed` result.
20
+ */
21
+ resume?: {
22
+ kind: 'model-stream-idle';
23
+ request: string;
24
+ retryAttempt: number;
25
+ } | {
26
+ kind: 'incomplete-goal';
27
+ checkpoint: GoalCheckpoint;
28
+ };
29
+ }
30
+ export interface GoalRunOptions {
31
+ request: string;
32
+ displayValue?: string;
33
+ contextFiles: ContextFile[];
34
+ callbacks: StreamCallbacks;
35
+ session?: PromptSession;
36
+ modelOverride?: string;
37
+ /** Whole-logical-goal wall-clock budget (headless `--timeout`); unset means continue while progress. */
38
+ goalDeadlineMs?: number;
39
+ /** Base per-turn options (attachments, blessed paths); attachments apply to the first physical turn only. */
40
+ turnOptions?: TurnExecutionOptions;
41
+ /** Explicit resume of a paused goal: an idle-stalled turn pool or a stored goal checkpoint. */
42
+ resumeFrom?: {
43
+ kind: 'model-stream-idle';
44
+ retryAttempt: number;
45
+ } | {
46
+ kind: 'incomplete-goal';
47
+ checkpoint: GoalCheckpoint;
48
+ };
49
+ }
50
+ /**
51
+ * Logical-goal supervisor. Runs bounded physical turns (`runAgentTurn`) until
52
+ * the user's goal is structurally complete, autonomously starting the next
53
+ * physical turn whenever the previous one ended `recoverable-incomplete` —
54
+ * including at step/tool budget boundaries, which end a physical turn, not the
55
+ * goal. Per-turn limits stay safety boundaries; they no longer imply goal
56
+ * completion.
57
+ *
58
+ * Stops only for: structured completion, a concrete external blocker (hard
59
+ * tool/provider failure), user cancellation, the goal-level deadline, or
60
+ * repeated no-progress cycles. Conversation and completed tool results carry
61
+ * across turns, so mutations are never replayed. Emits exactly one `goal_start`
62
+ * and one terminal `goal_end`, plus `goal_continue` between physical turns.
63
+ */
64
+ export declare function runAgentGoal(options: GoalRunOptions): Promise<GoalRunResult>;
@@ -0,0 +1,127 @@
1
+ import { agentEvent } from '../../../core/agent/events.js';
2
+ import { DEFAULT_TURN_DEADLINE_MS } from '../../../core/agent/budgets.js';
3
+ import { describeCompletionReadiness } from '../../../core/agent/completionController.js';
4
+ import { goalContinuationPrompt } from '../../../core/goal/completionPolicy.js';
5
+ import { runAgentTurn } from '../streaming.js';
6
+ import { goalCheckpointSignature } from './goalCheckpoint.js';
7
+ /** Pause after this many consecutive physical turns without measurable progress (one corrective cycle allowed). */
8
+ const GOAL_NO_PROGRESS_LIMIT = 2;
9
+ function checkpointFromResume(resume, noProgressCount) {
10
+ const validationOutcome = resume.validationOutcome ?? 'not_applicable';
11
+ return {
12
+ goalId: resume.goalId,
13
+ request: resume.request,
14
+ cycle: resume.cycle,
15
+ readiness: resume.reason,
16
+ ...(resume.taskCounts ? { taskCounts: resume.taskCounts } : {}),
17
+ mutationCount: resume.mutationCount,
18
+ validationOutcome,
19
+ progressSignature: goalCheckpointSignature({ mutationCount: resume.mutationCount, validationOutcome, taskCounts: resume.taskCounts }),
20
+ noProgressCount,
21
+ };
22
+ }
23
+ function countsToTaskProgress(counts) {
24
+ return { total: counts.total, pending: counts.pending, inProgress: counts.inProgress, completed: counts.completed, revision: 1 };
25
+ }
26
+ /**
27
+ * Logical-goal supervisor. Runs bounded physical turns (`runAgentTurn`) until
28
+ * the user's goal is structurally complete, autonomously starting the next
29
+ * physical turn whenever the previous one ended `recoverable-incomplete` —
30
+ * including at step/tool budget boundaries, which end a physical turn, not the
31
+ * goal. Per-turn limits stay safety boundaries; they no longer imply goal
32
+ * completion.
33
+ *
34
+ * Stops only for: structured completion, a concrete external blocker (hard
35
+ * tool/provider failure), user cancellation, the goal-level deadline, or
36
+ * repeated no-progress cycles. Conversation and completed tool results carry
37
+ * across turns, so mutations are never replayed. Emits exactly one `goal_start`
38
+ * and one terminal `goal_end`, plus `goal_continue` between physical turns.
39
+ */
40
+ export async function runAgentGoal(options) {
41
+ const { request, contextFiles, callbacks } = options;
42
+ const startedAt = Date.now();
43
+ const goalId = options.resumeFrom?.kind === 'incomplete-goal' ? options.resumeFrom.checkpoint.goalId : `goal-${startedAt}-${Math.random().toString(36).slice(2)}`;
44
+ const sharedTurnScope = {};
45
+ let checkpoint = options.resumeFrom?.kind === 'incomplete-goal' ? options.resumeFrom.checkpoint : undefined;
46
+ let initialRetryAttempt = options.resumeFrom?.kind === 'model-stream-idle' ? options.resumeFrom.retryAttempt : 0;
47
+ let cycle = checkpoint?.cycle ?? 0;
48
+ let noProgressCount = checkpoint?.noProgressCount ?? 0;
49
+ let prevSignature = checkpoint?.progressSignature;
50
+ let lastEvidence;
51
+ callbacks.onEvent?.(agentEvent({ type: 'goal_start', goalId, request }));
52
+ // Observable capability line at every goal start (debug panel, --debug LLM
53
+ // log, headless stderr): failures can be tied to runtime behavior, not
54
+ // guessed from semantic versions.
55
+ callbacks.debugLog('goal supervisor enabled; automatic continuation across physical-turn budgets');
56
+ const finish = (status, stopReason, resume) => {
57
+ callbacks.onEvent?.(agentEvent({ type: 'goal_end', goalId, status, cycles: cycle, ...(stopReason !== 'completed' ? { stopReason } : {}), ...(lastEvidence ? { evidence: lastEvidence } : {}) }));
58
+ return { status, stopReason, cycles: cycle, ...(lastEvidence ? { evidence: lastEvidence } : {}), ...(resume ? { resume } : {}) };
59
+ };
60
+ while (true) {
61
+ const remainingMs = options.goalDeadlineMs != null ? options.goalDeadlineMs - (Date.now() - startedAt) : undefined;
62
+ if (cycle > 0 && remainingMs != null && remainingMs <= 0) {
63
+ return finish('failed', 'goal-deadline', checkpoint ? { kind: 'incomplete-goal', checkpoint } : undefined);
64
+ }
65
+ const continuing = cycle > 0 || checkpoint != null || initialRetryAttempt > 0;
66
+ const turnOptions = {
67
+ ...options.turnOptions,
68
+ ...(checkpoint
69
+ ? {
70
+ // The conversation already carries the user message; a continuation
71
+ // turn rides it with a synthetic control. Attachments belong to the
72
+ // first attempt only.
73
+ ephemeralControl: goalContinuationPrompt(describeCompletionReadiness(checkpoint.readiness, checkpoint.taskCounts ? countsToTaskProgress(checkpoint.taskCounts) : undefined), checkpoint.taskCounts),
74
+ attachments: undefined,
75
+ }
76
+ : {}),
77
+ // Always tag the turn with the logical goal id/cycle so cycle-0
78
+ // checkpoints carry the supervisor's goal identity, and hydrate carried
79
+ // evidence on continuation turns (a no-op seed for a fresh goal).
80
+ goalContext: {
81
+ goalId,
82
+ cycle: cycle + 1,
83
+ carried: checkpoint
84
+ ? { mutationCount: checkpoint.mutationCount, validationOutcome: checkpoint.validationOutcome, ...(checkpoint.taskCounts ? { taskProgress: countsToTaskProgress(checkpoint.taskCounts) } : {}) }
85
+ : { mutationCount: 0, validationOutcome: 'not_applicable' },
86
+ noProgressCount,
87
+ },
88
+ sharedTurnScope,
89
+ ...(remainingMs != null ? { turnDeadlineMs: Math.min(remainingMs, DEFAULT_TURN_DEADLINE_MS) } : {}),
90
+ };
91
+ const result = await runAgentTurn(request, continuing ? undefined : options.displayValue, contextFiles, callbacks, initialRetryAttempt, continuing, false, options.session, options.modelOverride, turnOptions);
92
+ initialRetryAttempt = 0;
93
+ cycle += 1;
94
+ lastEvidence = result.evidence;
95
+ if (result.status === 'complete')
96
+ return finish('complete', 'completed');
97
+ if (result.status === 'aborted')
98
+ return finish('aborted', 'user-aborted');
99
+ if (result.resume?.kind === 'incomplete-goal') {
100
+ const next = checkpointFromResume(result.resume, 0);
101
+ noProgressCount = prevSignature != null && next.progressSignature === prevSignature ? noProgressCount + 1 : 0;
102
+ prevSignature = next.progressSignature;
103
+ checkpoint = { ...next, noProgressCount };
104
+ if (noProgressCount >= GOAL_NO_PROGRESS_LIMIT) {
105
+ callbacks.addMessage({ role: 'system', text: `Unfinished goal paused after ${noProgressCount} cycles without measurable progress (${describeCompletionReadiness(checkpoint.readiness, checkpoint.taskCounts ? countsToTaskProgress(checkpoint.taskCounts) : undefined)}). Completed work is preserved in the conversation. Press R to resume, or send a follow-up.` });
106
+ return finish('failed', 'no-progress', { kind: 'incomplete-goal', checkpoint });
107
+ }
108
+ const remainingNow = options.goalDeadlineMs != null ? options.goalDeadlineMs - (Date.now() - startedAt) : undefined;
109
+ if (remainingNow != null && remainingNow <= 0) {
110
+ callbacks.addMessage({ role: 'system', text: 'Goal deadline reached before the remaining work finished. Completed work is preserved in the conversation; send a follow-up to continue.' });
111
+ return finish('failed', 'goal-deadline', { kind: 'incomplete-goal', checkpoint });
112
+ }
113
+ const openTasks = checkpoint.taskCounts ? checkpoint.taskCounts.pending + checkpoint.taskCounts.inProgress : undefined;
114
+ callbacks.onEvent?.(agentEvent({ type: 'goal_continue', goalId, cycle, reason: checkpoint.readiness }));
115
+ callbacks.addMessage({ role: 'system', text: `Continuing unfinished goal — cycle ${cycle + 1}${openTasks != null ? ` (${openTasks} task${openTasks === 1 ? '' : 's'} remaining)` : ''}: ${describeCompletionReadiness(checkpoint.readiness, checkpoint.taskCounts ? countsToTaskProgress(checkpoint.taskCounts) : undefined)}.` });
116
+ continue;
117
+ }
118
+ if (result.resume?.kind === 'model-stream-idle') {
119
+ // Bounded in-turn retries are exhausted; a transport stall is a concrete
120
+ // external blocker — pause with the existing one-key resume path.
121
+ return finish('failed', 'model-stream-idle', { kind: 'model-stream-idle', request: result.resume.request, retryAttempt: result.resume.retryAttempt });
122
+ }
123
+ // Failed without a checkpoint: hard blocker (failed tool, invalid input,
124
+ // provider error) or an unresolved synthesis failure.
125
+ return finish('failed', result.evidence?.finishCause === 'error' ? 'model-error' : 'blocked');
126
+ }
127
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * An idle timer for the main agent turn.
3
+ *
4
+ * The turn is considered "idle" (and aborted) after `timeoutMs` with no stream
5
+ * activity — UNLESS a tool call is currently executing (`isBusy()` returns
6
+ * true). Concurrent subagents can run for many minutes while emitting no stream
7
+ * parts; that is legitimate work, not a dead stream, so the timer defers (rearms)
8
+ * while any tool is in flight. This prevents a long subagent wave from being
9
+ * mistaken for a hung turn.
10
+ *
11
+ * Note: there is intentionally no upper bound on how long a single tool may run
12
+ * while in flight — a genuinely hung tool would defer indefinitely. A per-tool
13
+ * hard timeout is a separate concern; the idle timer only guards against a turn
14
+ * that is producing no model output AND doing no tool work.
15
+ */
16
+ export interface IdleTimer {
17
+ /** Clear any pending deadline and rearm it for a fresh idle window. */
18
+ reset: () => void;
19
+ /** Cancel the pending deadline without rearming. */
20
+ clear: () => void;
21
+ }
22
+ export declare function createIdleTimer(input: {
23
+ timeoutMs: number;
24
+ isBusy: () => boolean;
25
+ onTimeout: () => void;
26
+ }): IdleTimer;
@@ -0,0 +1,24 @@
1
+ export function createIdleTimer(input) {
2
+ const { timeoutMs, isBusy, onTimeout } = input;
3
+ let timer;
4
+ const fire = () => {
5
+ if (isBusy()) {
6
+ // Tools are executing — that is activity. Defer by rearming.
7
+ timer = setTimeout(fire, timeoutMs);
8
+ return;
9
+ }
10
+ onTimeout();
11
+ };
12
+ return {
13
+ reset: () => {
14
+ if (timer)
15
+ clearTimeout(timer);
16
+ timer = setTimeout(fire, timeoutMs);
17
+ },
18
+ clear: () => {
19
+ if (timer)
20
+ clearTimeout(timer);
21
+ timer = undefined;
22
+ },
23
+ };
24
+ }
@@ -0,0 +1,2 @@
1
+ /** Identifies tool-input failures that are safe to send back to the model for a smaller retry. */
2
+ export declare function isMalformedToolInputError(error: unknown): boolean;
@@ -0,0 +1,24 @@
1
+ function errorFragments(error, depth = 0) {
2
+ if (depth > 4 || error == null)
3
+ return [];
4
+ if (typeof error === 'string')
5
+ return [error];
6
+ if (error instanceof Error) {
7
+ const cause = 'cause' in error ? error.cause : undefined;
8
+ return [error.name, error.message, ...errorFragments(cause, depth + 1)];
9
+ }
10
+ if (typeof error !== 'object')
11
+ return [String(error)];
12
+ const record = error;
13
+ return [
14
+ ...errorFragments(record.name, depth + 1),
15
+ ...errorFragments(record.message, depth + 1),
16
+ ...errorFragments(record.cause, depth + 1),
17
+ ...errorFragments(record.error, depth + 1),
18
+ ];
19
+ }
20
+ /** Identifies tool-input failures that are safe to send back to the model for a smaller retry. */
21
+ export function isMalformedToolInputError(error) {
22
+ const text = errorFragments(error).join(' ');
23
+ return /AI_(?:JSONParse|InvalidToolInput)Error|JSON parsing failed|Invalid input for tool|invalid tool input/i.test(text);
24
+ }
@@ -11,6 +11,30 @@ export type NativeToolCall = {
11
11
  toolName: string;
12
12
  input: unknown;
13
13
  };
14
+ export type ToolDisplayDiffLine = {
15
+ type: 'add' | 'remove' | 'context';
16
+ oldLine?: number;
17
+ newLine?: number;
18
+ text: string;
19
+ } | {
20
+ type: 'gap';
21
+ omittedLines: number;
22
+ } | {
23
+ type: 'meta';
24
+ text: string;
25
+ };
26
+ export type ToolDisplayDiff = {
27
+ id: string;
28
+ path: string;
29
+ addedLines: number;
30
+ removedLines: number;
31
+ lines: ToolDisplayDiffLine[];
32
+ truncated?: boolean;
33
+ omittedLines?: number;
34
+ handle?: string;
35
+ complete?: boolean;
36
+ previousContentOmittedBytes?: number;
37
+ };
14
38
  export type ToolDisplayItem = {
15
39
  id: string;
16
40
  summary: string;
@@ -20,6 +44,7 @@ export type ToolDisplayItem = {
20
44
  finishedAt?: number;
21
45
  durationMs?: number;
22
46
  showResult?: boolean;
47
+ diff?: ToolDisplayDiff;
23
48
  };
24
49
  export interface ToolGroupRendererDeps {
25
50
  addMessage: (msg: {
@@ -27,10 +52,14 @@ export interface ToolGroupRendererDeps {
27
52
  role: 'tool';
28
53
  text: string;
29
54
  streaming: boolean;
55
+ toolCount: number;
56
+ toolDiffs?: ToolDisplayDiff[];
30
57
  }) => void;
31
58
  updateMessage: (id: string, update: {
32
59
  text?: string;
33
60
  streaming?: boolean;
61
+ toolCount?: number;
62
+ toolDiffs?: ToolDisplayDiff[];
34
63
  }) => void;
35
64
  debugLog: (line: string) => void;
36
65
  onEvent?: AgentEventSink;
@@ -52,4 +81,6 @@ export interface ToolGroupRenderer {
52
81
  /** Add a scoped context-file read to the active tool group display. */
53
82
  addContextFileRead: (path: string) => void;
54
83
  }
84
+ /** Extract the bounded structured diff returned by dedicated file mutation tools for rich terminal rendering. */
85
+ export declare function toolDiffFromResult(toolCall: NativeToolCall, output: unknown): ToolDisplayDiff | undefined;
55
86
  export declare function createToolGroupRenderer(deps: ToolGroupRendererDeps): ToolGroupRenderer;
@@ -6,6 +6,51 @@ function logEntry(log, entry) {
6
6
  void logAppend(log, entry).catch(() => undefined);
7
7
  }
8
8
  const createToolGroup = () => ({ id: `tools-${Date.now()}-${Math.random().toString(36).slice(2)}`, items: [], started: false, finalized: false });
9
+ function record(value) {
10
+ return typeof value === 'object' && value != null ? value : undefined;
11
+ }
12
+ /** Extract the bounded structured diff returned by dedicated file mutation tools for rich terminal rendering. */
13
+ export function toolDiffFromResult(toolCall, output) {
14
+ if (toolCall.toolName !== 'editFile' && toolCall.toolName !== 'replaceLines' && toolCall.toolName !== 'writeFile')
15
+ return undefined;
16
+ const result = record(output);
17
+ if (!result || result.ok !== true || !Array.isArray(result.diff))
18
+ return undefined;
19
+ const lines = result.diff.flatMap((candidate) => {
20
+ const line = record(candidate);
21
+ if (!line)
22
+ return [];
23
+ if (line.type === 'gap' && typeof line.omittedLines === 'number' && line.omittedLines > 0) {
24
+ return [{ type: 'gap', omittedLines: line.omittedLines }];
25
+ }
26
+ if (line.type === 'meta' && typeof line.text === 'string')
27
+ return [{ type: 'meta', text: line.text }];
28
+ if ((line.type !== 'add' && line.type !== 'remove' && line.type !== 'context') || typeof line.text !== 'string')
29
+ return [];
30
+ return [{
31
+ type: line.type,
32
+ ...(typeof line.oldLine === 'number' ? { oldLine: line.oldLine } : {}),
33
+ ...(typeof line.newLine === 'number' ? { newLine: line.newLine } : {}),
34
+ text: line.text,
35
+ }];
36
+ });
37
+ if (lines.length === 0)
38
+ return undefined;
39
+ const input = record(toolCall.input);
40
+ const path = typeof result.path === 'string' ? result.path : typeof input?.path === 'string' ? input.path : 'edited file';
41
+ return {
42
+ id: toolCall.toolCallId,
43
+ path,
44
+ addedLines: typeof result.addedLines === 'number' ? result.addedLines : lines.filter(line => line.type === 'add').length,
45
+ removedLines: typeof result.removedLines === 'number' ? result.removedLines : lines.filter(line => line.type === 'remove').length,
46
+ lines,
47
+ truncated: result.diffTruncated === true,
48
+ omittedLines: typeof result.diffOmittedLines === 'number' ? result.diffOmittedLines : 0,
49
+ ...(typeof result.diffHandle === 'string' ? { handle: result.diffHandle } : {}),
50
+ complete: result.diffComplete !== false,
51
+ ...(typeof result.previousContentOmittedBytes === 'number' ? { previousContentOmittedBytes: result.previousContentOmittedBytes } : {}),
52
+ };
53
+ }
9
54
  export function createToolGroupRenderer(deps) {
10
55
  let toolGroup = createToolGroup();
11
56
  let toolTimer;
@@ -31,14 +76,17 @@ export function createToolGroupRenderer(deps) {
31
76
  };
32
77
  const updateToolGroup = (streaming = true, group = toolGroup) => {
33
78
  const text = renderToolGroup(group);
79
+ const toolDiffs = group.items.flatMap(item => item.diff ? [item.diff] : []);
80
+ // toolCount and diffs are carried structurally so metrics and rich code
81
+ // rendering never depend on parsing the compact caption/row format.
34
82
  if (!group.started) {
35
83
  group.started = true;
36
84
  group.finalized = !streaming;
37
- deps.addMessage({ id: group.id, role: 'tool', text, streaming });
85
+ deps.addMessage({ id: group.id, role: 'tool', text, streaming, toolCount: group.items.length, toolDiffs });
38
86
  }
39
87
  else {
40
88
  group.finalized = !streaming;
41
- deps.updateMessage(group.id, { text, streaming });
89
+ deps.updateMessage(group.id, { text, streaming, toolCount: group.items.length, toolDiffs });
42
90
  }
43
91
  };
44
92
  const finalizeToolGroup = (group = toolGroup) => {
@@ -10,4 +10,9 @@ export declare function applyToolResultState(state: ToolResultState, event: {
10
10
  output: unknown;
11
11
  ok: boolean;
12
12
  }): ToolResultState;
13
- export declare function isMutatingToolName(toolName: string): boolean;
13
+ /**
14
+ * Update recovery state from the SDK's internally ordered step content. This
15
+ * runs in onStepEnd, before prepareStep can start the next model request, so a
16
+ * fast provider cannot outrun state updates queued on the public stream.
17
+ */
18
+ export declare function applyStepToolResultState(state: ToolResultState, content: readonly unknown[]): ToolResultState;
@@ -1,25 +1,47 @@
1
- import { isDuplicateSkippedOutput, toolInputField } from '../../../core/agent/toolResults.js';
1
+ import { isDuplicateSkippedOutput, requiresReadFileRecovery, toolInputField, toolOutputOk } from '../../../core/agent/toolResults.js';
2
+ import { workspacePathKey } from '../../../utils/path.js';
2
3
  const MUTATING_TOOLS = new Set(['editFile', 'replaceLines', 'writeFile']);
4
+ function samePath(first, second) {
5
+ return first != null && second != null && workspacePathKey(first) === workspacePathKey(second);
6
+ }
3
7
  export function initialToolResultState() {
4
8
  return { mutatingToolSucceeded: false, editRecoveryReadSatisfied: false };
5
9
  }
6
10
  export function applyToolResultState(state, event) {
7
11
  const path = toolInputField(event.input, 'path');
8
- if (!event.ok && MUTATING_TOOLS.has(event.toolName)) {
12
+ if (!event.ok && MUTATING_TOOLS.has(event.toolName) && path && requiresReadFileRecovery(event.output)) {
9
13
  return { ...state, editRecoveryPath: path, editRecoveryReadSatisfied: false };
10
14
  }
11
- if (event.ok && event.toolName === 'readFile' && path && path === state.editRecoveryPath && !isDuplicateSkippedOutput(event.output)) {
15
+ if (event.ok && event.toolName === 'readFile' && samePath(path, state.editRecoveryPath) && !isDuplicateSkippedOutput(event.output)) {
12
16
  return { ...state, editRecoveryReadSatisfied: true };
13
17
  }
14
18
  if (event.ok && !isDuplicateSkippedOutput(event.output) && MUTATING_TOOLS.has(event.toolName)) {
19
+ const clearsRecovery = !path || samePath(path, state.editRecoveryPath);
15
20
  return {
16
21
  mutatingToolSucceeded: true,
17
- editRecoveryPath: !path || path === state.editRecoveryPath ? undefined : state.editRecoveryPath,
18
- editRecoveryReadSatisfied: !path || path === state.editRecoveryPath ? false : state.editRecoveryReadSatisfied,
22
+ editRecoveryPath: clearsRecovery ? undefined : state.editRecoveryPath,
23
+ editRecoveryReadSatisfied: clearsRecovery ? false : state.editRecoveryReadSatisfied,
19
24
  };
20
25
  }
21
26
  return state;
22
27
  }
23
- export function isMutatingToolName(toolName) {
24
- return MUTATING_TOOLS.has(toolName);
28
+ /**
29
+ * Update recovery state from the SDK's internally ordered step content. This
30
+ * runs in onStepEnd, before prepareStep can start the next model request, so a
31
+ * fast provider cannot outrun state updates queued on the public stream.
32
+ */
33
+ export function applyStepToolResultState(state, content) {
34
+ let next = state;
35
+ for (const part of content) {
36
+ if (typeof part !== 'object' || part == null || !('type' in part))
37
+ continue;
38
+ const value = part;
39
+ if (value.type === 'tool-result' && typeof value.toolName === 'string') {
40
+ next = applyToolResultState(next, { toolName: value.toolName, input: value.input, output: value.output, ok: toolOutputOk(value.output, true) });
41
+ }
42
+ else if (value.type === 'tool-error' && typeof value.toolName === 'string') {
43
+ next = applyToolResultState(next, { toolName: value.toolName, input: value.input, output: value.error, ok: false });
44
+ }
45
+ }
46
+ return next;
25
47
  }
@@ -1,4 +1,16 @@
1
+ import type { RequestIntent } from '../../../core/goal/requestClassifier.js';
2
+ import type { ValidationOutcome, WorkTaskProgress } from '../../../core/agent/workState.js';
1
3
  import type { TurnStatus } from '../streaming.js';
4
+ /**
5
+ * CLI adapter for the authoritative turn-status decision. The pure policy
6
+ * lives in `core/agent/completionController.ts`; this keeps the single call site
7
+ * in the agent turn (see streaming/AGENTS.md) and preserves the documented
8
+ * field-based signature exercised by `tests/cli/turnOutcome.test.ts`.
9
+ *
10
+ * The optional work-evidence fields (intent, mutation/validation counts, task
11
+ * progress) project the turn-wide `TurnExecutionState`; when omitted, the
12
+ * defaults cannot reject a turn (unknown intent, no mutations, no task list).
13
+ */
2
14
  export declare function terminalTurnStatus(input: {
3
15
  aborted: boolean;
4
16
  error?: unknown;
@@ -7,4 +19,9 @@ export declare function terminalTurnStatus(input: {
7
19
  lastToolOk?: boolean;
8
20
  finishReason?: string;
9
21
  budgetReached?: boolean;
22
+ unresolvedToolInputError?: boolean;
23
+ intent?: RequestIntent;
24
+ mutationCount?: number;
25
+ validationOutcome?: ValidationOutcome;
26
+ taskProgress?: WorkTaskProgress;
10
27
  }): TurnStatus;
@@ -1,13 +1,29 @@
1
+ import { createTurnExecutionState, decideTerminalStatus, normalizeFinishReason } from '../../../core/agent/completionController.js';
2
+ /**
3
+ * CLI adapter for the authoritative turn-status decision. The pure policy
4
+ * lives in `core/agent/completionController.ts`; this keeps the single call site
5
+ * in the agent turn (see streaming/AGENTS.md) and preserves the documented
6
+ * field-based signature exercised by `tests/cli/turnOutcome.test.ts`.
7
+ *
8
+ * The optional work-evidence fields (intent, mutation/validation counts, task
9
+ * progress) project the turn-wide `TurnExecutionState`; when omitted, the
10
+ * defaults cannot reject a turn (unknown intent, no mutations, no task list).
11
+ */
1
12
  export function terminalTurnStatus(input) {
2
- if (input.aborted)
3
- return 'aborted';
4
- if (input.error)
5
- return 'failed';
6
- if (input.lastToolOk === false)
7
- return 'failed';
8
- if (input.budgetReached || input.finishReason === 'length' || input.finishReason === 'error')
9
- return 'failed';
10
- if (input.sawToolCall && input.assistantText.trim().length === 0)
11
- return 'failed';
12
- return input.assistantText.trim().length > 0 ? 'complete' : 'failed';
13
+ void input.error;
14
+ const state = {
15
+ ...createTurnExecutionState(),
16
+ aborted: input.aborted,
17
+ finishCause: normalizeFinishReason(input.finishReason),
18
+ intent: input.intent ?? 'unknown',
19
+ mutationCount: input.mutationCount ?? 0,
20
+ ...(input.validationOutcome ? { validationOutcome: input.validationOutcome } : {}),
21
+ ...(input.taskProgress ? { taskProgress: input.taskProgress } : {}),
22
+ };
23
+ return decideTerminalStatus(state, {
24
+ sawToolCall: input.sawToolCall,
25
+ assistantText: input.assistantText,
26
+ lastToolOk: input.lastToolOk,
27
+ unresolvedToolInputError: Boolean(input.unresolvedToolInputError),
28
+ }, Boolean(input.budgetReached));
13
29
  }
@@ -58,11 +58,13 @@ export function stepCacheMetrics(usage) {
58
58
  };
59
59
  }
60
60
  export function subagentTokenEstimate(output) {
61
- if (typeof output !== 'object' || output == null || !('tokens' in output))
61
+ if (typeof output !== 'object' || output == null)
62
62
  return undefined;
63
- const tokens = output.tokens;
64
- const input = typeof tokens?.in === 'number' ? tokens.in : 0;
65
- const outputTokens = typeof tokens?.out === 'number' ? tokens.out : 0;
63
+ const value = output;
64
+ const inputValue = value.telemetry?.usage?.inputTokens ?? value.tokens?.in;
65
+ const outputValue = value.telemetry?.usage?.outputTokens ?? value.tokens?.out;
66
+ const input = typeof inputValue === 'number' ? inputValue : 0;
67
+ const outputTokens = typeof outputValue === 'number' ? outputValue : 0;
66
68
  return input > 0 || outputTokens > 0 ? { input, output: outputTokens } : undefined;
67
69
  }
68
70
  export function rememberContextFilesFromToolOutput(activeContextFiles, output) {