@denizokcu/haze 1.1.1 → 1.4.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 +78 -0
- package/README.md +26 -15
- package/SECURITY.md +1 -1
- package/bin/haze.js +27 -7
- package/dist/buildInfo.json +3 -3
- package/dist/cli/chat/inputSuggestions.js +3 -0
- package/dist/cli/chat/liveMessages.d.ts +36 -0
- package/dist/cli/chat/liveMessages.js +64 -0
- package/dist/cli/chat/sessionLifecycle.d.ts +2 -1
- package/dist/cli/chat/sessionLifecycle.js +25 -2
- package/dist/cli/chat/sessionRecorder.d.ts +7 -0
- package/dist/cli/chat/sessionRecorder.js +6 -0
- package/dist/cli/chat/wizard/sessionThemeHandlers.d.ts +1 -1
- package/dist/cli/chat/wizard/sessionThemeHandlers.js +16 -1
- package/dist/cli/commands/chat.js +63 -36
- package/dist/cli/commands/commandHelp.js +2 -0
- package/dist/cli/commands/commands.js +2 -0
- package/dist/cli/commands/formatters.js +5 -1
- package/dist/cli/commands/ndjsonSink.d.ts +12 -0
- package/dist/cli/commands/ndjsonSink.js +29 -0
- package/dist/cli/commands/reasoningCommand.d.ts +35 -0
- package/dist/cli/commands/reasoningCommand.js +46 -0
- package/dist/cli/commands/runCommand.d.ts +14 -0
- package/dist/cli/commands/runCommand.js +43 -11
- package/dist/cli/commands/settingsSummary.js +2 -0
- package/dist/cli/commands/streaming/agentAttempt.d.ts +14 -1
- package/dist/cli/commands/streaming/agentAttempt.js +9 -5
- 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 +23 -3
- package/dist/cli/commands/streaming/attemptOutcome.js +64 -11
- package/dist/cli/commands/streaming/attemptSetup.d.ts +13 -3
- package/dist/cli/commands/streaming/attemptSetup.js +40 -15
- package/dist/cli/commands/streaming/goalCheckpoint.d.ts +6 -0
- package/dist/cli/commands/streaming/goalCheckpoint.js +1 -0
- package/dist/cli/commands/streaming/goalSupervisor.d.ts +6 -1
- package/dist/cli/commands/streaming/goalSupervisor.js +18 -4
- package/dist/cli/commands/streaming/prepareStep.d.ts +6 -4
- package/dist/cli/commands/streaming/prepareStep.js +43 -22
- package/dist/cli/commands/streaming/stallRecovery.js +2 -2
- package/dist/cli/commands/streaming/streamLoop.d.ts +31 -4
- package/dist/cli/commands/streaming/streamLoop.js +280 -44
- package/dist/cli/commands/streaming/toolPartHandlers.js +13 -0
- package/dist/cli/commands/streaming/turnRuntime.d.ts +1 -1
- package/dist/cli/commands/streaming/turnRuntime.js +3 -2
- package/dist/cli/commands/streaming.d.ts +15 -2
- package/dist/cli/commands/streaming.js +37 -8
- package/dist/cli/commands/wizardFlow.d.ts +7 -0
- package/dist/cli/commands/wizardFlow.js +22 -0
- package/dist/cli/index.js +8 -3
- package/dist/config/modelCatalog.d.ts +32 -0
- package/dist/config/modelCatalog.js +84 -0
- package/dist/config/modelDiscovery.js +68 -5
- package/dist/config/settings.d.ts +18 -6
- package/dist/config/settings.js +11 -1
- package/dist/core/agent/budgets.d.ts +10 -2
- package/dist/core/agent/budgets.js +10 -2
- package/dist/core/agent/compaction.d.ts +42 -3
- package/dist/core/agent/compaction.js +53 -5
- package/dist/core/agent/completionController.d.ts +11 -1
- package/dist/core/agent/completionController.js +33 -0
- package/dist/core/agent/contextBudget.d.ts +56 -0
- package/dist/core/agent/contextBudget.js +53 -0
- package/dist/core/agent/errors.js +2 -2
- package/dist/core/agent/events.d.ts +26 -2
- package/dist/core/agent/goalPolicy.d.ts +7 -0
- package/dist/core/agent/goalPolicy.js +9 -0
- package/dist/core/agent/overflow.d.ts +45 -0
- package/dist/core/agent/overflow.js +91 -0
- package/dist/core/agent/reasoningPolicy.d.ts +45 -9
- package/dist/core/agent/reasoningPolicy.js +49 -9
- package/dist/core/agent/requestAssembly.d.ts +7 -0
- package/dist/core/agent/requestAssembly.js +15 -7
- package/dist/core/agent/toolCapabilities.d.ts +3 -3
- package/dist/core/agent/toolCapabilities.js +31 -7
- package/dist/core/agent/workState.d.ts +6 -4
- package/dist/core/agent/workState.js +53 -29
- package/dist/core/deadline.js +22 -24
- package/dist/core/safety/secretPaths.js +10 -7
- package/dist/core/safety/shellClassifier.d.ts +18 -0
- package/dist/core/safety/shellClassifier.js +39 -0
- package/dist/core/session/sessionSlimming.d.ts +2 -0
- package/dist/core/session/sessionSlimming.js +50 -1
- package/dist/core/session/sessionStore.d.ts +14 -8
- package/dist/core/session/sessionStore.js +59 -32
- 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 +8 -1
- package/dist/core/subagent/subagentRunner.d.ts +4 -0
- package/dist/core/subagent/subagentRunner.js +33 -25
- package/dist/core/tasks/taskStorage.js +8 -1
- package/dist/core/validation/outputParser.d.ts +1 -1
- package/dist/core/validation/outputParser.js +30 -1
- package/dist/llm/client.d.ts +4 -3
- package/dist/llm/client.js +34 -16
- package/dist/llm/hazeTools.d.ts +2039 -16
- package/dist/llm/hazeTools.js +43 -2
- 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/requestContext.d.ts +3 -2
- package/dist/llm/requestContext.js +8 -4
- package/dist/llm/systemPrompt.js +2 -2
- package/dist/llm/tools/fetchTool.d.ts +4 -0
- package/dist/llm/tools/processTool.d.ts +4 -0
- package/dist/llm/tools/replaceInFiles.d.ts +105 -0
- package/dist/llm/tools/replaceInFiles.js +131 -0
- package/dist/llm/tools/shellTool.d.ts +4 -0
- package/dist/llm/tools/shellTool.js +27 -8
- 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 -0
- package/dist/llm/tools/toolContext.js +26 -4
- package/dist/skills/SkillLoader.js +27 -1
- package/dist/ui/components/TextInput.d.ts +18 -1
- package/dist/ui/components/TextInput.js +44 -6
- package/dist/ui/components/useInputSuggestions.js +18 -6
- package/dist/utils/buildInfo.js +29 -8
- package/dist/utils/fs.js +5 -1
- package/package.json +20 -19
|
@@ -2,11 +2,13 @@ import type { ContextFile } from '../../../config/contextFiles.js';
|
|
|
2
2
|
import type { PromptSession } from '../../../llm/systemPrompt.js';
|
|
3
3
|
import type { TurnExecutionScope } from '../../../llm/requestContext.js';
|
|
4
4
|
import type { ToolExecutionBudgetState, TurnBudget } from '../../../core/agent/budgets.js';
|
|
5
|
+
import type { ContextUsageAnchor } from '../../../core/agent/contextBudget.js';
|
|
5
6
|
import type { TurnExecutionState } from '../../../core/agent/completionController.js';
|
|
6
7
|
import type { SessionGoal } from '../../../core/agent/goalPolicy.js';
|
|
7
8
|
import { type AgentAttemptResult } from './attemptOutcome.js';
|
|
8
9
|
import type { AttemptCleanupRegistry } from './attemptLifecycle.js';
|
|
9
10
|
import type { TurnAbortCause } from './abortCause.js';
|
|
11
|
+
import type { StoredReasoningSetting } from '../../../core/agent/reasoningPolicy.js';
|
|
10
12
|
import type { StreamCallbacks, TurnExecutionOptions } from '../streaming.js';
|
|
11
13
|
export interface AgentAttemptInput {
|
|
12
14
|
value: string;
|
|
@@ -14,9 +16,16 @@ export interface AgentAttemptInput {
|
|
|
14
16
|
callbacks: StreamCallbacks;
|
|
15
17
|
retryAttempt: number;
|
|
16
18
|
retryingExistingRequest: boolean;
|
|
17
|
-
|
|
19
|
+
/** Multiplier for the message-token budget after context-overflow retries (1 = none; Pillar 1.4). */
|
|
20
|
+
overflowShrinkFactor: number;
|
|
21
|
+
/** Context-overflow retries already consumed by this turn (Pillar 1.4). */
|
|
22
|
+
overflowRetries: number;
|
|
23
|
+
/** Whether this attempt runs after progress since the previous retry (Pillar 1.3 pool reset). */
|
|
24
|
+
progressSinceLastRetry: boolean;
|
|
18
25
|
session: PromptSession | undefined;
|
|
19
26
|
modelOverride: string | undefined;
|
|
27
|
+
/** Run-scoped reasoning level/sentinel (CLI `--reasoning`); overrides the stored setting for this run. */
|
|
28
|
+
reasoningOverride: StoredReasoningSetting | undefined;
|
|
20
29
|
abortController: AbortController;
|
|
21
30
|
turnOptions: TurnExecutionOptions;
|
|
22
31
|
turnScope: {
|
|
@@ -32,6 +41,10 @@ export interface AgentAttemptInput {
|
|
|
32
41
|
/** Exactly-once teardown registry; shared with the turn's forced-settlement path. */
|
|
33
42
|
cleanup: AttemptCleanupRegistry;
|
|
34
43
|
remainingTurnDeadlineMs: () => number;
|
|
44
|
+
/** Turn-scoped usage anchor for provider-usage-backed context estimation (Pillar 1.1). */
|
|
45
|
+
usageAnchor: {
|
|
46
|
+
current: ContextUsageAnchor | undefined;
|
|
47
|
+
};
|
|
35
48
|
}
|
|
36
49
|
/**
|
|
37
50
|
* Run one agent attempt end to end: setup (`attemptSetup`), the stream loop
|
|
@@ -15,7 +15,11 @@ 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,
|
|
18
|
+
const { value, contextFiles, callbacks, retryingExistingRequest, session, modelOverride, reasoningOverride, abortController, turnOptions, turnScope, turnState, turnBudget, globalBudget, sliceBudget, goal, abortCause, cleanup, remainingTurnDeadlineMs, usageAnchor } = input;
|
|
19
|
+
// Pillar 1.3: progress since the previous retry resets the shared retry pool
|
|
20
|
+
// (mirrors a per-burst budget), applied to both the stall guard's retry
|
|
21
|
+
// eligibility and the failure classification below.
|
|
22
|
+
const retryAttempt = input.progressSinceLastRetry && input.retryAttempt > 0 ? 0 : input.retryAttempt;
|
|
19
23
|
callbacks.setBusyLabel?.(modelThinkingLabel(undefined));
|
|
20
24
|
let loadedMcp;
|
|
21
25
|
let lspPool;
|
|
@@ -43,7 +47,7 @@ export async function runAgentAttempt(input) {
|
|
|
43
47
|
let stallGuard;
|
|
44
48
|
let setup;
|
|
45
49
|
try {
|
|
46
|
-
setup = await prepareAttempt({ value, contextFiles, callbacks, retryingExistingRequest,
|
|
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 });
|
|
47
51
|
if (!setup)
|
|
48
52
|
return { status: 'failed' };
|
|
49
53
|
const attemptSetupResult = setup;
|
|
@@ -66,11 +70,11 @@ export async function runAgentAttempt(input) {
|
|
|
66
70
|
log: callbacks.log,
|
|
67
71
|
debugLog: callbacks.debugLog,
|
|
68
72
|
});
|
|
69
|
-
const stream = await runAttemptStream({ setup, callbacks, abortController, retryAttempt, recoverySlice: turnOptions.recoverySlice, turnState, turnBudget, globalBudget, goal, stallGuard, loopState, toolDisplay, salvage });
|
|
70
|
-
return finalizeAttemptOutcome({ value, callbacks, abortController, turnOptions, turnState, turnBudget, goal, remainingTurnDeadlineMs, stream });
|
|
73
|
+
const stream = await runAttemptStream({ setup, callbacks, abortController, retryAttempt, recoverySlice: turnOptions.recoverySlice, turnState, turnBudget, globalBudget, goal, stallGuard, loopState, toolDisplay, salvage, usageAnchor });
|
|
74
|
+
return finalizeAttemptOutcome({ value, callbacks, abortController, turnOptions, turnState, turnBudget, goal, remainingTurnDeadlineMs, stream, retryAttempt, overflowRetries: input.overflowRetries });
|
|
71
75
|
}
|
|
72
76
|
catch (error) {
|
|
73
|
-
return handleAttemptFailure({ value, callbacks, abortController, turnState, retryAttempt,
|
|
77
|
+
return handleAttemptFailure({ value, callbacks, abortController, turnState, retryAttempt, progressSinceLastRetry: input.progressSinceLastRetry, overflowRetries: input.overflowRetries, abortCause, stallGuard, salvage, error, maxRetries: setup?.modelRetries, retryBaseDelayMs: setup?.retryBaseDelayMs, goal, turnOptions });
|
|
74
78
|
}
|
|
75
79
|
finally {
|
|
76
80
|
await cleanup.closeOnce(ATTEMPT_TEARDOWN_BOUND_MS);
|
|
@@ -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
|
},
|
|
@@ -45,9 +45,9 @@ export type AttemptRecovery = {
|
|
|
45
45
|
export type AgentAttemptResult = TurnResult & {
|
|
46
46
|
retry?: {
|
|
47
47
|
attempt: number;
|
|
48
|
-
contextOverflowRecovered: boolean;
|
|
49
48
|
delayMs: number; /** The retry aborts the previous controller (idle stall); hand the loop a fresh one. */
|
|
50
|
-
freshController?: boolean;
|
|
49
|
+
freshController?: boolean; /** Message-budget multiplier for the next attempt after an overflow retry (Pillar 1.4). */
|
|
50
|
+
overflowShrinkFactor?: number;
|
|
51
51
|
};
|
|
52
52
|
/** When set, run one bounded recovery slice next (length-continuation, rescue, or goal continuation). */
|
|
53
53
|
recovery?: AttemptRecovery;
|
|
@@ -64,6 +64,10 @@ export interface AttemptOutcomeDeps {
|
|
|
64
64
|
goal: SessionGoal;
|
|
65
65
|
remainingTurnDeadlineMs: () => number;
|
|
66
66
|
stream: AttemptStreamOutcome;
|
|
67
|
+
/** Current attempt number (for overflow retry bookkeeping). */
|
|
68
|
+
retryAttempt: number;
|
|
69
|
+
/** Context-overflow retries already consumed by this turn (Pillar 1.4). */
|
|
70
|
+
overflowRetries: number;
|
|
67
71
|
}
|
|
68
72
|
/**
|
|
69
73
|
* Classify the finished attempt: project work evidence onto the turn state,
|
|
@@ -79,18 +83,34 @@ export interface AttemptFailureDeps {
|
|
|
79
83
|
abortController: AbortController;
|
|
80
84
|
turnState: TurnExecutionState;
|
|
81
85
|
retryAttempt: number;
|
|
82
|
-
|
|
86
|
+
/** Whether the failed attempt completed at least one step since the previous retry (Pillar 1.3: progress refills the shared pool). */
|
|
87
|
+
progressSinceLastRetry?: boolean;
|
|
88
|
+
/** Context-overflow retries already consumed by this turn (Pillar 1.4). */
|
|
89
|
+
overflowRetries?: number;
|
|
83
90
|
abortCause: TurnAbortCause;
|
|
84
91
|
stallGuard: StreamStallGuard | undefined;
|
|
85
92
|
salvage: AttemptSalvage;
|
|
86
93
|
error: unknown;
|
|
87
94
|
/** Retry-pool size for this turn (`modelRetries` setting); defaults to DEFAULT_MODEL_RETRIES. */
|
|
88
95
|
maxRetries?: number;
|
|
96
|
+
/** Backoff base for the shared model-retry pool (`retryBaseDelayMs` setting); defaults to DEFAULT_RETRY_BASE_DELAY_MS. */
|
|
97
|
+
retryBaseDelayMs?: number;
|
|
98
|
+
goal: SessionGoal;
|
|
99
|
+
turnOptions: TurnExecutionOptions;
|
|
89
100
|
}
|
|
90
101
|
/**
|
|
91
102
|
* Classify a failed attempt from the recorded abort cause and the error:
|
|
92
103
|
* idle-stall retry/pause (shared bounded retry pool), absolute turn deadline,
|
|
93
104
|
* user abort, context-overflow compaction retry, transient model retry, or a
|
|
94
105
|
* hard model-call failure. Completed-step progress is always preserved.
|
|
106
|
+
*
|
|
107
|
+
* Pillar 1.3: the shared retry pool resets whenever the failed attempt made
|
|
108
|
+
* progress (completed at least one step) since the previous retry — a long
|
|
109
|
+
* turn with intermittent blips never exhausts the pool. Pillar 1.4: each
|
|
110
|
+
* context-overflow retry shrinks the message budget (0.6 → 0.36); once the
|
|
111
|
+
* bounded overflow retries are exhausted the goal checkpoints
|
|
112
|
+
* (`context_exhausted`) instead of hard-failing, so the supervisor or the
|
|
113
|
+
* R-resume can continue after the user compacts, clears context, or switches
|
|
114
|
+
* models — never a false hard block.
|
|
95
115
|
*/
|
|
96
116
|
export declare function handleAttemptFailure(deps: AttemptFailureDeps): AgentAttemptResult;
|
|
@@ -1,9 +1,8 @@
|
|
|
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 { clampSlice, remainingSteps, remainingToolCalls, DEFAULT_TURN_DEADLINE_MS, IDLE_TIMEOUT_MS, DEFAULT_MODEL_RETRIES } from '../../../core/agent/budgets.js';
|
|
5
|
+
import { clampSlice, DEFAULT_MODEL_RETRIES, DEFAULT_RETRY_BASE_DELAY_MS, MAX_OVERFLOW_RETRIES, OVERFLOW_SHRINK_FACTOR, remainingSteps, remainingToolCalls, DEFAULT_TURN_DEADLINE_MS, IDLE_TIMEOUT_MS } from '../../../core/agent/budgets.js';
|
|
7
6
|
import { deriveValidationOutcome, redPairStatus } from '../../../core/agent/workState.js';
|
|
8
7
|
import { withoutRejectedAssistantFinal } from '../../../core/agent/requestAssembly.js';
|
|
9
8
|
import { buildIncompleteGoalResume, taskCountsOf } from './goalCheckpoint.js';
|
|
@@ -72,6 +71,24 @@ export function finalizeAttemptOutcome(deps) {
|
|
|
72
71
|
if (stream.unresolvedMalformedToolName)
|
|
73
72
|
callbacks.addMessage({ role: 'system', text: `${stream.unresolvedMalformedToolName} did not execute because its generated input remained invalid or truncated. The requested work is incomplete.` });
|
|
74
73
|
goal.phase = 'done';
|
|
74
|
+
// Non-error overflow recovery (Pillar 1.2/1.4): a silent overflow completed
|
|
75
|
+
// its response, so compact only — the next physical turn (or the supervisor)
|
|
76
|
+
// continues from the smaller history; a length-stop overflow dropped the
|
|
77
|
+
// truncated final and retries the same request once per shrink step.
|
|
78
|
+
if (stream.usageOverflow && !abortController.signal.aborted) {
|
|
79
|
+
const compacted = callbacks.compactConversation?.('Automatic recovery after a context-window overflow detected from provider usage. Preserve the active user request and concrete next steps.') ?? false;
|
|
80
|
+
const willRetry = compacted && stream.usageOverflow === 'length-stop' && deps.overflowRetries < MAX_OVERFLOW_RETRIES;
|
|
81
|
+
callbacks.onEvent?.(agentEvent({ type: 'context_overflow', recovered: compacted, error: `silent usage overflow (window exceeded on a successful finish)` }));
|
|
82
|
+
callbacks.onEvent?.(agentEvent({ type: 'compaction_start', reason: 'overflow', method: 'heuristic' }));
|
|
83
|
+
callbacks.onEvent?.(agentEvent({ type: 'compaction_end', reason: 'overflow', method: compacted ? 'heuristic' : 'none', compacted, willRetry }));
|
|
84
|
+
if (willRetry) {
|
|
85
|
+
callbacks.setConversation(withoutRejectedAssistantFinal(callbacks.getConversation()));
|
|
86
|
+
callbacks.addMessage({ role: 'system', text: 'Context window filled by truncated input; compacted older context and retrying the same request at a smaller budget.' });
|
|
87
|
+
return { status: 'failed', retry: { attempt: deps.retryAttempt, delayMs: 0, overflowShrinkFactor: OVERFLOW_SHRINK_FACTOR ** (deps.overflowRetries + 1) } };
|
|
88
|
+
}
|
|
89
|
+
if (compacted)
|
|
90
|
+
callbacks.addMessage({ role: 'system', text: 'Context overflow detected from provider usage; compacted older context. Completed work is preserved.' });
|
|
91
|
+
}
|
|
75
92
|
// Goal status reflects completion readiness, not the shallow text status:
|
|
76
93
|
// unfinished-but-recoverable work is waiting on continuation (supervisor or
|
|
77
94
|
// the user), while tool/input failures are concrete blockers. Prose alone
|
|
@@ -98,6 +115,7 @@ export function finalizeAttemptOutcome(deps) {
|
|
|
98
115
|
// Carry red evidence until the same check passes after the mutation. This
|
|
99
116
|
// includes boundaries reached after red capture but before the first edit.
|
|
100
117
|
...(turnState.redPair !== 'satisfied' && goal.redEvidence ? { redEvidence: { ...goal.redEvidence } } : {}),
|
|
118
|
+
...(turnState.validationKind ? { validationKind: turnState.validationKind } : {}),
|
|
101
119
|
};
|
|
102
120
|
const discardRejectedFinal = () => callbacks.setConversation(withoutRejectedAssistantFinal(callbacks.getConversation()));
|
|
103
121
|
const checkpointResult = () => {
|
|
@@ -146,10 +164,24 @@ export function finalizeAttemptOutcome(deps) {
|
|
|
146
164
|
* idle-stall retry/pause (shared bounded retry pool), absolute turn deadline,
|
|
147
165
|
* user abort, context-overflow compaction retry, transient model retry, or a
|
|
148
166
|
* hard model-call failure. Completed-step progress is always preserved.
|
|
167
|
+
*
|
|
168
|
+
* Pillar 1.3: the shared retry pool resets whenever the failed attempt made
|
|
169
|
+
* progress (completed at least one step) since the previous retry — a long
|
|
170
|
+
* turn with intermittent blips never exhausts the pool. Pillar 1.4: each
|
|
171
|
+
* context-overflow retry shrinks the message budget (0.6 → 0.36); once the
|
|
172
|
+
* bounded overflow retries are exhausted the goal checkpoints
|
|
173
|
+
* (`context_exhausted`) instead of hard-failing, so the supervisor or the
|
|
174
|
+
* R-resume can continue after the user compacts, clears context, or switches
|
|
175
|
+
* models — never a false hard block.
|
|
149
176
|
*/
|
|
150
177
|
export function handleAttemptFailure(deps) {
|
|
151
|
-
const { value, callbacks, abortController, turnState,
|
|
178
|
+
const { value, callbacks, abortController, turnState, abortCause, stallGuard, salvage, error, goal, turnOptions } = deps;
|
|
152
179
|
const maxRetries = deps.maxRetries ?? DEFAULT_MODEL_RETRIES;
|
|
180
|
+
const retryBaseDelayMs = deps.retryBaseDelayMs ?? DEFAULT_RETRY_BASE_DELAY_MS;
|
|
181
|
+
const overflowRetries = deps.overflowRetries ?? 0;
|
|
182
|
+
// Progress refills the shared pool: consecutive failures chain backoff, but
|
|
183
|
+
// a failed attempt that completed steps since the last retry starts fresh.
|
|
184
|
+
const retryAttempt = deps.progressSinceLastRetry && deps.retryAttempt > 0 ? 0 : deps.retryAttempt;
|
|
153
185
|
if (abortController.signal.aborted) {
|
|
154
186
|
if (abortCause.kind === 'model-stream-idle') {
|
|
155
187
|
// Transport stall, not a user cancel. Preserve completed work first: the
|
|
@@ -158,12 +190,12 @@ export function handleAttemptFailure(deps) {
|
|
|
158
190
|
// instead of re-running — possibly mutating — tool work.
|
|
159
191
|
salvageConversationToLastStep(callbacks, salvage);
|
|
160
192
|
if (stallGuard?.retryEligible) {
|
|
161
|
-
const delay = retryDelayMs(retryAttempt);
|
|
193
|
+
const delay = retryDelayMs(retryAttempt, retryBaseDelayMs);
|
|
162
194
|
callbacks.onEvent?.(agentEvent({ type: 'retry', attempt: retryAttempt + 1, maxAttempts: maxRetries, delayMs: delay, error: `model stream idle for ${formatSeconds(IDLE_TIMEOUT_MS)}` }));
|
|
163
195
|
callbacks.addMessage({ role: 'system', text: `Model stream stalled for ${formatIdleMinutes(IDLE_TIMEOUT_MS)}; retrying attempt ${retryAttempt + 1}/${maxRetries} in ${formatSeconds(delay)}. Completed steps are preserved.` });
|
|
164
196
|
// freshController: this stall aborted the controller to kill the hung
|
|
165
197
|
// stream; the retry needs a live signal.
|
|
166
|
-
return { status: 'failed', retry: { attempt: retryAttempt + 1,
|
|
198
|
+
return { status: 'failed', retry: { attempt: retryAttempt + 1, delayMs: delay, freshController: true } };
|
|
167
199
|
}
|
|
168
200
|
// Bounded retries exhausted, or the stalled step emitted partial output.
|
|
169
201
|
// Pause with the active goal preserved (work state is untouched by this
|
|
@@ -189,15 +221,36 @@ export function handleAttemptFailure(deps) {
|
|
|
189
221
|
}
|
|
190
222
|
const text = error instanceof Error ? error.message : String(error);
|
|
191
223
|
callbacks.debugLog(`error: ${text}`);
|
|
192
|
-
|
|
224
|
+
// Bounded overflow retries with progressive shrink (Pillar 1.4): each retry
|
|
225
|
+
// compacts and multiplies the message budget by 0.6; once MAX_OVERFLOW_RETRIES
|
|
226
|
+
// are consumed the goal checkpoints instead of hard-failing.
|
|
227
|
+
if (overflowRetries >= MAX_OVERFLOW_RETRIES && isContextOverflowError(error)) {
|
|
228
|
+
callbacks.onEvent?.(agentEvent({ type: 'context_overflow', recovered: false, error: text }));
|
|
229
|
+
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
|
+
// Project the goal's evidence before checkpointing: the failing attempt
|
|
231
|
+
// threw before finalizeAttemptOutcome, so its validation outcome/kind and
|
|
232
|
+
// unresolved red evidence would otherwise be lost from the checkpoint
|
|
233
|
+
// (R2-02) — a resumed goal must still owe the same checks.
|
|
234
|
+
projectGoalEvidence(turnState, goal);
|
|
235
|
+
const carried = {
|
|
236
|
+
...(turnOptions.goalContext?.requestHash ? { requestHash: turnOptions.goalContext.requestHash } : {}),
|
|
237
|
+
...(redPairStatus(goal) !== 'satisfied' && goal.redEvidence ? { redEvidence: { ...goal.redEvidence } } : {}),
|
|
238
|
+
...(turnState.validationKind ? { validationKind: turnState.validationKind } : {}),
|
|
239
|
+
};
|
|
240
|
+
return { status: 'failed', resume: buildIncompleteGoalResume(value, turnOptions.goalContext?.goalId ?? goal.id, turnOptions.goalContext?.cycle ?? 1, turnState, 'context_exhausted', carried) };
|
|
241
|
+
}
|
|
242
|
+
if (isContextOverflowError(error)) {
|
|
193
243
|
const canCompact = typeof callbacks.compactConversation === 'function';
|
|
194
244
|
const compacted = canCompact
|
|
195
245
|
? callbacks.compactConversation?.('Automatic recovery after provider context overflow. Preserve the active user request and concrete next steps.') ?? false
|
|
196
246
|
: false;
|
|
197
247
|
callbacks.onEvent?.(agentEvent({ type: 'context_overflow', recovered: compacted, error: text }));
|
|
248
|
+
callbacks.onEvent?.(agentEvent({ type: 'compaction_start', reason: 'overflow', method: 'heuristic' }));
|
|
249
|
+
callbacks.onEvent?.(agentEvent({ type: 'compaction_end', reason: 'overflow', method: compacted ? 'heuristic' : 'none', compacted, willRetry: compacted }));
|
|
198
250
|
if (compacted) {
|
|
199
|
-
|
|
200
|
-
|
|
251
|
+
const shrink = OVERFLOW_SHRINK_FACTOR ** (overflowRetries + 1);
|
|
252
|
+
callbacks.addMessage({ role: 'system', text: `Context overflow detected; compacted older context and retrying the same request at ${Math.round(shrink * 100)}% of the message budget.` });
|
|
253
|
+
return { status: 'failed', retry: { attempt: retryAttempt, delayMs: 0, overflowShrinkFactor: shrink } };
|
|
201
254
|
}
|
|
202
255
|
callbacks.addMessage({ role: 'system', text: canCompact
|
|
203
256
|
? 'Context overflow detected, but there was not enough conversation history to compact automatically.'
|
|
@@ -206,10 +259,10 @@ export function handleAttemptFailure(deps) {
|
|
|
206
259
|
// Transient model errors share the bounded retry pool with idle-stream
|
|
207
260
|
// stalls, so a turn can never retry more than its configured total.
|
|
208
261
|
if (retryAttempt < maxRetries && isRetryableModelError(error)) {
|
|
209
|
-
const delay = retryDelayMs(retryAttempt);
|
|
262
|
+
const delay = retryDelayMs(retryAttempt, retryBaseDelayMs);
|
|
210
263
|
callbacks.onEvent?.(agentEvent({ type: 'retry', attempt: retryAttempt + 1, maxAttempts: maxRetries, delayMs: delay, error: text }));
|
|
211
264
|
callbacks.addMessage({ role: 'system', text: `Transient model error; retrying attempt ${retryAttempt + 1}/${maxRetries} in ${formatSeconds(delay)}: ${text}` });
|
|
212
|
-
return { status: 'failed', retry: { attempt: retryAttempt + 1,
|
|
265
|
+
return { status: 'failed', retry: { attempt: retryAttempt + 1, delayMs: delay } };
|
|
213
266
|
}
|
|
214
267
|
callbacks.addMessage({ role: 'assistant', text: `Model call failed: ${text}` });
|
|
215
268
|
return { status: 'failed' };
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import type { ModelMessage, ToolSet } from 'ai';
|
|
2
2
|
import type { ContextFile } from '../../../config/contextFiles.js';
|
|
3
|
-
import { type SessionGoal } from '../../../core/agent/goalPolicy.js';
|
|
4
|
-
import { calculateRequestTokenBudget } from '../../../core/agent/contextBudget.js';
|
|
5
3
|
import { type ToolExecutionBudgetState, type TurnBudget } from '../../../core/agent/budgets.js';
|
|
4
|
+
import { type SessionGoal } from '../../../core/agent/goalPolicy.js';
|
|
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';
|
|
@@ -47,15 +48,20 @@ export interface AttemptSetup {
|
|
|
47
48
|
toolCategories: Map<string, ToolCategory>;
|
|
48
49
|
/** Retry-pool size for this attempt's turn, from the `modelRetries` setting (default 2). */
|
|
49
50
|
modelRetries: number;
|
|
51
|
+
/** Backoff base for the shared model-retry pool, from the `retryBaseDelayMs` setting (default 1000ms). */
|
|
52
|
+
retryBaseDelayMs: number;
|
|
50
53
|
}
|
|
51
54
|
export interface AttemptSetupDeps {
|
|
52
55
|
value: string;
|
|
53
56
|
contextFiles: ContextFile[];
|
|
54
57
|
callbacks: StreamCallbacks;
|
|
55
58
|
retryingExistingRequest: boolean;
|
|
56
|
-
|
|
59
|
+
/** Multiplier for the message-token budget after context-overflow retries (1 = none, 0.6/0.36 after each; Pillar 1.4). */
|
|
60
|
+
overflowShrinkFactor: number;
|
|
57
61
|
session: PromptSession | undefined;
|
|
58
62
|
modelOverride: string | undefined;
|
|
63
|
+
/** Run-scoped reasoning level/sentinel (CLI `--reasoning`); overrides the stored setting for this run. */
|
|
64
|
+
reasoningOverride: StoredReasoningSetting | undefined;
|
|
59
65
|
abortController: AbortController;
|
|
60
66
|
turnOptions: TurnExecutionOptions;
|
|
61
67
|
turnScope: {
|
|
@@ -67,6 +73,10 @@ export interface AttemptSetupDeps {
|
|
|
67
73
|
sliceBudget: ToolExecutionBudgetState;
|
|
68
74
|
goal: SessionGoal;
|
|
69
75
|
onContextFileRead: (path: string) => void;
|
|
76
|
+
/** Turn-scoped usage anchor for provider-usage-backed context estimation (Pillar 1.1). */
|
|
77
|
+
usageAnchor: {
|
|
78
|
+
current: ContextUsageAnchor | undefined;
|
|
79
|
+
};
|
|
70
80
|
}
|
|
71
81
|
/**
|
|
72
82
|
* Assemble one attempt: resolve the model (single fresh settings read, CR-024),
|
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
import { readSettings } from '../../../config/settings.js';
|
|
2
|
-
import { DEFAULT_MODEL_RETRIES } from '../../../core/agent/budgets.js';
|
|
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
4
|
import { isPlanOnlyRequest } from '../../../core/agent/goalPolicy.js';
|
|
5
5
|
import { formatGoalStatus } from '../../../core/agent/goalPolicy.js';
|
|
6
|
-
import { calculateRequestTokenBudget,
|
|
7
|
-
import {
|
|
6
|
+
import { calculateRequestTokenBudget, estimateConversationTokens } from '../../../core/agent/contextBudget.js';
|
|
7
|
+
import { stripSyntheticControls, withSyntheticControl, withoutSystemMessages } from '../../../core/agent/requestAssembly.js';
|
|
8
8
|
import { compactModelMessages } from '../../../core/agent/compaction.js';
|
|
9
|
-
import { DEFAULT_MAX_OUTPUT_TOKENS, MAIN_STEP_LIMIT, MAIN_TOOL_CALL_LIMIT, SUBAGENT_TOOL_DEADLINE_MS, DEFAULT_TOOL_DEADLINE_MS, withToolExecutionBudget } from '../../../core/agent/budgets.js';
|
|
10
9
|
import { withToolDeadline } from '../../../core/deadline.js';
|
|
11
10
|
import { isMutatingCapability, isValidationCapable } from '../../../core/agent/toolCapabilities.js';
|
|
12
11
|
import { userTurnMessage } from '../../../core/attachments/imageAttachments.js';
|
|
@@ -40,11 +39,13 @@ export function restrictToRescueTools(tools) {
|
|
|
40
39
|
* configured (the caller-reported failure path).
|
|
41
40
|
*/
|
|
42
41
|
export async function prepareAttempt(deps) {
|
|
43
|
-
const { value, contextFiles, callbacks, retryingExistingRequest,
|
|
44
|
-
// Single choke point: one fresh settings read per
|
|
45
|
-
// resolution and request assembly (CR-024
|
|
42
|
+
const { value, contextFiles, callbacks, retryingExistingRequest, session, modelOverride, reasoningOverride, abortController, turnOptions, turnScope, turnBudget, goal, globalBudget, sliceBudget, onContextFileRead, usageAnchor } = deps;
|
|
43
|
+
// Single choke point: one fresh settings read per attempt, shared by model
|
|
44
|
+
// resolution and request assembly (CR-024, relaxed in Pillar 1.9 so a
|
|
45
|
+
// provider/model switch mid-goal applies from the next attempt — the first
|
|
46
|
+
// attempt of each physical turn keeps the original read).
|
|
46
47
|
const turnSettings = await readSettings();
|
|
47
|
-
const runtime = await modelWithConfig({ cwd: session?.cwd, modelSelector: modelOverride }, turnSettings);
|
|
48
|
+
const runtime = await modelWithConfig({ cwd: session?.cwd, modelSelector: modelOverride, reasoningOverride }, turnSettings);
|
|
48
49
|
if (!runtime?.model) {
|
|
49
50
|
callbacks.addMessage({ role: 'assistant', text: 'No model provider configured. Run /provider to choose or add a provider. haze cannot hallucinate without a model. Progress.' });
|
|
50
51
|
return undefined;
|
|
@@ -88,9 +89,14 @@ export async function prepareAttempt(deps) {
|
|
|
88
89
|
callbacks.setWorkState?.(goal);
|
|
89
90
|
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
90
91
|
const likelyPlanOnlyRequest = isPlanOnlyRequest(value);
|
|
91
|
-
|
|
92
|
+
// Keep the active provider history exact. Routine tool-history slimming used
|
|
93
|
+
// to rewrite older successful calls/results here, invalidating provider
|
|
94
|
+
// prompt-cache prefixes before the context budget required compaction.
|
|
95
|
+
// Durable session snapshots are slimmed independently at the persistence
|
|
96
|
+
// boundary; only the model-aware compaction below may rewrite active history.
|
|
97
|
+
const durableRequestMessages = retryingExistingRequest
|
|
92
98
|
? stripSyntheticControls(callbacks.getConversation())
|
|
93
|
-
: [...stripSyntheticControls(callbacks.getConversation()), userTurnMessage(value, turnOptions.attachments ?? [])]
|
|
99
|
+
: [...stripSyntheticControls(callbacks.getConversation()), userTurnMessage(value, turnOptions.attachments ?? [])];
|
|
94
100
|
// Model-aware request budget (RH-005): message allowance is the context
|
|
95
101
|
// window minus system prompt, tool schemas, output reserve, and a safety
|
|
96
102
|
// margin — not a fixed 40K constant. Small contexts get a safe budget; the
|
|
@@ -98,11 +104,21 @@ export async function prepareAttempt(deps) {
|
|
|
98
104
|
const requestedOutputTokens = runtime.config.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS;
|
|
99
105
|
const requestBudget = calculateRequestTokenBudget({ contextWindowTokens: runtime.config.contextWindowTokens, requestedOutputTokens, system: assembled.systemPrompt, tools: availableTools });
|
|
100
106
|
// A context-overflow retry progressively shrinks the target so it cannot loop
|
|
101
|
-
// at an unchanged budget; further overflows get even smaller (RH-005
|
|
102
|
-
|
|
107
|
+
// at an unchanged budget; further overflows get even smaller (RH-005, Pillar
|
|
108
|
+
// 1.4: 0.6 after the first, 0.36 after the second).
|
|
109
|
+
const overflowShrinkFactor = deps.overflowShrinkFactor;
|
|
110
|
+
const overflowTargetTokens = overflowShrinkFactor < 1 ? Math.floor(requestBudget.messageTokens * overflowShrinkFactor) : requestBudget.messageTokens;
|
|
111
|
+
const overheadTokens = requestBudget.systemTokens + requestBudget.toolSchemaTokens;
|
|
103
112
|
let requestMessages = durableRequestMessages;
|
|
104
|
-
if (
|
|
105
|
-
|
|
113
|
+
if (estimateConversationTokens(requestMessages, usageAnchor.current, overheadTokens).tokens > overflowTargetTokens) {
|
|
114
|
+
callbacks.onEvent?.(agentEvent({ type: 'compaction_start', reason: 'threshold', method: 'heuristic' }));
|
|
115
|
+
const compacted = compactModelMessages(requestMessages, { tokenBudget: overflowTargetTokens, workState: goal });
|
|
116
|
+
requestMessages = compacted.messages;
|
|
117
|
+
if (compacted.compacted) {
|
|
118
|
+
usageAnchor.current = undefined;
|
|
119
|
+
callbacks.recordCompaction?.({ method: 'heuristic', olderCount: compacted.olderCount, keptCount: compacted.keptCount, summary: compacted.summary ?? '' });
|
|
120
|
+
}
|
|
121
|
+
callbacks.onEvent?.(agentEvent({ type: 'compaction_end', reason: 'threshold', method: compacted.compacted ? 'heuristic' : 'none', compacted: compacted.compacted, olderCount: compacted.olderCount, keptCount: compacted.keptCount }));
|
|
106
122
|
}
|
|
107
123
|
requestMessages = withoutSystemMessages(requestMessages);
|
|
108
124
|
callbacks.setConversation(stripSyntheticControls(requestMessages));
|
|
@@ -113,7 +129,15 @@ export async function prepareAttempt(deps) {
|
|
|
113
129
|
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'request', stream: 'main', system: systemPrompt, messages: requestMessages, tools: Object.keys(availableTools), context: inputBreakdown.breakdown });
|
|
114
130
|
const contextFileSignatures = callbacks.contextFileSignatures ?? new Map(activeContextFiles.flatMap(file => file.signature ? [[file.path, file.signature]] : []));
|
|
115
131
|
const mutationPolicy = assembled.executionScope?.mutationPolicy ?? new WorkspaceMutationPolicy();
|
|
116
|
-
const toolExecutionContext = {
|
|
132
|
+
const toolExecutionContext = {
|
|
133
|
+
inFlightToolCalls: new Map(),
|
|
134
|
+
loadedContextFilePaths: new Set(activeContextFiles.map(file => file.path)),
|
|
135
|
+
loadedContextFileSignatures: contextFileSignatures,
|
|
136
|
+
onContextFileRead,
|
|
137
|
+
mutationPolicy,
|
|
138
|
+
blessedPaths: turnOptions.blessedPaths,
|
|
139
|
+
postMutationDiagnostics: assembled.postMutationDiagnostics,
|
|
140
|
+
};
|
|
117
141
|
const recoverySlice = turnOptions.recoverySlice;
|
|
118
142
|
const stepCap = recoverySlice?.maxSteps ?? MAIN_STEP_LIMIT;
|
|
119
143
|
// Rescue exposes only mutation + validation-capable built-in tools so
|
|
@@ -163,5 +187,6 @@ export async function prepareAttempt(deps) {
|
|
|
163
187
|
contextFiles: activeContextFiles,
|
|
164
188
|
toolCategories,
|
|
165
189
|
modelRetries: typeof turnSettings.modelRetries === 'number' ? turnSettings.modelRetries : DEFAULT_MODEL_RETRIES,
|
|
190
|
+
retryBaseDelayMs: typeof turnSettings.retryBaseDelayMs === 'number' ? turnSettings.retryBaseDelayMs : DEFAULT_RETRY_BASE_DELAY_MS,
|
|
166
191
|
};
|
|
167
192
|
}
|
|
@@ -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,8 @@ 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;
|
|
35
38
|
}
|
|
36
39
|
/** Supervisor-level checkpoint persisted between physical turns (in memory and, via the goal ledger, in the session JSONL). */
|
|
37
40
|
export interface GoalCheckpoint {
|
|
@@ -60,6 +63,8 @@ export interface GoalCheckpoint {
|
|
|
60
63
|
requestHash?: string;
|
|
61
64
|
intent?: RequestIntent;
|
|
62
65
|
redEvidence?: RedEvidence;
|
|
66
|
+
/** Kind of the carried validation, when one rode the checkpoint (R2-03). */
|
|
67
|
+
validationKind?: ValidationKind;
|
|
63
68
|
}
|
|
64
69
|
/** Durable goal-ledger append (P1): one entry per supervisor boundary; the writer stamps `type`/`at`. Shared by the supervisor and the session recorder. */
|
|
65
70
|
export interface GoalLedgerAppend {
|
|
@@ -100,6 +105,7 @@ export interface CarriedGoalEvidence {
|
|
|
100
105
|
requestHash?: string;
|
|
101
106
|
intent?: RequestIntent;
|
|
102
107
|
redEvidence?: RedEvidence;
|
|
108
|
+
validationKind?: ValidationKind;
|
|
103
109
|
}
|
|
104
110
|
/**
|
|
105
111
|
* Build the checkpoint payload for a `recoverable-incomplete` attempt that no
|
|
@@ -54,5 +54,6 @@ 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 } : {}),
|
|
57
58
|
};
|
|
58
59
|
}
|
|
@@ -1,10 +1,11 @@
|
|
|
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. */
|
|
7
|
-
export type GoalStopReason = 'completed' | 'no-progress' | 'goal-deadline' | 'blocked' | 'model-error' | 'model-stream-idle' | 'user-aborted';
|
|
8
|
+
export type GoalStopReason = 'completed' | 'no-progress' | 'goal-deadline' | 'blocked' | 'model-error' | 'model-stream-idle' | 'user-aborted' | 'context-exhausted';
|
|
8
9
|
export type { GoalLedgerAppend };
|
|
9
10
|
/** Authoritative outcome of a logical goal (one or more physical turns). */
|
|
10
11
|
export interface GoalRunResult {
|
|
@@ -23,6 +24,7 @@ export interface GoalRunResult {
|
|
|
23
24
|
kind: 'model-stream-idle';
|
|
24
25
|
request: string;
|
|
25
26
|
retryAttempt: number;
|
|
27
|
+
checkpoint?: GoalCheckpoint;
|
|
26
28
|
} | {
|
|
27
29
|
kind: 'incomplete-goal';
|
|
28
30
|
checkpoint: GoalCheckpoint;
|
|
@@ -35,6 +37,8 @@ export interface GoalRunOptions {
|
|
|
35
37
|
callbacks: StreamCallbacks;
|
|
36
38
|
session?: PromptSession;
|
|
37
39
|
modelOverride?: string;
|
|
40
|
+
/** Run-scoped reasoning level/sentinel (CLI `--reasoning`); applies to every attempt of the goal. */
|
|
41
|
+
reasoningOverride?: StoredReasoningSetting;
|
|
38
42
|
/** Whole-logical-goal wall-clock budget (headless `--timeout`); unset means continue while progress. */
|
|
39
43
|
goalDeadlineMs?: number;
|
|
40
44
|
/** Base per-turn options (attachments, blessed paths); attachments apply to the first physical turn only. */
|
|
@@ -43,6 +47,7 @@ export interface GoalRunOptions {
|
|
|
43
47
|
resumeFrom?: {
|
|
44
48
|
kind: 'model-stream-idle';
|
|
45
49
|
retryAttempt: number;
|
|
50
|
+
checkpoint?: GoalCheckpoint;
|
|
46
51
|
} | {
|
|
47
52
|
kind: 'incomplete-goal';
|
|
48
53
|
checkpoint: GoalCheckpoint;
|