@denizokcu/haze 0.10.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 (169) hide show
  1. package/CHANGELOG.md +77 -1
  2. package/README.md +66 -25
  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/contextReport.js +2 -0
  9. package/dist/cli/chat/fileMentionSuggestions.js +3 -2
  10. package/dist/cli/chat/liveRegion.d.ts +25 -0
  11. package/dist/cli/chat/liveRegion.js +48 -0
  12. package/dist/cli/chat/messages.d.ts +33 -2
  13. package/dist/cli/chat/messages.js +216 -33
  14. package/dist/cli/chat/sessionLifecycle.d.ts +9 -0
  15. package/dist/cli/chat/sessionLifecycle.js +64 -14
  16. package/dist/cli/chat/sessionRecorder.js +75 -7
  17. package/dist/cli/chat/startupInfo.d.ts +0 -1
  18. package/dist/cli/chat/startupInfo.js +11 -15
  19. package/dist/cli/chat/wizardDispatch.js +111 -12
  20. package/dist/cli/commands/chat.d.ts +5 -0
  21. package/dist/cli/commands/chat.js +203 -101
  22. package/dist/cli/commands/commands.d.ts +2 -0
  23. package/dist/cli/commands/commands.js +10 -5
  24. package/dist/cli/commands/doctor.d.ts +19 -0
  25. package/dist/cli/commands/doctor.js +76 -0
  26. package/dist/cli/commands/formatters.js +2 -0
  27. package/dist/cli/commands/ndjsonSink.d.ts +23 -0
  28. package/dist/cli/commands/ndjsonSink.js +38 -0
  29. package/dist/cli/commands/providerWizard.d.ts +9 -2
  30. package/dist/cli/commands/providerWizard.js +37 -4
  31. package/dist/cli/commands/runCommand.d.ts +3 -0
  32. package/dist/cli/commands/runCommand.js +117 -11
  33. package/dist/cli/commands/streaming/abortCause.d.ts +24 -0
  34. package/dist/cli/commands/streaming/abortCause.js +16 -0
  35. package/dist/cli/commands/streaming/assistantText.js +9 -2
  36. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +65 -0
  37. package/dist/cli/commands/streaming/goalCheckpoint.js +23 -0
  38. package/dist/cli/commands/streaming/goalSupervisor.d.ts +64 -0
  39. package/dist/cli/commands/streaming/goalSupervisor.js +127 -0
  40. package/dist/cli/commands/streaming/toolCallRecovery.d.ts +2 -0
  41. package/dist/cli/commands/streaming/toolCallRecovery.js +24 -0
  42. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +29 -0
  43. package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -4
  44. package/dist/cli/commands/streaming/toolResultState.d.ts +6 -1
  45. package/dist/cli/commands/streaming/toolResultState.js +29 -7
  46. package/dist/cli/commands/streaming/turnOutcome.d.ts +17 -0
  47. package/dist/cli/commands/streaming/turnOutcome.js +27 -11
  48. package/dist/cli/commands/streaming.d.ts +70 -3
  49. package/dist/cli/commands/streaming.js +491 -77
  50. package/dist/cli/commands/wizardActions.d.ts +1 -0
  51. package/dist/cli/commands/wizardActions.js +1 -0
  52. package/dist/cli/commands/wizardPrompts.js +7 -1
  53. package/dist/cli/commands/wizardSuggestions.js +5 -3
  54. package/dist/cli/index.js +68 -22
  55. package/dist/cli/terminalTitle.js +1 -1
  56. package/dist/config/modelDiscovery.d.ts +51 -0
  57. package/dist/config/modelDiscovery.js +164 -1
  58. package/dist/config/privateStorage.js +28 -2
  59. package/dist/config/providerAuth.d.ts +14 -0
  60. package/dist/config/providerAuth.js +49 -0
  61. package/dist/config/providerPresets.d.ts +39 -7
  62. package/dist/config/providerPresets.js +371 -100
  63. package/dist/config/providers.js +2 -0
  64. package/dist/config/settings.d.ts +36 -0
  65. package/dist/config/settings.js +9 -0
  66. package/dist/core/agent/budgets.d.ts +10 -0
  67. package/dist/core/agent/budgets.js +10 -0
  68. package/dist/core/agent/compaction.d.ts +38 -0
  69. package/dist/core/agent/compaction.js +92 -17
  70. package/dist/core/agent/completionController.d.ts +230 -0
  71. package/dist/core/agent/completionController.js +287 -0
  72. package/dist/core/agent/contextBudget.d.ts +38 -0
  73. package/dist/core/agent/contextBudget.js +60 -7
  74. package/dist/core/agent/events.d.ts +74 -0
  75. package/dist/core/agent/reasoningPolicy.d.ts +31 -0
  76. package/dist/core/agent/reasoningPolicy.js +27 -0
  77. package/dist/core/agent/toolCapabilities.d.ts +27 -0
  78. package/dist/core/agent/toolCapabilities.js +58 -0
  79. package/dist/core/agent/toolExecutionBudget.d.ts +35 -0
  80. package/dist/core/agent/toolExecutionBudget.js +49 -0
  81. package/dist/core/agent/toolOutputStore.d.ts +8 -0
  82. package/dist/core/agent/toolOutputStore.js +10 -10
  83. package/dist/core/agent/toolResults.d.ts +12 -0
  84. package/dist/core/agent/toolResults.js +38 -0
  85. package/dist/core/agent/turnBudget.d.ts +35 -0
  86. package/dist/core/agent/turnBudget.js +27 -0
  87. package/dist/core/agent/turnPolicy.d.ts +11 -0
  88. package/dist/core/agent/turnPolicy.js +19 -0
  89. package/dist/core/agent/workState.d.ts +75 -0
  90. package/dist/core/agent/workState.js +120 -9
  91. package/dist/core/deadline.d.ts +33 -0
  92. package/dist/core/deadline.js +74 -0
  93. package/dist/core/goal/completionPolicy.d.ts +27 -0
  94. package/dist/core/goal/completionPolicy.js +37 -1
  95. package/dist/core/limits/byteBudgets.d.ts +2 -0
  96. package/dist/core/limits/byteBudgets.js +2 -0
  97. package/dist/core/limits/textBudgets.d.ts +2 -0
  98. package/dist/core/limits/textBudgets.js +2 -0
  99. package/dist/core/log/llmLog.js +7 -0
  100. package/dist/core/persistence/orderedFileWriter.d.ts +10 -0
  101. package/dist/core/persistence/orderedFileWriter.js +16 -2
  102. package/dist/core/process/backgroundRegistry.js +8 -7
  103. package/dist/core/process/runBoundedProcess.d.ts +8 -2
  104. package/dist/core/process/runBoundedProcess.js +15 -6
  105. package/dist/core/safety/missingExecutable.d.ts +42 -0
  106. package/dist/core/safety/missingExecutable.js +77 -0
  107. package/dist/core/session/sessionStore.d.ts +37 -0
  108. package/dist/core/session/sessionStore.js +215 -51
  109. package/dist/core/subagent/contracts.d.ts +4 -0
  110. package/dist/core/subagent/contracts.js +1 -0
  111. package/dist/core/subagent/subagentCoordinator.d.ts +4 -0
  112. package/dist/core/subagent/subagentCoordinator.js +32 -2
  113. package/dist/core/subagent/subagentRunner.js +17 -37
  114. package/dist/llm/client.d.ts +17 -1
  115. package/dist/llm/client.js +82 -14
  116. package/dist/llm/hazeTools.d.ts +554 -80
  117. package/dist/llm/hazeTools.js +103 -24
  118. package/dist/llm/lsp.d.ts +24 -4
  119. package/dist/llm/lsp.js +72 -11
  120. package/dist/llm/lspTools.d.ts +2366 -0
  121. package/dist/llm/lspTools.js +87 -79
  122. package/dist/llm/openaiCodex.d.ts +3 -0
  123. package/dist/llm/openaiCodex.js +47 -0
  124. package/dist/llm/openaiCodexOAuth.d.ts +54 -0
  125. package/dist/llm/openaiCodexOAuth.js +214 -0
  126. package/dist/llm/requestContext.d.ts +3 -0
  127. package/dist/llm/requestContext.js +7 -4
  128. package/dist/llm/systemPrompt.d.ts +11 -0
  129. package/dist/llm/systemPrompt.js +12 -6
  130. package/dist/llm/toolResultTypes.d.ts +8 -1
  131. package/dist/llm/tools/bashTool.d.ts +48 -16
  132. package/dist/llm/tools/bashTool.js +5 -0
  133. package/dist/llm/tools/editMatch.d.ts +14 -0
  134. package/dist/llm/tools/editMatch.js +72 -0
  135. package/dist/llm/tools/failures.d.ts +2 -0
  136. package/dist/llm/tools/failures.js +1 -0
  137. package/dist/llm/tools/fetchTool.d.ts +16 -0
  138. package/dist/llm/tools/fileToolShared.d.ts +4 -3
  139. package/dist/llm/tools/fileToolShared.js +16 -21
  140. package/dist/llm/tools/gitIgnore.d.ts +49 -0
  141. package/dist/llm/tools/gitIgnore.js +129 -0
  142. package/dist/llm/tools/readRecovery.d.ts +10 -0
  143. package/dist/llm/tools/readRecovery.js +135 -0
  144. package/dist/llm/tools/toolContext.d.ts +1 -1
  145. package/dist/llm/tools/toolContext.js +61 -32
  146. package/dist/llm/webFetch.d.ts +17 -0
  147. package/dist/llm/webFetch.js +64 -97
  148. package/dist/ui/codeHighlight.d.ts +4 -0
  149. package/dist/ui/codeHighlight.js +31 -0
  150. package/dist/ui/components/Header.d.ts +1 -1
  151. package/dist/ui/components/MarkdownText.d.ts +16 -2
  152. package/dist/ui/components/MarkdownText.js +244 -34
  153. package/dist/ui/components/TextInput.d.ts +8 -1
  154. package/dist/ui/components/TextInput.js +6 -2
  155. package/dist/ui/theme.d.ts +4 -3
  156. package/dist/ui/theme.js +5 -4
  157. package/dist/utils/buildInfo.d.ts +104 -0
  158. package/dist/utils/buildInfo.js +253 -0
  159. package/dist/utils/fs.d.ts +9 -0
  160. package/dist/utils/fs.js +87 -25
  161. package/dist/utils/openPath.d.ts +2 -2
  162. package/dist/utils/openPath.js +19 -6
  163. package/dist/utils/path.d.ts +2 -0
  164. package/dist/utils/path.js +5 -1
  165. package/dist/utils/utf8.d.ts +22 -0
  166. package/dist/utils/utf8.js +54 -0
  167. package/dist/utils/version.d.ts +9 -3
  168. package/dist/utils/version.js +28 -2
  169. package/package.json +24 -19
@@ -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,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: {
@@ -28,11 +53,13 @@ export interface ToolGroupRendererDeps {
28
53
  text: string;
29
54
  streaming: boolean;
30
55
  toolCount: number;
56
+ toolDiffs?: ToolDisplayDiff[];
31
57
  }) => void;
32
58
  updateMessage: (id: string, update: {
33
59
  text?: string;
34
60
  streaming?: boolean;
35
61
  toolCount?: number;
62
+ toolDiffs?: ToolDisplayDiff[];
36
63
  }) => void;
37
64
  debugLog: (line: string) => void;
38
65
  onEvent?: AgentEventSink;
@@ -54,4 +81,6 @@ export interface ToolGroupRenderer {
54
81
  /** Add a scoped context-file read to the active tool group display. */
55
82
  addContextFileRead: (path: string) => void;
56
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;
57
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,16 +76,17 @@ export function createToolGroupRenderer(deps) {
31
76
  };
32
77
  const updateToolGroup = (streaming = true, group = toolGroup) => {
33
78
  const text = renderToolGroup(group);
34
- // toolCount is carried structurally so metrics never depend on the rendered
35
- // caption/row format (CR-015).
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.
36
82
  if (!group.started) {
37
83
  group.started = true;
38
84
  group.finalized = !streaming;
39
- deps.addMessage({ id: group.id, role: 'tool', text, streaming, toolCount: group.items.length });
85
+ deps.addMessage({ id: group.id, role: 'tool', text, streaming, toolCount: group.items.length, toolDiffs });
40
86
  }
41
87
  else {
42
88
  group.finalized = !streaming;
43
- deps.updateMessage(group.id, { text, streaming, toolCount: group.items.length });
89
+ deps.updateMessage(group.id, { text, streaming, toolCount: group.items.length, toolDiffs });
44
90
  }
45
91
  };
46
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
  }
@@ -1,13 +1,18 @@
1
- import { type ModelMessage } from 'ai';
1
+ import { type ModelMessage, type ToolSet } from 'ai';
2
2
  import type { LlmLog } from '../../core/log/llmLog.js';
3
- import { type SubagentOverrides } from '../../llm/requestContext.js';
3
+ import { type SubagentOverrides, type TurnExecutionScope } from '../../llm/requestContext.js';
4
4
  import { type PromptSession } from '../../llm/systemPrompt.js';
5
5
  import type { ContextFile } from '../../config/contextFiles.js';
6
6
  import { type AgentEventSink } from '../../core/agent/events.js';
7
7
  import { type ImageAttachment } from '../../core/attachments/imageAttachments.js';
8
8
  import { type BlessedPath } from '../../core/attachments/readBlessings.js';
9
- export { uniqueRepeatedToolNames, toolOnlyStepCount } from '../../core/agent/turnPolicy.js';
9
+ export { latestRepeatedToolNames, uniqueRepeatedToolNames, toolOnlyStepCount } from '../../core/agent/turnPolicy.js';
10
+ import { type TurnCompletionEvidence } from '../../core/agent/completionController.js';
11
+ export type { TurnCompletionEvidence } from '../../core/agent/completionController.js';
12
+ import { type ValidationOutcome, type WorkTaskProgress } from '../../core/agent/workState.js';
10
13
  import type { WorkState } from '../../core/agent/workState.js';
14
+ import { type IncompleteGoalResume } from './streaming/goalCheckpoint.js';
15
+ import { type ToolDisplayDiff } from './streaming/toolGroupRenderer.js';
11
16
  import { type TokenUsage } from './streaming/turnRuntime.js';
12
17
  export type { TokenUsage } from './streaming/turnRuntime.js';
13
18
  export type Message = {
@@ -21,11 +26,49 @@ export type Message = {
21
26
  tokensPerSecond?: number;
22
27
  displayOrder?: number;
23
28
  toolCount?: number;
29
+ toolDiffs?: ToolDisplayDiff[];
24
30
  };
25
31
  export type TurnStatus = 'complete' | 'aborted' | 'failed';
26
32
  /** Authoritative outcome of a turn, so callers (esp. headless/CI) need not sniff message text. */
27
33
  export interface TurnResult {
28
34
  status: TurnStatus;
35
+ /** Bounded, safe completion evidence (no raw commands/output). Additive. */
36
+ evidence?: TurnCompletionEvidence;
37
+ /**
38
+ * The turn paused with recoverable work unfinished; this carries what a
39
+ * one-key/automatic resume needs instead of forcing the user to restate the
40
+ * task. Safe metadata only (reasons, counts, enums) — never commands,
41
+ * content, or credentials.
42
+ *
43
+ * - `model-stream-idle`: the model stream stalled past the idle window and
44
+ * bounded retries could not continue. The conversation keeps completed
45
+ * steps; resume continues the same logical turn's retry pool.
46
+ * - `incomplete-goal`: the attempt ended `recoverable-incomplete` (declared
47
+ * tasks or post-edit validation outstanding) with no same-turn recovery
48
+ * available — including step/tool budget boundaries that finish as
49
+ * `tool-calls`. A goal supervisor (or the interactive R key) continues the
50
+ * logical goal in a fresh physical turn against the preserved
51
+ * conversation; completed mutations are never replayed.
52
+ */
53
+ resume?: {
54
+ kind: 'model-stream-idle';
55
+ request: string;
56
+ retryAttempt: number;
57
+ } | IncompleteGoalResume;
58
+ }
59
+ /** Supervisor-provided logical-goal context: tags checkpoints and seeds cumulative evidence. */
60
+ export interface TurnGoalContext {
61
+ goalId: string;
62
+ /** 1-based physical-turn counter for the logical goal. */
63
+ cycle: number;
64
+ /** Cumulative evidence carried from earlier physical turns. */
65
+ carried: {
66
+ mutationCount: number;
67
+ validationOutcome: ValidationOutcome;
68
+ taskProgress?: WorkTaskProgress;
69
+ };
70
+ /** Consecutive no-progress physical turns at goal level (diagnostics). */
71
+ noProgressCount: number;
29
72
  }
30
73
  export interface TurnExecutionOptions {
31
74
  ephemeralControl?: string;
@@ -34,7 +77,31 @@ export interface TurnExecutionOptions {
34
77
  attachments?: readonly ImageAttachment[];
35
78
  /** User-mentioned paths whose reads may escape workspace confinement this turn. */
36
79
  blessedPaths?: readonly BlessedPath[];
80
+ /** When set, this attempt is a bounded recovery slice (length-continuation, rescue, or goal continuation). */
81
+ recoverySlice?: {
82
+ kind: 'length' | 'rescue' | 'goal';
83
+ maxSteps: number;
84
+ maxToolCalls: number;
85
+ };
86
+ /** Absolute turn deadline in milliseconds (headless `--timeout`); defaults to DEFAULT_TURN_DEADLINE_MS. */
87
+ turnDeadlineMs?: number;
88
+ /** Logical-goal context from the goal supervisor; hydrates cumulative evidence so a fresh physical turn cannot complete while carried work remains. */
89
+ goalContext?: TurnGoalContext;
90
+ /** Shared turn scope (coordinator admission + workspace mutation lease) reused across a logical goal's physical turns. */
91
+ sharedTurnScope?: {
92
+ executionScope?: TurnExecutionScope;
93
+ };
37
94
  }
95
+ /**
96
+ * Restrict a tool set to the capabilities permitted in a completion-rescue
97
+ * slice: mutation (edit/write/replace) and validation-capable (bash) built-in
98
+ * tools only. Discovery, read, coordinate, and all third-party (MCP) tools are
99
+ * dropped so the rescue cannot reopen exploration. May return an empty set
100
+ * when no built-in mutation/validation tools exist (only possible if builtins
101
+ * were removed); the caller then forces a tool-free synthesis slice instead
102
+ * of silently keeping the unfiltered tool set (F-08).
103
+ */
104
+ export declare function restrictToRescueTools(tools: ToolSet): ToolSet;
38
105
  export interface StreamCallbacks {
39
106
  addMessage: (msg: Message) => void;
40
107
  updateMessage: (id: string, update: Partial<Message>) => void;