@denizokcu/haze 1.2.0 → 1.5.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.
- package/CHANGELOG.md +86 -1
- package/README.md +23 -10
- package/SECURITY.md +1 -1
- package/bin/haze.js +27 -7
- package/dist/buildInfo.json +3 -3
- package/dist/cli/chat/BusyBar.d.ts +7 -0
- package/dist/cli/chat/BusyBar.js +8 -0
- package/dist/cli/chat/DynamicFrame.d.ts +37 -0
- package/dist/cli/chat/DynamicFrame.js +43 -0
- package/dist/cli/chat/busyIndicator.d.ts +3 -1
- package/dist/cli/chat/busyIndicator.js +11 -9
- package/dist/cli/chat/chatMetrics.d.ts +1 -1
- package/dist/cli/chat/chatMetrics.js +3 -3
- package/dist/cli/chat/inputSuggestions.js +4 -0
- package/dist/cli/chat/liveMessages.d.ts +36 -0
- package/dist/cli/chat/liveMessages.js +64 -0
- package/dist/cli/chat/liveRegion.js +1 -1
- package/dist/cli/chat/messages.js +27 -16
- package/dist/cli/chat/sessionLifecycle.d.ts +5 -2
- package/dist/cli/chat/sessionLifecycle.js +36 -4
- package/dist/cli/chat/sessionRecorder.d.ts +2 -1
- package/dist/cli/chat/sessionRecorder.js +8 -0
- package/dist/cli/chat/shutdown.d.ts +27 -0
- package/dist/cli/chat/shutdown.js +79 -0
- package/dist/cli/chat/terminalControl.d.ts +45 -0
- package/dist/cli/chat/terminalControl.js +107 -0
- package/dist/cli/chat/tips.js +1 -0
- package/dist/cli/chat/userInput.d.ts +43 -0
- package/dist/cli/chat/userInput.js +63 -0
- package/dist/cli/chat/wizard/sessionThemeHandlers.d.ts +1 -1
- package/dist/cli/chat/wizard/sessionThemeHandlers.js +24 -1
- package/dist/cli/chat/wizard/types.d.ts +8 -1
- package/dist/cli/chat/wizardDispatch.js +1 -1
- package/dist/cli/commands/chat.js +277 -193
- package/dist/cli/commands/commandHelp.js +6 -0
- package/dist/cli/commands/commands.d.ts +8 -0
- package/dist/cli/commands/commands.js +13 -0
- package/dist/cli/commands/formatters.d.ts +1 -1
- package/dist/cli/commands/formatters.js +25 -3
- package/dist/cli/commands/logsCommand.js +21 -2
- package/dist/cli/commands/ndjsonSink.d.ts +12 -0
- package/dist/cli/commands/ndjsonSink.js +29 -0
- package/dist/cli/commands/reasoningCommand.d.ts +44 -0
- package/dist/cli/commands/reasoningCommand.js +79 -0
- package/dist/cli/commands/runCommand.d.ts +14 -0
- package/dist/cli/commands/runCommand.js +56 -22
- package/dist/cli/commands/settingsSummary.js +2 -0
- package/dist/cli/commands/streaming/agentAttempt.d.ts +3 -0
- package/dist/cli/commands/streaming/agentAttempt.js +2 -2
- package/dist/cli/commands/streaming/assistantSegments.d.ts +0 -7
- package/dist/cli/commands/streaming/assistantSegments.js +1 -1
- package/dist/cli/commands/streaming/attemptLifecycle.js +13 -9
- package/dist/cli/commands/streaming/attemptOutcome.d.ts +2 -0
- package/dist/cli/commands/streaming/attemptOutcome.js +24 -9
- package/dist/cli/commands/streaming/attemptSetup.d.ts +4 -0
- package/dist/cli/commands/streaming/attemptSetup.js +21 -7
- package/dist/cli/commands/streaming/goalCheckpoint.d.ts +14 -1
- package/dist/cli/commands/streaming/goalCheckpoint.js +4 -2
- package/dist/cli/commands/streaming/goalSupervisor.d.ts +9 -0
- package/dist/cli/commands/streaming/goalSupervisor.js +51 -10
- package/dist/cli/commands/streaming/prepareStep.d.ts +0 -3
- package/dist/cli/commands/streaming/prepareStep.js +14 -5
- package/dist/cli/commands/streaming/streamLoop.d.ts +5 -0
- package/dist/cli/commands/streaming/streamLoop.js +3 -0
- package/dist/cli/commands/streaming/toolPartHandlers.js +6 -0
- package/dist/cli/commands/streaming.d.ts +8 -3
- package/dist/cli/commands/streaming.js +46 -21
- package/dist/cli/commands/wizardFlow.d.ts +10 -0
- package/dist/cli/commands/wizardFlow.js +34 -5
- package/dist/cli/index.js +22 -2
- package/dist/config/contextFiles.d.ts +9 -0
- package/dist/config/contextFiles.js +21 -1
- package/dist/config/modelCatalog.d.ts +3 -0
- package/dist/config/modelCatalog.js +29 -0
- package/dist/config/modelDiscovery.js +68 -5
- package/dist/config/providerPresets.d.ts +1 -1
- package/dist/config/providerPresets.js +42 -3
- package/dist/config/settings.d.ts +14 -6
- package/dist/config/settings.js +16 -1
- package/dist/core/agent/budgets.d.ts +13 -17
- package/dist/core/agent/budgets.js +15 -19
- package/dist/core/agent/completionController.d.ts +14 -2
- package/dist/core/agent/completionController.js +48 -3
- package/dist/core/agent/events.d.ts +2 -1
- package/dist/core/agent/goalPolicy.d.ts +17 -0
- package/dist/core/agent/goalPolicy.js +53 -6
- package/dist/core/agent/projectPreflight.d.ts +2 -0
- package/dist/core/agent/projectPreflight.js +56 -0
- package/dist/core/agent/reasoningPolicy.d.ts +76 -10
- package/dist/core/agent/reasoningPolicy.js +72 -9
- package/dist/core/agent/toolCapabilities.d.ts +3 -3
- package/dist/core/agent/toolCapabilities.js +31 -7
- package/dist/core/agent/workState.d.ts +14 -4
- package/dist/core/agent/workState.js +229 -34
- package/dist/core/deadline.js +22 -24
- package/dist/core/providerContracts.d.ts +29 -0
- package/dist/core/providerContracts.js +1 -0
- package/dist/core/safety/secretPaths.js +10 -7
- package/dist/core/safety/shellClassifier.d.ts +2 -0
- package/dist/core/safety/shellClassifier.js +9 -1
- package/dist/core/session/sessionReport.d.ts +33 -0
- package/dist/core/session/sessionReport.js +121 -0
- package/dist/core/session/sessionSlimming.d.ts +2 -0
- package/dist/core/session/sessionSlimming.js +59 -4
- package/dist/core/session/sessionStore.d.ts +16 -8
- package/dist/core/session/sessionStore.js +71 -34
- package/dist/core/shellOutput/reducers/git.js +7 -2
- package/dist/core/shellOutput/reducers/validation.d.ts +1 -1
- package/dist/core/shellOutput/reducers/validation.js +14 -1
- package/dist/core/shellOutput/registry.js +3 -2
- package/dist/core/subagent/contracts.d.ts +3 -18
- package/dist/core/subagent/executionProfiles.js +4 -4
- package/dist/core/tasks/taskStorage.js +8 -1
- package/dist/core/validation/outputParser.d.ts +6 -1
- package/dist/core/validation/outputParser.js +30 -2
- package/dist/llm/client.d.ts +6 -3
- package/dist/llm/client.js +28 -11
- package/dist/llm/hazeTools.d.ts +9161 -7135
- package/dist/llm/hazeTools.js +6 -462
- package/dist/llm/lsp/client.d.ts +7 -1
- package/dist/llm/lsp/client.js +58 -9
- package/dist/llm/lsp/pool.d.ts +11 -0
- package/dist/llm/lsp/pool.js +61 -4
- package/dist/llm/lsp/protocol.d.ts +6 -23
- package/dist/llm/lsp/requests.d.ts +54 -60
- package/dist/llm/lsp/requests.js +152 -28
- package/dist/llm/lsp/symbols.d.ts +16 -0
- package/dist/llm/lsp/symbols.js +70 -0
- package/dist/llm/lsp/workspaceEdit.d.ts +43 -0
- package/dist/llm/lsp/workspaceEdit.js +117 -0
- package/dist/llm/lspTools.d.ts +7518 -2859
- package/dist/llm/lspTools.js +195 -110
- package/dist/llm/mcp.js +3 -0
- package/dist/llm/requestContext.d.ts +4 -3
- package/dist/llm/requestContext.js +9 -5
- package/dist/{core/subagent → llm}/subagentRunner.d.ts +13 -9
- package/dist/{core/subagent → llm}/subagentRunner.js +54 -49
- package/dist/llm/systemPrompt.d.ts +11 -1
- package/dist/llm/systemPrompt.js +4 -13
- package/dist/llm/tools/fetchTool.d.ts +34 -30
- package/dist/llm/tools/fileTools.d.ts +7768 -0
- package/dist/llm/tools/fileTools.js +510 -0
- package/dist/llm/tools/processTool.d.ts +34 -30
- package/dist/llm/tools/replaceInFiles.d.ts +105 -0
- package/dist/llm/tools/replaceInFiles.js +131 -0
- package/dist/llm/tools/shellTool.d.ts +34 -30
- package/dist/llm/tools/shellTool.js +8 -4
- package/dist/llm/tools/storedOutputTool.d.ts +4 -0
- package/dist/llm/tools/taskTool.d.ts +4 -0
- package/dist/llm/tools/toolContext.d.ts +3 -29
- package/dist/llm/tools/toolContext.js +56 -53
- package/dist/llm/tools/toolContextState.d.ts +40 -0
- package/dist/llm/tools/toolContextState.js +34 -0
- package/dist/llm/workerContext.d.ts +7 -0
- package/dist/llm/workerContext.js +18 -1
- package/dist/skills/SkillLoader.js +30 -4
- package/dist/skills/SkillRegistry.js +3 -3
- package/dist/skills/builder/SkillBuilder.js +3 -3
- package/dist/skills/confinement.d.ts +7 -0
- package/dist/skills/confinement.js +15 -0
- package/dist/ui/codeHighlight.js +4 -4
- package/dist/ui/components/MarkdownText.js +7 -8
- package/dist/ui/components/NativeIndicators.d.ts +15 -0
- package/dist/ui/components/NativeIndicators.js +32 -0
- package/dist/ui/components/StreamingMarkdownText.d.ts +9 -0
- package/dist/ui/components/StreamingMarkdownText.js +38 -0
- package/dist/ui/components/TextInput.d.ts +7 -2
- package/dist/ui/components/TextInput.js +103 -46
- package/dist/ui/components/WizardChoices.d.ts +18 -0
- package/dist/ui/components/WizardChoices.js +32 -0
- package/dist/ui/components/useInputSuggestions.js +18 -6
- package/dist/ui/inputBuffer.js +12 -6
- package/dist/ui/textGeometry.d.ts +14 -0
- package/dist/ui/textGeometry.js +31 -0
- package/dist/utils/buildInfo.js +29 -8
- package/dist/utils/fs.js +5 -1
- package/package.json +23 -22
- /package/dist/cli/{contextReport.d.ts → contextReportCli.d.ts} +0 -0
- /package/dist/cli/{contextReport.js → contextReportCli.js} +0 -0
|
@@ -15,7 +15,7 @@ import { ATTEMPT_TEARDOWN_BOUND_MS } from './attemptLifecycle.js';
|
|
|
15
15
|
* display are always torn down.
|
|
16
16
|
*/
|
|
17
17
|
export async function runAgentAttempt(input) {
|
|
18
|
-
const { value, contextFiles, callbacks, retryingExistingRequest, session, modelOverride, abortController, turnOptions, turnScope, turnState, turnBudget, globalBudget, sliceBudget, goal, abortCause, cleanup, remainingTurnDeadlineMs, usageAnchor } = input;
|
|
18
|
+
const { value, contextFiles, callbacks, retryingExistingRequest, session, modelOverride, reasoningOverride, abortController, turnOptions, turnScope, turnState, turnBudget, globalBudget, sliceBudget, goal, abortCause, cleanup, remainingTurnDeadlineMs, usageAnchor } = input;
|
|
19
19
|
// Pillar 1.3: progress since the previous retry resets the shared retry pool
|
|
20
20
|
// (mirrors a per-burst budget), applied to both the stall guard's retry
|
|
21
21
|
// eligibility and the failure classification below.
|
|
@@ -47,7 +47,7 @@ export async function runAgentAttempt(input) {
|
|
|
47
47
|
let stallGuard;
|
|
48
48
|
let setup;
|
|
49
49
|
try {
|
|
50
|
-
setup = await prepareAttempt({ value, contextFiles, callbacks, retryingExistingRequest, overflowShrinkFactor: input.overflowShrinkFactor, session, modelOverride, abortController, turnOptions, turnScope, turnBudget, globalBudget, sliceBudget, goal, onContextFileRead: path => toolDisplay.addContextFileRead(path), usageAnchor });
|
|
50
|
+
setup = await prepareAttempt({ value, contextFiles, callbacks, retryingExistingRequest, overflowShrinkFactor: input.overflowShrinkFactor, session, modelOverride, reasoningOverride, abortController, turnOptions, turnScope, turnBudget, globalBudget, sliceBudget, goal, onContextFileRead: path => toolDisplay.addContextFileRead(path), usageAnchor });
|
|
51
51
|
if (!setup)
|
|
52
52
|
return { status: 'failed' };
|
|
53
53
|
const attemptSetupResult = setup;
|
|
@@ -1,13 +1,6 @@
|
|
|
1
1
|
import type { StreamCallbacks } from '../streaming.js';
|
|
2
2
|
import type { ToolGroupRenderer } from './toolGroupRenderer.js';
|
|
3
3
|
import type { AttemptLoopState } from './streamLoop.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 declare function resetAssistantSegment(loopState: AttemptLoopState): void;
|
|
11
4
|
export declare function finalizeAssistantSegment(loopState: AttemptLoopState, callbacks: StreamCallbacks, options?: {
|
|
12
5
|
beforeTool?: boolean;
|
|
13
6
|
}): boolean;
|
|
@@ -7,7 +7,7 @@ import { responseCompletionMetrics } from './turnRuntime.js';
|
|
|
7
7
|
* (gated by `shouldStartAssistantStream`), finalize with duplicate/lead-in
|
|
8
8
|
* suppression, and reset for the next segment.
|
|
9
9
|
*/
|
|
10
|
-
|
|
10
|
+
function resetAssistantSegment(loopState) {
|
|
11
11
|
loopState.currentAssistantId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
12
12
|
loopState.assistantStarted = false;
|
|
13
13
|
loopState.assistantStartedAt = Date.now();
|
|
@@ -41,20 +41,24 @@ export function createQuarantinableCallbacks(callbacks) {
|
|
|
41
41
|
// a quarantined call must answer "not compacted" instead of undefined.
|
|
42
42
|
const whileLiveBoolean = (fn) => (...args) => (state.quarantined ? false : fn(...args));
|
|
43
43
|
const guarded = {
|
|
44
|
-
|
|
44
|
+
// Enumerate every callback so new fields require an explicit quarantine decision.
|
|
45
|
+
debugLog: callbacks.debugLog,
|
|
46
|
+
getConversation: callbacks.getConversation,
|
|
47
|
+
getLastAssistantText: callbacks.getLastAssistantText,
|
|
45
48
|
addMessage: whileLive(callbacks.addMessage),
|
|
46
49
|
updateMessage: whileLive(callbacks.updateMessage),
|
|
47
50
|
setConversation: whileLive(callbacks.setConversation),
|
|
48
51
|
setBusy: whileLive(callbacks.setBusy),
|
|
49
52
|
setLastAssistantText: whileLive(callbacks.setLastAssistantText),
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
53
|
+
setBusyLabel: callbacks.setBusyLabel && whileLive(callbacks.setBusyLabel),
|
|
54
|
+
setAbortController: callbacks.setAbortController && whileLive(callbacks.setAbortController),
|
|
55
|
+
setGoalStatus: callbacks.setGoalStatus && whileLive(callbacks.setGoalStatus),
|
|
56
|
+
onEvent: callbacks.onEvent && whileLive(callbacks.onEvent),
|
|
57
|
+
compactConversation: callbacks.compactConversation && whileLiveBoolean(callbacks.compactConversation),
|
|
58
|
+
recordCompaction: callbacks.recordCompaction && whileLive(callbacks.recordCompaction),
|
|
59
|
+
recordTokenUsage: callbacks.recordTokenUsage && whileLive(callbacks.recordTokenUsage),
|
|
60
|
+
setWorkState: callbacks.setWorkState && whileLive(callbacks.setWorkState),
|
|
61
|
+
onTasksChanged: callbacks.onTasksChanged && whileLive(callbacks.onTasksChanged),
|
|
58
62
|
get log() {
|
|
59
63
|
return state.quarantined ? undefined : callbacks.log;
|
|
60
64
|
},
|
|
@@ -23,6 +23,7 @@ export declare function terminalTurnStatus(input: {
|
|
|
23
23
|
assistantText: string;
|
|
24
24
|
sawToolCall: boolean;
|
|
25
25
|
lastToolOk?: boolean;
|
|
26
|
+
lastFailedToolWasValidation?: boolean;
|
|
26
27
|
finishReason?: string;
|
|
27
28
|
budgetReached?: boolean;
|
|
28
29
|
unresolvedToolInputError?: boolean;
|
|
@@ -30,6 +31,7 @@ export declare function terminalTurnStatus(input: {
|
|
|
30
31
|
mutationCount?: number;
|
|
31
32
|
validationOutcome?: ValidationOutcome;
|
|
32
33
|
taskProgress?: WorkTaskProgress;
|
|
34
|
+
requiresTaskLedger?: boolean;
|
|
33
35
|
redPair?: 'not-required' | 'missing' | 'satisfied';
|
|
34
36
|
}): TurnStatus;
|
|
35
37
|
/** Bounded recovery slice an attempt proposes for the next agent call. */
|
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import { createTurnExecutionState, decideTerminalStatus, normalizeFinishReason } from '../../../core/agent/completionController.js';
|
|
1
|
+
import { assessCompletionReadiness, classifyTerminalOutcome, createTurnExecutionState, decideGoalContinuation, decideLengthRecovery, decideRescue, decideTerminalStatus, describeCompletionReadiness, goalContinuationRecoverable, isBudgetExhausted, normalizeFinishReason, rescueEligibleRequest } from '../../../core/agent/completionController.js';
|
|
2
2
|
import { agentEvent } from '../../../core/agent/events.js';
|
|
3
3
|
import { isContextOverflowError, isRetryableModelError } from '../../../core/agent/errors.js';
|
|
4
4
|
import { completionRescuePrompt, goalContinuationPrompt, lengthContinuationPrompt } from '../../../core/agent/goalPolicy.js';
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import { deriveValidationOutcome, redPairStatus } from '../../../core/agent/workState.js';
|
|
5
|
+
import { clampSlice, DEFAULT_MODEL_RETRIES, DEFAULT_RETRY_BASE_DELAY_MS, MAX_OVERFLOW_RETRIES, OVERFLOW_SHRINK_FACTOR, remainingSteps, remainingToolCalls, IDLE_TIMEOUT_MS } from '../../../core/agent/budgets.js';
|
|
6
|
+
import { deriveValidationOutcome, redPairStatus, unresolvedFailedCheckIds } from '../../../core/agent/workState.js';
|
|
8
7
|
import { withoutRejectedAssistantFinal } from '../../../core/agent/requestAssembly.js';
|
|
9
8
|
import { buildIncompleteGoalResume, taskCountsOf } from './goalCheckpoint.js';
|
|
10
9
|
import { formatSeconds } from '../../../utils/format.js';
|
|
@@ -31,12 +30,14 @@ export function terminalTurnStatus(input) {
|
|
|
31
30
|
mutationCount: input.mutationCount ?? 0,
|
|
32
31
|
...(input.validationOutcome ? { validationOutcome: input.validationOutcome } : {}),
|
|
33
32
|
...(input.taskProgress ? { taskProgress: input.taskProgress } : {}),
|
|
33
|
+
requiresTaskLedger: Boolean(input.requiresTaskLedger),
|
|
34
34
|
...(input.redPair ? { redPair: input.redPair } : {}),
|
|
35
35
|
};
|
|
36
36
|
return decideTerminalStatus(state, {
|
|
37
37
|
sawToolCall: input.sawToolCall,
|
|
38
38
|
assistantText: input.assistantText,
|
|
39
39
|
lastToolOk: input.lastToolOk,
|
|
40
|
+
lastFailedToolWasValidation: Boolean(input.lastFailedToolWasValidation),
|
|
40
41
|
unresolvedToolInputError: Boolean(input.unresolvedToolInputError),
|
|
41
42
|
}, Boolean(input.budgetReached));
|
|
42
43
|
}
|
|
@@ -48,6 +49,7 @@ export function projectGoalEvidence(turnState, goal) {
|
|
|
48
49
|
turnState.validationKind = goal.validations.at(-1)?.kind ?? goal.carriedValidation?.kind;
|
|
49
50
|
turnState.validationAfterMutation = goal.validationSeq > 0 && goal.validationSeq >= goal.mutationSeq;
|
|
50
51
|
turnState.taskProgress = goal.taskProgress;
|
|
52
|
+
turnState.requiresTaskLedger = Boolean(goal.requiresTaskLedger);
|
|
51
53
|
// Opportunistic red→green: only an actually observed red can gate.
|
|
52
54
|
turnState.redPair = redPairStatus(goal);
|
|
53
55
|
}
|
|
@@ -65,10 +67,10 @@ export function finalizeAttemptOutcome(deps) {
|
|
|
65
67
|
// terminal paths report the same cumulative state.
|
|
66
68
|
projectGoalEvidence(turnState, goal);
|
|
67
69
|
turnState.budgetBoundary = isBudgetExhausted(turnState, turnBudget);
|
|
68
|
-
const completionEvidence = { sawToolCall: stream.sawToolCall, assistantText: stream.assistantText, lastToolOk: stream.lastToolOk, unresolvedToolInputError: stream.unresolvedToolInputError };
|
|
70
|
+
const completionEvidence = { sawToolCall: stream.sawToolCall, assistantText: stream.assistantText, lastToolOk: stream.lastToolOk, lastFailedToolWasValidation: stream.lastFailedToolWasValidation, unresolvedToolInputError: stream.unresolvedToolInputError };
|
|
69
71
|
const readiness = assessCompletionReadiness(turnState, completionEvidence);
|
|
70
72
|
const classification = classifyTerminalOutcome(turnState, completionEvidence);
|
|
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 } : {}) });
|
|
73
|
+
const turnStatus = terminalTurnStatus({ aborted: false, assistantText: stream.assistantText, sawToolCall: stream.sawToolCall, lastToolOk: stream.lastToolOk, lastFailedToolWasValidation: stream.lastFailedToolWasValidation, finishReason: stream.finishReason, budgetReached: turnState.budgetBoundary, unresolvedToolInputError: stream.unresolvedToolInputError, intent: turnState.intent, mutationCount: turnState.mutationCount, validationOutcome: turnState.validationOutcome, taskProgress: turnState.taskProgress, requiresTaskLedger: turnState.requiresTaskLedger, ...(turnState.redPair ? { redPair: turnState.redPair } : {}) });
|
|
72
74
|
if (stream.unresolvedMalformedToolName)
|
|
73
75
|
callbacks.addMessage({ role: 'system', text: `${stream.unresolvedMalformedToolName} did not execute because its generated input remained invalid or truncated. The requested work is incomplete.` });
|
|
74
76
|
goal.phase = 'done';
|
|
@@ -116,6 +118,8 @@ export function finalizeAttemptOutcome(deps) {
|
|
|
116
118
|
// Carry red evidence until the same check passes after the mutation. This
|
|
117
119
|
// includes boundaries reached after red capture but before the first edit.
|
|
118
120
|
...(turnState.redPair !== 'satisfied' && goal.redEvidence ? { redEvidence: { ...goal.redEvidence } } : {}),
|
|
121
|
+
...(turnState.validationKind ? { validationKind: turnState.validationKind } : {}),
|
|
122
|
+
...(unresolvedFailedCheckIds(goal).length ? { failedCheckIds: unresolvedFailedCheckIds(goal) } : {}),
|
|
119
123
|
};
|
|
120
124
|
const discardRejectedFinal = () => callbacks.setConversation(withoutRejectedAssistantFinal(callbacks.getConversation()));
|
|
121
125
|
const checkpointResult = () => {
|
|
@@ -144,7 +148,7 @@ export function finalizeAttemptOutcome(deps) {
|
|
|
144
148
|
discardRejectedFinal();
|
|
145
149
|
if (readiness === 'validation_failed' || readiness === 'validation_stale' || readiness === 'validation_absent_after_mutation')
|
|
146
150
|
turnState.validationContinuationUsed = true;
|
|
147
|
-
return { status: turnStatus, recovery: { kind: 'goal', control: goalContinuationPrompt(describeCompletionReadiness(readiness, turnState.taskProgress), taskCountsOf(turnState.taskProgress)), slice: { maxSteps: goalSlice.steps, maxToolCalls: goalSlice.toolCalls } } };
|
|
151
|
+
return { status: turnStatus, recovery: { kind: 'goal', control: goalContinuationPrompt(describeCompletionReadiness(readiness, turnState.taskProgress), taskCountsOf(turnState.taskProgress), turnState.redPair === 'missing' ? 'The captured pre-edit failing check still needs the same validation command to pass after the fix.' : undefined), slice: { maxSteps: goalSlice.steps, maxToolCalls: goalSlice.toolCalls } } };
|
|
148
152
|
}
|
|
149
153
|
else if (rescueSlice && rescueSlice.steps > 0) {
|
|
150
154
|
return { status: turnStatus, recovery: { kind: 'rescue', control: completionRescuePrompt(), slice: { maxSteps: rescueSlice.steps, maxToolCalls: rescueSlice.toolCalls } } };
|
|
@@ -211,7 +215,7 @@ export function handleAttemptFailure(deps) {
|
|
|
211
215
|
// the bound), but completed-step progress stays in the conversation.
|
|
212
216
|
turnState.aborted = true;
|
|
213
217
|
callbacks.debugLog('turn exceeded the absolute deadline');
|
|
214
|
-
callbacks.addMessage({ role: 'system', text: `Turn stopped: the ${formatIdleMinutes(abortCause.timeoutMs ??
|
|
218
|
+
callbacks.addMessage({ role: 'system', text: `Turn stopped: the ${formatIdleMinutes(abortCause.timeoutMs ?? 0)} turn budget elapsed before the model finished. Completed steps are preserved in the conversation; send a follow-up to continue.` });
|
|
215
219
|
return { status: 'aborted', abortReason: 'turn-deadline' };
|
|
216
220
|
}
|
|
217
221
|
turnState.aborted = true;
|
|
@@ -227,7 +231,18 @@ export function handleAttemptFailure(deps) {
|
|
|
227
231
|
if (overflowRetries >= MAX_OVERFLOW_RETRIES && isContextOverflowError(error)) {
|
|
228
232
|
callbacks.onEvent?.(agentEvent({ type: 'context_overflow', recovered: false, error: text }));
|
|
229
233
|
callbacks.addMessage({ role: 'system', text: 'Context overflow persisted after bounded compaction retries; pausing the goal with a checkpoint. Completed work is preserved in the conversation. Press R to resume after compacting or clearing context, or switch to a larger-context model.' });
|
|
230
|
-
|
|
234
|
+
// Project the goal's evidence before checkpointing: the failing attempt
|
|
235
|
+
// threw before finalizeAttemptOutcome, so its validation outcome/kind and
|
|
236
|
+
// unresolved red evidence would otherwise be lost from the checkpoint
|
|
237
|
+
// (R2-02) — a resumed goal must still owe the same checks.
|
|
238
|
+
projectGoalEvidence(turnState, goal);
|
|
239
|
+
const carried = {
|
|
240
|
+
...(turnOptions.goalContext?.requestHash ? { requestHash: turnOptions.goalContext.requestHash } : {}),
|
|
241
|
+
...(redPairStatus(goal) !== 'satisfied' && goal.redEvidence ? { redEvidence: { ...goal.redEvidence } } : {}),
|
|
242
|
+
...(turnState.validationKind ? { validationKind: turnState.validationKind } : {}),
|
|
243
|
+
...(unresolvedFailedCheckIds(goal).length ? { failedCheckIds: unresolvedFailedCheckIds(goal) } : {}),
|
|
244
|
+
};
|
|
245
|
+
return { status: 'failed', resume: buildIncompleteGoalResume(value, turnOptions.goalContext?.goalId ?? goal.id, turnOptions.goalContext?.cycle ?? 1, turnState, 'context_exhausted', carried) };
|
|
231
246
|
}
|
|
232
247
|
if (isContextOverflowError(error)) {
|
|
233
248
|
const canCompact = typeof callbacks.compactConversation === 'function';
|
|
@@ -4,6 +4,7 @@ import { type ToolExecutionBudgetState, type TurnBudget } from '../../../core/ag
|
|
|
4
4
|
import { type SessionGoal } from '../../../core/agent/goalPolicy.js';
|
|
5
5
|
import { calculateRequestTokenBudget, type ContextUsageAnchor } from '../../../core/agent/contextBudget.js';
|
|
6
6
|
import { providerRequestSettings, type ModelRuntimeSelection } from '../../../llm/client.js';
|
|
7
|
+
import type { StoredReasoningSetting } from '../../../core/agent/reasoningPolicy.js';
|
|
7
8
|
import { type ToolCategory, type TurnExecutionScope } from '../../../llm/requestContext.js';
|
|
8
9
|
import type { LoadedMcpTools } from '../../../llm/mcp.js';
|
|
9
10
|
import type { LspPool } from '../../../llm/lsp/pool.js';
|
|
@@ -49,6 +50,7 @@ export interface AttemptSetup {
|
|
|
49
50
|
modelRetries: number;
|
|
50
51
|
/** Backoff base for the shared model-retry pool, from the `retryBaseDelayMs` setting (default 1000ms). */
|
|
51
52
|
retryBaseDelayMs: number;
|
|
53
|
+
steeringProfile: 'standard' | 'compact';
|
|
52
54
|
}
|
|
53
55
|
export interface AttemptSetupDeps {
|
|
54
56
|
value: string;
|
|
@@ -59,6 +61,8 @@ export interface AttemptSetupDeps {
|
|
|
59
61
|
overflowShrinkFactor: number;
|
|
60
62
|
session: PromptSession | undefined;
|
|
61
63
|
modelOverride: string | undefined;
|
|
64
|
+
/** Run-scoped reasoning level/sentinel (CLI `--reasoning`); overrides the stored setting for this run. */
|
|
65
|
+
reasoningOverride: StoredReasoningSetting | undefined;
|
|
62
66
|
abortController: AbortController;
|
|
63
67
|
turnOptions: TurnExecutionOptions;
|
|
64
68
|
turnScope: {
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { readSettings } from '../../../config/settings.js';
|
|
2
2
|
import { DEFAULT_MAX_OUTPUT_TOKENS, DEFAULT_RETRY_BASE_DELAY_MS, MAIN_STEP_LIMIT, MAIN_TOOL_CALL_LIMIT, SUBAGENT_TOOL_DEADLINE_MS, DEFAULT_TOOL_DEADLINE_MS, DEFAULT_MODEL_RETRIES, withToolExecutionBudget } from '../../../core/agent/budgets.js';
|
|
3
3
|
import { agentEvent } from '../../../core/agent/events.js';
|
|
4
|
-
import { isPlanOnlyRequest } from '../../../core/agent/goalPolicy.js';
|
|
4
|
+
import { goalDirectionPrompt, isPlanOnlyRequest } from '../../../core/agent/goalPolicy.js';
|
|
5
|
+
import { projectPreflight } from '../../../core/agent/projectPreflight.js';
|
|
5
6
|
import { formatGoalStatus } from '../../../core/agent/goalPolicy.js';
|
|
6
7
|
import { calculateRequestTokenBudget, estimateConversationTokens } from '../../../core/agent/contextBudget.js';
|
|
7
8
|
import { stripSyntheticControls, withSyntheticControl, withoutSystemMessages } from '../../../core/agent/requestAssembly.js';
|
|
@@ -39,13 +40,14 @@ export function restrictToRescueTools(tools) {
|
|
|
39
40
|
* configured (the caller-reported failure path).
|
|
40
41
|
*/
|
|
41
42
|
export async function prepareAttempt(deps) {
|
|
42
|
-
const { value, contextFiles, callbacks, retryingExistingRequest, session, modelOverride, abortController, turnOptions, turnScope, turnBudget, goal, globalBudget, sliceBudget, onContextFileRead, usageAnchor } = deps;
|
|
43
|
+
const { value, contextFiles, callbacks, retryingExistingRequest, session, modelOverride, reasoningOverride, abortController, turnOptions, turnScope, turnBudget, goal, globalBudget, sliceBudget, onContextFileRead, usageAnchor } = deps;
|
|
43
44
|
// Single choke point: one fresh settings read per attempt, shared by model
|
|
44
45
|
// resolution and request assembly (CR-024, relaxed in Pillar 1.9 so a
|
|
45
46
|
// provider/model switch mid-goal applies from the next attempt — the first
|
|
46
47
|
// attempt of each physical turn keeps the original read).
|
|
47
48
|
const turnSettings = await readSettings();
|
|
48
|
-
const
|
|
49
|
+
const steeringProfile = turnSettings.steeringProfile ?? 'standard';
|
|
50
|
+
const runtime = await modelWithConfig({ cwd: session?.cwd, modelSelector: modelOverride, reasoningOverride, reasoningByModel: session?.reasoningByModel }, turnSettings);
|
|
49
51
|
if (!runtime?.model) {
|
|
50
52
|
callbacks.addMessage({ role: 'assistant', text: 'No model provider configured. Run /provider to choose or add a provider. haze cannot hallucinate without a model. Progress.' });
|
|
51
53
|
return undefined;
|
|
@@ -81,6 +83,9 @@ export async function prepareAttempt(deps) {
|
|
|
81
83
|
: { type: 'subagent_state', id: event.id, state: 'settled', mode: event.mode, queueMs: event.queueMs, durationMs: event.durationMs, termination: event.termination, execution: 'settled', running: event.running })) });
|
|
82
84
|
turnScope.executionScope ??= assembled.executionScope;
|
|
83
85
|
const availableTools = assembled.availableTools;
|
|
86
|
+
const direction = goalDirectionPrompt(goal.intent, steeringProfile === 'compact');
|
|
87
|
+
const preflight = steeringProfile === 'compact' ? await projectPreflight(session?.cwd ?? process.cwd()) : '';
|
|
88
|
+
const systemPrompt = [assembled.systemPrompt, direction, preflight].filter(Boolean).join('\n\n');
|
|
84
89
|
const toolCategories = assembled.toolCategories;
|
|
85
90
|
const loadedMcp = assembled.loadedMcp;
|
|
86
91
|
const lspPool = assembled.lspPool;
|
|
@@ -102,12 +107,13 @@ export async function prepareAttempt(deps) {
|
|
|
102
107
|
// margin — not a fixed 40K constant. Small contexts get a safe budget; the
|
|
103
108
|
// assembled request plus output reserve stays within configured capacity.
|
|
104
109
|
const requestedOutputTokens = runtime.config.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS;
|
|
105
|
-
const requestBudget = calculateRequestTokenBudget({ contextWindowTokens: runtime.config.contextWindowTokens, requestedOutputTokens, system:
|
|
110
|
+
const requestBudget = calculateRequestTokenBudget({ contextWindowTokens: runtime.config.contextWindowTokens, requestedOutputTokens, system: systemPrompt, tools: availableTools });
|
|
106
111
|
// A context-overflow retry progressively shrinks the target so it cannot loop
|
|
107
112
|
// at an unchanged budget; further overflows get even smaller (RH-005, Pillar
|
|
108
113
|
// 1.4: 0.6 after the first, 0.36 after the second).
|
|
109
114
|
const overflowShrinkFactor = deps.overflowShrinkFactor;
|
|
110
|
-
const
|
|
115
|
+
const profileTargetTokens = Math.floor(requestBudget.messageTokens * (steeringProfile === 'compact' ? 0.7 : 1));
|
|
116
|
+
const overflowTargetTokens = overflowShrinkFactor < 1 ? Math.floor(profileTargetTokens * overflowShrinkFactor) : profileTargetTokens;
|
|
111
117
|
const overheadTokens = requestBudget.systemTokens + requestBudget.toolSchemaTokens;
|
|
112
118
|
let requestMessages = durableRequestMessages;
|
|
113
119
|
if (estimateConversationTokens(requestMessages, usageAnchor.current, overheadTokens).tokens > overflowTargetTokens) {
|
|
@@ -124,12 +130,19 @@ export async function prepareAttempt(deps) {
|
|
|
124
130
|
callbacks.setConversation(stripSyntheticControls(requestMessages));
|
|
125
131
|
if (turnOptions.ephemeralControl)
|
|
126
132
|
requestMessages = withSyntheticControl(requestMessages, turnOptions.ephemeralControl);
|
|
127
|
-
const systemPrompt = assembled.systemPrompt;
|
|
128
133
|
const inputBreakdown = estimateInputBreakdown({ system: systemPrompt, contextFiles: activeContextFiles, messages: requestMessages, tools: availableTools });
|
|
129
134
|
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'request', stream: 'main', system: systemPrompt, messages: requestMessages, tools: Object.keys(availableTools), context: inputBreakdown.breakdown });
|
|
130
135
|
const contextFileSignatures = callbacks.contextFileSignatures ?? new Map(activeContextFiles.flatMap(file => file.signature ? [[file.path, file.signature]] : []));
|
|
131
136
|
const mutationPolicy = assembled.executionScope?.mutationPolicy ?? new WorkspaceMutationPolicy();
|
|
132
|
-
const toolExecutionContext = {
|
|
137
|
+
const toolExecutionContext = {
|
|
138
|
+
inFlightToolCalls: new Map(),
|
|
139
|
+
loadedContextFilePaths: new Set(activeContextFiles.map(file => file.path)),
|
|
140
|
+
loadedContextFileSignatures: contextFileSignatures,
|
|
141
|
+
onContextFileRead,
|
|
142
|
+
mutationPolicy,
|
|
143
|
+
blessedPaths: turnOptions.blessedPaths,
|
|
144
|
+
postMutationDiagnostics: assembled.postMutationDiagnostics,
|
|
145
|
+
};
|
|
133
146
|
const recoverySlice = turnOptions.recoverySlice;
|
|
134
147
|
const stepCap = recoverySlice?.maxSteps ?? MAIN_STEP_LIMIT;
|
|
135
148
|
// Rescue exposes only mutation + validation-capable built-in tools so
|
|
@@ -180,5 +193,6 @@ export async function prepareAttempt(deps) {
|
|
|
180
193
|
toolCategories,
|
|
181
194
|
modelRetries: typeof turnSettings.modelRetries === 'number' ? turnSettings.modelRetries : DEFAULT_MODEL_RETRIES,
|
|
182
195
|
retryBaseDelayMs: typeof turnSettings.retryBaseDelayMs === 'number' ? turnSettings.retryBaseDelayMs : DEFAULT_RETRY_BASE_DELAY_MS,
|
|
196
|
+
steeringProfile,
|
|
183
197
|
};
|
|
184
198
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { CompletionReadiness, TurnExecutionState } from '../../../core/agent/completionController.js';
|
|
2
2
|
import type { RequestIntent } from '../../../core/agent/goalPolicy.js';
|
|
3
3
|
import type { RedEvidence, ValidationOutcome, WorkTaskProgress } from '../../../core/agent/workState.js';
|
|
4
|
+
import type { ValidationKind } from '../../../llm/toolResultTypes.js';
|
|
4
5
|
import type { GoalLedgerFrontier } from '../../../core/session/sessionStore.js';
|
|
5
6
|
/**
|
|
6
7
|
* Bounded continuation checkpoint for a logical goal whose work is recoverably
|
|
@@ -32,6 +33,9 @@ export interface IncompleteGoalResume {
|
|
|
32
33
|
requestHash?: string;
|
|
33
34
|
/** Unresolved pre-mutation failing repro for fix goals. */
|
|
34
35
|
redEvidence?: RedEvidence;
|
|
36
|
+
/** Kind of the carried validation, when one rode the checkpoint (R2-03). */
|
|
37
|
+
validationKind?: ValidationKind;
|
|
38
|
+
failedCheckIds?: string[];
|
|
35
39
|
}
|
|
36
40
|
/** Supervisor-level checkpoint persisted between physical turns (in memory and, via the goal ledger, in the session JSONL). */
|
|
37
41
|
export interface GoalCheckpoint {
|
|
@@ -60,6 +64,9 @@ export interface GoalCheckpoint {
|
|
|
60
64
|
requestHash?: string;
|
|
61
65
|
intent?: RequestIntent;
|
|
62
66
|
redEvidence?: RedEvidence;
|
|
67
|
+
/** Kind of the carried validation, when one rode the checkpoint (R2-03). */
|
|
68
|
+
validationKind?: ValidationKind;
|
|
69
|
+
failedCheckIds?: string[];
|
|
63
70
|
}
|
|
64
71
|
/** Durable goal-ledger append (P1): one entry per supervisor boundary; the writer stamps `type`/`at`. Shared by the supervisor and the session recorder. */
|
|
65
72
|
export interface GoalLedgerAppend {
|
|
@@ -71,6 +78,8 @@ export interface GoalLedgerAppend {
|
|
|
71
78
|
cycle: number;
|
|
72
79
|
mutationCount: number;
|
|
73
80
|
validationOutcome: ValidationOutcome;
|
|
81
|
+
validationKind?: ValidationKind;
|
|
82
|
+
failedCheckIds?: string[];
|
|
74
83
|
progressSignature: string;
|
|
75
84
|
taskCounts?: {
|
|
76
85
|
total: number;
|
|
@@ -81,10 +90,11 @@ export interface GoalLedgerAppend {
|
|
|
81
90
|
redEvidence?: RedEvidence;
|
|
82
91
|
stopReason?: string;
|
|
83
92
|
status?: 'complete' | 'failed' | 'aborted';
|
|
93
|
+
gateDecision?: CompletionReadiness;
|
|
84
94
|
}
|
|
85
95
|
/** Hash binding for the exact mission bytes (P1): everything downstream that references "the mission" carries this. */
|
|
86
96
|
export declare function hashRequest(request: string): string;
|
|
87
|
-
/** Cumulative outcome signature; monotonic mutation activity alone is not net progress. */
|
|
97
|
+
/** Cumulative outcome signature; monotonic mutation activity alone is not net progress. Open failed-check count is progress too: a turn that greens one of three red checks must not look identical to a turn that greened none (observed 2026-10-04, goal `on373gg0l1e`). */
|
|
88
98
|
export declare function goalCheckpointSignature(input: {
|
|
89
99
|
mutationCount: number;
|
|
90
100
|
validationOutcome: ValidationOutcome;
|
|
@@ -94,12 +104,15 @@ export declare function goalCheckpointSignature(input: {
|
|
|
94
104
|
completed: number;
|
|
95
105
|
total: number;
|
|
96
106
|
};
|
|
107
|
+
openCheckCount?: number;
|
|
97
108
|
}): string;
|
|
98
109
|
/** Goal-scoped evidence carried across a physical-turn boundary (checkpoint subset). */
|
|
99
110
|
export interface CarriedGoalEvidence {
|
|
100
111
|
requestHash?: string;
|
|
101
112
|
intent?: RequestIntent;
|
|
102
113
|
redEvidence?: RedEvidence;
|
|
114
|
+
validationKind?: ValidationKind;
|
|
115
|
+
failedCheckIds?: string[];
|
|
103
116
|
}
|
|
104
117
|
/**
|
|
105
118
|
* Build the checkpoint payload for a `recoverable-incomplete` attempt that no
|
|
@@ -3,9 +3,9 @@ import crypto from 'node:crypto';
|
|
|
3
3
|
export function hashRequest(request) {
|
|
4
4
|
return crypto.createHash('sha256').update(request, 'utf8').digest('hex').slice(0, 16);
|
|
5
5
|
}
|
|
6
|
-
/** Cumulative outcome signature; monotonic mutation activity alone is not net progress. */
|
|
6
|
+
/** Cumulative outcome signature; monotonic mutation activity alone is not net progress. Open failed-check count is progress too: a turn that greens one of three red checks must not look identical to a turn that greened none (observed 2026-10-04, goal `on373gg0l1e`). */
|
|
7
7
|
export function goalCheckpointSignature(input) {
|
|
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
|
+
return JSON.stringify([input.mutationCount > 0, input.validationOutcome, input.taskCounts ? [input.taskCounts.total, input.taskCounts.pending, input.taskCounts.inProgress, input.taskCounts.completed] : null, input.openCheckCount ?? 0]);
|
|
9
9
|
}
|
|
10
10
|
/**
|
|
11
11
|
* Build the checkpoint payload for a `recoverable-incomplete` attempt that no
|
|
@@ -54,5 +54,7 @@ export function checkpointFromGoalFrontier(frontier) {
|
|
|
54
54
|
...(frontier.intent ? { intent: frontier.intent } : {}),
|
|
55
55
|
...(frontier.taskCounts ? { taskCounts: frontier.taskCounts } : {}),
|
|
56
56
|
...(frontier.redEvidence ? { redEvidence: { ...frontier.redEvidence } } : {}),
|
|
57
|
+
...(frontier.validationKind ? { validationKind: frontier.validationKind } : {}),
|
|
58
|
+
...(frontier.failedCheckIds?.length ? { failedCheckIds: [...frontier.failedCheckIds] } : {}),
|
|
57
59
|
};
|
|
58
60
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
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
|
+
import type { StoredReasoningSetting } from '../../../core/agent/reasoningPolicy.js';
|
|
4
5
|
import { type StreamCallbacks, type TurnExecutionOptions } from '../streaming.js';
|
|
5
6
|
import { type GoalCheckpoint, type GoalLedgerAppend } from './goalCheckpoint.js';
|
|
6
7
|
/** Why a logical goal stopped. `completed` is the only success. */
|
|
@@ -12,6 +13,8 @@ export interface GoalRunResult {
|
|
|
12
13
|
stopReason: GoalStopReason;
|
|
13
14
|
/** Physical turns consumed by the logical goal. */
|
|
14
15
|
cycles: number;
|
|
16
|
+
/** Number of explicit fallback switches used by this run (zero or one). */
|
|
17
|
+
escalations: number;
|
|
15
18
|
/** Last physical turn's bounded evidence. */
|
|
16
19
|
evidence?: TurnCompletionEvidence;
|
|
17
20
|
/**
|
|
@@ -23,6 +26,7 @@ export interface GoalRunResult {
|
|
|
23
26
|
kind: 'model-stream-idle';
|
|
24
27
|
request: string;
|
|
25
28
|
retryAttempt: number;
|
|
29
|
+
checkpoint?: GoalCheckpoint;
|
|
26
30
|
} | {
|
|
27
31
|
kind: 'incomplete-goal';
|
|
28
32
|
checkpoint: GoalCheckpoint;
|
|
@@ -35,6 +39,10 @@ export interface GoalRunOptions {
|
|
|
35
39
|
callbacks: StreamCallbacks;
|
|
36
40
|
session?: PromptSession;
|
|
37
41
|
modelOverride?: string;
|
|
42
|
+
/** Explicit opt-in fallback model; attempted once only after no progress or context exhaustion. */
|
|
43
|
+
escalationModel?: string;
|
|
44
|
+
/** Run-scoped reasoning level/sentinel (CLI `--reasoning`); applies to every attempt of the goal. */
|
|
45
|
+
reasoningOverride?: StoredReasoningSetting;
|
|
38
46
|
/** Whole-logical-goal wall-clock budget (headless `--timeout`); unset means continue while progress. */
|
|
39
47
|
goalDeadlineMs?: number;
|
|
40
48
|
/** Base per-turn options (attachments, blessed paths); attachments apply to the first physical turn only. */
|
|
@@ -43,6 +51,7 @@ export interface GoalRunOptions {
|
|
|
43
51
|
resumeFrom?: {
|
|
44
52
|
kind: 'model-stream-idle';
|
|
45
53
|
retryAttempt: number;
|
|
54
|
+
checkpoint?: GoalCheckpoint;
|
|
46
55
|
} | {
|
|
47
56
|
kind: 'incomplete-goal';
|
|
48
57
|
checkpoint: GoalCheckpoint;
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { agentEvent } from '../../../core/agent/events.js';
|
|
2
|
-
import { DEFAULT_TURN_DEADLINE_MS } from '../../../core/agent/budgets.js';
|
|
3
2
|
import { describeCompletionReadiness } from '../../../core/agent/completionController.js';
|
|
4
3
|
import { classifyRequestIntent, goalContinuationPrompt } from '../../../core/agent/goalPolicy.js';
|
|
5
4
|
import { runAgentTurn } from '../streaming.js';
|
|
@@ -16,10 +15,12 @@ function checkpointFromResume(resume, noProgressCount) {
|
|
|
16
15
|
...(resume.taskCounts ? { taskCounts: resume.taskCounts } : {}),
|
|
17
16
|
mutationCount: resume.mutationCount,
|
|
18
17
|
validationOutcome,
|
|
19
|
-
progressSignature: goalCheckpointSignature({ mutationCount: resume.mutationCount, validationOutcome, taskCounts: resume.taskCounts }),
|
|
18
|
+
progressSignature: goalCheckpointSignature({ mutationCount: resume.mutationCount, validationOutcome, taskCounts: resume.taskCounts, openCheckCount: resume.failedCheckIds?.length ?? 0 }),
|
|
20
19
|
noProgressCount,
|
|
21
20
|
...(resume.requestHash ? { requestHash: resume.requestHash } : {}),
|
|
22
21
|
...(resume.redEvidence ? { redEvidence: { ...resume.redEvidence } } : {}),
|
|
22
|
+
...(resume.validationKind ? { validationKind: resume.validationKind } : {}),
|
|
23
|
+
...(resume.failedCheckIds?.length ? { failedCheckIds: [...resume.failedCheckIds] } : {}),
|
|
23
24
|
};
|
|
24
25
|
}
|
|
25
26
|
function countsToTaskProgress(counts) {
|
|
@@ -38,6 +39,8 @@ function carriedOf(checkpoint) {
|
|
|
38
39
|
validationOutcome: checkpoint.validationOutcome,
|
|
39
40
|
...(checkpoint.taskCounts ? { taskProgress: countsToTaskProgress(checkpoint.taskCounts) } : {}),
|
|
40
41
|
...(checkpoint.redEvidence ? { redEvidence: { ...checkpoint.redEvidence } } : {}),
|
|
42
|
+
...(checkpoint.validationKind ? { validationKind: checkpoint.validationKind } : {}),
|
|
43
|
+
...(checkpoint.failedCheckIds?.length ? { failedCheckIds: [...checkpoint.failedCheckIds] } : {}),
|
|
41
44
|
}
|
|
42
45
|
: { mutationCount: 0, validationOutcome: 'not_applicable' };
|
|
43
46
|
}
|
|
@@ -63,7 +66,7 @@ function carriedOf(checkpoint) {
|
|
|
63
66
|
export async function runAgentGoal(options) {
|
|
64
67
|
const { request, contextFiles, callbacks } = options;
|
|
65
68
|
const startedAt = Date.now();
|
|
66
|
-
const resumedCheckpoint = options.resumeFrom?.
|
|
69
|
+
const resumedCheckpoint = options.resumeFrom?.checkpoint;
|
|
67
70
|
const goalId = resumedCheckpoint?.goalId ?? `goal-${startedAt}-${Math.random().toString(36).slice(2)}`;
|
|
68
71
|
const requestHash = resumedCheckpoint?.requestHash ?? hashRequest(request);
|
|
69
72
|
const intent = resumedCheckpoint?.intent ?? classifyRequestIntent(request);
|
|
@@ -74,6 +77,22 @@ export async function runAgentGoal(options) {
|
|
|
74
77
|
let noProgressCount = checkpoint?.noProgressCount ?? 0;
|
|
75
78
|
let prevSignature = checkpoint?.progressSignature;
|
|
76
79
|
let lastEvidence;
|
|
80
|
+
let activeModelOverride = options.modelOverride;
|
|
81
|
+
let escalated = false;
|
|
82
|
+
const tryEscalation = (reason) => {
|
|
83
|
+
const selected = options.escalationModel?.trim();
|
|
84
|
+
if (!selected || escalated || selected === activeModelOverride)
|
|
85
|
+
return false;
|
|
86
|
+
escalated = true;
|
|
87
|
+
activeModelOverride = selected;
|
|
88
|
+
noProgressCount = 0;
|
|
89
|
+
prevSignature = undefined;
|
|
90
|
+
// The model switch is a supervisor boundary like any other: it must reach
|
|
91
|
+
// the durable ledger so a crash resume does not silently lose it.
|
|
92
|
+
appendLedger('goal_continue');
|
|
93
|
+
callbacks.onEvent?.(agentEvent({ type: 'goal_notice', text: `Continuing with explicitly configured escalation model ${selected} after ${reason}.` }));
|
|
94
|
+
return true;
|
|
95
|
+
};
|
|
77
96
|
const appendLedger = (phase, extra = {}) => {
|
|
78
97
|
if (!options.goalLedger)
|
|
79
98
|
return;
|
|
@@ -92,6 +111,8 @@ export async function runAgentGoal(options) {
|
|
|
92
111
|
// Unresolved red evidence keeps crash resumes at parity with in-process
|
|
93
112
|
// continuation; satisfied pairs are deliberately not carried.
|
|
94
113
|
...(source?.redEvidence ? { redEvidence: { ...source.redEvidence } } : {}),
|
|
114
|
+
...(source?.validationKind ? { validationKind: source.validationKind } : {}),
|
|
115
|
+
...(source?.failedCheckIds?.length ? { failedCheckIds: [...source.failedCheckIds] } : {}),
|
|
95
116
|
...extra,
|
|
96
117
|
});
|
|
97
118
|
};
|
|
@@ -102,9 +123,21 @@ export async function runAgentGoal(options) {
|
|
|
102
123
|
// guessed from semantic versions.
|
|
103
124
|
callbacks.debugLog('goal supervisor enabled; automatic continuation across physical-turn budgets');
|
|
104
125
|
const finish = (status, stopReason, resume) => {
|
|
105
|
-
appendLedger('goal_end', {
|
|
126
|
+
appendLedger('goal_end', {
|
|
127
|
+
status,
|
|
128
|
+
gateDecision: status === 'complete' ? 'ready' : ['no-progress', 'context-exhausted', 'goal-deadline'].includes(stopReason) ? checkpoint?.readiness : undefined,
|
|
129
|
+
...(lastEvidence ? {
|
|
130
|
+
mutationCount: lastEvidence.mutationCount,
|
|
131
|
+
validationOutcome: lastEvidence.validationOutcome,
|
|
132
|
+
validationKind: lastEvidence.validationKind,
|
|
133
|
+
taskCounts: lastEvidence.taskProgress,
|
|
134
|
+
progressSignature: goalCheckpointSignature({ mutationCount: lastEvidence.mutationCount, validationOutcome: lastEvidence.validationOutcome, taskCounts: lastEvidence.taskProgress, openCheckCount: checkpoint?.failedCheckIds?.length ?? 0 }),
|
|
135
|
+
} : {}),
|
|
136
|
+
...(status === 'complete' ? { failedCheckIds: [], redEvidence: undefined } : {}),
|
|
137
|
+
...(stopReason !== 'completed' ? { stopReason } : {}),
|
|
138
|
+
});
|
|
106
139
|
callbacks.onEvent?.(agentEvent({ type: 'goal_end', goalId, status, cycles: cycle, ...(stopReason !== 'completed' ? { stopReason } : {}), ...(lastEvidence ? { evidence: lastEvidence } : {}) }));
|
|
107
|
-
return { status, stopReason, cycles: cycle, ...(lastEvidence ? { evidence: lastEvidence } : {}), ...(resume ? { resume } : {}) };
|
|
140
|
+
return { status, stopReason, cycles: cycle, escalations: escalated ? 1 : 0, ...(lastEvidence ? { evidence: lastEvidence } : {}), ...(resume ? { resume } : {}) };
|
|
108
141
|
};
|
|
109
142
|
while (true) {
|
|
110
143
|
const remainingMs = options.goalDeadlineMs != null ? options.goalDeadlineMs - (Date.now() - startedAt) : undefined;
|
|
@@ -119,7 +152,7 @@ export async function runAgentGoal(options) {
|
|
|
119
152
|
// The conversation already carries the user message; a continuation
|
|
120
153
|
// turn rides it with a synthetic control. Attachments belong to the
|
|
121
154
|
// first attempt only.
|
|
122
|
-
ephemeralControl: goalContinuationPrompt(checkpointReason(checkpoint), checkpoint.taskCounts),
|
|
155
|
+
ephemeralControl: goalContinuationPrompt(checkpointReason(checkpoint), checkpoint.taskCounts, checkpoint.redEvidence ? 'The captured pre-edit failing check still needs the same validation command to pass after the fix.' : undefined),
|
|
123
156
|
attachments: undefined,
|
|
124
157
|
}
|
|
125
158
|
: {}),
|
|
@@ -134,12 +167,16 @@ export async function runAgentGoal(options) {
|
|
|
134
167
|
requestHash,
|
|
135
168
|
},
|
|
136
169
|
sharedTurnScope,
|
|
137
|
-
|
|
170
|
+
// Only an explicit whole-goal deadline (headless --timeout) bounds a
|
|
171
|
+
// physical turn; without one, turns run unbounded.
|
|
172
|
+
...(remainingMs != null ? { turnDeadlineMs: remainingMs } : {}),
|
|
138
173
|
};
|
|
139
|
-
const result = await runAgentTurn(request, continuing ? undefined : options.displayValue, contextFiles, callbacks, initialRetryAttempt, continuing, false, options.session,
|
|
174
|
+
const result = await runAgentTurn(request, continuing ? undefined : options.displayValue, contextFiles, callbacks, initialRetryAttempt, continuing, false, options.session, activeModelOverride, turnOptions, options.reasoningOverride);
|
|
140
175
|
initialRetryAttempt = 0;
|
|
141
176
|
cycle += 1;
|
|
142
177
|
lastEvidence = result.evidence;
|
|
178
|
+
if (result.checkpoint)
|
|
179
|
+
checkpoint = result.checkpoint;
|
|
143
180
|
if (result.status === 'complete')
|
|
144
181
|
return finish('complete', 'completed');
|
|
145
182
|
if (result.status === 'aborted') {
|
|
@@ -158,11 +195,15 @@ export async function runAgentGoal(options) {
|
|
|
158
195
|
// Pause with the resumable checkpoint instead (Pillar 1.4); the user
|
|
159
196
|
// compacts/clears context or switches models, then resumes.
|
|
160
197
|
if (checkpoint.readiness === 'context_exhausted') {
|
|
198
|
+
if (tryEscalation('context exhaustion'))
|
|
199
|
+
continue;
|
|
161
200
|
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
201
|
return finish('failed', 'context-exhausted', { kind: 'incomplete-goal', checkpoint });
|
|
163
202
|
}
|
|
164
203
|
appendLedger('goal_continue');
|
|
165
204
|
if (noProgressCount >= GOAL_NO_PROGRESS_LIMIT) {
|
|
205
|
+
if (tryEscalation('no progress'))
|
|
206
|
+
continue;
|
|
166
207
|
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
208
|
callbacks.onEvent?.(agentEvent({ type: 'goal_notice', text: `Unfinished goal paused without measurable progress: ${checkpointReason(checkpoint)}` }));
|
|
168
209
|
return finish('failed', 'no-progress', { kind: 'incomplete-goal', checkpoint });
|
|
@@ -180,10 +221,10 @@ export async function runAgentGoal(options) {
|
|
|
180
221
|
if (result.resume?.kind === 'model-stream-idle') {
|
|
181
222
|
// Bounded in-turn retries are exhausted; a transport stall is a concrete
|
|
182
223
|
// external blocker — pause with the existing one-key resume path.
|
|
183
|
-
return finish('failed', 'model-stream-idle', { kind: 'model-stream-idle', request: result.resume.request, retryAttempt: result.resume.retryAttempt });
|
|
224
|
+
return finish('failed', 'model-stream-idle', { kind: 'model-stream-idle', request: result.resume.request, retryAttempt: result.resume.retryAttempt, ...(checkpoint ? { checkpoint } : {}) });
|
|
184
225
|
}
|
|
185
226
|
// Failed without a checkpoint: hard blocker (failed tool, invalid input,
|
|
186
227
|
// provider error) or an unresolved synthesis failure.
|
|
187
|
-
return finish('failed', result.evidence?.finishCause === 'error' ? 'model-error' : 'blocked');
|
|
228
|
+
return finish('failed', result.evidence?.finishCause === 'error' ? 'model-error' : 'blocked', checkpoint ? { kind: 'incomplete-goal', checkpoint } : undefined);
|
|
188
229
|
}
|
|
189
230
|
}
|
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
import type { ModelMessage } from 'ai';
|
|
2
1
|
import { type SessionGoal } from '../../../core/agent/goalPolicy.js';
|
|
3
2
|
import { type ContextUsageAnchor } from '../../../core/agent/contextBudget.js';
|
|
4
|
-
import type { HazeToolContext } from '../../../llm/tools/toolContext.js';
|
|
5
3
|
import type { StreamCallbacks, TurnExecutionOptions } from '../streaming.js';
|
|
6
4
|
import type { AttemptSetup } from './attemptSetup.js';
|
|
7
5
|
import type { AttemptLoopState } from './streamLoop.js';
|
|
@@ -18,7 +16,6 @@ type AgentOptions = NonNullable<ConstructorParameters<typeof import('ai').ToolLo
|
|
|
18
16
|
type RepairToolCallFn = NonNullable<AgentOptions['experimental_repairToolCall']>;
|
|
19
17
|
type PrepareStepFn = NonNullable<AgentOptions['prepareStep']>;
|
|
20
18
|
type SyncPrepareStepResult = Exclude<ReturnType<PrepareStepFn>, PromiseLike<unknown>>;
|
|
21
|
-
export declare function withScopedContextControl(messages: ModelMessage[], context: HazeToolContext): ModelMessage[];
|
|
22
19
|
export declare function createRepairToolCall(deps: {
|
|
23
20
|
callbacks: StreamCallbacks;
|
|
24
21
|
loopState: AttemptLoopState;
|