@denizokcu/haze 1.0.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 (116) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +17 -8
  3. package/SECURITY.md +3 -1
  4. package/dist/buildInfo.json +3 -3
  5. package/dist/cli/chat/TaskBar.js +1 -1
  6. package/dist/cli/chat/busyIndicator.d.ts +11 -0
  7. package/dist/cli/chat/busyIndicator.js +34 -0
  8. package/dist/cli/chat/chatMetrics.d.ts +0 -1
  9. package/dist/cli/chat/chatMetrics.js +1 -7
  10. package/dist/cli/chat/followUpQueue.d.ts +11 -0
  11. package/dist/cli/chat/followUpQueue.js +38 -0
  12. package/dist/cli/chat/inputSuggestions.js +1 -0
  13. package/dist/cli/chat/messages.d.ts +0 -22
  14. package/dist/cli/chat/messages.js +42 -87
  15. package/dist/cli/chat/sessionLifecycle.d.ts +3 -1
  16. package/dist/cli/chat/sessionLifecycle.js +6 -1
  17. package/dist/cli/chat/sessionRecorder.d.ts +2 -0
  18. package/dist/cli/chat/sessionRecorder.js +6 -0
  19. package/dist/cli/chat/startupSequence.d.ts +29 -0
  20. package/dist/cli/chat/startupSequence.js +59 -0
  21. package/dist/cli/chat/transcriptPartition.d.ts +23 -0
  22. package/dist/cli/chat/transcriptPartition.js +78 -0
  23. package/dist/cli/chat/wizard/fieldTransitions.d.ts +38 -0
  24. package/dist/cli/chat/wizard/fieldTransitions.js +43 -0
  25. package/dist/cli/chat/wizard/lspHandlers.d.ts +4 -0
  26. package/dist/cli/chat/wizard/lspHandlers.js +85 -0
  27. package/dist/cli/chat/wizard/mcpHandlers.d.ts +8 -0
  28. package/dist/cli/chat/wizard/mcpHandlers.js +82 -0
  29. package/dist/cli/chat/wizard/providerHandlers.d.ts +12 -0
  30. package/dist/cli/chat/wizard/providerHandlers.js +420 -0
  31. package/dist/cli/chat/wizard/sessionThemeHandlers.d.ts +4 -0
  32. package/dist/cli/chat/wizard/sessionThemeHandlers.js +48 -0
  33. package/dist/cli/chat/wizard/skillsHandlers.d.ts +4 -0
  34. package/dist/cli/chat/wizard/skillsHandlers.js +125 -0
  35. package/dist/cli/chat/wizard/types.d.ts +63 -0
  36. package/dist/cli/chat/wizard/types.js +24 -0
  37. package/dist/cli/chat/wizard/uiState.d.ts +56 -0
  38. package/dist/cli/chat/wizard/uiState.js +15 -0
  39. package/dist/cli/chat/wizardDispatch.d.ts +11 -113
  40. package/dist/cli/chat/wizardDispatch.js +41 -805
  41. package/dist/cli/commands/chat.js +89 -110
  42. package/dist/cli/commands/commandHelp.js +2 -0
  43. package/dist/cli/commands/commands.js +2 -0
  44. package/dist/cli/commands/formatters.d.ts +0 -3
  45. package/dist/cli/commands/formatters.js +6 -29
  46. package/dist/cli/commands/runCommand.d.ts +2 -0
  47. package/dist/cli/commands/runCommand.js +67 -4
  48. package/dist/cli/commands/settingsSummary.js +2 -0
  49. package/dist/cli/commands/streaming/assistantSegments.d.ts +19 -0
  50. package/dist/cli/commands/streaming/assistantSegments.js +48 -0
  51. package/dist/cli/commands/streaming/attemptOutcome.d.ts +2 -2
  52. package/dist/cli/commands/streaming/attemptOutcome.js +17 -7
  53. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +69 -8
  54. package/dist/cli/commands/streaming/goalCheckpoint.js +36 -1
  55. package/dist/cli/commands/streaming/goalSupervisor.d.ts +17 -2
  56. package/dist/cli/commands/streaming/goalSupervisor.js +62 -12
  57. package/dist/cli/commands/streaming/prepareStep.d.ts +35 -0
  58. package/dist/cli/commands/streaming/prepareStep.js +100 -0
  59. package/dist/cli/commands/streaming/recoverySlices.d.ts +15 -0
  60. package/dist/cli/commands/streaming/recoverySlices.js +29 -0
  61. package/dist/cli/commands/streaming/stallRecovery.d.ts +0 -1
  62. package/dist/cli/commands/streaming/stallRecovery.js +0 -4
  63. package/dist/cli/commands/streaming/streamLoop.js +9 -230
  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 +95 -0
  67. package/dist/cli/commands/streaming.d.ts +4 -1
  68. package/dist/cli/commands/streaming.js +6 -21
  69. package/dist/cli/commands/themesCommand.d.ts +17 -0
  70. package/dist/cli/commands/themesCommand.js +24 -0
  71. package/dist/cli/commands/wizardFlow.d.ts +7 -0
  72. package/dist/cli/commands/wizardFlow.js +20 -0
  73. package/dist/cli/index.js +3 -1
  74. package/dist/config/providerPresets.d.ts +7 -0
  75. package/dist/config/providerPresets.js +195 -391
  76. package/dist/config/settings.d.ts +2 -0
  77. package/dist/config/settings.js +1 -0
  78. package/dist/core/agent/completionController.d.ts +14 -7
  79. package/dist/core/agent/completionController.js +12 -6
  80. package/dist/core/agent/events.d.ts +12 -0
  81. package/dist/core/agent/goalPolicy.d.ts +4 -3
  82. package/dist/core/agent/goalPolicy.js +9 -4
  83. package/dist/core/agent/workState.d.ts +25 -15
  84. package/dist/core/agent/workState.js +71 -43
  85. package/dist/core/safety/secretPaths.d.ts +18 -0
  86. package/dist/core/safety/secretPaths.js +115 -0
  87. package/dist/core/session/sessionSlimming.js +8 -0
  88. package/dist/core/session/sessionStore.d.ts +61 -1
  89. package/dist/core/session/sessionStore.js +115 -6
  90. package/dist/llm/hazeTools.d.ts +64 -208
  91. package/dist/llm/hazeTools.js +6 -0
  92. package/dist/llm/systemPrompt.js +3 -1
  93. package/dist/llm/toolResultTypes.d.ts +1 -1
  94. package/dist/llm/tools/failures.d.ts +6 -0
  95. package/dist/llm/tools/failures.js +8 -2
  96. package/dist/llm/tools/readRecovery.js +2 -0
  97. package/dist/llm/tools/shellTool.js +3 -0
  98. package/dist/llm/tools/taskTool.d.ts +64 -208
  99. package/dist/llm/tools/taskTool.js +22 -10
  100. package/dist/llm/tools/workspaceFile.d.ts +4 -3
  101. package/dist/llm/tools/workspaceFile.js +30 -13
  102. package/dist/ui/components/Header.js +1 -1
  103. package/dist/ui/components/MarkdownText.js +10 -10
  104. package/dist/ui/components/TextInput.d.ts +1 -1
  105. package/dist/ui/components/TextInput.js +8 -69
  106. package/dist/ui/components/useInputSuggestions.d.ts +27 -0
  107. package/dist/ui/components/useInputSuggestions.js +98 -0
  108. package/dist/ui/terminalColors.d.ts +29 -0
  109. package/dist/ui/terminalColors.js +47 -0
  110. package/dist/ui/theme.d.ts +105 -10
  111. package/dist/ui/theme.js +125 -15
  112. package/dist/ui/themes/registry.d.ts +5 -0
  113. package/dist/ui/themes/registry.js +436 -0
  114. package/dist/utils/format.d.ts +10 -0
  115. package/dist/utils/format.js +45 -0
  116. package/package.json +1 -1
@@ -0,0 +1,48 @@
1
+ import { agentEvent } from '../../../core/agent/events.js';
2
+ import { assistantDisplayText, normalizeAssistantText, isHiddenAssistantFragment, isHiddenUnstartedFinalText, isShortLeadInBeforeTool, isShortUnfinishedLeadIn } from './assistantText.js';
3
+ import { responseCompletionMetrics } from './turnRuntime.js';
4
+ /**
5
+ * Assistant segment lifecycle (extracted from streamLoop.ts): one segment is
6
+ * the text between tool calls (or the final answer). Segments start lazily
7
+ * (gated by `shouldStartAssistantStream`), finalize with duplicate/lead-in
8
+ * suppression, and reset for the next segment.
9
+ */
10
+ export function resetAssistantSegment(loopState) {
11
+ loopState.currentAssistantId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
12
+ loopState.assistantStarted = false;
13
+ loopState.assistantStartedAt = Date.now();
14
+ loopState.currentAssistantText = '';
15
+ }
16
+ export function finalizeAssistantSegment(loopState, callbacks, options = {}) {
17
+ const finalText = assistantDisplayText(loopState.currentAssistantText);
18
+ const normalized = normalizeAssistantText(finalText);
19
+ const hidden = (loopState.assistantStarted ? isHiddenAssistantFragment(finalText) : isHiddenUnstartedFinalText(finalText))
20
+ || (options.beforeTool === true && isShortLeadInBeforeTool(finalText))
21
+ || (options.beforeTool !== true && isShortUnfinishedLeadIn(finalText))
22
+ || (normalized.length > 0 && loopState.visibleAssistantTexts.has(normalized));
23
+ if (loopState.assistantStarted) {
24
+ if (!hidden)
25
+ loopState.rememberVisibleAssistantText(finalText);
26
+ callbacks.onEvent?.(agentEvent({ type: 'message_end', id: loopState.currentAssistantId, text: finalText, hidden }));
27
+ callbacks.updateMessage(loopState.currentAssistantId, { text: finalText, streaming: false, hidden, ...responseCompletionMetrics(finalText, loopState.assistantStartedAt) });
28
+ }
29
+ else if (!hidden) {
30
+ if (!hidden)
31
+ loopState.rememberVisibleAssistantText(finalText);
32
+ callbacks.onEvent?.(agentEvent({ type: 'message_start', id: loopState.currentAssistantId, role: 'assistant' }));
33
+ callbacks.onEvent?.(agentEvent({ type: 'message_end', id: loopState.currentAssistantId, text: finalText, hidden: false }));
34
+ callbacks.addMessage({ id: loopState.currentAssistantId, role: 'assistant', text: finalText, streaming: false, startedAt: loopState.assistantStartedAt, ...responseCompletionMetrics(finalText, loopState.assistantStartedAt) });
35
+ }
36
+ resetAssistantSegment(loopState);
37
+ return !hidden;
38
+ }
39
+ /** Finalize any pending assistant text right before a tool call starts, demoting hidden lead-ins to the tool group caption. */
40
+ export function finalizePendingAssistantBeforeTool(deps) {
41
+ const { loopState, callbacks, toolDisplay } = deps;
42
+ if (loopState.currentAssistantText.trim().length > 0 || loopState.assistantStarted) {
43
+ const pending = assistantDisplayText(loopState.currentAssistantText);
44
+ const shown = finalizeAssistantSegment(loopState, callbacks, { beforeTool: true });
45
+ if (!shown && pending)
46
+ toolDisplay.setGroupCaption(pending);
47
+ }
48
+ }
@@ -30,9 +30,10 @@ export declare function terminalTurnStatus(input: {
30
30
  mutationCount?: number;
31
31
  validationOutcome?: ValidationOutcome;
32
32
  taskProgress?: WorkTaskProgress;
33
+ redPair?: 'not-required' | 'missing' | 'satisfied';
33
34
  }): TurnStatus;
34
35
  /** Bounded recovery slice an attempt proposes for the next agent call. */
35
- type AttemptRecovery = {
36
+ export type AttemptRecovery = {
36
37
  kind: 'length' | 'rescue' | 'goal';
37
38
  control: string;
38
39
  slice: {
@@ -93,4 +94,3 @@ export interface AttemptFailureDeps {
93
94
  * hard model-call failure. Completed-step progress is always preserved.
94
95
  */
95
96
  export declare function handleAttemptFailure(deps: AttemptFailureDeps): AgentAttemptResult;
96
- export {};
@@ -4,12 +4,13 @@ import { isContextOverflowError, isRetryableModelError } from '../../../core/age
4
4
  import { completionRescuePrompt, goalContinuationPrompt, lengthContinuationPrompt } from '../../../core/agent/goalPolicy.js';
5
5
  import { assessCompletionReadiness, classifyTerminalOutcome, decideGoalContinuation, decideLengthRecovery, decideRescue, describeCompletionReadiness, goalContinuationRecoverable, isBudgetExhausted, rescueEligibleRequest } from '../../../core/agent/completionController.js';
6
6
  import { clampSlice, remainingSteps, remainingToolCalls, DEFAULT_TURN_DEADLINE_MS, IDLE_TIMEOUT_MS, DEFAULT_MODEL_RETRIES } from '../../../core/agent/budgets.js';
7
- import { deriveValidationOutcome } from '../../../core/agent/workState.js';
7
+ import { deriveValidationOutcome, redPairStatus } from '../../../core/agent/workState.js';
8
8
  import { withoutRejectedAssistantFinal } from '../../../core/agent/requestAssembly.js';
9
- import { buildIncompleteGoalResume } from './goalCheckpoint.js';
10
- import { formatSeconds } from '../formatters.js';
9
+ import { buildIncompleteGoalResume, taskCountsOf } from './goalCheckpoint.js';
10
+ import { formatSeconds } from '../../../utils/format.js';
11
11
  import { retryDelayMs } from './turnRuntime.js';
12
- import { formatIdleMinutes, salvageConversationToLastStep } from './stallRecovery.js';
12
+ import { salvageConversationToLastStep } from './stallRecovery.js';
13
+ import { formatIdleMinutes } from '../../../utils/format.js';
13
14
  /**
14
15
  * CLI adapter for the authoritative turn-status decision. The pure policy
15
16
  * lives in `core/agent/completionController.ts`; this keeps the single call site
@@ -30,6 +31,7 @@ export function terminalTurnStatus(input) {
30
31
  mutationCount: input.mutationCount ?? 0,
31
32
  ...(input.validationOutcome ? { validationOutcome: input.validationOutcome } : {}),
32
33
  ...(input.taskProgress ? { taskProgress: input.taskProgress } : {}),
34
+ ...(input.redPair ? { redPair: input.redPair } : {}),
33
35
  };
34
36
  return decideTerminalStatus(state, {
35
37
  sawToolCall: input.sawToolCall,
@@ -46,6 +48,8 @@ export function projectGoalEvidence(turnState, goal) {
46
48
  turnState.validationKind = goal.validations.at(-1)?.kind ?? goal.carriedValidation?.kind;
47
49
  turnState.validationAfterMutation = goal.validationSeq > 0 && goal.validationSeq >= goal.mutationSeq;
48
50
  turnState.taskProgress = goal.taskProgress;
51
+ // Opportunistic red→green: only an actually observed red can gate.
52
+ turnState.redPair = redPairStatus(goal);
49
53
  }
50
54
  /**
51
55
  * Classify the finished attempt: project work evidence onto the turn state,
@@ -64,7 +68,7 @@ export function finalizeAttemptOutcome(deps) {
64
68
  const completionEvidence = { sawToolCall: stream.sawToolCall, assistantText: stream.assistantText, lastToolOk: stream.lastToolOk, unresolvedToolInputError: stream.unresolvedToolInputError };
65
69
  const readiness = assessCompletionReadiness(turnState, completionEvidence);
66
70
  const classification = classifyTerminalOutcome(turnState, completionEvidence);
67
- const turnStatus = terminalTurnStatus({ aborted: false, assistantText: stream.assistantText, sawToolCall: stream.sawToolCall, lastToolOk: stream.lastToolOk, finishReason: stream.finishReason, budgetReached: turnState.budgetBoundary, unresolvedToolInputError: stream.unresolvedToolInputError, intent: turnState.intent, mutationCount: turnState.mutationCount, validationOutcome: turnState.validationOutcome, taskProgress: turnState.taskProgress });
71
+ const turnStatus = terminalTurnStatus({ aborted: false, assistantText: stream.assistantText, sawToolCall: stream.sawToolCall, lastToolOk: stream.lastToolOk, finishReason: stream.finishReason, budgetReached: turnState.budgetBoundary, unresolvedToolInputError: stream.unresolvedToolInputError, intent: turnState.intent, mutationCount: turnState.mutationCount, validationOutcome: turnState.validationOutcome, taskProgress: turnState.taskProgress, ...(turnState.redPair ? { redPair: turnState.redPair } : {}) });
68
72
  if (stream.unresolvedMalformedToolName)
69
73
  callbacks.addMessage({ role: 'system', text: `${stream.unresolvedMalformedToolName} did not execute because its generated input remained invalid or truncated. The requested work is incomplete.` });
70
74
  goal.phase = 'done';
@@ -89,10 +93,16 @@ export function finalizeAttemptOutcome(deps) {
89
93
  // physical turns; a bare runAgentTurn caller surfaces them as resume info.
90
94
  const goalId = turnOptions.goalContext?.goalId ?? goal.id;
91
95
  const goalCycle = turnOptions.goalContext?.cycle ?? 1;
96
+ const carriedEvidence = {
97
+ ...(turnOptions.goalContext?.requestHash ? { requestHash: turnOptions.goalContext.requestHash } : {}),
98
+ // Carry red evidence until the same check passes after the mutation. This
99
+ // includes boundaries reached after red capture but before the first edit.
100
+ ...(turnState.redPair !== 'satisfied' && goal.redEvidence ? { redEvidence: { ...goal.redEvidence } } : {}),
101
+ };
92
102
  const discardRejectedFinal = () => callbacks.setConversation(withoutRejectedAssistantFinal(callbacks.getConversation()));
93
103
  const checkpointResult = () => {
94
104
  discardRejectedFinal();
95
- return { status: 'failed', resume: buildIncompleteGoalResume(value, goalId, goalCycle, turnState, readiness) };
105
+ return { status: 'failed', resume: buildIncompleteGoalResume(value, goalId, goalCycle, turnState, readiness, carriedEvidence) };
96
106
  };
97
107
  if (!abortController.signal.aborted) {
98
108
  const lengthDecision = decideLengthRecovery(turnState, turnBudget);
@@ -116,7 +126,7 @@ export function finalizeAttemptOutcome(deps) {
116
126
  discardRejectedFinal();
117
127
  if (readiness === 'validation_failed' || readiness === 'validation_stale' || readiness === 'validation_absent_after_mutation')
118
128
  turnState.validationContinuationUsed = true;
119
- return { status: turnStatus, recovery: { kind: 'goal', control: goalContinuationPrompt(describeCompletionReadiness(readiness, turnState.taskProgress)), slice: { maxSteps: goalSlice.steps, maxToolCalls: goalSlice.toolCalls } } };
129
+ return { status: turnStatus, recovery: { kind: 'goal', control: goalContinuationPrompt(describeCompletionReadiness(readiness, turnState.taskProgress), taskCountsOf(turnState.taskProgress)), slice: { maxSteps: goalSlice.steps, maxToolCalls: goalSlice.toolCalls } } };
120
130
  }
121
131
  else if (rescueSlice && rescueSlice.steps > 0) {
122
132
  return { status: turnStatus, recovery: { kind: 'rescue', control: completionRescuePrompt(), slice: { maxSteps: rescueSlice.steps, maxToolCalls: rescueSlice.toolCalls } } };
@@ -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 {};