@denizokcu/haze 0.11.0 → 1.1.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 +33 -0
- package/README.md +28 -14
- package/SECURITY.md +5 -3
- package/dist/buildInfo.json +3 -3
- package/dist/cli/chat/TaskBar.js +1 -1
- package/dist/cli/chat/chatMetrics.d.ts +2 -2
- package/dist/cli/chat/chatMetrics.js +1 -1
- package/dist/cli/chat/fileMentionSuggestions.js +1 -1
- package/dist/cli/chat/inputSuggestions.d.ts +8 -16
- package/dist/cli/chat/inputSuggestions.js +10 -41
- package/dist/cli/chat/messages.d.ts +0 -2
- package/dist/cli/chat/messages.js +5 -5
- package/dist/cli/chat/sessionLifecycle.d.ts +2 -1
- package/dist/cli/chat/turnState.d.ts +1 -1
- package/dist/cli/chat/wizardDispatch.d.ts +90 -28
- package/dist/cli/chat/wizardDispatch.js +257 -130
- package/dist/cli/commands/chat.js +61 -77
- package/dist/cli/commands/chatModes.d.ts +8 -1
- package/dist/cli/commands/chatModes.js +9 -44
- package/dist/cli/commands/commandHelp.js +2 -0
- package/dist/cli/commands/commands.js +2 -0
- package/dist/cli/commands/doctor.js +1 -1
- package/dist/cli/commands/formatters.d.ts +3 -3
- package/dist/cli/commands/formatters.js +12 -25
- package/dist/cli/commands/providerWizard.js +2 -3
- package/dist/cli/commands/runCommand.js +1 -1
- package/dist/cli/commands/serverWizard.d.ts +34 -0
- package/dist/cli/commands/{mcpWizard.js → serverWizard.js} +44 -2
- package/dist/cli/commands/settingsSummary.js +2 -0
- package/dist/cli/commands/skillsWizard.d.ts +41 -0
- package/dist/cli/commands/{skillWizard.js → skillsWizard.js} +33 -11
- package/dist/cli/commands/streaming/abortCause.d.ts +2 -1
- package/dist/cli/commands/streaming/agentAttempt.d.ts +43 -0
- package/dist/cli/commands/streaming/agentAttempt.js +79 -0
- package/dist/cli/commands/streaming/attemptLifecycle.d.ts +56 -0
- package/dist/cli/commands/streaming/attemptLifecycle.js +110 -0
- package/dist/cli/commands/streaming/attemptOutcome.d.ts +96 -0
- package/dist/cli/commands/streaming/attemptOutcome.js +206 -0
- package/dist/cli/commands/streaming/attemptSetup.d.ts +78 -0
- package/dist/cli/commands/streaming/attemptSetup.js +167 -0
- package/dist/cli/commands/streaming/goalCheckpoint.d.ts +1 -1
- package/dist/cli/commands/streaming/goalCheckpoint.js +2 -2
- package/dist/cli/commands/streaming/goalSupervisor.js +9 -6
- package/dist/cli/commands/streaming/stallRecovery.d.ts +94 -0
- package/dist/cli/commands/streaming/stallRecovery.js +105 -0
- package/dist/cli/commands/streaming/streamLoop.d.ts +72 -0
- package/dist/cli/commands/streaming/streamLoop.js +448 -0
- package/dist/cli/commands/streaming/toolCallRecovery.d.ts +14 -0
- package/dist/cli/commands/streaming/toolCallRecovery.js +56 -0
- package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +2 -1
- package/dist/cli/commands/streaming/turnRuntime.d.ts +4 -0
- package/dist/cli/commands/streaming/turnRuntime.js +6 -0
- package/dist/cli/commands/streaming.d.ts +14 -25
- package/dist/cli/commands/streaming.js +43 -754
- package/dist/cli/commands/themesCommand.d.ts +17 -0
- package/dist/cli/commands/themesCommand.js +24 -0
- package/dist/cli/commands/wizardFlow.d.ts +341 -0
- package/dist/cli/commands/wizardFlow.js +397 -0
- package/dist/cli/contextReport.js +3 -0
- package/dist/cli/index.js +1 -1
- package/dist/config/contextFiles.js +9 -3
- package/dist/config/inputHistory.d.ts +0 -1
- package/dist/config/inputHistory.js +1 -1
- package/dist/config/modelDiscovery.d.ts +0 -15
- package/dist/config/modelDiscovery.js +1 -1
- package/dist/config/settings.d.ts +9 -0
- package/dist/config/settings.js +4 -0
- package/dist/config/skillSettings.js +4 -4
- package/dist/config/updateCheck.d.ts +0 -1
- package/dist/config/updateCheck.js +1 -1
- package/dist/core/agent/budgets.d.ts +63 -1
- package/dist/core/agent/budgets.js +84 -1
- package/dist/core/agent/compaction.js +1 -1
- package/dist/core/agent/completionController.d.ts +7 -13
- package/dist/core/agent/completionController.js +17 -8
- package/dist/core/agent/contextBudget.d.ts +0 -4
- package/dist/core/agent/contextBudget.js +3 -3
- package/dist/core/agent/errors.d.ts +0 -1
- package/dist/core/agent/errors.js +1 -1
- package/dist/core/agent/events.d.ts +5 -1
- package/dist/core/{goal/completionPolicy.d.ts → agent/goalPolicy.d.ts} +18 -0
- package/dist/core/agent/goalPolicy.js +106 -0
- package/dist/core/agent/requestAssembly.d.ts +2 -2
- package/dist/core/agent/requestAssembly.js +16 -4
- package/dist/core/agent/toolCapabilities.d.ts +2 -2
- package/dist/core/agent/toolCapabilities.js +5 -5
- package/dist/core/agent/toolOutputStore.js +1 -1
- package/dist/core/agent/toolResults.js +1 -1
- package/dist/core/agent/workState.d.ts +6 -3
- package/dist/core/agent/workState.js +62 -7
- package/dist/core/attachments/imageAttachments.js +90 -42
- package/dist/core/deadline.d.ts +0 -6
- package/dist/core/deadline.js +1 -1
- package/dist/core/io/boundedRead.js +1 -1
- package/dist/core/limits.d.ts +51 -0
- package/dist/core/limits.js +51 -0
- package/dist/core/log/llmLog.js +1 -1
- package/dist/core/process/backgroundRegistry.d.ts +2 -3
- package/dist/core/process/backgroundRegistry.js +10 -6
- package/dist/core/process/userShell.d.ts +16 -0
- package/dist/core/process/userShell.js +59 -0
- package/dist/core/safety/secretPaths.d.ts +18 -0
- package/dist/core/safety/secretPaths.js +115 -0
- package/dist/core/safety/shellClassifier.d.ts +11 -0
- package/dist/core/safety/{bashClassifier.js → shellClassifier.js} +5 -3
- package/dist/core/safety/urlGuard.d.ts +1 -1
- package/dist/core/session/sessionSlimming.d.ts +0 -3
- package/dist/core/session/sessionSlimming.js +2 -3
- package/dist/core/session/sessionStore.d.ts +1 -0
- package/dist/core/session/sessionStore.js +39 -20
- package/dist/core/{bashOutput → shellOutput}/lineFilter.js +8 -2
- package/dist/core/{bashOutput → shellOutput}/reducers/search.d.ts +0 -1
- package/dist/core/{bashOutput → shellOutput}/reducers/search.js +1 -1
- package/dist/core/shellOutput/registry.d.ts +2 -0
- package/dist/core/{bashOutput → shellOutput}/registry.js +3 -3
- package/dist/core/{bashOutput → shellOutput}/types.d.ts +6 -5
- package/dist/core/subagent/contracts.d.ts +2 -14
- package/dist/core/subagent/contracts.js +3 -3
- package/dist/core/subagent/executionProfiles.js +2 -2
- package/dist/core/subagent/subagentRunner.js +3 -4
- package/dist/core/toolOutput/reduction.d.ts +0 -12
- package/dist/core/toolOutput/reduction.js +1 -1
- package/dist/core/validation/outputParser.d.ts +2 -2
- package/dist/llm/client.js +5 -1
- package/dist/llm/hazeTools.d.ts +139 -124
- package/dist/llm/hazeTools.js +20 -11
- package/dist/llm/initPrompt.js +1 -1
- package/dist/llm/lsp/client.d.ts +45 -0
- package/dist/llm/lsp/client.js +195 -0
- package/dist/llm/lsp/pool.d.ts +23 -0
- package/dist/llm/lsp/pool.js +86 -0
- package/dist/llm/lsp/protocol.d.ts +64 -0
- package/dist/llm/lsp/protocol.js +128 -0
- package/dist/llm/lsp/requests.d.ts +94 -0
- package/dist/llm/lsp/requests.js +119 -0
- package/dist/llm/lspTools.d.ts +3824 -570
- package/dist/llm/lspTools.js +65 -1
- package/dist/llm/openaiCodex.d.ts +0 -2
- package/dist/llm/openaiCodex.js +0 -4
- package/dist/llm/openaiCodexOAuth.d.ts +0 -3
- package/dist/llm/openaiCodexOAuth.js +6 -3
- package/dist/llm/requestContext.d.ts +5 -1
- package/dist/llm/requestContext.js +25 -2
- package/dist/llm/systemPrompt.d.ts +1 -0
- package/dist/llm/systemPrompt.js +16 -7
- package/dist/llm/toolResultTypes.d.ts +1 -15
- package/dist/llm/toolResultTypes.js +1 -4
- package/dist/llm/tools/editMatch.d.ts +0 -9
- package/dist/llm/tools/editMatch.js +1 -1
- package/dist/llm/tools/failures.d.ts +6 -0
- package/dist/llm/tools/failures.js +8 -2
- package/dist/llm/tools/fetchTool.js +1 -1
- package/dist/llm/tools/fileToolShared.d.ts +4 -2
- package/dist/llm/tools/fileToolShared.js +9 -5
- package/dist/llm/tools/gitIgnore.d.ts +25 -32
- package/dist/llm/tools/gitIgnore.js +216 -98
- package/dist/llm/tools/grepParse.d.ts +2 -1
- package/dist/llm/tools/grepRunner.d.ts +1 -1
- package/dist/llm/tools/grepRunner.js +2 -2
- package/dist/llm/tools/outputCap.d.ts +2 -7
- package/dist/llm/tools/outputCap.js +3 -3
- package/dist/llm/tools/processTool.d.ts +16 -16
- package/dist/llm/tools/processTool.js +1 -1
- package/dist/llm/tools/readRecovery.d.ts +0 -2
- package/dist/llm/tools/readRecovery.js +4 -2
- package/dist/llm/tools/{bashTool.d.ts → shellTool.d.ts} +123 -107
- package/dist/llm/tools/{bashTool.js → shellTool.js} +18 -14
- package/dist/llm/tools/toolContext.js +5 -5
- package/dist/llm/tools/workspaceFile.d.ts +4 -4
- package/dist/llm/tools/workspaceFile.js +29 -17
- package/dist/llm/webFetch.d.ts +1 -1
- package/dist/skills/SkillLoader.d.ts +1 -11
- package/dist/skills/SkillLoader.js +1 -2
- package/dist/skills/types.d.ts +2 -1
- package/dist/ui/components/Header.js +1 -1
- package/dist/ui/components/MarkdownText.js +10 -10
- package/dist/ui/components/TextInput.d.ts +1 -1
- package/dist/ui/components/TextInput.js +2 -2
- package/dist/ui/terminalColors.d.ts +29 -0
- package/dist/ui/terminalColors.js +47 -0
- package/dist/ui/theme.d.ts +105 -10
- package/dist/ui/theme.js +126 -15
- package/dist/ui/themes/af-magic.d.ts +7 -0
- package/dist/ui/themes/af-magic.js +25 -0
- package/dist/ui/themes/agnoster.d.ts +10 -0
- package/dist/ui/themes/agnoster.js +40 -0
- package/dist/ui/themes/bira.d.ts +10 -0
- package/dist/ui/themes/bira.js +28 -0
- package/dist/ui/themes/bureau.d.ts +10 -0
- package/dist/ui/themes/bureau.js +28 -0
- package/dist/ui/themes/clean.d.ts +9 -0
- package/dist/ui/themes/clean.js +27 -0
- package/dist/ui/themes/cloud.d.ts +6 -0
- package/dist/ui/themes/cloud.js +24 -0
- package/dist/ui/themes/dst.d.ts +10 -0
- package/dist/ui/themes/dst.js +28 -0
- package/dist/ui/themes/fishy.d.ts +7 -0
- package/dist/ui/themes/fishy.js +25 -0
- package/dist/ui/themes/index.d.ts +8 -0
- package/dist/ui/themes/index.js +36 -0
- package/dist/ui/themes/light.d.ts +3 -0
- package/dist/ui/themes/light.js +21 -0
- package/dist/ui/themes/purple.d.ts +7 -0
- package/dist/ui/themes/purple.js +26 -0
- package/dist/ui/themes/robbyrussell.d.ts +8 -0
- package/dist/ui/themes/robbyrussell.js +26 -0
- package/dist/ui/themes/solarized-dark.d.ts +16 -0
- package/dist/ui/themes/solarized-dark.js +44 -0
- package/dist/ui/themes/solarized-light.d.ts +12 -0
- package/dist/ui/themes/solarized-light.js +40 -0
- package/dist/ui/themes/steeef.d.ts +11 -0
- package/dist/ui/themes/steeef.js +29 -0
- package/dist/utils/buildInfo.d.ts +6 -13
- package/dist/utils/buildInfo.js +6 -15
- package/dist/utils/fs.d.ts +7 -5
- package/dist/utils/fs.js +5 -2
- package/dist/utils/path.d.ts +0 -1
- package/dist/utils/path.js +1 -1
- package/package.json +6 -4
- package/dist/cli/commands/lspWizard.d.ts +0 -14
- package/dist/cli/commands/lspWizard.js +0 -44
- package/dist/cli/commands/mcpWizard.d.ts +0 -15
- package/dist/cli/commands/skillConfirmRemove.d.ts +0 -11
- package/dist/cli/commands/skillConfirmRemove.js +0 -20
- package/dist/cli/commands/skillCreation.d.ts +0 -12
- package/dist/cli/commands/skillCreation.js +0 -14
- package/dist/cli/commands/skillWizard.d.ts +0 -17
- package/dist/cli/commands/streaming/idleTimer.d.ts +0 -26
- package/dist/cli/commands/streaming/idleTimer.js +0 -24
- package/dist/cli/commands/streaming/turnOutcome.d.ts +0 -27
- package/dist/cli/commands/streaming/turnOutcome.js +0 -29
- package/dist/cli/commands/wizardActions.d.ts +0 -47
- package/dist/cli/commands/wizardActions.js +0 -47
- package/dist/cli/commands/wizardInput.d.ts +0 -4
- package/dist/cli/commands/wizardInput.js +0 -19
- package/dist/cli/commands/wizardPrompts.d.ts +0 -22
- package/dist/cli/commands/wizardPrompts.js +0 -58
- package/dist/cli/commands/wizardSuggestions.d.ts +0 -31
- package/dist/cli/commands/wizardSuggestions.js +0 -190
- package/dist/cli/commands/wizardTransition.d.ts +0 -37
- package/dist/cli/commands/wizardTransition.js +0 -43
- package/dist/core/agent/toolExecutionBudget.d.ts +0 -35
- package/dist/core/agent/toolExecutionBudget.js +0 -49
- package/dist/core/agent/turnBudget.d.ts +0 -35
- package/dist/core/agent/turnBudget.js +0 -27
- package/dist/core/bashOutput/ansi.d.ts +0 -1
- package/dist/core/bashOutput/ansi.js +0 -7
- package/dist/core/bashOutput/registry.d.ts +0 -4
- package/dist/core/goal/completionPolicy.js +0 -43
- package/dist/core/goal/requestClassifier.d.ts +0 -3
- package/dist/core/goal/requestClassifier.js +0 -18
- package/dist/core/goal/sessionGoal.d.ts +0 -8
- package/dist/core/goal/sessionGoal.js +0 -30
- package/dist/core/limits/byteBudgets.d.ts +0 -20
- package/dist/core/limits/byteBudgets.js +0 -20
- package/dist/core/limits/textBudgets.d.ts +0 -25
- package/dist/core/limits/textBudgets.js +0 -25
- package/dist/core/safety/bashClassifier.d.ts +0 -10
- package/dist/llm/lsp.d.ts +0 -149
- package/dist/llm/lsp.js +0 -368
- package/dist/ui/components/ErrorView.d.ts +0 -4
- package/dist/ui/components/ErrorView.js +0 -7
- package/dist/utils/yaml.d.ts +0 -2
- package/dist/utils/yaml.js +0 -8
- package/examples/skills/files/SKILL.md +0 -16
- package/examples/skills/files/examples/file-editing.md +0 -3
- /package/dist/core/{bashOutput → shellOutput}/command.d.ts +0 -0
- /package/dist/core/{bashOutput → shellOutput}/command.js +0 -0
- /package/dist/core/{bashOutput → shellOutput}/lineFilter.d.ts +0 -0
- /package/dist/core/{bashOutput → shellOutput}/reducers/content.d.ts +0 -0
- /package/dist/core/{bashOutput → shellOutput}/reducers/content.js +0 -0
- /package/dist/core/{bashOutput → shellOutput}/reducers/gh.d.ts +0 -0
- /package/dist/core/{bashOutput → shellOutput}/reducers/gh.js +0 -0
- /package/dist/core/{bashOutput → shellOutput}/reducers/git.d.ts +0 -0
- /package/dist/core/{bashOutput → shellOutput}/reducers/git.js +0 -0
- /package/dist/core/{bashOutput → shellOutput}/reducers/validation.d.ts +0 -0
- /package/dist/core/{bashOutput → shellOutput}/reducers/validation.js +0 -0
- /package/dist/core/{bashOutput → shellOutput}/types.js +0 -0
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { createTurnExecutionState, decideTerminalStatus, normalizeFinishReason } from '../../../core/agent/completionController.js';
|
|
2
|
+
import { agentEvent } from '../../../core/agent/events.js';
|
|
3
|
+
import { isContextOverflowError, isRetryableModelError } from '../../../core/agent/errors.js';
|
|
4
|
+
import { completionRescuePrompt, goalContinuationPrompt, lengthContinuationPrompt } from '../../../core/agent/goalPolicy.js';
|
|
5
|
+
import { assessCompletionReadiness, classifyTerminalOutcome, decideGoalContinuation, decideLengthRecovery, decideRescue, describeCompletionReadiness, goalContinuationRecoverable, isBudgetExhausted, rescueEligibleRequest } from '../../../core/agent/completionController.js';
|
|
6
|
+
import { clampSlice, remainingSteps, remainingToolCalls, DEFAULT_TURN_DEADLINE_MS, IDLE_TIMEOUT_MS, DEFAULT_MODEL_RETRIES } from '../../../core/agent/budgets.js';
|
|
7
|
+
import { deriveValidationOutcome } from '../../../core/agent/workState.js';
|
|
8
|
+
import { withoutRejectedAssistantFinal } from '../../../core/agent/requestAssembly.js';
|
|
9
|
+
import { buildIncompleteGoalResume } from './goalCheckpoint.js';
|
|
10
|
+
import { formatSeconds } from '../formatters.js';
|
|
11
|
+
import { retryDelayMs } from './turnRuntime.js';
|
|
12
|
+
import { formatIdleMinutes, salvageConversationToLastStep } from './stallRecovery.js';
|
|
13
|
+
/**
|
|
14
|
+
* CLI adapter for the authoritative turn-status decision. The pure policy
|
|
15
|
+
* lives in `core/agent/completionController.ts`; this keeps the single call site
|
|
16
|
+
* in the agent turn (see streaming/AGENTS.md) and preserves the documented
|
|
17
|
+
* field-based signature exercised by `tests/cli/commands/streaming/attemptOutcome.test.ts`.
|
|
18
|
+
*
|
|
19
|
+
* The optional work-evidence fields (intent, mutation/validation counts, task
|
|
20
|
+
* progress) project the turn-wide `TurnExecutionState`; when omitted, the
|
|
21
|
+
* defaults cannot reject a turn (unknown intent, no mutations, no task list).
|
|
22
|
+
*/
|
|
23
|
+
export function terminalTurnStatus(input) {
|
|
24
|
+
void input.error;
|
|
25
|
+
const state = {
|
|
26
|
+
...createTurnExecutionState(),
|
|
27
|
+
aborted: input.aborted,
|
|
28
|
+
finishCause: normalizeFinishReason(input.finishReason),
|
|
29
|
+
intent: input.intent ?? 'unknown',
|
|
30
|
+
mutationCount: input.mutationCount ?? 0,
|
|
31
|
+
...(input.validationOutcome ? { validationOutcome: input.validationOutcome } : {}),
|
|
32
|
+
...(input.taskProgress ? { taskProgress: input.taskProgress } : {}),
|
|
33
|
+
};
|
|
34
|
+
return decideTerminalStatus(state, {
|
|
35
|
+
sawToolCall: input.sawToolCall,
|
|
36
|
+
assistantText: input.assistantText,
|
|
37
|
+
lastToolOk: input.lastToolOk,
|
|
38
|
+
unresolvedToolInputError: Boolean(input.unresolvedToolInputError),
|
|
39
|
+
}, Boolean(input.budgetReached));
|
|
40
|
+
}
|
|
41
|
+
/** Keep terminal evidence truthful on normal, timeout, and forced-settlement paths. */
|
|
42
|
+
export function projectGoalEvidence(turnState, goal) {
|
|
43
|
+
turnState.intent = goal.intent;
|
|
44
|
+
turnState.validationOutcome = deriveValidationOutcome(goal);
|
|
45
|
+
turnState.mutationCount = goal.mutationCount;
|
|
46
|
+
turnState.validationKind = goal.validations.at(-1)?.kind ?? goal.carriedValidation?.kind;
|
|
47
|
+
turnState.validationAfterMutation = goal.validationSeq > 0 && goal.validationSeq >= goal.mutationSeq;
|
|
48
|
+
turnState.taskProgress = goal.taskProgress;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Classify the finished attempt: project work evidence onto the turn state,
|
|
52
|
+
* decide the authoritative turn status and goal status, then propose bounded
|
|
53
|
+
* recovery (length-continuation, goal continuation, rescue) or an
|
|
54
|
+
* `incomplete-goal` checkpoint when no same-turn recovery can run. Never
|
|
55
|
+
* reports incomplete work as `complete`.
|
|
56
|
+
*/
|
|
57
|
+
export function finalizeAttemptOutcome(deps) {
|
|
58
|
+
const { value, callbacks, abortController, turnOptions, turnState, turnBudget, goal, remainingTurnDeadlineMs, stream } = deps;
|
|
59
|
+
turnState.finishCause = normalizeFinishReason(stream.finishReason);
|
|
60
|
+
// Observable work evidence is projected through one helper so abnormal
|
|
61
|
+
// terminal paths report the same cumulative state.
|
|
62
|
+
projectGoalEvidence(turnState, goal);
|
|
63
|
+
turnState.budgetBoundary = isBudgetExhausted(turnState, turnBudget);
|
|
64
|
+
const completionEvidence = { sawToolCall: stream.sawToolCall, assistantText: stream.assistantText, lastToolOk: stream.lastToolOk, unresolvedToolInputError: stream.unresolvedToolInputError };
|
|
65
|
+
const readiness = assessCompletionReadiness(turnState, completionEvidence);
|
|
66
|
+
const classification = classifyTerminalOutcome(turnState, completionEvidence);
|
|
67
|
+
const turnStatus = terminalTurnStatus({ aborted: false, assistantText: stream.assistantText, sawToolCall: stream.sawToolCall, lastToolOk: stream.lastToolOk, finishReason: stream.finishReason, budgetReached: turnState.budgetBoundary, unresolvedToolInputError: stream.unresolvedToolInputError, intent: turnState.intent, mutationCount: turnState.mutationCount, validationOutcome: turnState.validationOutcome, taskProgress: turnState.taskProgress });
|
|
68
|
+
if (stream.unresolvedMalformedToolName)
|
|
69
|
+
callbacks.addMessage({ role: 'system', text: `${stream.unresolvedMalformedToolName} did not execute because its generated input remained invalid or truncated. The requested work is incomplete.` });
|
|
70
|
+
goal.phase = 'done';
|
|
71
|
+
// Goal status reflects completion readiness, not the shallow text status:
|
|
72
|
+
// unfinished-but-recoverable work is waiting on continuation (supervisor or
|
|
73
|
+
// the user), while tool/input failures are concrete blockers. Prose alone
|
|
74
|
+
// can never turn pending work into 'complete'.
|
|
75
|
+
goal.status = turnStatus === 'aborted' ? 'aborted'
|
|
76
|
+
: turnStatus === 'complete' ? 'complete'
|
|
77
|
+
: readiness === 'tool_failure' || readiness === 'unresolved_tool_input' ? 'blocked'
|
|
78
|
+
: goalContinuationRecoverable(readiness) ? 'needs-user'
|
|
79
|
+
: 'blocked';
|
|
80
|
+
callbacks.setWorkState?.(goal);
|
|
81
|
+
callbacks.setGoalStatus?.(undefined);
|
|
82
|
+
// Bounded recovery + the goal-level invariant. Length/rescue credits are
|
|
83
|
+
// single-use and only the main flow proposes them; goal continuation is
|
|
84
|
+
// repeatable while measurable progress continues. The invariant: when the
|
|
85
|
+
// attempt classified `recoverable-incomplete` and no same-turn recovery can
|
|
86
|
+
// run (budget/deadline boundary, exhausted slice, no-progress guard), the
|
|
87
|
+
// attempt returns an `incomplete-goal` checkpoint — never a silent failure,
|
|
88
|
+
// and never `complete`. The goal supervisor turns checkpoints into fresh
|
|
89
|
+
// physical turns; a bare runAgentTurn caller surfaces them as resume info.
|
|
90
|
+
const goalId = turnOptions.goalContext?.goalId ?? goal.id;
|
|
91
|
+
const goalCycle = turnOptions.goalContext?.cycle ?? 1;
|
|
92
|
+
const discardRejectedFinal = () => callbacks.setConversation(withoutRejectedAssistantFinal(callbacks.getConversation()));
|
|
93
|
+
const checkpointResult = () => {
|
|
94
|
+
discardRejectedFinal();
|
|
95
|
+
return { status: 'failed', resume: buildIncompleteGoalResume(value, goalId, goalCycle, turnState, readiness) };
|
|
96
|
+
};
|
|
97
|
+
if (!abortController.signal.aborted) {
|
|
98
|
+
const lengthDecision = decideLengthRecovery(turnState, turnBudget);
|
|
99
|
+
if (lengthDecision.action === 'continue') {
|
|
100
|
+
const clamped = clampSlice(lengthDecision.slice, { steps: remainingSteps(turnState.stepsUsed, turnBudget), toolCalls: remainingToolCalls(turnState.toolCallsUsed, turnBudget) });
|
|
101
|
+
if (clamped.steps > 0)
|
|
102
|
+
return { status: turnStatus, recovery: { kind: 'length', control: lengthContinuationPrompt(), slice: { maxSteps: clamped.steps, maxToolCalls: clamped.toolCalls } } };
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
const goalDecision = decideGoalContinuation(turnState, completionEvidence, turnBudget);
|
|
106
|
+
const rescueDecision = turnOptions.recoverySlice == null
|
|
107
|
+
? decideRescue(turnState, completionEvidence, turnBudget, rescueEligibleRequest(goal.intent))
|
|
108
|
+
: undefined;
|
|
109
|
+
const goalSlice = goalDecision.action === 'continue' && remainingTurnDeadlineMs() > 0
|
|
110
|
+
? clampSlice(goalDecision.slice, { steps: remainingSteps(turnState.stepsUsed, turnBudget), toolCalls: remainingToolCalls(turnState.toolCallsUsed, turnBudget) })
|
|
111
|
+
: undefined;
|
|
112
|
+
const rescueSlice = goalSlice && goalSlice.steps > 0 ? undefined : rescueDecision?.action === 'continue'
|
|
113
|
+
? clampSlice(rescueDecision.slice, { steps: remainingSteps(turnState.stepsUsed, turnBudget), toolCalls: remainingToolCalls(turnState.toolCallsUsed, turnBudget) })
|
|
114
|
+
: undefined;
|
|
115
|
+
if (goalSlice && goalSlice.steps > 0) {
|
|
116
|
+
discardRejectedFinal();
|
|
117
|
+
if (readiness === 'validation_failed' || readiness === 'validation_stale' || readiness === 'validation_absent_after_mutation')
|
|
118
|
+
turnState.validationContinuationUsed = true;
|
|
119
|
+
return { status: turnStatus, recovery: { kind: 'goal', control: goalContinuationPrompt(describeCompletionReadiness(readiness, turnState.taskProgress)), slice: { maxSteps: goalSlice.steps, maxToolCalls: goalSlice.toolCalls } } };
|
|
120
|
+
}
|
|
121
|
+
else if (rescueSlice && rescueSlice.steps > 0) {
|
|
122
|
+
return { status: turnStatus, recovery: { kind: 'rescue', control: completionRescuePrompt(), slice: { maxSteps: rescueSlice.steps, maxToolCalls: rescueSlice.toolCalls } } };
|
|
123
|
+
}
|
|
124
|
+
else if (classification === 'recoverable-incomplete') {
|
|
125
|
+
// Budget boundary (`tool-calls`), exhausted slice, deadline, or no-progress
|
|
126
|
+
// guard: end the physical turn with a resumable checkpoint.
|
|
127
|
+
callbacks.debugLog(`goal checkpoint: readiness=${readiness}; goalDecision=${goalDecision.reason}; rescueDecision=${rescueDecision?.reason ?? 'not proposed from a recovery slice'}`);
|
|
128
|
+
return checkpointResult();
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return { status: turnStatus };
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Classify a failed attempt from the recorded abort cause and the error:
|
|
136
|
+
* idle-stall retry/pause (shared bounded retry pool), absolute turn deadline,
|
|
137
|
+
* user abort, context-overflow compaction retry, transient model retry, or a
|
|
138
|
+
* hard model-call failure. Completed-step progress is always preserved.
|
|
139
|
+
*/
|
|
140
|
+
export function handleAttemptFailure(deps) {
|
|
141
|
+
const { value, callbacks, abortController, turnState, retryAttempt, contextOverflowRecovered, abortCause, stallGuard, salvage, error } = deps;
|
|
142
|
+
const maxRetries = deps.maxRetries ?? DEFAULT_MODEL_RETRIES;
|
|
143
|
+
if (abortController.signal.aborted) {
|
|
144
|
+
if (abortCause.kind === 'model-stream-idle') {
|
|
145
|
+
// Transport stall, not a user cancel. Preserve completed work first: the
|
|
146
|
+
// conversation is salvaged from the last fully completed step so an
|
|
147
|
+
// automatic retry (or a user-triggered resume) continues from there
|
|
148
|
+
// instead of re-running — possibly mutating — tool work.
|
|
149
|
+
salvageConversationToLastStep(callbacks, salvage);
|
|
150
|
+
if (stallGuard?.retryEligible) {
|
|
151
|
+
const delay = retryDelayMs(retryAttempt);
|
|
152
|
+
callbacks.onEvent?.(agentEvent({ type: 'retry', attempt: retryAttempt + 1, maxAttempts: maxRetries, delayMs: delay, error: `model stream idle for ${formatSeconds(IDLE_TIMEOUT_MS)}` }));
|
|
153
|
+
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.` });
|
|
154
|
+
// freshController: this stall aborted the controller to kill the hung
|
|
155
|
+
// stream; the retry needs a live signal.
|
|
156
|
+
return { status: 'failed', retry: { attempt: retryAttempt + 1, contextOverflowRecovered, delayMs: delay, freshController: true } };
|
|
157
|
+
}
|
|
158
|
+
// Bounded retries exhausted, or the stalled step emitted partial output.
|
|
159
|
+
// Pause with the active goal preserved (work state is untouched by this
|
|
160
|
+
// path) instead of discarding progress; the interactive UI offers a
|
|
161
|
+
// one-key resume from TurnResult.resume.
|
|
162
|
+
const afterStep = turnState.stepsUsed > 0 ? ` after step ${turnState.stepsUsed}` : '';
|
|
163
|
+
callbacks.addMessage({ role: 'system', text: `Model stream stalled for ${formatIdleMinutes(IDLE_TIMEOUT_MS)}; unfinished task paused${afterStep}. Press R to retry, or send a follow-up message to continue.` });
|
|
164
|
+
return { status: 'failed', resume: { kind: 'model-stream-idle', request: value, retryAttempt } };
|
|
165
|
+
}
|
|
166
|
+
if (abortCause.kind === 'turn-deadline') {
|
|
167
|
+
// Absolute turn budget exhausted — distinct from a user cancel: the turn
|
|
168
|
+
// ran out of time, not patience. No retry by definition (the deadline is
|
|
169
|
+
// the bound), but completed-step progress stays in the conversation.
|
|
170
|
+
turnState.aborted = true;
|
|
171
|
+
callbacks.debugLog('turn exceeded the absolute deadline');
|
|
172
|
+
callbacks.addMessage({ role: 'system', text: `Turn stopped: the ${formatIdleMinutes(abortCause.timeoutMs ?? DEFAULT_TURN_DEADLINE_MS)} turn budget elapsed before the model finished. Completed steps are preserved in the conversation; send a follow-up to continue.` });
|
|
173
|
+
return { status: 'aborted', abortReason: 'turn-deadline' };
|
|
174
|
+
}
|
|
175
|
+
turnState.aborted = true;
|
|
176
|
+
callbacks.debugLog('request aborted');
|
|
177
|
+
callbacks.addMessage({ role: 'system', text: 'Thinking aborted. You can type again.' });
|
|
178
|
+
return { status: 'aborted', abortReason: 'user' };
|
|
179
|
+
}
|
|
180
|
+
const text = error instanceof Error ? error.message : String(error);
|
|
181
|
+
callbacks.debugLog(`error: ${text}`);
|
|
182
|
+
if (!contextOverflowRecovered && isContextOverflowError(error)) {
|
|
183
|
+
const canCompact = typeof callbacks.compactConversation === 'function';
|
|
184
|
+
const compacted = canCompact
|
|
185
|
+
? callbacks.compactConversation?.('Automatic recovery after provider context overflow. Preserve the active user request and concrete next steps.') ?? false
|
|
186
|
+
: false;
|
|
187
|
+
callbacks.onEvent?.(agentEvent({ type: 'context_overflow', recovered: compacted, error: text }));
|
|
188
|
+
if (compacted) {
|
|
189
|
+
callbacks.addMessage({ role: 'system', text: 'Context overflow detected; compacted older context and retrying the same request once.' });
|
|
190
|
+
return { status: 'failed', retry: { attempt: retryAttempt, contextOverflowRecovered: true, delayMs: 0 } };
|
|
191
|
+
}
|
|
192
|
+
callbacks.addMessage({ role: 'system', text: canCompact
|
|
193
|
+
? 'Context overflow detected, but there was not enough conversation history to compact automatically.'
|
|
194
|
+
: 'Context overflow detected, and this mode does not attempt automatic compaction. Resume the session interactively or retry with a smaller request.' });
|
|
195
|
+
}
|
|
196
|
+
// Transient model errors share the bounded retry pool with idle-stream
|
|
197
|
+
// stalls, so a turn can never retry more than its configured total.
|
|
198
|
+
if (retryAttempt < maxRetries && isRetryableModelError(error)) {
|
|
199
|
+
const delay = retryDelayMs(retryAttempt);
|
|
200
|
+
callbacks.onEvent?.(agentEvent({ type: 'retry', attempt: retryAttempt + 1, maxAttempts: maxRetries, delayMs: delay, error: text }));
|
|
201
|
+
callbacks.addMessage({ role: 'system', text: `Transient model error; retrying attempt ${retryAttempt + 1}/${maxRetries} in ${formatSeconds(delay)}: ${text}` });
|
|
202
|
+
return { status: 'failed', retry: { attempt: retryAttempt + 1, contextOverflowRecovered, delayMs: delay } };
|
|
203
|
+
}
|
|
204
|
+
callbacks.addMessage({ role: 'assistant', text: `Model call failed: ${text}` });
|
|
205
|
+
return { status: 'failed' };
|
|
206
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import type { ModelMessage, ToolSet } from 'ai';
|
|
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
|
+
import { type ToolExecutionBudgetState, type TurnBudget } from '../../../core/agent/budgets.js';
|
|
6
|
+
import { providerRequestSettings, type ModelRuntimeSelection } from '../../../llm/client.js';
|
|
7
|
+
import { type ToolCategory, type TurnExecutionScope } from '../../../llm/requestContext.js';
|
|
8
|
+
import type { LoadedMcpTools } from '../../../llm/mcp.js';
|
|
9
|
+
import type { LspPool } from '../../../llm/lsp/pool.js';
|
|
10
|
+
import type { PromptSession } from '../../../llm/systemPrompt.js';
|
|
11
|
+
import type { HazeToolContext } from '../../../llm/tools/toolContext.js';
|
|
12
|
+
import type { StreamCallbacks, TurnExecutionOptions } from '../streaming.js';
|
|
13
|
+
import { estimateInputBreakdown } from './turnRuntime.js';
|
|
14
|
+
/**
|
|
15
|
+
* Restrict a tool set to the capabilities permitted in a completion-rescue
|
|
16
|
+
* slice: mutation (edit/write/replace) and validation-capable (shell) built-in
|
|
17
|
+
* tools only. Discovery, read, coordinate, and all third-party (MCP) tools are
|
|
18
|
+
* dropped so the rescue cannot reopen exploration. May return an empty set
|
|
19
|
+
* when no built-in mutation/validation tools exist (only possible if builtins
|
|
20
|
+
* were removed); the caller then forces a tool-free synthesis slice instead
|
|
21
|
+
* of silently keeping the unfiltered tool set (F-08).
|
|
22
|
+
*/
|
|
23
|
+
export declare function restrictToRescueTools(tools: ToolSet): ToolSet;
|
|
24
|
+
/** What `prepareAttempt` produced for the rest of the attempt (loop, outcome, cleanup). */
|
|
25
|
+
export interface AttemptSetup {
|
|
26
|
+
/** Resolved provider model handle and effective config for this attempt. */
|
|
27
|
+
runtime: ModelRuntimeSelection;
|
|
28
|
+
thinkingLabel: string;
|
|
29
|
+
systemPrompt: string;
|
|
30
|
+
/** Durable request messages (synthetic control already applied). */
|
|
31
|
+
requestMessages: ModelMessage[];
|
|
32
|
+
requestBudget: ReturnType<typeof calculateRequestTokenBudget>;
|
|
33
|
+
inputBreakdown: ReturnType<typeof estimateInputBreakdown>;
|
|
34
|
+
providerSettings: Omit<ReturnType<typeof providerRequestSettings>, 'omitMaxOutputTokens'>;
|
|
35
|
+
omitMaxOutputTokens: boolean | undefined;
|
|
36
|
+
/** Tools visible to this attempt: rescue-restricted, budget-clamped, and deadline-wrapped. */
|
|
37
|
+
sliceTools: ToolSet;
|
|
38
|
+
stepCap: number;
|
|
39
|
+
/** A rescue slice with no qualifying tools must synthesize, never reopen discovery (F-08). */
|
|
40
|
+
rescueWithoutTools: boolean;
|
|
41
|
+
toolExecutionContext: HazeToolContext;
|
|
42
|
+
likelyPlanOnlyRequest: boolean;
|
|
43
|
+
loadedMcp: LoadedMcpTools | undefined;
|
|
44
|
+
lspPool: LspPool | undefined;
|
|
45
|
+
contextFiles: ContextFile[];
|
|
46
|
+
/** Tool category map from request assembly (builtin/lsp/subagent/skill/mcp). */
|
|
47
|
+
toolCategories: Map<string, ToolCategory>;
|
|
48
|
+
/** Retry-pool size for this attempt's turn, from the `modelRetries` setting (default 2). */
|
|
49
|
+
modelRetries: number;
|
|
50
|
+
}
|
|
51
|
+
export interface AttemptSetupDeps {
|
|
52
|
+
value: string;
|
|
53
|
+
contextFiles: ContextFile[];
|
|
54
|
+
callbacks: StreamCallbacks;
|
|
55
|
+
retryingExistingRequest: boolean;
|
|
56
|
+
contextOverflowRecovered: boolean;
|
|
57
|
+
session: PromptSession | undefined;
|
|
58
|
+
modelOverride: string | undefined;
|
|
59
|
+
abortController: AbortController;
|
|
60
|
+
turnOptions: TurnExecutionOptions;
|
|
61
|
+
turnScope: {
|
|
62
|
+
executionScope?: TurnExecutionScope;
|
|
63
|
+
};
|
|
64
|
+
turnBudget: TurnBudget;
|
|
65
|
+
globalBudget: ToolExecutionBudgetState;
|
|
66
|
+
/** Shared slice execution state (see AgentAttemptInput.sliceBudget). */
|
|
67
|
+
sliceBudget: ToolExecutionBudgetState;
|
|
68
|
+
goal: SessionGoal;
|
|
69
|
+
onContextFileRead: (path: string) => void;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Assemble one attempt: resolve the model (single fresh settings read, CR-024),
|
|
73
|
+
* build the request context, clamp the request to the model-aware token budget,
|
|
74
|
+
* and wrap the slice's tools with the execution-boundary budget (RH-003) and
|
|
75
|
+
* per-tool deadlines (RH-004). Returns `undefined` when no provider is
|
|
76
|
+
* configured (the caller-reported failure path).
|
|
77
|
+
*/
|
|
78
|
+
export declare function prepareAttempt(deps: AttemptSetupDeps): Promise<AttemptSetup | undefined>;
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { readSettings } from '../../../config/settings.js';
|
|
2
|
+
import { DEFAULT_MODEL_RETRIES } from '../../../core/agent/budgets.js';
|
|
3
|
+
import { agentEvent } from '../../../core/agent/events.js';
|
|
4
|
+
import { isPlanOnlyRequest } from '../../../core/agent/goalPolicy.js';
|
|
5
|
+
import { formatGoalStatus } from '../../../core/agent/goalPolicy.js';
|
|
6
|
+
import { calculateRequestTokenBudget, estimateMessagesTokens } from '../../../core/agent/contextBudget.js';
|
|
7
|
+
import { compactToolHistory, stripSyntheticControls, withSyntheticControl, withoutSystemMessages } from '../../../core/agent/requestAssembly.js';
|
|
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
|
+
import { withToolDeadline } from '../../../core/deadline.js';
|
|
11
|
+
import { isMutatingCapability, isValidationCapable } from '../../../core/agent/toolCapabilities.js';
|
|
12
|
+
import { userTurnMessage } from '../../../core/attachments/imageAttachments.js';
|
|
13
|
+
import { WorkspaceMutationPolicy } from '../../../core/subagent/workspaceMutationPolicy.js';
|
|
14
|
+
import { modelWithConfig, providerRequestSettings } from '../../../llm/client.js';
|
|
15
|
+
import { assembleRequestContext } from '../../../llm/requestContext.js';
|
|
16
|
+
import { modelThinkingLabel } from '../../../utils/modelName.js';
|
|
17
|
+
import { estimateInputBreakdown, logEntry } from './turnRuntime.js';
|
|
18
|
+
/**
|
|
19
|
+
* Restrict a tool set to the capabilities permitted in a completion-rescue
|
|
20
|
+
* slice: mutation (edit/write/replace) and validation-capable (shell) built-in
|
|
21
|
+
* tools only. Discovery, read, coordinate, and all third-party (MCP) tools are
|
|
22
|
+
* dropped so the rescue cannot reopen exploration. May return an empty set
|
|
23
|
+
* when no built-in mutation/validation tools exist (only possible if builtins
|
|
24
|
+
* were removed); the caller then forces a tool-free synthesis slice instead
|
|
25
|
+
* of silently keeping the unfiltered tool set (F-08).
|
|
26
|
+
*/
|
|
27
|
+
export function restrictToRescueTools(tools) {
|
|
28
|
+
const restricted = {};
|
|
29
|
+
for (const [name, tool] of Object.entries(tools)) {
|
|
30
|
+
if (isMutatingCapability(name) || isValidationCapable(name))
|
|
31
|
+
restricted[name] = tool;
|
|
32
|
+
}
|
|
33
|
+
return restricted;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Assemble one attempt: resolve the model (single fresh settings read, CR-024),
|
|
37
|
+
* build the request context, clamp the request to the model-aware token budget,
|
|
38
|
+
* and wrap the slice's tools with the execution-boundary budget (RH-003) and
|
|
39
|
+
* per-tool deadlines (RH-004). Returns `undefined` when no provider is
|
|
40
|
+
* configured (the caller-reported failure path).
|
|
41
|
+
*/
|
|
42
|
+
export async function prepareAttempt(deps) {
|
|
43
|
+
const { value, contextFiles, callbacks, retryingExistingRequest, contextOverflowRecovered, session, modelOverride, abortController, turnOptions, turnScope, turnBudget, goal, globalBudget, sliceBudget, onContextFileRead } = deps;
|
|
44
|
+
// Single choke point: one fresh settings read per turn, shared by model
|
|
45
|
+
// resolution and request assembly (CR-024).
|
|
46
|
+
const turnSettings = await readSettings();
|
|
47
|
+
const runtime = await modelWithConfig({ cwd: session?.cwd, modelSelector: modelOverride }, turnSettings);
|
|
48
|
+
if (!runtime?.model) {
|
|
49
|
+
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
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
const thinkingLabel = modelThinkingLabel(runtime.config.modelName);
|
|
53
|
+
callbacks.setBusyLabel?.(thinkingLabel);
|
|
54
|
+
// Observable requested-vs-effective reasoning policy (safe: level strings + reason only).
|
|
55
|
+
const reasoningPolicy = runtime.config.reasoningPolicy;
|
|
56
|
+
if (reasoningPolicy)
|
|
57
|
+
callbacks.onEvent?.(agentEvent({ type: 'reasoning_policy', requested: reasoningPolicy.requested, effective: reasoningPolicy.effective, reason: reasoningPolicy.reason }));
|
|
58
|
+
// Make the context-budget guess observable: a stream event every turn
|
|
59
|
+
// (headless consumers can gate on it), and — interactively — a system
|
|
60
|
+
// message only when the built-in default was used for a model this session
|
|
61
|
+
// has not warned about yet (a user-set fallback setting is an intentional
|
|
62
|
+
// choice and is not warned about). The warned key is `provider:model`, so
|
|
63
|
+
// the message appears at the start of a session and once after a model
|
|
64
|
+
// switch, never on every turn.
|
|
65
|
+
callbacks.onEvent?.(agentEvent({ type: 'context_budget', contextWindowTokens: runtime.config.contextWindowTokens, source: runtime.config.contextWindowSource }));
|
|
66
|
+
const fallbackModelKey = `${runtime.config.providerName}:${runtime.config.modelName}`;
|
|
67
|
+
if (runtime.config.contextWindowSource === 'default-fallback' && session && session.contextFallbackWarned !== fallbackModelKey) {
|
|
68
|
+
session.contextFallbackWarned = fallbackModelKey;
|
|
69
|
+
callbacks.addMessage({ role: 'system', text: `No context-window data for ${runtime.config.providerName}:${runtime.config.modelName}; budgeting conservatively at ${runtime.config.contextWindowTokens.toLocaleString('en-US')} tokens. Set modelLimits for this model via /provider, or contextWindowFallbackTokens in settings, to use its real window.` });
|
|
70
|
+
}
|
|
71
|
+
const activeContextFiles = contextFiles;
|
|
72
|
+
const activeModel = runtime.model;
|
|
73
|
+
const { omitMaxOutputTokens, ...providerSettings } = providerRequestSettings(runtime.config);
|
|
74
|
+
const assembled = await assembleRequestContext({ request: value, contextFiles: activeContextFiles, session, model: activeModel, modelRuntime: runtime, subagentOverrides: turnOptions.subagentOverrides, abortSignal: abortController.signal, executionScope: turnScope.executionScope, settings: turnSettings, onSubagentEvent: event => callbacks.onEvent?.(agentEvent(event.type === 'queued'
|
|
75
|
+
? { type: 'subagent_state', id: event.id, state: 'queued', mode: event.mode, queued: event.queued, running: event.running }
|
|
76
|
+
: event.type === 'started'
|
|
77
|
+
? { type: 'subagent_state', id: event.id, state: 'started', mode: event.mode, queueMs: event.queueMs, running: event.running }
|
|
78
|
+
: event.type === 'terminal'
|
|
79
|
+
? { type: 'subagent_state', id: event.id, state: 'terminal', mode: event.mode, queueMs: event.queueMs, durationMs: event.durationMs, termination: event.termination, execution: event.execution, running: event.running }
|
|
80
|
+
: { 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 })) });
|
|
81
|
+
turnScope.executionScope ??= assembled.executionScope;
|
|
82
|
+
const availableTools = assembled.availableTools;
|
|
83
|
+
const toolCategories = assembled.toolCategories;
|
|
84
|
+
const loadedMcp = assembled.loadedMcp;
|
|
85
|
+
const lspPool = assembled.lspPool;
|
|
86
|
+
if (loadedMcp?.errors.length)
|
|
87
|
+
callbacks.addMessage({ role: 'system', text: `MCP: ${loadedMcp.errors.join('; ')}` });
|
|
88
|
+
callbacks.setWorkState?.(goal);
|
|
89
|
+
callbacks.setGoalStatus?.(formatGoalStatus(goal));
|
|
90
|
+
const likelyPlanOnlyRequest = isPlanOnlyRequest(value);
|
|
91
|
+
const durableRequestMessages = compactToolHistory(retryingExistingRequest
|
|
92
|
+
? stripSyntheticControls(callbacks.getConversation())
|
|
93
|
+
: [...stripSyntheticControls(callbacks.getConversation()), userTurnMessage(value, turnOptions.attachments ?? [])]).messages;
|
|
94
|
+
// Model-aware request budget (RH-005): message allowance is the context
|
|
95
|
+
// window minus system prompt, tool schemas, output reserve, and a safety
|
|
96
|
+
// margin — not a fixed 40K constant. Small contexts get a safe budget; the
|
|
97
|
+
// assembled request plus output reserve stays within configured capacity.
|
|
98
|
+
const requestedOutputTokens = runtime.config.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS;
|
|
99
|
+
const requestBudget = calculateRequestTokenBudget({ contextWindowTokens: runtime.config.contextWindowTokens, requestedOutputTokens, system: assembled.systemPrompt, tools: availableTools });
|
|
100
|
+
// 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
|
+
const overflowTargetTokens = contextOverflowRecovered ? Math.floor(requestBudget.messageTokens * 0.6) : requestBudget.messageTokens;
|
|
103
|
+
let requestMessages = durableRequestMessages;
|
|
104
|
+
if (estimateMessagesTokens(requestMessages) > overflowTargetTokens) {
|
|
105
|
+
requestMessages = compactModelMessages(requestMessages, { tokenBudget: overflowTargetTokens, workState: goal }).messages;
|
|
106
|
+
}
|
|
107
|
+
requestMessages = withoutSystemMessages(requestMessages);
|
|
108
|
+
callbacks.setConversation(stripSyntheticControls(requestMessages));
|
|
109
|
+
if (turnOptions.ephemeralControl)
|
|
110
|
+
requestMessages = withSyntheticControl(requestMessages, turnOptions.ephemeralControl);
|
|
111
|
+
const systemPrompt = assembled.systemPrompt;
|
|
112
|
+
const inputBreakdown = estimateInputBreakdown({ system: systemPrompt, contextFiles: activeContextFiles, messages: requestMessages, tools: availableTools });
|
|
113
|
+
logEntry(callbacks.log, { at: new Date().toISOString(), type: 'request', stream: 'main', system: systemPrompt, messages: requestMessages, tools: Object.keys(availableTools), context: inputBreakdown.breakdown });
|
|
114
|
+
const contextFileSignatures = callbacks.contextFileSignatures ?? new Map(activeContextFiles.flatMap(file => file.signature ? [[file.path, file.signature]] : []));
|
|
115
|
+
const mutationPolicy = assembled.executionScope?.mutationPolicy ?? new WorkspaceMutationPolicy();
|
|
116
|
+
const toolExecutionContext = { inFlightToolCalls: new Map(), loadedContextFilePaths: new Set(activeContextFiles.map(file => file.path)), loadedContextFileSignatures: contextFileSignatures, onContextFileRead, mutationPolicy, blessedPaths: turnOptions.blessedPaths };
|
|
117
|
+
const recoverySlice = turnOptions.recoverySlice;
|
|
118
|
+
const stepCap = recoverySlice?.maxSteps ?? MAIN_STEP_LIMIT;
|
|
119
|
+
// Rescue exposes only mutation + validation-capable built-in tools so
|
|
120
|
+
// discovery cannot be reopened near the boundary. Length-continuation keeps
|
|
121
|
+
// the full tool set. When no built-in mutation/validation tool qualifies,
|
|
122
|
+
// the rescue slice runs tool-free (forced synthesis) rather than keeping
|
|
123
|
+
// the unfiltered set — the "discovery must not be reopened" invariant (F-08).
|
|
124
|
+
const rescueTools = recoverySlice?.kind === 'rescue' ? restrictToRescueTools(availableTools) : availableTools;
|
|
125
|
+
const rescueWithoutTools = recoverySlice?.kind === 'rescue' && Object.keys(rescueTools).length === 0;
|
|
126
|
+
const sliceTools = rescueWithoutTools ? {} : rescueTools;
|
|
127
|
+
// Execution-boundary budgets (RH-003). The global budget is turn-wide
|
|
128
|
+
// (shared across retries and recovery slices); the slice budget belongs to
|
|
129
|
+
// the current slice (main phase or one recovery slice) and is provided by
|
|
130
|
+
// the turn loop so provider retries within the slice cannot re-arm its cap
|
|
131
|
+
// (round-1 C2): the slice envelope is clamped once at slice admission. Both
|
|
132
|
+
// are checked atomically at the actual execute boundary so one oversized
|
|
133
|
+
// parallel batch cannot overshoot.
|
|
134
|
+
const sliceToolCallCap = turnOptions.recoverySlice?.maxToolCalls ?? MAIN_TOOL_CALL_LIMIT;
|
|
135
|
+
const budgetedTools = withToolExecutionBudget(sliceTools, { state: globalBudget, limit: turnBudget.toolCallLimit }, { state: sliceBudget, limit: sliceToolCallCap });
|
|
136
|
+
// Layer a per-tool execution deadline on top of the budget (RH-004). The
|
|
137
|
+
// budget is checked first (cheap); a permitted call then runs under a
|
|
138
|
+
// deadline so an uncooperative tool cannot defer the turn indefinitely.
|
|
139
|
+
// Subagents legitimately run long, so their wrapper gets a larger bound.
|
|
140
|
+
const deadlineWrappedTools = Object.fromEntries(Object.entries(budgetedTools).map(([name, definition]) => {
|
|
141
|
+
if (typeof definition.execute !== 'function')
|
|
142
|
+
return [name, definition];
|
|
143
|
+
const execute = definition.execute;
|
|
144
|
+
const deadlineMs = name === 'subagent' ? SUBAGENT_TOOL_DEADLINE_MS : DEFAULT_TOOL_DEADLINE_MS;
|
|
145
|
+
return [name, { ...definition, execute: (...args) => withToolDeadline(() => execute(...args), deadlineMs, abortController.signal) }];
|
|
146
|
+
}));
|
|
147
|
+
return {
|
|
148
|
+
runtime,
|
|
149
|
+
thinkingLabel,
|
|
150
|
+
systemPrompt,
|
|
151
|
+
requestMessages,
|
|
152
|
+
requestBudget,
|
|
153
|
+
inputBreakdown,
|
|
154
|
+
providerSettings,
|
|
155
|
+
omitMaxOutputTokens,
|
|
156
|
+
sliceTools: deadlineWrappedTools,
|
|
157
|
+
stepCap,
|
|
158
|
+
rescueWithoutTools,
|
|
159
|
+
toolExecutionContext,
|
|
160
|
+
likelyPlanOnlyRequest,
|
|
161
|
+
loadedMcp,
|
|
162
|
+
lspPool,
|
|
163
|
+
contextFiles: activeContextFiles,
|
|
164
|
+
toolCategories,
|
|
165
|
+
modelRetries: typeof turnSettings.modelRetries === 'number' ? turnSettings.modelRetries : DEFAULT_MODEL_RETRIES,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
@@ -45,7 +45,7 @@ export interface GoalCheckpoint {
|
|
|
45
45
|
/** Consecutive physical turns without measurable progress. */
|
|
46
46
|
noProgressCount: number;
|
|
47
47
|
}
|
|
48
|
-
/** Cumulative
|
|
48
|
+
/** Cumulative outcome signature; monotonic mutation activity alone is not net progress. */
|
|
49
49
|
export declare function goalCheckpointSignature(input: {
|
|
50
50
|
mutationCount: number;
|
|
51
51
|
validationOutcome: ValidationOutcome;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
/** Cumulative
|
|
1
|
+
/** Cumulative outcome signature; monotonic mutation activity alone is not net progress. */
|
|
2
2
|
export function goalCheckpointSignature(input) {
|
|
3
|
-
return JSON.stringify([input.mutationCount, input.validationOutcome, input.taskCounts ? [input.taskCounts.total, input.taskCounts.pending, input.taskCounts.inProgress, input.taskCounts.completed] : null]);
|
|
3
|
+
return JSON.stringify([input.mutationCount > 0, input.validationOutcome, input.taskCounts ? [input.taskCounts.total, input.taskCounts.pending, input.taskCounts.inProgress, input.taskCounts.completed] : null]);
|
|
4
4
|
}
|
|
5
5
|
/**
|
|
6
6
|
* Build the checkpoint payload for a `recoverable-incomplete` attempt that no
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { agentEvent } from '../../../core/agent/events.js';
|
|
2
2
|
import { DEFAULT_TURN_DEADLINE_MS } from '../../../core/agent/budgets.js';
|
|
3
3
|
import { describeCompletionReadiness } from '../../../core/agent/completionController.js';
|
|
4
|
-
import { goalContinuationPrompt } from '../../../core/
|
|
4
|
+
import { goalContinuationPrompt } from '../../../core/agent/goalPolicy.js';
|
|
5
5
|
import { runAgentTurn } from '../streaming.js';
|
|
6
6
|
import { goalCheckpointSignature } from './goalCheckpoint.js';
|
|
7
|
-
/** Pause after
|
|
8
|
-
const GOAL_NO_PROGRESS_LIMIT =
|
|
7
|
+
/** Pause after one corrective physical turn without measurable outcome progress. */
|
|
8
|
+
const GOAL_NO_PROGRESS_LIMIT = 1;
|
|
9
9
|
function checkpointFromResume(resume, noProgressCount) {
|
|
10
10
|
const validationOutcome = resume.validationOutcome ?? 'not_applicable';
|
|
11
11
|
return {
|
|
@@ -94,15 +94,18 @@ export async function runAgentGoal(options) {
|
|
|
94
94
|
lastEvidence = result.evidence;
|
|
95
95
|
if (result.status === 'complete')
|
|
96
96
|
return finish('complete', 'completed');
|
|
97
|
-
if (result.status === 'aborted')
|
|
98
|
-
return
|
|
97
|
+
if (result.status === 'aborted') {
|
|
98
|
+
return result.abortReason === 'turn-deadline'
|
|
99
|
+
? finish('failed', 'goal-deadline', checkpoint ? { kind: 'incomplete-goal', checkpoint } : undefined)
|
|
100
|
+
: finish('aborted', 'user-aborted');
|
|
101
|
+
}
|
|
99
102
|
if (result.resume?.kind === 'incomplete-goal') {
|
|
100
103
|
const next = checkpointFromResume(result.resume, 0);
|
|
101
104
|
noProgressCount = prevSignature != null && next.progressSignature === prevSignature ? noProgressCount + 1 : 0;
|
|
102
105
|
prevSignature = next.progressSignature;
|
|
103
106
|
checkpoint = { ...next, noProgressCount };
|
|
104
107
|
if (noProgressCount >= GOAL_NO_PROGRESS_LIMIT) {
|
|
105
|
-
callbacks.addMessage({ role: 'system', text: `Unfinished goal paused after ${noProgressCount}
|
|
108
|
+
callbacks.addMessage({ role: 'system', text: `Unfinished goal paused after ${noProgressCount} corrective cycle${noProgressCount === 1 ? '' : 's'} without measurable progress (${describeCompletionReadiness(checkpoint.readiness, checkpoint.taskCounts ? countsToTaskProgress(checkpoint.taskCounts) : undefined)}). Completed work is preserved in the conversation. Press R to resume, or send a follow-up.` });
|
|
106
109
|
return finish('failed', 'no-progress', { kind: 'incomplete-goal', checkpoint });
|
|
107
110
|
}
|
|
108
111
|
const remainingNow = options.goalDeadlineMs != null ? options.goalDeadlineMs - (Date.now() - startedAt) : undefined;
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import type { LlmLog } from '../../../core/log/llmLog.js';
|
|
2
|
+
import { type AgentEventSink } from '../../../core/agent/events.js';
|
|
3
|
+
import type { ModelMessage } from 'ai';
|
|
4
|
+
import { type TurnAbortCause } from './abortCause.js';
|
|
5
|
+
/** What the stalled step had emitted when the stream went quiet. Only 'none' is auto-retryable. */
|
|
6
|
+
type StallEmission = 'none' | 'text' | 'tool';
|
|
7
|
+
export declare function formatIdleMinutes(milliseconds: number): string;
|
|
8
|
+
/**
|
|
9
|
+
* An idle timer for the main agent turn.
|
|
10
|
+
*
|
|
11
|
+
* The turn is considered "idle" (and aborted) after `timeoutMs` with no stream
|
|
12
|
+
* activity — UNLESS a tool call is currently executing (`isBusy()` returns
|
|
13
|
+
* true). Concurrent subagents can run for many minutes while emitting no stream
|
|
14
|
+
* parts; that is legitimate work, not a dead stream, so the timer defers (rearms)
|
|
15
|
+
* while any tool is in flight. This prevents a long subagent wave from being
|
|
16
|
+
* mistaken for a hung turn.
|
|
17
|
+
*
|
|
18
|
+
* `clear()` is a permanent quiescence barrier: once cleared, `reset()` can never
|
|
19
|
+
* rearm it, so a late stream part from an abort-ignoring stream cannot keep the
|
|
20
|
+
* timer (and whatever its timeout would trigger) alive after teardown.
|
|
21
|
+
*
|
|
22
|
+
* Note: there is intentionally no upper bound on how long a single tool may run
|
|
23
|
+
* while in flight — a genuinely hung tool would defer indefinitely. A per-tool
|
|
24
|
+
* hard timeout is a separate concern; the idle timer only guards against a turn
|
|
25
|
+
* that is producing no model output AND doing no tool work.
|
|
26
|
+
*/
|
|
27
|
+
export interface IdleTimer {
|
|
28
|
+
/** Clear any pending deadline and rearm it for a fresh idle window. No-op after `clear()`. */
|
|
29
|
+
reset: () => void;
|
|
30
|
+
/** Cancel the pending deadline permanently; later `reset()` calls are ignored. */
|
|
31
|
+
clear: () => void;
|
|
32
|
+
}
|
|
33
|
+
export declare function createIdleTimer(input: {
|
|
34
|
+
timeoutMs: number;
|
|
35
|
+
isBusy: () => boolean;
|
|
36
|
+
onTimeout: () => void;
|
|
37
|
+
}): IdleTimer;
|
|
38
|
+
/**
|
|
39
|
+
* Idle-stall guard for one attempt: the idle timer plus the hoisted stall
|
|
40
|
+
* state the attempt catch needs (last stream event, emission classification,
|
|
41
|
+
* retry eligibility). `onTimeout` classifies the stall from live stream state
|
|
42
|
+
* (via `classifyEmission`), reports it through the timeout event protocol, and
|
|
43
|
+
* aborts the shared controller with the `model-stream-idle` cause. Diagnostics
|
|
44
|
+
* carry safe metadata only (names, timestamps, enums, phases) — never prompt
|
|
45
|
+
* content or credentials.
|
|
46
|
+
*/
|
|
47
|
+
export interface StreamStallGuard {
|
|
48
|
+
/** Record a consumed stream part (type + timestamp) and rearm the idle window. */
|
|
49
|
+
noteStreamEvent: (type: string) => void;
|
|
50
|
+
/** Rearm the idle window without recording an event (before the first request). */
|
|
51
|
+
rearm: () => void;
|
|
52
|
+
/** Cancel the pending deadline. */
|
|
53
|
+
clear: () => void;
|
|
54
|
+
/** Emission classified by the last timeout; only meaningful after a stall fired. */
|
|
55
|
+
readonly stallEmission: StallEmission;
|
|
56
|
+
/** Whether the last stall rides the bounded model-retry pool. */
|
|
57
|
+
readonly retryEligible: boolean;
|
|
58
|
+
}
|
|
59
|
+
export interface StreamStallGuardDeps {
|
|
60
|
+
controller: AbortController;
|
|
61
|
+
abortCause: TurnAbortCause;
|
|
62
|
+
retryAttempt: number;
|
|
63
|
+
/** Retry-pool size for this turn (`modelRetries` setting); defaults to DEFAULT_MODEL_RETRIES. */
|
|
64
|
+
maxRetries?: number;
|
|
65
|
+
/** Classify what the stalled step emitted so far: partial text, in-flight tool, or nothing. */
|
|
66
|
+
classifyEmission: () => StallEmission;
|
|
67
|
+
isToolInFlight: () => boolean;
|
|
68
|
+
provider: () => string | undefined;
|
|
69
|
+
model: () => string | undefined;
|
|
70
|
+
workPhase: () => string;
|
|
71
|
+
stepsUsed: () => number;
|
|
72
|
+
onEvent?: AgentEventSink;
|
|
73
|
+
log?: LlmLog;
|
|
74
|
+
debugLog: (line: string) => void;
|
|
75
|
+
}
|
|
76
|
+
export declare function createStreamStallGuard(deps: StreamStallGuardDeps): StreamStallGuard;
|
|
77
|
+
/**
|
|
78
|
+
* Salvage state shared by the attempt phases: the request messages this
|
|
79
|
+
* attempt sent, and the latest fully completed step's accumulated response
|
|
80
|
+
* messages (captured in `onStepEnd`) that an idle-stall retry resumes from.
|
|
81
|
+
*/
|
|
82
|
+
export interface AttemptSalvage {
|
|
83
|
+
requestMessages: ModelMessage[];
|
|
84
|
+
accumulated: ModelMessage[];
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Salvage the conversation to the last fully completed step after a stalled or
|
|
88
|
+
* failed stream: completed — possibly mutating — tool work is preserved so an
|
|
89
|
+
* idle retry (or a user resume) continues from there instead of re-running it.
|
|
90
|
+
*/
|
|
91
|
+
export declare function salvageConversationToLastStep(callbacks: {
|
|
92
|
+
setConversation: (messages: ModelMessage[]) => void;
|
|
93
|
+
}, salvage: AttemptSalvage): void;
|
|
94
|
+
export {};
|