@denizokcu/haze 1.1.0 → 1.1.1

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 (118) hide show
  1. package/CHANGELOG.md +24 -1
  2. package/README.md +9 -5
  3. package/dist/buildInfo.json +3 -3
  4. package/dist/cli/chat/busyIndicator.d.ts +11 -0
  5. package/dist/cli/chat/busyIndicator.js +34 -0
  6. package/dist/cli/chat/chatMetrics.d.ts +0 -1
  7. package/dist/cli/chat/chatMetrics.js +1 -7
  8. package/dist/cli/chat/followUpQueue.d.ts +11 -0
  9. package/dist/cli/chat/followUpQueue.js +38 -0
  10. package/dist/cli/chat/messages.d.ts +0 -22
  11. package/dist/cli/chat/messages.js +40 -85
  12. package/dist/cli/chat/sessionLifecycle.d.ts +3 -1
  13. package/dist/cli/chat/sessionLifecycle.js +6 -1
  14. package/dist/cli/chat/sessionRecorder.d.ts +2 -0
  15. package/dist/cli/chat/sessionRecorder.js +6 -0
  16. package/dist/cli/chat/startupSequence.d.ts +29 -0
  17. package/dist/cli/chat/startupSequence.js +59 -0
  18. package/dist/cli/chat/transcriptPartition.d.ts +23 -0
  19. package/dist/cli/chat/transcriptPartition.js +78 -0
  20. package/dist/cli/chat/wizard/fieldTransitions.d.ts +38 -0
  21. package/dist/cli/chat/wizard/fieldTransitions.js +43 -0
  22. package/dist/cli/chat/wizard/lspHandlers.d.ts +4 -0
  23. package/dist/cli/chat/wizard/lspHandlers.js +85 -0
  24. package/dist/cli/chat/wizard/mcpHandlers.d.ts +8 -0
  25. package/dist/cli/chat/wizard/mcpHandlers.js +82 -0
  26. package/dist/cli/chat/wizard/providerHandlers.d.ts +12 -0
  27. package/dist/cli/chat/wizard/providerHandlers.js +420 -0
  28. package/dist/cli/chat/wizard/sessionThemeHandlers.d.ts +4 -0
  29. package/dist/cli/chat/wizard/sessionThemeHandlers.js +48 -0
  30. package/dist/cli/chat/wizard/skillsHandlers.d.ts +4 -0
  31. package/dist/cli/chat/wizard/skillsHandlers.js +125 -0
  32. package/dist/cli/chat/wizard/types.d.ts +63 -0
  33. package/dist/cli/chat/wizard/types.js +24 -0
  34. package/dist/cli/chat/wizard/uiState.d.ts +56 -0
  35. package/dist/cli/chat/wizard/uiState.js +15 -0
  36. package/dist/cli/chat/wizardDispatch.d.ts +11 -113
  37. package/dist/cli/chat/wizardDispatch.js +41 -815
  38. package/dist/cli/commands/chat.js +45 -108
  39. package/dist/cli/commands/formatters.d.ts +0 -3
  40. package/dist/cli/commands/formatters.js +0 -29
  41. package/dist/cli/commands/runCommand.d.ts +2 -0
  42. package/dist/cli/commands/runCommand.js +67 -4
  43. package/dist/cli/commands/streaming/assistantSegments.d.ts +19 -0
  44. package/dist/cli/commands/streaming/assistantSegments.js +48 -0
  45. package/dist/cli/commands/streaming/attemptOutcome.d.ts +2 -2
  46. package/dist/cli/commands/streaming/attemptOutcome.js +17 -7
  47. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +69 -8
  48. package/dist/cli/commands/streaming/goalCheckpoint.js +36 -1
  49. package/dist/cli/commands/streaming/goalSupervisor.d.ts +17 -2
  50. package/dist/cli/commands/streaming/goalSupervisor.js +62 -12
  51. package/dist/cli/commands/streaming/prepareStep.d.ts +35 -0
  52. package/dist/cli/commands/streaming/prepareStep.js +100 -0
  53. package/dist/cli/commands/streaming/recoverySlices.d.ts +15 -0
  54. package/dist/cli/commands/streaming/recoverySlices.js +29 -0
  55. package/dist/cli/commands/streaming/stallRecovery.d.ts +0 -1
  56. package/dist/cli/commands/streaming/stallRecovery.js +0 -4
  57. package/dist/cli/commands/streaming/streamLoop.js +9 -230
  58. package/dist/cli/commands/streaming/toolGroupRenderer.js +2 -1
  59. package/dist/cli/commands/streaming/toolPartHandlers.d.ts +19 -0
  60. package/dist/cli/commands/streaming/toolPartHandlers.js +95 -0
  61. package/dist/cli/commands/streaming.d.ts +4 -1
  62. package/dist/cli/commands/streaming.js +6 -21
  63. package/dist/cli/index.js +3 -1
  64. package/dist/config/providerPresets.d.ts +7 -0
  65. package/dist/config/providerPresets.js +195 -391
  66. package/dist/core/agent/completionController.d.ts +14 -7
  67. package/dist/core/agent/completionController.js +12 -6
  68. package/dist/core/agent/events.d.ts +12 -0
  69. package/dist/core/agent/goalPolicy.d.ts +4 -3
  70. package/dist/core/agent/goalPolicy.js +9 -4
  71. package/dist/core/agent/workState.d.ts +25 -15
  72. package/dist/core/agent/workState.js +71 -43
  73. package/dist/core/session/sessionSlimming.js +8 -0
  74. package/dist/core/session/sessionStore.d.ts +61 -1
  75. package/dist/core/session/sessionStore.js +115 -6
  76. package/dist/llm/hazeTools.d.ts +64 -208
  77. package/dist/llm/tools/taskTool.d.ts +64 -208
  78. package/dist/llm/tools/taskTool.js +22 -10
  79. package/dist/ui/components/TextInput.js +6 -67
  80. package/dist/ui/components/useInputSuggestions.d.ts +27 -0
  81. package/dist/ui/components/useInputSuggestions.js +98 -0
  82. package/dist/ui/theme.d.ts +8 -8
  83. package/dist/ui/theme.js +11 -12
  84. package/dist/ui/themes/registry.d.ts +5 -0
  85. package/dist/ui/themes/registry.js +436 -0
  86. package/dist/utils/format.d.ts +10 -0
  87. package/dist/utils/format.js +45 -0
  88. package/package.json +1 -1
  89. package/dist/ui/themes/af-magic.d.ts +0 -7
  90. package/dist/ui/themes/af-magic.js +0 -25
  91. package/dist/ui/themes/agnoster.d.ts +0 -10
  92. package/dist/ui/themes/agnoster.js +0 -40
  93. package/dist/ui/themes/bira.d.ts +0 -10
  94. package/dist/ui/themes/bira.js +0 -28
  95. package/dist/ui/themes/bureau.d.ts +0 -10
  96. package/dist/ui/themes/bureau.js +0 -28
  97. package/dist/ui/themes/clean.d.ts +0 -9
  98. package/dist/ui/themes/clean.js +0 -27
  99. package/dist/ui/themes/cloud.d.ts +0 -6
  100. package/dist/ui/themes/cloud.js +0 -24
  101. package/dist/ui/themes/dst.d.ts +0 -10
  102. package/dist/ui/themes/dst.js +0 -28
  103. package/dist/ui/themes/fishy.d.ts +0 -7
  104. package/dist/ui/themes/fishy.js +0 -25
  105. package/dist/ui/themes/index.d.ts +0 -8
  106. package/dist/ui/themes/index.js +0 -36
  107. package/dist/ui/themes/light.d.ts +0 -3
  108. package/dist/ui/themes/light.js +0 -21
  109. package/dist/ui/themes/purple.d.ts +0 -7
  110. package/dist/ui/themes/purple.js +0 -26
  111. package/dist/ui/themes/robbyrussell.d.ts +0 -8
  112. package/dist/ui/themes/robbyrussell.js +0 -26
  113. package/dist/ui/themes/solarized-dark.d.ts +0 -16
  114. package/dist/ui/themes/solarized-dark.js +0 -44
  115. package/dist/ui/themes/solarized-light.d.ts +0 -12
  116. package/dist/ui/themes/solarized-light.js +0 -40
  117. package/dist/ui/themes/steeef.d.ts +0 -11
  118. package/dist/ui/themes/steeef.js +0 -29
@@ -1,11 +1,14 @@
1
1
  import type { CompletionReadiness, TurnExecutionState } from '../../../core/agent/completionController.js';
2
- import type { ValidationOutcome } from '../../../core/agent/workState.js';
2
+ import type { RequestIntent } from '../../../core/agent/goalPolicy.js';
3
+ import type { RedEvidence, ValidationOutcome, WorkTaskProgress } from '../../../core/agent/workState.js';
4
+ import type { GoalLedgerFrontier } from '../../../core/session/sessionStore.js';
3
5
  /**
4
6
  * 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.
7
+ * unfinished. Safe metadata only — reasons, counts, enums, and red-evidence
8
+ * command strings without output bodies —
9
+ * never raw content or credentials. Carried on `TurnResult.resume` so a goal
10
+ * supervisor (or the interactive resume affordance) can continue the same
11
+ * logical goal in a fresh physical turn without replaying completed work.
9
12
  */
10
13
  export interface IncompleteGoalResume {
11
14
  kind: 'incomplete-goal';
@@ -25,13 +28,23 @@ export interface IncompleteGoalResume {
25
28
  completed: number;
26
29
  };
27
30
  validationOutcome?: ValidationOutcome;
31
+ /** sha256 prefix of the exact request bytes; binds downstream evidence to the mission (P1). */
32
+ requestHash?: string;
33
+ /** Unresolved pre-mutation failing repro for fix goals. */
34
+ redEvidence?: RedEvidence;
28
35
  }
29
- /** Supervisor-level checkpoint persisted between physical turns (in memory). */
36
+ /** Supervisor-level checkpoint persisted between physical turns (in memory and, via the goal ledger, in the session JSONL). */
30
37
  export interface GoalCheckpoint {
31
38
  goalId: string;
32
39
  request: string;
33
40
  cycle: number;
34
- readiness: CompletionReadiness;
41
+ /**
42
+ * Structured readiness that still blocks completion. Optional for a
43
+ * stored-goal resume whose ledger frontier predates a specific readiness
44
+ * (e.g. a crashed run): the continuation then uses the generic unfinished
45
+ * reason instead of guessing one.
46
+ */
47
+ readiness?: CompletionReadiness;
35
48
  taskCounts?: {
36
49
  total: number;
37
50
  pending: number;
@@ -44,7 +57,33 @@ export interface GoalCheckpoint {
44
57
  progressSignature: string;
45
58
  /** Consecutive physical turns without measurable progress. */
46
59
  noProgressCount: number;
60
+ requestHash?: string;
61
+ intent?: RequestIntent;
62
+ redEvidence?: RedEvidence;
47
63
  }
64
+ /** Durable goal-ledger append (P1): one entry per supervisor boundary; the writer stamps `type`/`at`. Shared by the supervisor and the session recorder. */
65
+ export interface GoalLedgerAppend {
66
+ goalId: string;
67
+ phase: 'goal_start' | 'goal_continue' | 'goal_end';
68
+ request: string;
69
+ requestHash: string;
70
+ intent: RequestIntent;
71
+ cycle: number;
72
+ mutationCount: number;
73
+ validationOutcome: ValidationOutcome;
74
+ progressSignature: string;
75
+ taskCounts?: {
76
+ total: number;
77
+ pending: number;
78
+ inProgress: number;
79
+ completed: number;
80
+ };
81
+ redEvidence?: RedEvidence;
82
+ stopReason?: string;
83
+ status?: 'complete' | 'failed' | 'aborted';
84
+ }
85
+ /** Hash binding for the exact mission bytes (P1): everything downstream that references "the mission" carries this. */
86
+ export declare function hashRequest(request: string): string;
48
87
  /** Cumulative outcome signature; monotonic mutation activity alone is not net progress. */
49
88
  export declare function goalCheckpointSignature(input: {
50
89
  mutationCount: number;
@@ -56,10 +95,32 @@ export declare function goalCheckpointSignature(input: {
56
95
  total: number;
57
96
  };
58
97
  }): string;
98
+ /** Goal-scoped evidence carried across a physical-turn boundary (checkpoint subset). */
99
+ export interface CarriedGoalEvidence {
100
+ requestHash?: string;
101
+ intent?: RequestIntent;
102
+ redEvidence?: RedEvidence;
103
+ }
59
104
  /**
60
105
  * Build the checkpoint payload for a `recoverable-incomplete` attempt that no
61
106
  * same-turn recovery can continue. Single construction site so every path
62
107
  * (voluntary final, budget boundary, tool-calls finish, exhausted recovery
63
108
  * slice) yields the same bounded shape.
64
109
  */
65
- export declare function buildIncompleteGoalResume(request: string, goalId: string, cycle: number, state: Pick<TurnExecutionState, 'stepsUsed' | 'mutationCount' | 'validationOutcome' | 'taskProgress'>, reason: CompletionReadiness): IncompleteGoalResume;
110
+ export declare function buildIncompleteGoalResume(request: string, goalId: string, cycle: number, state: Pick<TurnExecutionState, 'stepsUsed' | 'mutationCount' | 'validationOutcome' | 'taskProgress'>, reason: CompletionReadiness, carried?: CarriedGoalEvidence): IncompleteGoalResume;
111
+ /** Project task progress into the plain counts shape used by checkpoints and prompts. */
112
+ export declare function taskCountsOf(taskProgress: WorkTaskProgress | undefined): {
113
+ total: number;
114
+ pending: number;
115
+ inProgress: number;
116
+ completed: number;
117
+ } | undefined;
118
+ /**
119
+ * Rebuild a supervisor checkpoint from a durable ledger frontier (P1 resume
120
+ * path): safe metadata only, tolerant of ledger fields written by older
121
+ * versions. Carries red→green evidence so a crash resume matches in-process
122
+ * continuation (a captured red repro stays captured).
123
+ * `readiness` stays unset — the frontier predates a specific readiness, so
124
+ * continuation uses the generic unfinished reason.
125
+ */
126
+ export declare function checkpointFromGoalFrontier(frontier: GoalLedgerFrontier): GoalCheckpoint;
@@ -1,3 +1,8 @@
1
+ import crypto from 'node:crypto';
2
+ /** Hash binding for the exact mission bytes (P1): everything downstream that references "the mission" carries this. */
3
+ export function hashRequest(request) {
4
+ return crypto.createHash('sha256').update(request, 'utf8').digest('hex').slice(0, 16);
5
+ }
1
6
  /** Cumulative outcome signature; monotonic mutation activity alone is not net progress. */
2
7
  export function goalCheckpointSignature(input) {
3
8
  return JSON.stringify([input.mutationCount > 0, input.validationOutcome, input.taskCounts ? [input.taskCounts.total, input.taskCounts.pending, input.taskCounts.inProgress, input.taskCounts.completed] : null]);
@@ -8,7 +13,7 @@ export function goalCheckpointSignature(input) {
8
13
  * (voluntary final, budget boundary, tool-calls finish, exhausted recovery
9
14
  * slice) yields the same bounded shape.
10
15
  */
11
- export function buildIncompleteGoalResume(request, goalId, cycle, state, reason) {
16
+ export function buildIncompleteGoalResume(request, goalId, cycle, state, reason, carried = {}) {
12
17
  return {
13
18
  kind: 'incomplete-goal',
14
19
  request,
@@ -19,5 +24,35 @@ export function buildIncompleteGoalResume(request, goalId, cycle, state, reason)
19
24
  mutationCount: state.mutationCount,
20
25
  ...(state.taskProgress ? { taskCounts: { total: state.taskProgress.total, pending: state.taskProgress.pending, inProgress: state.taskProgress.inProgress, completed: state.taskProgress.completed } } : {}),
21
26
  ...(state.validationOutcome !== 'not_applicable' ? { validationOutcome: state.validationOutcome } : {}),
27
+ ...carried,
28
+ };
29
+ }
30
+ /** Project task progress into the plain counts shape used by checkpoints and prompts. */
31
+ export function taskCountsOf(taskProgress) {
32
+ return taskProgress ? { total: taskProgress.total, pending: taskProgress.pending, inProgress: taskProgress.inProgress, completed: taskProgress.completed } : undefined;
33
+ }
34
+ const VALIDATION_OUTCOMES = new Set(['passed', 'failed', 'stale', 'absent', 'not_applicable']);
35
+ /**
36
+ * Rebuild a supervisor checkpoint from a durable ledger frontier (P1 resume
37
+ * path): safe metadata only, tolerant of ledger fields written by older
38
+ * versions. Carries red→green evidence so a crash resume matches in-process
39
+ * continuation (a captured red repro stays captured).
40
+ * `readiness` stays unset — the frontier predates a specific readiness, so
41
+ * continuation uses the generic unfinished reason.
42
+ */
43
+ export function checkpointFromGoalFrontier(frontier) {
44
+ const validationOutcome = (VALIDATION_OUTCOMES.has(frontier.validationOutcome) ? frontier.validationOutcome : 'not_applicable');
45
+ return {
46
+ goalId: frontier.goalId,
47
+ request: frontier.request,
48
+ cycle: frontier.cycle,
49
+ mutationCount: frontier.mutationCount,
50
+ validationOutcome,
51
+ progressSignature: frontier.progressSignature,
52
+ noProgressCount: 0,
53
+ requestHash: frontier.requestHash,
54
+ ...(frontier.intent ? { intent: frontier.intent } : {}),
55
+ ...(frontier.taskCounts ? { taskCounts: frontier.taskCounts } : {}),
56
+ ...(frontier.redEvidence ? { redEvidence: { ...frontier.redEvidence } } : {}),
22
57
  };
23
58
  }
@@ -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
7
  export type GoalStopReason = 'completed' | 'no-progress' | 'goal-deadline' | 'blocked' | 'model-error' | 'model-stream-idle' | 'user-aborted';
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,10 @@ 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
+ appendLedger('goal_continue');
107
156
  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.` });
157
+ 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.` });
158
+ callbacks.onEvent?.(agentEvent({ type: 'goal_notice', text: `Unfinished goal paused without measurable progress: ${checkpointReason(checkpoint)}` }));
109
159
  return finish('failed', 'no-progress', { kind: 'incomplete-goal', checkpoint });
110
160
  }
111
161
  const remainingNow = options.goalDeadlineMs != null ? options.goalDeadlineMs - (Date.now() - startedAt) : undefined;
@@ -114,8 +164,8 @@ export async function runAgentGoal(options) {
114
164
  return finish('failed', 'goal-deadline', { kind: 'incomplete-goal', checkpoint });
115
165
  }
116
166
  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)}.` });
167
+ callbacks.onEvent?.(agentEvent({ type: 'goal_continue', goalId, cycle, reason: checkpoint.readiness ?? 'unfinished', text: checkpointReason(checkpoint) }));
168
+ callbacks.addMessage({ role: 'system', text: `Continuing unfinished goal — cycle ${cycle + 1}${openTasks != null ? ` (${openTasks} task${openTasks === 1 ? '' : 's'} remaining)` : ''}: ${checkpointReason(checkpoint)}.` });
119
169
  continue;
120
170
  }
121
171
  if (result.resume?.kind === 'model-stream-idle') {
@@ -0,0 +1,35 @@
1
+ import type { ModelMessage } from 'ai';
2
+ import { type SessionGoal } from '../../../core/agent/goalPolicy.js';
3
+ import type { HazeToolContext } from '../../../llm/tools/toolContext.js';
4
+ import type { StreamCallbacks, TurnExecutionOptions } from '../streaming.js';
5
+ import type { AttemptSetup } from './attemptSetup.js';
6
+ import type { AttemptLoopState } from './streamLoop.js';
7
+ import type { TurnExecutionState } from '../../../core/agent/completionController.js';
8
+ /**
9
+ * The per-step request preparation decision tree (extracted from
10
+ * streamLoop.ts): scoped context injection, mid-turn compaction, and the
11
+ * ordered model-constraint guards (rescue synthesis, plan-only finals,
12
+ * malformed-tool retries, edit recovery, repeated-tool suppression, budget
13
+ * exhaustion). Each guard returns the step's tool-choice/messages override or
14
+ * falls through to the default request.
15
+ */
16
+ type AgentOptions = NonNullable<ConstructorParameters<typeof import('ai').ToolLoopAgent>[0]>;
17
+ type RepairToolCallFn = NonNullable<AgentOptions['experimental_repairToolCall']>;
18
+ type PrepareStepFn = NonNullable<AgentOptions['prepareStep']>;
19
+ export declare function withScopedContextControl(messages: ModelMessage[], context: HazeToolContext): ModelMessage[];
20
+ export declare function createRepairToolCall(deps: {
21
+ callbacks: StreamCallbacks;
22
+ loopState: AttemptLoopState;
23
+ }): RepairToolCallFn;
24
+ export declare function createPrepareStep(deps: {
25
+ setup: AttemptSetup;
26
+ callbacks: StreamCallbacks;
27
+ loopState: AttemptLoopState;
28
+ turnState: TurnExecutionState;
29
+ turnBudget: {
30
+ toolCallLimit: number;
31
+ };
32
+ goal: SessionGoal;
33
+ recoverySlice: TurnExecutionOptions['recoverySlice'];
34
+ }): PrepareStepFn;
35
+ export {};
@@ -0,0 +1,100 @@
1
+ import { malformedToolCallPrompt, repeatedToolCallPrompt, toolLoopBudgetPrompt } from '../../../core/agent/goalPolicy.js';
2
+ import { estimateMessagesTokens } from '../../../core/agent/contextBudget.js';
3
+ import { compactModelMessages } from '../../../core/agent/compaction.js';
4
+ import { stripSyntheticControls, withSyntheticControl } from '../../../core/agent/requestAssembly.js';
5
+ import { latestRepeatedToolNames, toolOnlyStepCount } from '../../../core/agent/turnPolicy.js';
6
+ import { RESCUE_BOUNDARY } from '../../../core/agent/completionController.js';
7
+ import { MAIN_TOOL_CALL_LIMIT, WRITE_FILE_CHUNK_BYTES } from '../../../core/agent/budgets.js';
8
+ import { projectContextSection } from '../../../llm/systemPrompt.js';
9
+ import { clampOutOfBoundsToolNumbers, isMalformedToolInputError } from './toolCallRecovery.js';
10
+ export function withScopedContextControl(messages, context) {
11
+ const files = context.pendingContextFiles ?? [];
12
+ if (files.length === 0)
13
+ return messages;
14
+ context.pendingContextFiles = [];
15
+ return withSyntheticControl(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)}`);
16
+ }
17
+ export function createRepairToolCall(deps) {
18
+ const { callbacks, loopState } = deps;
19
+ return async ({ toolCall, error, inputSchema }) => {
20
+ if (isMalformedToolInputError(error)) {
21
+ const clamped = await clampOutOfBoundsToolNumbers(toolCall.input, toolCall.toolName, inputSchema);
22
+ if (clamped != null) {
23
+ callbacks.debugLog(`clamped out-of-range numeric input for ${toolCall.toolName}; executing repaired call`);
24
+ return { type: 'tool-call', toolCallId: toolCall.toolCallId, toolName: toolCall.toolName, input: JSON.stringify(clamped) };
25
+ }
26
+ loopState.pendingMalformedToolName = toolCall.toolName;
27
+ loopState.unresolvedMalformedToolName = toolCall.toolName;
28
+ }
29
+ // Truncated generated file content cannot be reconstructed safely here;
30
+ // let the next agent step retry under the bounded tool-choice constraint.
31
+ return null;
32
+ };
33
+ }
34
+ export function createPrepareStep(deps) {
35
+ const { setup, callbacks, loopState, turnState, turnBudget, goal, recoverySlice } = deps;
36
+ const { sliceTools, requestBudget, toolExecutionContext, likelyPlanOnlyRequest, rescueWithoutTools } = setup;
37
+ return ({ steps, messages }) => {
38
+ // A rescue slice with no qualifying tools must synthesize, never reopen
39
+ // discovery by falling back to the full tool set (F-08).
40
+ if (rescueWithoutTools) {
41
+ callbacks.debugLog('rescue slice has no mutation/validation tools; forcing tool-free synthesis');
42
+ return { toolChoice: 'none' };
43
+ }
44
+ const toolCalls = steps.flatMap(step => step.toolCalls);
45
+ const repeatedToolNames = latestRepeatedToolNames(steps);
46
+ let scopedMessages = withScopedContextControl(messages, toolExecutionContext);
47
+ let messagesChanged = scopedMessages !== messages;
48
+ // Re-evaluate the accumulated request size before each provider call and
49
+ // compact old tool history when it exceeds the model-aware budget, so a
50
+ // long multi-step turn compacts before overflowing (RH-005).
51
+ if (estimateMessagesTokens(scopedMessages) > requestBudget.messageTokens) {
52
+ const compacted = compactModelMessages(stripSyntheticControls(scopedMessages), { tokenBudget: requestBudget.messageTokens, workState: goal }).messages;
53
+ scopedMessages = compacted;
54
+ messagesChanged = true;
55
+ }
56
+ // Turn-wide hard caps (shared across retries and recovery slices).
57
+ const turnToolCallsExhausted = turnState.toolCallsUsed >= turnBudget.toolCallLimit;
58
+ // Per-slice tool-call cap for a recovery slice (counts this slice's calls).
59
+ const sliceToolCallsExhausted = recoverySlice ? toolCalls.length >= recoverySlice.maxToolCalls : false;
60
+ // Reserve the final tool-only slot for rescue: normal exploration stops at
61
+ // the boundary; a rescue slice is exempt so it may use the reserved slot.
62
+ const toolOnlyBoundaryHit = !recoverySlice && toolOnlyStepCount(steps) >= RESCUE_BOUNDARY;
63
+ if (likelyPlanOnlyRequest && loopState.toolResultState.mutatingToolSucceeded)
64
+ return messagesChanged ? { toolChoice: 'none', messages: scopedMessages } : { toolChoice: 'none' };
65
+ if (loopState.pendingMalformedToolName && loopState.pendingMalformedToolName in sliceTools) {
66
+ const toolName = loopState.pendingMalformedToolName;
67
+ const attempt = loopState.malformedRecoveryAttempts.get(String(toolName)) ?? 0;
68
+ loopState.pendingMalformedToolName = undefined;
69
+ if (attempt >= 2) {
70
+ callbacks.debugLog(`malformed ${String(toolName)} recovery exhausted`);
71
+ return { toolChoice: 'none', messages: withSyntheticControl(scopedMessages, `The ${String(toolName)} input remained invalid after two smaller retries. Report this as blocked; do not promise another retry or claim completion.`) };
72
+ }
73
+ loopState.malformedRecoveryAttempts.set(String(toolName), attempt + 1);
74
+ callbacks.debugLog(`forcing smaller retry after malformed ${String(toolName)} input`);
75
+ // OpenAI-compatible servers differ in tool_choice support: several
76
+ // (LM Studio, llama.cpp) accept only the string form (none/auto/
77
+ // required) and reject the object form with HTTP 400. Narrowing to a
78
+ // single active tool plus 'required' preserves the forced-call
79
+ // semantics on every server.
80
+ return { activeTools: [toolName], toolChoice: 'required', messages: withSyntheticControl(scopedMessages, malformedToolCallPrompt(String(toolName), WRITE_FILE_CHUNK_BYTES)) };
81
+ }
82
+ if (loopState.toolResultState.editRecoveryPath && !loopState.toolResultState.editRecoveryReadSatisfied) {
83
+ if ('readFile' in sliceTools)
84
+ return messagesChanged ? { activeTools: ['readFile'], messages: scopedMessages } : { activeTools: ['readFile'] };
85
+ return { toolChoice: 'none', messages: withSyntheticControl(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.`) };
86
+ }
87
+ if (repeatedToolNames.length > 0) {
88
+ const activeTools = Object.keys(sliceTools).filter(name => !repeatedToolNames.includes(name));
89
+ callbacks.debugLog(`disabling repeated tools for next step: ${repeatedToolNames.join(', ')}`);
90
+ return activeTools.length > 0
91
+ ? { activeTools, messages: withSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) }
92
+ : { toolChoice: 'none', messages: withSyntheticControl(scopedMessages, repeatedToolCallPrompt(repeatedToolNames)) };
93
+ }
94
+ if (turnToolCallsExhausted || sliceToolCallsExhausted || toolOnlyBoundaryHit || toolCalls.length >= MAIN_TOOL_CALL_LIMIT) {
95
+ callbacks.debugLog('forcing text response to avoid tool loop');
96
+ return { toolChoice: 'none', messages: withSyntheticControl(scopedMessages, toolLoopBudgetPrompt()) };
97
+ }
98
+ return messagesChanged ? { messages: scopedMessages } : undefined;
99
+ };
100
+ }
@@ -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
  *
@@ -3,10 +3,6 @@ import { IDLE_TIMEOUT_MS, DEFAULT_MODEL_RETRIES } from '../../../core/agent/budg
3
3
  import { compactToolHistory, 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;