@denizokcu/haze 1.1.0 → 1.2.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 (149) hide show
  1. package/CHANGELOG.md +49 -1
  2. package/README.md +17 -10
  3. package/SECURITY.md +1 -1
  4. package/dist/buildInfo.json +3 -3
  5. package/dist/cli/chat/busyIndicator.d.ts +11 -0
  6. package/dist/cli/chat/busyIndicator.js +34 -0
  7. package/dist/cli/chat/chatMetrics.d.ts +0 -1
  8. package/dist/cli/chat/chatMetrics.js +1 -7
  9. package/dist/cli/chat/followUpQueue.d.ts +11 -0
  10. package/dist/cli/chat/followUpQueue.js +38 -0
  11. package/dist/cli/chat/messages.d.ts +0 -22
  12. package/dist/cli/chat/messages.js +40 -85
  13. package/dist/cli/chat/sessionLifecycle.d.ts +3 -1
  14. package/dist/cli/chat/sessionLifecycle.js +8 -1
  15. package/dist/cli/chat/sessionRecorder.d.ts +9 -0
  16. package/dist/cli/chat/sessionRecorder.js +12 -0
  17. package/dist/cli/chat/startupSequence.d.ts +29 -0
  18. package/dist/cli/chat/startupSequence.js +59 -0
  19. package/dist/cli/chat/transcriptPartition.d.ts +23 -0
  20. package/dist/cli/chat/transcriptPartition.js +78 -0
  21. package/dist/cli/chat/wizard/fieldTransitions.d.ts +38 -0
  22. package/dist/cli/chat/wizard/fieldTransitions.js +43 -0
  23. package/dist/cli/chat/wizard/lspHandlers.d.ts +4 -0
  24. package/dist/cli/chat/wizard/lspHandlers.js +85 -0
  25. package/dist/cli/chat/wizard/mcpHandlers.d.ts +8 -0
  26. package/dist/cli/chat/wizard/mcpHandlers.js +82 -0
  27. package/dist/cli/chat/wizard/providerHandlers.d.ts +12 -0
  28. package/dist/cli/chat/wizard/providerHandlers.js +420 -0
  29. package/dist/cli/chat/wizard/sessionThemeHandlers.d.ts +4 -0
  30. package/dist/cli/chat/wizard/sessionThemeHandlers.js +48 -0
  31. package/dist/cli/chat/wizard/skillsHandlers.d.ts +4 -0
  32. package/dist/cli/chat/wizard/skillsHandlers.js +125 -0
  33. package/dist/cli/chat/wizard/types.d.ts +63 -0
  34. package/dist/cli/chat/wizard/types.js +24 -0
  35. package/dist/cli/chat/wizard/uiState.d.ts +56 -0
  36. package/dist/cli/chat/wizard/uiState.js +15 -0
  37. package/dist/cli/chat/wizardDispatch.d.ts +11 -113
  38. package/dist/cli/chat/wizardDispatch.js +41 -815
  39. package/dist/cli/commands/chat.js +69 -110
  40. package/dist/cli/commands/formatters.d.ts +0 -3
  41. package/dist/cli/commands/formatters.js +0 -29
  42. package/dist/cli/commands/runCommand.d.ts +2 -0
  43. package/dist/cli/commands/runCommand.js +73 -4
  44. package/dist/cli/commands/streaming/agentAttempt.d.ts +11 -1
  45. package/dist/cli/commands/streaming/agentAttempt.js +9 -5
  46. package/dist/cli/commands/streaming/assistantSegments.d.ts +19 -0
  47. package/dist/cli/commands/streaming/assistantSegments.js +48 -0
  48. package/dist/cli/commands/streaming/attemptOutcome.d.ts +25 -5
  49. package/dist/cli/commands/streaming/attemptOutcome.js +69 -16
  50. package/dist/cli/commands/streaming/attemptSetup.d.ts +10 -3
  51. package/dist/cli/commands/streaming/attemptSetup.js +30 -13
  52. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +69 -8
  53. package/dist/cli/commands/streaming/goalCheckpoint.js +36 -1
  54. package/dist/cli/commands/streaming/goalSupervisor.d.ts +18 -3
  55. package/dist/cli/commands/streaming/goalSupervisor.js +71 -12
  56. package/dist/cli/commands/streaming/prepareStep.d.ts +40 -0
  57. package/dist/cli/commands/streaming/prepareStep.js +116 -0
  58. package/dist/cli/commands/streaming/recoverySlices.d.ts +15 -0
  59. package/dist/cli/commands/streaming/recoverySlices.js +29 -0
  60. package/dist/cli/commands/streaming/stallRecovery.d.ts +0 -1
  61. package/dist/cli/commands/streaming/stallRecovery.js +2 -6
  62. package/dist/cli/commands/streaming/streamLoop.d.ts +31 -4
  63. package/dist/cli/commands/streaming/streamLoop.js +283 -268
  64. package/dist/cli/commands/streaming/toolGroupRenderer.js +2 -1
  65. package/dist/cli/commands/streaming/toolPartHandlers.d.ts +19 -0
  66. package/dist/cli/commands/streaming/toolPartHandlers.js +108 -0
  67. package/dist/cli/commands/streaming/turnRuntime.d.ts +1 -1
  68. package/dist/cli/commands/streaming/turnRuntime.js +3 -2
  69. package/dist/cli/commands/streaming.d.ts +12 -1
  70. package/dist/cli/commands/streaming.js +20 -25
  71. package/dist/cli/index.js +6 -3
  72. package/dist/config/modelCatalog.d.ts +32 -0
  73. package/dist/config/modelCatalog.js +84 -0
  74. package/dist/config/providerPresets.d.ts +7 -0
  75. package/dist/config/providerPresets.js +195 -391
  76. package/dist/config/settings.d.ts +10 -2
  77. package/dist/config/settings.js +3 -0
  78. package/dist/core/agent/budgets.d.ts +10 -0
  79. package/dist/core/agent/budgets.js +10 -0
  80. package/dist/core/agent/compaction.d.ts +42 -3
  81. package/dist/core/agent/compaction.js +53 -5
  82. package/dist/core/agent/completionController.d.ts +16 -7
  83. package/dist/core/agent/completionController.js +13 -6
  84. package/dist/core/agent/contextBudget.d.ts +56 -0
  85. package/dist/core/agent/contextBudget.js +53 -0
  86. package/dist/core/agent/errors.js +2 -2
  87. package/dist/core/agent/events.d.ts +36 -1
  88. package/dist/core/agent/goalPolicy.d.ts +4 -3
  89. package/dist/core/agent/goalPolicy.js +9 -4
  90. package/dist/core/agent/overflow.d.ts +45 -0
  91. package/dist/core/agent/overflow.js +91 -0
  92. package/dist/core/agent/requestAssembly.d.ts +7 -0
  93. package/dist/core/agent/requestAssembly.js +15 -7
  94. package/dist/core/agent/workState.d.ts +25 -15
  95. package/dist/core/agent/workState.js +84 -44
  96. package/dist/core/safety/shellClassifier.d.ts +16 -0
  97. package/dist/core/safety/shellClassifier.js +31 -0
  98. package/dist/core/session/sessionSlimming.js +8 -0
  99. package/dist/core/session/sessionStore.d.ts +71 -1
  100. package/dist/core/session/sessionStore.js +121 -6
  101. package/dist/core/validation/outputParser.d.ts +1 -1
  102. package/dist/core/validation/outputParser.js +6 -1
  103. package/dist/llm/client.d.ts +2 -2
  104. package/dist/llm/client.js +14 -6
  105. package/dist/llm/hazeTools.d.ts +64 -208
  106. package/dist/llm/tools/shellTool.js +27 -8
  107. package/dist/llm/tools/taskTool.d.ts +64 -208
  108. package/dist/llm/tools/taskTool.js +22 -10
  109. package/dist/ui/components/TextInput.d.ts +18 -1
  110. package/dist/ui/components/TextInput.js +50 -73
  111. package/dist/ui/components/useInputSuggestions.d.ts +27 -0
  112. package/dist/ui/components/useInputSuggestions.js +98 -0
  113. package/dist/ui/theme.d.ts +8 -8
  114. package/dist/ui/theme.js +11 -12
  115. package/dist/ui/themes/registry.d.ts +5 -0
  116. package/dist/ui/themes/registry.js +436 -0
  117. package/dist/utils/format.d.ts +10 -0
  118. package/dist/utils/format.js +45 -0
  119. package/package.json +16 -15
  120. package/dist/ui/themes/af-magic.d.ts +0 -7
  121. package/dist/ui/themes/af-magic.js +0 -25
  122. package/dist/ui/themes/agnoster.d.ts +0 -10
  123. package/dist/ui/themes/agnoster.js +0 -40
  124. package/dist/ui/themes/bira.d.ts +0 -10
  125. package/dist/ui/themes/bira.js +0 -28
  126. package/dist/ui/themes/bureau.d.ts +0 -10
  127. package/dist/ui/themes/bureau.js +0 -28
  128. package/dist/ui/themes/clean.d.ts +0 -9
  129. package/dist/ui/themes/clean.js +0 -27
  130. package/dist/ui/themes/cloud.d.ts +0 -6
  131. package/dist/ui/themes/cloud.js +0 -24
  132. package/dist/ui/themes/dst.d.ts +0 -10
  133. package/dist/ui/themes/dst.js +0 -28
  134. package/dist/ui/themes/fishy.d.ts +0 -7
  135. package/dist/ui/themes/fishy.js +0 -25
  136. package/dist/ui/themes/index.d.ts +0 -8
  137. package/dist/ui/themes/index.js +0 -36
  138. package/dist/ui/themes/light.d.ts +0 -3
  139. package/dist/ui/themes/light.js +0 -21
  140. package/dist/ui/themes/purple.d.ts +0 -7
  141. package/dist/ui/themes/purple.js +0 -26
  142. package/dist/ui/themes/robbyrussell.d.ts +0 -8
  143. package/dist/ui/themes/robbyrussell.js +0 -26
  144. package/dist/ui/themes/solarized-dark.d.ts +0 -16
  145. package/dist/ui/themes/solarized-dark.js +0 -44
  146. package/dist/ui/themes/solarized-light.d.ts +0 -12
  147. package/dist/ui/themes/solarized-light.js +0 -40
  148. package/dist/ui/themes/steeef.d.ts +0 -11
  149. package/dist/ui/themes/steeef.js +0 -29
@@ -2,9 +2,10 @@ import type { ContextFile } from '../../../config/contextFiles.js';
2
2
  import type { TurnCompletionEvidence } from '../../../core/agent/completionController.js';
3
3
  import type { PromptSession } from '../../../llm/systemPrompt.js';
4
4
  import { type StreamCallbacks, type TurnExecutionOptions } from '../streaming.js';
5
- import { type GoalCheckpoint } from './goalCheckpoint.js';
5
+ import { type GoalCheckpoint, type GoalLedgerAppend } from './goalCheckpoint.js';
6
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';
7
+ export type GoalStopReason = 'completed' | 'no-progress' | 'goal-deadline' | 'blocked' | 'model-error' | 'model-stream-idle' | 'user-aborted' | 'context-exhausted';
8
+ export type { GoalLedgerAppend };
8
9
  /** Authoritative outcome of a logical goal (one or more physical turns). */
9
10
  export interface GoalRunResult {
10
11
  status: 'complete' | 'failed' | 'aborted';
@@ -38,13 +39,22 @@ export interface GoalRunOptions {
38
39
  goalDeadlineMs?: number;
39
40
  /** Base per-turn options (attachments, blessed paths); attachments apply to the first physical turn only. */
40
41
  turnOptions?: TurnExecutionOptions;
41
- /** Explicit resume of a paused goal: an idle-stalled turn pool or a stored goal checkpoint. */
42
+ /** Explicit resume of a paused goal: an idle-stalled turn pool, a stored goal checkpoint, or a durable ledger frontier. */
42
43
  resumeFrom?: {
43
44
  kind: 'model-stream-idle';
44
45
  retryAttempt: number;
45
46
  } | {
46
47
  kind: 'incomplete-goal';
47
48
  checkpoint: GoalCheckpoint;
49
+ } | {
50
+ kind: 'stored-goal';
51
+ checkpoint: GoalCheckpoint;
52
+ };
53
+ /** The preserved conversation already carries the user request (headless until-done relaunch): do not re-add it. */
54
+ conversationCarriesRequest?: boolean;
55
+ /** Durable goal-ledger sink (P1): the interactive UI wires the session recorder; headless runs stay in-process. */
56
+ goalLedger?: {
57
+ append(entry: GoalLedgerAppend): void;
48
58
  };
49
59
  }
50
60
  /**
@@ -60,5 +70,10 @@ export interface GoalRunOptions {
60
70
  * repeated no-progress cycles. Conversation and completed tool results carry
61
71
  * across turns, so mutations are never replayed. Emits exactly one `goal_start`
62
72
  * and one terminal `goal_end`, plus `goal_continue` between physical turns.
73
+ *
74
+ * Every boundary also appends to the durable goal ledger (P1) when a sink is
75
+ * wired: the append-only frontier survives crashes and session restarts, and
76
+ * `resumeFrom: {kind: 'stored-goal'}` continues a frontier without re-sending
77
+ * the user request.
63
78
  */
64
79
  export declare function runAgentGoal(options: GoalRunOptions): Promise<GoalRunResult>;
@@ -1,9 +1,9 @@
1
1
  import { agentEvent } from '../../../core/agent/events.js';
2
2
  import { DEFAULT_TURN_DEADLINE_MS } from '../../../core/agent/budgets.js';
3
3
  import { describeCompletionReadiness } from '../../../core/agent/completionController.js';
4
- import { goalContinuationPrompt } from '../../../core/agent/goalPolicy.js';
4
+ import { classifyRequestIntent, goalContinuationPrompt } from '../../../core/agent/goalPolicy.js';
5
5
  import { runAgentTurn } from '../streaming.js';
6
- import { goalCheckpointSignature } from './goalCheckpoint.js';
6
+ import { goalCheckpointSignature, hashRequest } from './goalCheckpoint.js';
7
7
  /** Pause after one corrective physical turn without measurable outcome progress. */
8
8
  const GOAL_NO_PROGRESS_LIMIT = 1;
9
9
  function checkpointFromResume(resume, noProgressCount) {
@@ -18,11 +18,29 @@ function checkpointFromResume(resume, noProgressCount) {
18
18
  validationOutcome,
19
19
  progressSignature: goalCheckpointSignature({ mutationCount: resume.mutationCount, validationOutcome, taskCounts: resume.taskCounts }),
20
20
  noProgressCount,
21
+ ...(resume.requestHash ? { requestHash: resume.requestHash } : {}),
22
+ ...(resume.redEvidence ? { redEvidence: { ...resume.redEvidence } } : {}),
21
23
  };
22
24
  }
23
25
  function countsToTaskProgress(counts) {
24
26
  return { total: counts.total, pending: counts.pending, inProgress: counts.inProgress, completed: counts.completed, revision: 1 };
25
27
  }
28
+ /** Human-readable continuation reason for a checkpoint; stored-goal frontiers may predate a specific readiness. */
29
+ function checkpointReason(checkpoint) {
30
+ return checkpoint.readiness
31
+ ? describeCompletionReadiness(checkpoint.readiness, checkpoint.taskCounts ? countsToTaskProgress(checkpoint.taskCounts) : undefined)
32
+ : 'the previous run ended before the goal was complete';
33
+ }
34
+ function carriedOf(checkpoint) {
35
+ return checkpoint
36
+ ? {
37
+ mutationCount: checkpoint.mutationCount,
38
+ validationOutcome: checkpoint.validationOutcome,
39
+ ...(checkpoint.taskCounts ? { taskProgress: countsToTaskProgress(checkpoint.taskCounts) } : {}),
40
+ ...(checkpoint.redEvidence ? { redEvidence: { ...checkpoint.redEvidence } } : {}),
41
+ }
42
+ : { mutationCount: 0, validationOutcome: 'not_applicable' };
43
+ }
26
44
  /**
27
45
  * Logical-goal supervisor. Runs bounded physical turns (`runAgentTurn`) until
28
46
  * the user's goal is structurally complete, autonomously starting the next
@@ -36,24 +54,55 @@ function countsToTaskProgress(counts) {
36
54
  * repeated no-progress cycles. Conversation and completed tool results carry
37
55
  * across turns, so mutations are never replayed. Emits exactly one `goal_start`
38
56
  * and one terminal `goal_end`, plus `goal_continue` between physical turns.
57
+ *
58
+ * Every boundary also appends to the durable goal ledger (P1) when a sink is
59
+ * wired: the append-only frontier survives crashes and session restarts, and
60
+ * `resumeFrom: {kind: 'stored-goal'}` continues a frontier without re-sending
61
+ * the user request.
39
62
  */
40
63
  export async function runAgentGoal(options) {
41
64
  const { request, contextFiles, callbacks } = options;
42
65
  const startedAt = Date.now();
43
- const goalId = options.resumeFrom?.kind === 'incomplete-goal' ? options.resumeFrom.checkpoint.goalId : `goal-${startedAt}-${Math.random().toString(36).slice(2)}`;
66
+ const resumedCheckpoint = options.resumeFrom?.kind === 'incomplete-goal' || options.resumeFrom?.kind === 'stored-goal' ? options.resumeFrom.checkpoint : undefined;
67
+ const goalId = resumedCheckpoint?.goalId ?? `goal-${startedAt}-${Math.random().toString(36).slice(2)}`;
68
+ const requestHash = resumedCheckpoint?.requestHash ?? hashRequest(request);
69
+ const intent = resumedCheckpoint?.intent ?? classifyRequestIntent(request);
44
70
  const sharedTurnScope = {};
45
- let checkpoint = options.resumeFrom?.kind === 'incomplete-goal' ? options.resumeFrom.checkpoint : undefined;
71
+ let checkpoint = resumedCheckpoint;
46
72
  let initialRetryAttempt = options.resumeFrom?.kind === 'model-stream-idle' ? options.resumeFrom.retryAttempt : 0;
47
73
  let cycle = checkpoint?.cycle ?? 0;
48
74
  let noProgressCount = checkpoint?.noProgressCount ?? 0;
49
75
  let prevSignature = checkpoint?.progressSignature;
50
76
  let lastEvidence;
77
+ const appendLedger = (phase, extra = {}) => {
78
+ if (!options.goalLedger)
79
+ return;
80
+ const source = checkpoint;
81
+ options.goalLedger.append({
82
+ goalId,
83
+ phase,
84
+ request,
85
+ requestHash,
86
+ intent,
87
+ cycle,
88
+ mutationCount: source?.mutationCount ?? 0,
89
+ validationOutcome: source?.validationOutcome ?? 'not_applicable',
90
+ progressSignature: source?.progressSignature ?? '',
91
+ ...(source?.taskCounts ? { taskCounts: source.taskCounts } : {}),
92
+ // Unresolved red evidence keeps crash resumes at parity with in-process
93
+ // continuation; satisfied pairs are deliberately not carried.
94
+ ...(source?.redEvidence ? { redEvidence: { ...source.redEvidence } } : {}),
95
+ ...extra,
96
+ });
97
+ };
51
98
  callbacks.onEvent?.(agentEvent({ type: 'goal_start', goalId, request }));
99
+ appendLedger('goal_start');
52
100
  // Observable capability line at every goal start (debug panel, --debug LLM
53
101
  // log, headless stderr): failures can be tied to runtime behavior, not
54
102
  // guessed from semantic versions.
55
103
  callbacks.debugLog('goal supervisor enabled; automatic continuation across physical-turn budgets');
56
104
  const finish = (status, stopReason, resume) => {
105
+ appendLedger('goal_end', { status, ...(stopReason !== 'completed' ? { stopReason } : {}) });
57
106
  callbacks.onEvent?.(agentEvent({ type: 'goal_end', goalId, status, cycles: cycle, ...(stopReason !== 'completed' ? { stopReason } : {}), ...(lastEvidence ? { evidence: lastEvidence } : {}) }));
58
107
  return { status, stopReason, cycles: cycle, ...(lastEvidence ? { evidence: lastEvidence } : {}), ...(resume ? { resume } : {}) };
59
108
  };
@@ -62,7 +111,7 @@ export async function runAgentGoal(options) {
62
111
  if (cycle > 0 && remainingMs != null && remainingMs <= 0) {
63
112
  return finish('failed', 'goal-deadline', checkpoint ? { kind: 'incomplete-goal', checkpoint } : undefined);
64
113
  }
65
- const continuing = cycle > 0 || checkpoint != null || initialRetryAttempt > 0;
114
+ const continuing = cycle > 0 || checkpoint != null || initialRetryAttempt > 0 || Boolean(options.conversationCarriesRequest);
66
115
  const turnOptions = {
67
116
  ...options.turnOptions,
68
117
  ...(checkpoint
@@ -70,7 +119,7 @@ export async function runAgentGoal(options) {
70
119
  // The conversation already carries the user message; a continuation
71
120
  // turn rides it with a synthetic control. Attachments belong to the
72
121
  // first attempt only.
73
- ephemeralControl: goalContinuationPrompt(describeCompletionReadiness(checkpoint.readiness, checkpoint.taskCounts ? countsToTaskProgress(checkpoint.taskCounts) : undefined), checkpoint.taskCounts),
122
+ ephemeralControl: goalContinuationPrompt(checkpointReason(checkpoint), checkpoint.taskCounts),
74
123
  attachments: undefined,
75
124
  }
76
125
  : {}),
@@ -80,10 +129,9 @@ export async function runAgentGoal(options) {
80
129
  goalContext: {
81
130
  goalId,
82
131
  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' },
132
+ carried: carriedOf(checkpoint),
86
133
  noProgressCount,
134
+ requestHash,
87
135
  },
88
136
  sharedTurnScope,
89
137
  ...(remainingMs != null ? { turnDeadlineMs: Math.min(remainingMs, DEFAULT_TURN_DEADLINE_MS) } : {}),
@@ -104,8 +152,19 @@ export async function runAgentGoal(options) {
104
152
  noProgressCount = prevSignature != null && next.progressSignature === prevSignature ? noProgressCount + 1 : 0;
105
153
  prevSignature = next.progressSignature;
106
154
  checkpoint = { ...next, noProgressCount };
155
+ // Context exhaustion is not a correctable-in-place condition: the window
156
+ // stayed full after the turn's bounded compact-and-retry attempts, so
157
+ // continuing immediately would relaunch the same oversized request.
158
+ // Pause with the resumable checkpoint instead (Pillar 1.4); the user
159
+ // compacts/clears context or switches models, then resumes.
160
+ if (checkpoint.readiness === 'context_exhausted') {
161
+ callbacks.onEvent?.(agentEvent({ type: 'goal_notice', text: `Goal paused: ${checkpointReason(checkpoint)}. Compact or clear context, or switch to a larger-context model, then resume.` }));
162
+ return finish('failed', 'context-exhausted', { kind: 'incomplete-goal', checkpoint });
163
+ }
164
+ appendLedger('goal_continue');
107
165
  if (noProgressCount >= GOAL_NO_PROGRESS_LIMIT) {
108
- callbacks.addMessage({ role: 'system', text: `Unfinished goal paused after ${noProgressCount} corrective cycle${noProgressCount === 1 ? '' : 's'} 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.` });
166
+ callbacks.addMessage({ role: 'system', text: `Unfinished goal paused after ${noProgressCount} corrective cycle${noProgressCount === 1 ? '' : 's'} without measurable progress (${checkpointReason(checkpoint)}). Completed work is preserved in the conversation. Press R to resume, or send a follow-up.` });
167
+ callbacks.onEvent?.(agentEvent({ type: 'goal_notice', text: `Unfinished goal paused without measurable progress: ${checkpointReason(checkpoint)}` }));
109
168
  return finish('failed', 'no-progress', { kind: 'incomplete-goal', checkpoint });
110
169
  }
111
170
  const remainingNow = options.goalDeadlineMs != null ? options.goalDeadlineMs - (Date.now() - startedAt) : undefined;
@@ -114,8 +173,8 @@ export async function runAgentGoal(options) {
114
173
  return finish('failed', 'goal-deadline', { kind: 'incomplete-goal', checkpoint });
115
174
  }
116
175
  const openTasks = checkpoint.taskCounts ? checkpoint.taskCounts.pending + checkpoint.taskCounts.inProgress : undefined;
117
- callbacks.onEvent?.(agentEvent({ type: 'goal_continue', goalId, cycle, reason: checkpoint.readiness }));
118
- 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)}.` });
176
+ callbacks.onEvent?.(agentEvent({ type: 'goal_continue', goalId, cycle, reason: checkpoint.readiness ?? 'unfinished', text: checkpointReason(checkpoint) }));
177
+ callbacks.addMessage({ role: 'system', text: `Continuing unfinished goal — cycle ${cycle + 1}${openTasks != null ? ` (${openTasks} task${openTasks === 1 ? '' : 's'} remaining)` : ''}: ${checkpointReason(checkpoint)}.` });
119
178
  continue;
120
179
  }
121
180
  if (result.resume?.kind === 'model-stream-idle') {
@@ -0,0 +1,40 @@
1
+ import type { ModelMessage } from 'ai';
2
+ import { type SessionGoal } from '../../../core/agent/goalPolicy.js';
3
+ import { type ContextUsageAnchor } from '../../../core/agent/contextBudget.js';
4
+ import type { HazeToolContext } from '../../../llm/tools/toolContext.js';
5
+ import type { StreamCallbacks, TurnExecutionOptions } from '../streaming.js';
6
+ import type { AttemptSetup } from './attemptSetup.js';
7
+ import type { AttemptLoopState } from './streamLoop.js';
8
+ import type { TurnExecutionState } from '../../../core/agent/completionController.js';
9
+ /**
10
+ * The per-step request preparation decision tree (extracted from
11
+ * streamLoop.ts): scoped context injection, mid-turn compaction, and the
12
+ * ordered model-constraint guards (rescue synthesis, plan-only finals,
13
+ * malformed-tool retries, edit recovery, repeated-tool suppression, budget
14
+ * exhaustion). Each guard returns the step's tool-choice/messages override or
15
+ * falls through to the default request.
16
+ */
17
+ type AgentOptions = NonNullable<ConstructorParameters<typeof import('ai').ToolLoopAgent>[0]>;
18
+ type RepairToolCallFn = NonNullable<AgentOptions['experimental_repairToolCall']>;
19
+ type PrepareStepFn = NonNullable<AgentOptions['prepareStep']>;
20
+ type SyncPrepareStepResult = Exclude<ReturnType<PrepareStepFn>, PromiseLike<unknown>>;
21
+ export declare function withScopedContextControl(messages: ModelMessage[], context: HazeToolContext): ModelMessage[];
22
+ export declare function createRepairToolCall(deps: {
23
+ callbacks: StreamCallbacks;
24
+ loopState: AttemptLoopState;
25
+ }): RepairToolCallFn;
26
+ export declare function createPrepareStep(deps: {
27
+ setup: AttemptSetup;
28
+ callbacks: StreamCallbacks;
29
+ loopState: AttemptLoopState;
30
+ turnState: TurnExecutionState;
31
+ turnBudget: {
32
+ toolCallLimit: number;
33
+ };
34
+ goal: SessionGoal;
35
+ recoverySlice: TurnExecutionOptions['recoverySlice'];
36
+ usageAnchor: {
37
+ current: ContextUsageAnchor | undefined;
38
+ };
39
+ }): (input: Parameters<PrepareStepFn>[0]) => SyncPrepareStepResult;
40
+ export {};
@@ -0,0 +1,116 @@
1
+ import { agentEvent } from '../../../core/agent/events.js';
2
+ import { malformedToolCallPrompt, repeatedToolCallPrompt, toolLoopBudgetPrompt } from '../../../core/agent/goalPolicy.js';
3
+ import { estimateConversationTokens } from '../../../core/agent/contextBudget.js';
4
+ import { compactModelMessages } from '../../../core/agent/compaction.js';
5
+ import { appendSyntheticControl, stripSyntheticControls } from '../../../core/agent/requestAssembly.js';
6
+ import { latestRepeatedToolNames, toolOnlyStepCount } from '../../../core/agent/turnPolicy.js';
7
+ import { RESCUE_BOUNDARY } from '../../../core/agent/completionController.js';
8
+ import { MAIN_TOOL_CALL_LIMIT, WRITE_FILE_CHUNK_BYTES } from '../../../core/agent/budgets.js';
9
+ import { projectContextSection } from '../../../llm/systemPrompt.js';
10
+ import { clampOutOfBoundsToolNumbers, isMalformedToolInputError } from './toolCallRecovery.js';
11
+ export function withScopedContextControl(messages, context) {
12
+ const files = context.pendingContextFiles ?? [];
13
+ if (files.length === 0)
14
+ return messages;
15
+ context.pendingContextFiles = [];
16
+ return appendSyntheticControl(messages, `Additional scoped project instructions were just read for a non-root path touched by a tool call. Apply them to subsequent work in that subtree.${projectContextSection(files)}`);
17
+ }
18
+ export function createRepairToolCall(deps) {
19
+ const { callbacks, loopState } = deps;
20
+ return async ({ toolCall, error, inputSchema }) => {
21
+ if (isMalformedToolInputError(error)) {
22
+ const clamped = await clampOutOfBoundsToolNumbers(toolCall.input, toolCall.toolName, inputSchema);
23
+ if (clamped != null) {
24
+ callbacks.debugLog(`clamped out-of-range numeric input for ${toolCall.toolName}; executing repaired call`);
25
+ return { type: 'tool-call', toolCallId: toolCall.toolCallId, toolName: toolCall.toolName, input: JSON.stringify(clamped) };
26
+ }
27
+ loopState.pendingMalformedToolName = toolCall.toolName;
28
+ loopState.unresolvedMalformedToolName = toolCall.toolName;
29
+ }
30
+ // Truncated generated file content cannot be reconstructed safely here;
31
+ // let the next agent step retry under the bounded tool-choice constraint.
32
+ return null;
33
+ };
34
+ }
35
+ export function createPrepareStep(deps) {
36
+ const { setup, callbacks, loopState, turnState, turnBudget, goal, recoverySlice, usageAnchor } = deps;
37
+ const { sliceTools, requestBudget, toolExecutionContext, likelyPlanOnlyRequest, rescueWithoutTools } = setup;
38
+ return ({ steps, messages }) => {
39
+ // A rescue slice with no qualifying tools must synthesize, never reopen
40
+ // discovery by falling back to the full tool set (F-08).
41
+ if (rescueWithoutTools) {
42
+ callbacks.debugLog('rescue slice has no mutation/validation tools; forcing tool-free synthesis');
43
+ return { toolChoice: 'none' };
44
+ }
45
+ const toolCalls = steps.flatMap(step => step.toolCalls);
46
+ // ToolLoopAgent instances are intentionally one step wide. SDK `steps`
47
+ // therefore resets at each resource epoch; retain only bounded policy
48
+ // metadata in loopState instead of holding prior StepResult graphs.
49
+ const repeatedToolNames = steps.length > 0 ? latestRepeatedToolNames(steps) : loopState.latestRepeatedToolNames;
50
+ let scopedMessages = withScopedContextControl(messages, toolExecutionContext);
51
+ let messagesChanged = scopedMessages !== messages;
52
+ // Re-evaluate the accumulated request size before each provider call and
53
+ // compact old tool history when it exceeds the model-aware budget, so a
54
+ // long multi-step turn compacts before overflowing (RH-005). The estimate
55
+ // prefers provider usage from the last completed step (Pillar 1.1); this
56
+ // sync path is the safety net under the epoch-boundary LLM compaction.
57
+ const contextEstimate = estimateConversationTokens(scopedMessages, usageAnchor.current, requestBudget.systemTokens + requestBudget.toolSchemaTokens);
58
+ if (contextEstimate.tokens > requestBudget.messageTokens) {
59
+ callbacks.onEvent?.(agentEvent({ type: 'compaction_start', reason: 'threshold', method: 'heuristic' }));
60
+ const compacted = compactModelMessages(stripSyntheticControls(scopedMessages), { tokenBudget: requestBudget.messageTokens, workState: goal });
61
+ if (compacted.compacted) {
62
+ scopedMessages = compacted.messages;
63
+ loopState.contextCompactedInEpoch = true;
64
+ messagesChanged = true;
65
+ usageAnchor.current = undefined;
66
+ callbacks.recordCompaction?.({ method: 'heuristic', olderCount: compacted.olderCount, keptCount: compacted.keptCount, summary: compacted.summary ?? '' });
67
+ }
68
+ callbacks.onEvent?.(agentEvent({ type: 'compaction_end', reason: 'threshold', method: compacted.compacted ? 'heuristic' : 'none', compacted: compacted.compacted, olderCount: compacted.olderCount, keptCount: compacted.keptCount }));
69
+ }
70
+ // Turn-wide hard caps (shared across retries and recovery slices).
71
+ const turnToolCallsExhausted = turnState.toolCallsUsed >= turnBudget.toolCallLimit;
72
+ // Per-slice tool-call cap for a recovery slice (counts this slice's calls).
73
+ const sliceToolCalls = steps.length > 0 ? toolCalls.length : loopState.generatedToolCalls;
74
+ const sliceToolCallsExhausted = recoverySlice ? sliceToolCalls >= recoverySlice.maxToolCalls : false;
75
+ // Reserve the final tool-only slot for rescue: normal exploration stops at
76
+ // the boundary; a rescue slice is exempt so it may use the reserved slot.
77
+ const consecutiveToolOnlySteps = steps.length > 0 ? toolOnlyStepCount(steps) : loopState.consecutiveToolOnlySteps;
78
+ const toolOnlyBoundaryHit = !recoverySlice && consecutiveToolOnlySteps >= RESCUE_BOUNDARY;
79
+ if (likelyPlanOnlyRequest && loopState.toolResultState.mutatingToolSucceeded)
80
+ return messagesChanged ? { toolChoice: 'none', messages: scopedMessages } : { toolChoice: 'none' };
81
+ if (loopState.pendingMalformedToolName && loopState.pendingMalformedToolName in sliceTools) {
82
+ const toolName = loopState.pendingMalformedToolName;
83
+ const attempt = loopState.malformedRecoveryAttempts.get(String(toolName)) ?? 0;
84
+ loopState.pendingMalformedToolName = undefined;
85
+ if (attempt >= 2) {
86
+ callbacks.debugLog(`malformed ${String(toolName)} recovery exhausted`);
87
+ return { toolChoice: 'none', messages: appendSyntheticControl(scopedMessages, `The ${String(toolName)} input remained invalid after two smaller retries. Report this as blocked; do not promise another retry or claim completion.`) };
88
+ }
89
+ loopState.malformedRecoveryAttempts.set(String(toolName), attempt + 1);
90
+ callbacks.debugLog(`forcing smaller retry after malformed ${String(toolName)} input`);
91
+ // OpenAI-compatible servers differ in tool_choice support: several
92
+ // (LM Studio, llama.cpp) accept only the string form (none/auto/
93
+ // required) and reject the object form with HTTP 400. Narrowing to a
94
+ // single active tool plus 'required' preserves the forced-call
95
+ // semantics on every server.
96
+ return { activeTools: [toolName], toolChoice: 'required', messages: appendSyntheticControl(scopedMessages, malformedToolCallPrompt(String(toolName), WRITE_FILE_CHUNK_BYTES)) };
97
+ }
98
+ if (loopState.toolResultState.editRecoveryPath && !loopState.toolResultState.editRecoveryReadSatisfied) {
99
+ if ('readFile' in sliceTools)
100
+ return messagesChanged ? { activeTools: ['readFile'], messages: scopedMessages } : { activeTools: ['readFile'] };
101
+ return { toolChoice: 'none', messages: appendSyntheticControl(scopedMessages, `The failed mutation of ${loopState.toolResultState.editRecoveryPath} requires a fresh read, but readFile is unavailable in this bounded recovery slice. Report the unfinished edit as blocked; do not claim it succeeded.`) };
102
+ }
103
+ if (repeatedToolNames.length > 0) {
104
+ const activeTools = Object.keys(sliceTools).filter(name => !repeatedToolNames.includes(name));
105
+ callbacks.debugLog(`disabling repeated tools for next step: ${repeatedToolNames.join(', ')}`);
106
+ return activeTools.length > 0
107
+ ? { activeTools, messages: appendSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) }
108
+ : { toolChoice: 'none', messages: appendSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) };
109
+ }
110
+ if (turnToolCallsExhausted || sliceToolCallsExhausted || toolOnlyBoundaryHit || sliceToolCalls >= MAIN_TOOL_CALL_LIMIT) {
111
+ callbacks.debugLog('forcing text response to avoid tool loop');
112
+ return { toolChoice: 'none', messages: appendSyntheticControl(scopedMessages, toolLoopBudgetPrompt()) };
113
+ }
114
+ return messagesChanged ? { messages: scopedMessages } : undefined;
115
+ };
116
+ }
@@ -0,0 +1,15 @@
1
+ import { type TurnExecutionState } from '../../../core/agent/completionController.js';
2
+ import type { ToolExecutionBudgetState } from '../../../core/agent/budgets.js';
3
+ import type { AttemptRecovery } from './attemptOutcome.js';
4
+ import type { TurnExecutionOptions } from '../streaming.js';
5
+ /**
6
+ * Recovery-slice admission for the turn loop (extracted from
7
+ * `runAgentTurn`). Length/rescue credits are single-use, so a slice cannot
8
+ * trigger another of the same kind; goal continuation is repeatable but
9
+ * progress-guarded and counts against the shared turn budget.
10
+ */
11
+ export declare function startRecoverySlice(recovery: AttemptRecovery, state: {
12
+ turnState: TurnExecutionState;
13
+ sliceBudget: ToolExecutionBudgetState;
14
+ options: TurnExecutionOptions;
15
+ }, debugLog: (line: string) => void): TurnExecutionOptions;
@@ -0,0 +1,29 @@
1
+ import { recordGoalContinuation } from '../../../core/agent/completionController.js';
2
+ /**
3
+ * Recovery-slice admission for the turn loop (extracted from
4
+ * `runAgentTurn`). Length/rescue credits are single-use, so a slice cannot
5
+ * trigger another of the same kind; goal continuation is repeatable but
6
+ * progress-guarded and counts against the shared turn budget.
7
+ */
8
+ export function startRecoverySlice(recovery, state, debugLog) {
9
+ if (recovery.kind === 'length') {
10
+ state.turnState.lengthCreditUsed = true;
11
+ state.turnState.lengthRecoveriesAttempted += 1;
12
+ }
13
+ else if (recovery.kind === 'rescue') {
14
+ state.turnState.rescueUsed = true;
15
+ }
16
+ else {
17
+ recordGoalContinuation(state.turnState);
18
+ }
19
+ // A new slice gets a fresh execution allowance, clamped once here; the
20
+ // slice budget persists across provider retries within the slice (C2).
21
+ state.sliceBudget.started = 0;
22
+ state.sliceBudget.exceeded = false;
23
+ debugLog(`starting ${recovery.kind} recovery slice: ${recovery.slice.maxSteps} steps / ${recovery.slice.maxToolCalls} tool calls`);
24
+ return {
25
+ ...state.options,
26
+ ephemeralControl: recovery.control,
27
+ recoverySlice: { kind: recovery.kind, maxSteps: recovery.slice.maxSteps, maxToolCalls: recovery.slice.maxToolCalls },
28
+ };
29
+ }
@@ -4,7 +4,6 @@ import type { ModelMessage } from 'ai';
4
4
  import { type TurnAbortCause } from './abortCause.js';
5
5
  /** What the stalled step had emitted when the stream went quiet. Only 'none' is auto-retryable. */
6
6
  type StallEmission = 'none' | 'text' | 'tool';
7
- export declare function formatIdleMinutes(milliseconds: number): string;
8
7
  /**
9
8
  * An idle timer for the main agent turn.
10
9
  *
@@ -1,12 +1,8 @@
1
1
  import { agentEvent } from '../../../core/agent/events.js';
2
2
  import { IDLE_TIMEOUT_MS, DEFAULT_MODEL_RETRIES } from '../../../core/agent/budgets.js';
3
- import { compactToolHistory, stripSyntheticControls } from '../../../core/agent/requestAssembly.js';
3
+ import { stripSyntheticControls } from '../../../core/agent/requestAssembly.js';
4
4
  import { abortForTurn } from './abortCause.js';
5
5
  import { logEntry } from './turnRuntime.js';
6
- export function formatIdleMinutes(milliseconds) {
7
- const minutes = Math.round(milliseconds / 60_000);
8
- return `${minutes} minute${minutes === 1 ? '' : 's'}`;
9
- }
10
6
  /** Auto-retry an idle stall only while the stalled step emitted nothing visible (no partial text or in-flight tool). */
11
7
  function idleStallAutoRetryEligible(retryAttempt, stallEmission, maxRetries) {
12
8
  return stallEmission === 'none' && retryAttempt < maxRetries;
@@ -100,6 +96,6 @@ export function createStreamStallGuard(deps) {
100
96
  */
101
97
  export function salvageConversationToLastStep(callbacks, salvage) {
102
98
  if (salvage.accumulated.length > 0) {
103
- callbacks.setConversation(compactToolHistory([...stripSyntheticControls(salvage.requestMessages), ...salvage.accumulated]).messages);
99
+ callbacks.setConversation([...stripSyntheticControls(salvage.requestMessages), ...salvage.accumulated]);
104
100
  }
105
101
  }
@@ -1,4 +1,5 @@
1
1
  import { type SessionGoal } from '../../../core/agent/goalPolicy.js';
2
+ import { type ContextUsageAnchor } from '../../../core/agent/contextBudget.js';
2
3
  import { type TurnExecutionState } from '../../../core/agent/completionController.js';
3
4
  import { type ToolExecutionBudgetState, type TurnBudget } from '../../../core/agent/budgets.js';
4
5
  import type { StreamCallbacks, TurnExecutionOptions } from '../streaming.js';
@@ -23,6 +24,7 @@ export interface AttemptLoopState {
23
24
  streamFinished: boolean;
24
25
  finishReason: string | undefined;
25
26
  lastToolOk: boolean | undefined;
27
+ sawToolCall: boolean;
26
28
  pendingMalformedToolName: string | undefined;
27
29
  unresolvedMalformedToolName: string | undefined;
28
30
  /** Per-attempt (not per-turn) recovery counter: a transient retry gets a fresh map. Bounded across the whole turn by MAIN_TOOL_CALL_LIMIT. */
@@ -37,6 +39,21 @@ export interface AttemptLoopState {
37
39
  rememberVisibleAssistantText: (text: string) => void;
38
40
  /** Context files active for this attempt; grows when tool outputs surface scoped instructions. */
39
41
  contextFiles: ContextFile[];
42
+ /** Lightweight cross-epoch history; never retains AI SDK StepResult objects. */
43
+ completedSteps: number;
44
+ generatedToolCalls: number;
45
+ consecutiveToolOnlySteps: number;
46
+ latestRepeatedToolNames: string[];
47
+ seenToolCallFingerprints: Set<string>;
48
+ /** The current epoch rewrote history because the real context budget fired. */
49
+ contextCompactedInEpoch: boolean;
50
+ /** Last valid per-step provider usage (input/output/cache), for usage-overflow detection (Pillar 1.2). */
51
+ lastUsage: {
52
+ inputTokens: number | undefined;
53
+ outputTokens: number;
54
+ cacheReadTokens: number;
55
+ cacheWriteTokens: number;
56
+ } | undefined;
40
57
  }
41
58
  export declare function createAttemptLoopState(previousAssistantText: string, contextFiles: ContextFile[], callbacks: Pick<StreamCallbacks, 'setLastAssistantText'>): AttemptLoopState;
42
59
  /** What the completed stream tells the attempt outcome (classification evidence). */
@@ -47,6 +64,13 @@ export interface AttemptStreamOutcome {
47
64
  sawToolCall: boolean;
48
65
  unresolvedMalformedToolName: string | undefined;
49
66
  unresolvedToolInputError: boolean;
67
+ /**
68
+ * Non-error context overflow detected from usage (Pillar 1.2): `silent`
69
+ * (usage exceeded the window on a successful finish) or `length-stop`
70
+ * (truncated input filled the window leaving no output room). Routed to
71
+ * compact-and-retry recovery in `finalizeAttemptOutcome`.
72
+ */
73
+ usageOverflow: 'silent' | 'length-stop' | undefined;
50
74
  }
51
75
  export interface AttemptStreamDeps {
52
76
  setup: AttemptSetup;
@@ -62,11 +86,14 @@ export interface AttemptStreamDeps {
62
86
  loopState: AttemptLoopState;
63
87
  toolDisplay: ToolGroupRenderer;
64
88
  salvage: AttemptSalvage;
89
+ /** Turn-scoped usage anchor for provider-usage-backed context estimation (Pillar 1.1). */
90
+ usageAnchor: {
91
+ current: ContextUsageAnchor | undefined;
92
+ };
65
93
  }
66
94
  /**
67
- * Drive one attempt's `ToolLoopAgent` stream: construct the agent (repair,
68
- * prepareStep, step observers), consume every stream part, and commit the
69
- * completed conversation. Throws the stream error so the attempt orchestrator
70
- * classifies failures (abort cause, retry pool, recovery) in one place.
95
+ * Drive one attempt through bounded ToolLoopAgent epochs. The provider prefix,
96
+ * tools, budgets, evidence, and deadline stay continuous; only the AI SDK's
97
+ * request-local retained graph is released at each completed step.
71
98
  */
72
99
  export declare function runAttemptStream(deps: AttemptStreamDeps): Promise<AttemptStreamOutcome>;