@denizokcu/haze 0.10.0 → 1.0.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 +100 -1
- package/README.md +77 -27
- package/SECURITY.md +22 -0
- package/bin/haze.js +102 -1
- package/dist/buildInfo.json +7 -0
- package/dist/cli/chat/TaskBar.d.ts +2 -1
- package/dist/cli/chat/TaskBar.js +7 -4
- package/dist/cli/chat/chatMetrics.d.ts +2 -2
- package/dist/cli/chat/chatMetrics.js +1 -1
- package/dist/cli/chat/contextReport.js +2 -0
- package/dist/cli/chat/fileMentionSuggestions.js +3 -2
- package/dist/cli/chat/inputSuggestions.d.ts +8 -16
- package/dist/cli/chat/inputSuggestions.js +9 -41
- package/dist/cli/chat/liveRegion.d.ts +25 -0
- package/dist/cli/chat/liveRegion.js +48 -0
- package/dist/cli/chat/messages.d.ts +33 -4
- package/dist/cli/chat/messages.js +218 -35
- package/dist/cli/chat/sessionLifecycle.d.ts +11 -1
- package/dist/cli/chat/sessionLifecycle.js +64 -14
- package/dist/cli/chat/sessionRecorder.js +75 -7
- package/dist/cli/chat/startupInfo.d.ts +0 -1
- package/dist/cli/chat/startupInfo.js +11 -15
- package/dist/cli/chat/turnState.d.ts +1 -1
- package/dist/cli/chat/wizardDispatch.d.ts +90 -28
- package/dist/cli/chat/wizardDispatch.js +349 -133
- package/dist/cli/commands/chat.d.ts +5 -0
- package/dist/cli/commands/chat.js +216 -172
- package/dist/cli/commands/chatModes.d.ts +8 -1
- package/dist/cli/commands/chatModes.js +9 -44
- package/dist/cli/commands/commands.d.ts +2 -0
- package/dist/cli/commands/commands.js +10 -5
- package/dist/cli/commands/doctor.d.ts +19 -0
- package/dist/cli/commands/doctor.js +76 -0
- package/dist/cli/commands/formatters.d.ts +3 -3
- package/dist/cli/commands/formatters.js +8 -25
- package/dist/cli/commands/ndjsonSink.d.ts +23 -0
- package/dist/cli/commands/ndjsonSink.js +38 -0
- package/dist/cli/commands/providerWizard.d.ts +9 -2
- package/dist/cli/commands/providerWizard.js +39 -7
- package/dist/cli/commands/runCommand.d.ts +3 -0
- package/dist/cli/commands/runCommand.js +117 -11
- package/dist/cli/commands/serverWizard.d.ts +34 -0
- package/dist/cli/commands/{mcpWizard.js → serverWizard.js} +44 -2
- 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 +25 -0
- package/dist/cli/commands/streaming/abortCause.js +16 -0
- package/dist/cli/commands/streaming/agentAttempt.d.ts +43 -0
- package/dist/cli/commands/streaming/agentAttempt.js +79 -0
- package/dist/cli/commands/streaming/assistantText.js +9 -2
- 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 +65 -0
- package/dist/cli/commands/streaming/goalCheckpoint.js +23 -0
- package/dist/cli/commands/streaming/goalSupervisor.d.ts +64 -0
- package/dist/cli/commands/streaming/goalSupervisor.js +130 -0
- 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 +16 -0
- package/dist/cli/commands/streaming/toolCallRecovery.js +80 -0
- package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +31 -1
- package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -4
- package/dist/cli/commands/streaming/toolResultState.d.ts +6 -1
- package/dist/cli/commands/streaming/toolResultState.js +29 -7
- 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 +65 -9
- package/dist/cli/commands/streaming.js +133 -430
- package/dist/cli/commands/wizardFlow.d.ts +334 -0
- package/dist/cli/commands/wizardFlow.js +377 -0
- package/dist/cli/contextReport.js +3 -0
- package/dist/cli/index.js +68 -22
- package/dist/cli/terminalTitle.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 +36 -0
- package/dist/config/modelDiscovery.js +164 -1
- package/dist/config/privateStorage.js +28 -2
- package/dist/config/providerAuth.d.ts +14 -0
- package/dist/config/providerAuth.js +49 -0
- package/dist/config/providerPresets.d.ts +39 -7
- package/dist/config/providerPresets.js +371 -100
- package/dist/config/providers.js +2 -0
- package/dist/config/settings.d.ts +43 -0
- package/dist/config/settings.js +12 -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 +73 -1
- package/dist/core/agent/budgets.js +94 -1
- package/dist/core/agent/compaction.d.ts +38 -0
- package/dist/core/agent/compaction.js +92 -17
- package/dist/core/agent/completionController.d.ts +224 -0
- package/dist/core/agent/completionController.js +296 -0
- package/dist/core/agent/contextBudget.d.ts +36 -2
- package/dist/core/agent/contextBudget.js +62 -9
- package/dist/core/agent/errors.d.ts +0 -1
- package/dist/core/agent/errors.js +1 -1
- package/dist/core/agent/events.d.ts +78 -0
- package/dist/core/agent/goalPolicy.d.ts +47 -0
- package/dist/core/agent/goalPolicy.js +106 -0
- package/dist/core/agent/reasoningPolicy.d.ts +31 -0
- package/dist/core/agent/reasoningPolicy.js +27 -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 +27 -0
- package/dist/core/agent/toolCapabilities.js +58 -0
- package/dist/core/agent/toolOutputStore.d.ts +8 -0
- package/dist/core/agent/toolOutputStore.js +11 -11
- package/dist/core/agent/toolResults.d.ts +12 -0
- package/dist/core/agent/toolResults.js +38 -0
- package/dist/core/agent/turnPolicy.d.ts +11 -0
- package/dist/core/agent/turnPolicy.js +19 -0
- package/dist/core/agent/workState.d.ts +81 -3
- package/dist/core/agent/workState.js +176 -10
- package/dist/core/attachments/imageAttachments.js +90 -42
- package/dist/core/deadline.d.ts +27 -0
- package/dist/core/deadline.js +74 -0
- 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 +8 -1
- package/dist/core/persistence/orderedFileWriter.d.ts +10 -0
- package/dist/core/persistence/orderedFileWriter.js +16 -2
- package/dist/core/process/backgroundRegistry.d.ts +2 -3
- package/dist/core/process/backgroundRegistry.js +15 -10
- package/dist/core/process/runBoundedProcess.d.ts +8 -2
- package/dist/core/process/runBoundedProcess.js +15 -6
- package/dist/core/process/userShell.d.ts +16 -0
- package/dist/core/process/userShell.js +59 -0
- package/dist/core/safety/missingExecutable.d.ts +42 -0
- package/dist/core/safety/missingExecutable.js +77 -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 +38 -0
- package/dist/core/session/sessionStore.js +242 -59
- 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 +6 -14
- package/dist/core/subagent/contracts.js +4 -3
- package/dist/core/subagent/executionProfiles.js +2 -2
- package/dist/core/subagent/subagentCoordinator.d.ts +4 -0
- package/dist/core/subagent/subagentCoordinator.js +32 -2
- package/dist/core/subagent/subagentRunner.js +19 -40
- 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.d.ts +17 -1
- package/dist/llm/client.js +86 -14
- package/dist/llm/hazeTools.d.ts +693 -204
- package/dist/llm/hazeTools.js +110 -28
- 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 +5653 -33
- package/dist/llm/lspTools.js +152 -80
- package/dist/llm/openaiCodex.d.ts +1 -0
- package/dist/llm/openaiCodex.js +43 -0
- package/dist/llm/openaiCodexOAuth.d.ts +51 -0
- package/dist/llm/openaiCodexOAuth.js +217 -0
- package/dist/llm/requestContext.d.ts +7 -0
- package/dist/llm/requestContext.js +30 -4
- package/dist/llm/systemPrompt.d.ts +12 -0
- package/dist/llm/systemPrompt.js +24 -11
- package/dist/llm/toolResultTypes.d.ts +7 -14
- package/dist/llm/toolResultTypes.js +1 -4
- package/dist/llm/tools/editMatch.d.ts +14 -9
- package/dist/llm/tools/editMatch.js +73 -1
- package/dist/llm/tools/failures.d.ts +2 -0
- package/dist/llm/tools/failures.js +1 -0
- package/dist/llm/tools/fetchTool.d.ts +16 -0
- package/dist/llm/tools/fetchTool.js +1 -1
- package/dist/llm/tools/fileToolShared.d.ts +8 -5
- package/dist/llm/tools/fileToolShared.js +22 -23
- package/dist/llm/tools/gitIgnore.d.ts +42 -0
- package/dist/llm/tools/gitIgnore.js +247 -0
- 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 +8 -0
- package/dist/llm/tools/readRecovery.js +135 -0
- package/dist/llm/tools/{bashTool.d.ts → shellTool.d.ts} +171 -123
- package/dist/llm/tools/{bashTool.js → shellTool.js} +20 -14
- package/dist/llm/tools/toolContext.d.ts +1 -1
- package/dist/llm/tools/toolContext.js +66 -37
- package/dist/llm/tools/workspaceFile.d.ts +0 -1
- package/dist/llm/tools/workspaceFile.js +1 -6
- package/dist/llm/webFetch.d.ts +18 -1
- package/dist/llm/webFetch.js +64 -97
- 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/codeHighlight.d.ts +4 -0
- package/dist/ui/codeHighlight.js +31 -0
- package/dist/ui/components/Header.d.ts +1 -1
- package/dist/ui/components/MarkdownText.d.ts +16 -2
- package/dist/ui/components/MarkdownText.js +244 -34
- package/dist/ui/components/TextInput.d.ts +8 -1
- package/dist/ui/components/TextInput.js +6 -2
- package/dist/ui/theme.d.ts +4 -3
- package/dist/ui/theme.js +5 -4
- package/dist/utils/buildInfo.d.ts +97 -0
- package/dist/utils/buildInfo.js +244 -0
- package/dist/utils/fs.d.ts +11 -0
- package/dist/utils/fs.js +91 -26
- package/dist/utils/openPath.d.ts +2 -2
- package/dist/utils/openPath.js +19 -6
- package/dist/utils/path.d.ts +2 -1
- package/dist/utils/path.js +6 -2
- package/dist/utils/utf8.d.ts +22 -0
- package/dist/utils/utf8.js +54 -0
- package/dist/utils/version.d.ts +9 -3
- package/dist/utils/version.js +28 -2
- package/package.json +28 -21
- 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 -10
- package/dist/cli/commands/streaming/turnOutcome.js +0 -13
- package/dist/cli/commands/wizardActions.d.ts +0 -46
- package/dist/cli/commands/wizardActions.js +0 -46
- 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 -52
- package/dist/cli/commands/wizardSuggestions.d.ts +0 -31
- package/dist/cli/commands/wizardSuggestions.js +0 -188
- package/dist/cli/commands/wizardTransition.d.ts +0 -37
- package/dist/cli/commands/wizardTransition.js +0 -43
- 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.d.ts +0 -2
- package/dist/core/goal/completionPolicy.js +0 -7
- 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 -18
- package/dist/core/limits/byteBudgets.js +0 -18
- package/dist/core/limits/textBudgets.d.ts +0 -23
- package/dist/core/limits/textBudgets.js +0 -23
- package/dist/core/safety/bashClassifier.d.ts +0 -10
- package/dist/llm/lsp.d.ts +0 -129
- package/dist/llm/lsp.js +0 -307
- 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,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
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { CompletionReadiness, TurnExecutionState } from '../../../core/agent/completionController.js';
|
|
2
|
+
import type { ValidationOutcome } from '../../../core/agent/workState.js';
|
|
3
|
+
/**
|
|
4
|
+
* Bounded continuation checkpoint for a logical goal whose work is recoverably
|
|
5
|
+
* unfinished. Safe metadata only — reasons, counts, enums — never commands,
|
|
6
|
+
* content, or credentials. Carried on `TurnResult.resume` so a goal supervisor
|
|
7
|
+
* (or the interactive resume affordance) can continue the same logical goal in
|
|
8
|
+
* a fresh physical turn without replaying completed work.
|
|
9
|
+
*/
|
|
10
|
+
export interface IncompleteGoalResume {
|
|
11
|
+
kind: 'incomplete-goal';
|
|
12
|
+
request: string;
|
|
13
|
+
reason: CompletionReadiness;
|
|
14
|
+
/** Logical-goal id shared across physical turns. */
|
|
15
|
+
goalId: string;
|
|
16
|
+
/** Physical turns consumed so far (including the one producing this). */
|
|
17
|
+
cycle: number;
|
|
18
|
+
stepsUsed: number;
|
|
19
|
+
/** Cumulative successful mutations across the logical goal. */
|
|
20
|
+
mutationCount: number;
|
|
21
|
+
taskCounts?: {
|
|
22
|
+
total: number;
|
|
23
|
+
pending: number;
|
|
24
|
+
inProgress: number;
|
|
25
|
+
completed: number;
|
|
26
|
+
};
|
|
27
|
+
validationOutcome?: ValidationOutcome;
|
|
28
|
+
}
|
|
29
|
+
/** Supervisor-level checkpoint persisted between physical turns (in memory). */
|
|
30
|
+
export interface GoalCheckpoint {
|
|
31
|
+
goalId: string;
|
|
32
|
+
request: string;
|
|
33
|
+
cycle: number;
|
|
34
|
+
readiness: CompletionReadiness;
|
|
35
|
+
taskCounts?: {
|
|
36
|
+
total: number;
|
|
37
|
+
pending: number;
|
|
38
|
+
inProgress: number;
|
|
39
|
+
completed: number;
|
|
40
|
+
};
|
|
41
|
+
mutationCount: number;
|
|
42
|
+
validationOutcome: ValidationOutcome;
|
|
43
|
+
/** Cumulative progress signature used by the no-progress guard. */
|
|
44
|
+
progressSignature: string;
|
|
45
|
+
/** Consecutive physical turns without measurable progress. */
|
|
46
|
+
noProgressCount: number;
|
|
47
|
+
}
|
|
48
|
+
/** Cumulative outcome signature; monotonic mutation activity alone is not net progress. */
|
|
49
|
+
export declare function goalCheckpointSignature(input: {
|
|
50
|
+
mutationCount: number;
|
|
51
|
+
validationOutcome: ValidationOutcome;
|
|
52
|
+
taskCounts?: {
|
|
53
|
+
pending: number;
|
|
54
|
+
inProgress: number;
|
|
55
|
+
completed: number;
|
|
56
|
+
total: number;
|
|
57
|
+
};
|
|
58
|
+
}): string;
|
|
59
|
+
/**
|
|
60
|
+
* Build the checkpoint payload for a `recoverable-incomplete` attempt that no
|
|
61
|
+
* same-turn recovery can continue. Single construction site so every path
|
|
62
|
+
* (voluntary final, budget boundary, tool-calls finish, exhausted recovery
|
|
63
|
+
* slice) yields the same bounded shape.
|
|
64
|
+
*/
|
|
65
|
+
export declare function buildIncompleteGoalResume(request: string, goalId: string, cycle: number, state: Pick<TurnExecutionState, 'stepsUsed' | 'mutationCount' | 'validationOutcome' | 'taskProgress'>, reason: CompletionReadiness): IncompleteGoalResume;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Cumulative outcome signature; monotonic mutation activity alone is not net progress. */
|
|
2
|
+
export function goalCheckpointSignature(input) {
|
|
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
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Build the checkpoint payload for a `recoverable-incomplete` attempt that no
|
|
7
|
+
* same-turn recovery can continue. Single construction site so every path
|
|
8
|
+
* (voluntary final, budget boundary, tool-calls finish, exhausted recovery
|
|
9
|
+
* slice) yields the same bounded shape.
|
|
10
|
+
*/
|
|
11
|
+
export function buildIncompleteGoalResume(request, goalId, cycle, state, reason) {
|
|
12
|
+
return {
|
|
13
|
+
kind: 'incomplete-goal',
|
|
14
|
+
request,
|
|
15
|
+
reason,
|
|
16
|
+
goalId,
|
|
17
|
+
cycle,
|
|
18
|
+
stepsUsed: state.stepsUsed,
|
|
19
|
+
mutationCount: state.mutationCount,
|
|
20
|
+
...(state.taskProgress ? { taskCounts: { total: state.taskProgress.total, pending: state.taskProgress.pending, inProgress: state.taskProgress.inProgress, completed: state.taskProgress.completed } } : {}),
|
|
21
|
+
...(state.validationOutcome !== 'not_applicable' ? { validationOutcome: state.validationOutcome } : {}),
|
|
22
|
+
};
|
|
23
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { ContextFile } from '../../../config/contextFiles.js';
|
|
2
|
+
import type { TurnCompletionEvidence } from '../../../core/agent/completionController.js';
|
|
3
|
+
import type { PromptSession } from '../../../llm/systemPrompt.js';
|
|
4
|
+
import { type StreamCallbacks, type TurnExecutionOptions } from '../streaming.js';
|
|
5
|
+
import { type GoalCheckpoint } from './goalCheckpoint.js';
|
|
6
|
+
/** 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
|
+
/** Authoritative outcome of a logical goal (one or more physical turns). */
|
|
9
|
+
export interface GoalRunResult {
|
|
10
|
+
status: 'complete' | 'failed' | 'aborted';
|
|
11
|
+
stopReason: GoalStopReason;
|
|
12
|
+
/** Physical turns consumed by the logical goal. */
|
|
13
|
+
cycles: number;
|
|
14
|
+
/** Last physical turn's bounded evidence. */
|
|
15
|
+
evidence?: TurnCompletionEvidence;
|
|
16
|
+
/**
|
|
17
|
+
* Present only for genuinely paused goals (no-progress, deadline, idle
|
|
18
|
+
* stall): what an explicit resume needs. Automatic continuation has already
|
|
19
|
+
* been attempted; this never rides a `completed` result.
|
|
20
|
+
*/
|
|
21
|
+
resume?: {
|
|
22
|
+
kind: 'model-stream-idle';
|
|
23
|
+
request: string;
|
|
24
|
+
retryAttempt: number;
|
|
25
|
+
} | {
|
|
26
|
+
kind: 'incomplete-goal';
|
|
27
|
+
checkpoint: GoalCheckpoint;
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
export interface GoalRunOptions {
|
|
31
|
+
request: string;
|
|
32
|
+
displayValue?: string;
|
|
33
|
+
contextFiles: ContextFile[];
|
|
34
|
+
callbacks: StreamCallbacks;
|
|
35
|
+
session?: PromptSession;
|
|
36
|
+
modelOverride?: string;
|
|
37
|
+
/** Whole-logical-goal wall-clock budget (headless `--timeout`); unset means continue while progress. */
|
|
38
|
+
goalDeadlineMs?: number;
|
|
39
|
+
/** Base per-turn options (attachments, blessed paths); attachments apply to the first physical turn only. */
|
|
40
|
+
turnOptions?: TurnExecutionOptions;
|
|
41
|
+
/** Explicit resume of a paused goal: an idle-stalled turn pool or a stored goal checkpoint. */
|
|
42
|
+
resumeFrom?: {
|
|
43
|
+
kind: 'model-stream-idle';
|
|
44
|
+
retryAttempt: number;
|
|
45
|
+
} | {
|
|
46
|
+
kind: 'incomplete-goal';
|
|
47
|
+
checkpoint: GoalCheckpoint;
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Logical-goal supervisor. Runs bounded physical turns (`runAgentTurn`) until
|
|
52
|
+
* the user's goal is structurally complete, autonomously starting the next
|
|
53
|
+
* physical turn whenever the previous one ended `recoverable-incomplete` —
|
|
54
|
+
* including at step/tool budget boundaries, which end a physical turn, not the
|
|
55
|
+
* goal. Per-turn limits stay safety boundaries; they no longer imply goal
|
|
56
|
+
* completion.
|
|
57
|
+
*
|
|
58
|
+
* Stops only for: structured completion, a concrete external blocker (hard
|
|
59
|
+
* tool/provider failure), user cancellation, the goal-level deadline, or
|
|
60
|
+
* repeated no-progress cycles. Conversation and completed tool results carry
|
|
61
|
+
* across turns, so mutations are never replayed. Emits exactly one `goal_start`
|
|
62
|
+
* and one terminal `goal_end`, plus `goal_continue` between physical turns.
|
|
63
|
+
*/
|
|
64
|
+
export declare function runAgentGoal(options: GoalRunOptions): Promise<GoalRunResult>;
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { agentEvent } from '../../../core/agent/events.js';
|
|
2
|
+
import { DEFAULT_TURN_DEADLINE_MS } from '../../../core/agent/budgets.js';
|
|
3
|
+
import { describeCompletionReadiness } from '../../../core/agent/completionController.js';
|
|
4
|
+
import { goalContinuationPrompt } from '../../../core/agent/goalPolicy.js';
|
|
5
|
+
import { runAgentTurn } from '../streaming.js';
|
|
6
|
+
import { goalCheckpointSignature } from './goalCheckpoint.js';
|
|
7
|
+
/** Pause after one corrective physical turn without measurable outcome progress. */
|
|
8
|
+
const GOAL_NO_PROGRESS_LIMIT = 1;
|
|
9
|
+
function checkpointFromResume(resume, noProgressCount) {
|
|
10
|
+
const validationOutcome = resume.validationOutcome ?? 'not_applicable';
|
|
11
|
+
return {
|
|
12
|
+
goalId: resume.goalId,
|
|
13
|
+
request: resume.request,
|
|
14
|
+
cycle: resume.cycle,
|
|
15
|
+
readiness: resume.reason,
|
|
16
|
+
...(resume.taskCounts ? { taskCounts: resume.taskCounts } : {}),
|
|
17
|
+
mutationCount: resume.mutationCount,
|
|
18
|
+
validationOutcome,
|
|
19
|
+
progressSignature: goalCheckpointSignature({ mutationCount: resume.mutationCount, validationOutcome, taskCounts: resume.taskCounts }),
|
|
20
|
+
noProgressCount,
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
function countsToTaskProgress(counts) {
|
|
24
|
+
return { total: counts.total, pending: counts.pending, inProgress: counts.inProgress, completed: counts.completed, revision: 1 };
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Logical-goal supervisor. Runs bounded physical turns (`runAgentTurn`) until
|
|
28
|
+
* the user's goal is structurally complete, autonomously starting the next
|
|
29
|
+
* physical turn whenever the previous one ended `recoverable-incomplete` —
|
|
30
|
+
* including at step/tool budget boundaries, which end a physical turn, not the
|
|
31
|
+
* goal. Per-turn limits stay safety boundaries; they no longer imply goal
|
|
32
|
+
* completion.
|
|
33
|
+
*
|
|
34
|
+
* Stops only for: structured completion, a concrete external blocker (hard
|
|
35
|
+
* tool/provider failure), user cancellation, the goal-level deadline, or
|
|
36
|
+
* repeated no-progress cycles. Conversation and completed tool results carry
|
|
37
|
+
* across turns, so mutations are never replayed. Emits exactly one `goal_start`
|
|
38
|
+
* and one terminal `goal_end`, plus `goal_continue` between physical turns.
|
|
39
|
+
*/
|
|
40
|
+
export async function runAgentGoal(options) {
|
|
41
|
+
const { request, contextFiles, callbacks } = options;
|
|
42
|
+
const startedAt = Date.now();
|
|
43
|
+
const goalId = options.resumeFrom?.kind === 'incomplete-goal' ? options.resumeFrom.checkpoint.goalId : `goal-${startedAt}-${Math.random().toString(36).slice(2)}`;
|
|
44
|
+
const sharedTurnScope = {};
|
|
45
|
+
let checkpoint = options.resumeFrom?.kind === 'incomplete-goal' ? options.resumeFrom.checkpoint : undefined;
|
|
46
|
+
let initialRetryAttempt = options.resumeFrom?.kind === 'model-stream-idle' ? options.resumeFrom.retryAttempt : 0;
|
|
47
|
+
let cycle = checkpoint?.cycle ?? 0;
|
|
48
|
+
let noProgressCount = checkpoint?.noProgressCount ?? 0;
|
|
49
|
+
let prevSignature = checkpoint?.progressSignature;
|
|
50
|
+
let lastEvidence;
|
|
51
|
+
callbacks.onEvent?.(agentEvent({ type: 'goal_start', goalId, request }));
|
|
52
|
+
// Observable capability line at every goal start (debug panel, --debug LLM
|
|
53
|
+
// log, headless stderr): failures can be tied to runtime behavior, not
|
|
54
|
+
// guessed from semantic versions.
|
|
55
|
+
callbacks.debugLog('goal supervisor enabled; automatic continuation across physical-turn budgets');
|
|
56
|
+
const finish = (status, stopReason, resume) => {
|
|
57
|
+
callbacks.onEvent?.(agentEvent({ type: 'goal_end', goalId, status, cycles: cycle, ...(stopReason !== 'completed' ? { stopReason } : {}), ...(lastEvidence ? { evidence: lastEvidence } : {}) }));
|
|
58
|
+
return { status, stopReason, cycles: cycle, ...(lastEvidence ? { evidence: lastEvidence } : {}), ...(resume ? { resume } : {}) };
|
|
59
|
+
};
|
|
60
|
+
while (true) {
|
|
61
|
+
const remainingMs = options.goalDeadlineMs != null ? options.goalDeadlineMs - (Date.now() - startedAt) : undefined;
|
|
62
|
+
if (cycle > 0 && remainingMs != null && remainingMs <= 0) {
|
|
63
|
+
return finish('failed', 'goal-deadline', checkpoint ? { kind: 'incomplete-goal', checkpoint } : undefined);
|
|
64
|
+
}
|
|
65
|
+
const continuing = cycle > 0 || checkpoint != null || initialRetryAttempt > 0;
|
|
66
|
+
const turnOptions = {
|
|
67
|
+
...options.turnOptions,
|
|
68
|
+
...(checkpoint
|
|
69
|
+
? {
|
|
70
|
+
// The conversation already carries the user message; a continuation
|
|
71
|
+
// turn rides it with a synthetic control. Attachments belong to the
|
|
72
|
+
// first attempt only.
|
|
73
|
+
ephemeralControl: goalContinuationPrompt(describeCompletionReadiness(checkpoint.readiness, checkpoint.taskCounts ? countsToTaskProgress(checkpoint.taskCounts) : undefined), checkpoint.taskCounts),
|
|
74
|
+
attachments: undefined,
|
|
75
|
+
}
|
|
76
|
+
: {}),
|
|
77
|
+
// Always tag the turn with the logical goal id/cycle so cycle-0
|
|
78
|
+
// checkpoints carry the supervisor's goal identity, and hydrate carried
|
|
79
|
+
// evidence on continuation turns (a no-op seed for a fresh goal).
|
|
80
|
+
goalContext: {
|
|
81
|
+
goalId,
|
|
82
|
+
cycle: cycle + 1,
|
|
83
|
+
carried: checkpoint
|
|
84
|
+
? { mutationCount: checkpoint.mutationCount, validationOutcome: checkpoint.validationOutcome, ...(checkpoint.taskCounts ? { taskProgress: countsToTaskProgress(checkpoint.taskCounts) } : {}) }
|
|
85
|
+
: { mutationCount: 0, validationOutcome: 'not_applicable' },
|
|
86
|
+
noProgressCount,
|
|
87
|
+
},
|
|
88
|
+
sharedTurnScope,
|
|
89
|
+
...(remainingMs != null ? { turnDeadlineMs: Math.min(remainingMs, DEFAULT_TURN_DEADLINE_MS) } : {}),
|
|
90
|
+
};
|
|
91
|
+
const result = await runAgentTurn(request, continuing ? undefined : options.displayValue, contextFiles, callbacks, initialRetryAttempt, continuing, false, options.session, options.modelOverride, turnOptions);
|
|
92
|
+
initialRetryAttempt = 0;
|
|
93
|
+
cycle += 1;
|
|
94
|
+
lastEvidence = result.evidence;
|
|
95
|
+
if (result.status === 'complete')
|
|
96
|
+
return finish('complete', 'completed');
|
|
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
|
+
}
|
|
102
|
+
if (result.resume?.kind === 'incomplete-goal') {
|
|
103
|
+
const next = checkpointFromResume(result.resume, 0);
|
|
104
|
+
noProgressCount = prevSignature != null && next.progressSignature === prevSignature ? noProgressCount + 1 : 0;
|
|
105
|
+
prevSignature = next.progressSignature;
|
|
106
|
+
checkpoint = { ...next, noProgressCount };
|
|
107
|
+
if (noProgressCount >= GOAL_NO_PROGRESS_LIMIT) {
|
|
108
|
+
callbacks.addMessage({ role: 'system', text: `Unfinished goal paused after ${noProgressCount} corrective cycle${noProgressCount === 1 ? '' : 's'} without measurable progress (${describeCompletionReadiness(checkpoint.readiness, checkpoint.taskCounts ? countsToTaskProgress(checkpoint.taskCounts) : undefined)}). Completed work is preserved in the conversation. Press R to resume, or send a follow-up.` });
|
|
109
|
+
return finish('failed', 'no-progress', { kind: 'incomplete-goal', checkpoint });
|
|
110
|
+
}
|
|
111
|
+
const remainingNow = options.goalDeadlineMs != null ? options.goalDeadlineMs - (Date.now() - startedAt) : undefined;
|
|
112
|
+
if (remainingNow != null && remainingNow <= 0) {
|
|
113
|
+
callbacks.addMessage({ role: 'system', text: 'Goal deadline reached before the remaining work finished. Completed work is preserved in the conversation; send a follow-up to continue.' });
|
|
114
|
+
return finish('failed', 'goal-deadline', { kind: 'incomplete-goal', checkpoint });
|
|
115
|
+
}
|
|
116
|
+
const openTasks = checkpoint.taskCounts ? checkpoint.taskCounts.pending + checkpoint.taskCounts.inProgress : undefined;
|
|
117
|
+
callbacks.onEvent?.(agentEvent({ type: 'goal_continue', goalId, cycle, reason: checkpoint.readiness }));
|
|
118
|
+
callbacks.addMessage({ role: 'system', text: `Continuing unfinished goal — cycle ${cycle + 1}${openTasks != null ? ` (${openTasks} task${openTasks === 1 ? '' : 's'} remaining)` : ''}: ${describeCompletionReadiness(checkpoint.readiness, checkpoint.taskCounts ? countsToTaskProgress(checkpoint.taskCounts) : undefined)}.` });
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
if (result.resume?.kind === 'model-stream-idle') {
|
|
122
|
+
// Bounded in-turn retries are exhausted; a transport stall is a concrete
|
|
123
|
+
// external blocker — pause with the existing one-key resume path.
|
|
124
|
+
return finish('failed', 'model-stream-idle', { kind: 'model-stream-idle', request: result.resume.request, retryAttempt: result.resume.retryAttempt });
|
|
125
|
+
}
|
|
126
|
+
// Failed without a checkpoint: hard blocker (failed tool, invalid input,
|
|
127
|
+
// provider error) or an unresolved synthesis failure.
|
|
128
|
+
return finish('failed', result.evidence?.finishCause === 'error' ? 'model-error' : 'blocked');
|
|
129
|
+
}
|
|
130
|
+
}
|
|
@@ -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 {};
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { agentEvent } from '../../../core/agent/events.js';
|
|
2
|
+
import { IDLE_TIMEOUT_MS, DEFAULT_MODEL_RETRIES } from '../../../core/agent/budgets.js';
|
|
3
|
+
import { compactToolHistory, stripSyntheticControls } from '../../../core/agent/requestAssembly.js';
|
|
4
|
+
import { abortForTurn } from './abortCause.js';
|
|
5
|
+
import { logEntry } from './turnRuntime.js';
|
|
6
|
+
export function formatIdleMinutes(milliseconds) {
|
|
7
|
+
const minutes = Math.round(milliseconds / 60_000);
|
|
8
|
+
return `${minutes} minute${minutes === 1 ? '' : 's'}`;
|
|
9
|
+
}
|
|
10
|
+
/** Auto-retry an idle stall only while the stalled step emitted nothing visible (no partial text or in-flight tool). */
|
|
11
|
+
function idleStallAutoRetryEligible(retryAttempt, stallEmission, maxRetries) {
|
|
12
|
+
return stallEmission === 'none' && retryAttempt < maxRetries;
|
|
13
|
+
}
|
|
14
|
+
export function createIdleTimer(input) {
|
|
15
|
+
const { timeoutMs, isBusy, onTimeout } = input;
|
|
16
|
+
let timer;
|
|
17
|
+
let stopped = false;
|
|
18
|
+
const fire = () => {
|
|
19
|
+
if (stopped)
|
|
20
|
+
return;
|
|
21
|
+
if (isBusy()) {
|
|
22
|
+
// Tools are executing — that is activity. Defer by rearming.
|
|
23
|
+
timer = setTimeout(fire, timeoutMs);
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
onTimeout();
|
|
27
|
+
};
|
|
28
|
+
return {
|
|
29
|
+
reset: () => {
|
|
30
|
+
if (stopped)
|
|
31
|
+
return;
|
|
32
|
+
if (timer)
|
|
33
|
+
clearTimeout(timer);
|
|
34
|
+
timer = setTimeout(fire, timeoutMs);
|
|
35
|
+
},
|
|
36
|
+
clear: () => {
|
|
37
|
+
stopped = true;
|
|
38
|
+
if (timer)
|
|
39
|
+
clearTimeout(timer);
|
|
40
|
+
timer = undefined;
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
export function createStreamStallGuard(deps) {
|
|
45
|
+
const maxRetries = deps.maxRetries ?? DEFAULT_MODEL_RETRIES;
|
|
46
|
+
let stallEmission = 'none';
|
|
47
|
+
let retryEligible = false;
|
|
48
|
+
let lastStreamEventAt;
|
|
49
|
+
let lastStreamEventType;
|
|
50
|
+
const timer = createIdleTimer({
|
|
51
|
+
timeoutMs: IDLE_TIMEOUT_MS,
|
|
52
|
+
isBusy: () => deps.isToolInFlight(),
|
|
53
|
+
onTimeout: () => {
|
|
54
|
+
if (deps.controller.signal.aborted)
|
|
55
|
+
return;
|
|
56
|
+
// What the stalled step had emitted when the stream went quiet. Retrying
|
|
57
|
+
// after partial output could duplicate or mangle it, so only 'none' is
|
|
58
|
+
// automatically retryable.
|
|
59
|
+
stallEmission = deps.classifyEmission();
|
|
60
|
+
retryEligible = idleStallAutoRetryEligible(deps.retryAttempt, stallEmission, maxRetries);
|
|
61
|
+
const lastEventAtIso = lastStreamEventAt != null ? new Date(lastStreamEventAt).toISOString() : undefined;
|
|
62
|
+
deps.onEvent?.(agentEvent({
|
|
63
|
+
type: 'timeout',
|
|
64
|
+
phase: 'model-stream',
|
|
65
|
+
timeoutMs: IDLE_TIMEOUT_MS,
|
|
66
|
+
provider: deps.provider(),
|
|
67
|
+
model: deps.model(),
|
|
68
|
+
lastStreamEventAt: lastEventAtIso,
|
|
69
|
+
lastStreamEventType: lastStreamEventType,
|
|
70
|
+
stallEmission: stallEmission,
|
|
71
|
+
workPhase: deps.workPhase(),
|
|
72
|
+
retryEligible: retryEligible,
|
|
73
|
+
maxRetries: maxRetries,
|
|
74
|
+
}));
|
|
75
|
+
logEntry(deps.log, { at: new Date().toISOString(), type: 'warning', stream: 'main', error: `model-stream idle ${IDLE_TIMEOUT_MS}ms: provider=${deps.provider() ?? 'unknown'} model=${deps.model() ?? 'unknown'} lastEvent=${lastStreamEventType ?? 'none'}@${lastEventAtIso ?? 'never'} stallEmission=${stallEmission} workPhase=${deps.workPhase()} retryEligible=${retryEligible} maxRetries=${maxRetries} stepsUsed=${deps.stepsUsed()}` });
|
|
76
|
+
deps.debugLog(`model stream idle for ${IDLE_TIMEOUT_MS}ms (last event: ${lastStreamEventType ?? 'none'}); ${retryEligible ? `retryable stall (${deps.retryAttempt}/${maxRetries} used)` : 'stall not retryable'}`);
|
|
77
|
+
abortForTurn(deps.abortCause, { kind: 'model-stream-idle', timeoutMs: IDLE_TIMEOUT_MS }, deps.controller, 'haze model stream was idle for the configured timeout.');
|
|
78
|
+
},
|
|
79
|
+
});
|
|
80
|
+
return {
|
|
81
|
+
noteStreamEvent: (type) => {
|
|
82
|
+
lastStreamEventAt = Date.now();
|
|
83
|
+
lastStreamEventType = type;
|
|
84
|
+
timer.reset();
|
|
85
|
+
},
|
|
86
|
+
rearm: () => timer.reset(),
|
|
87
|
+
clear: () => timer.clear(),
|
|
88
|
+
get stallEmission() {
|
|
89
|
+
return stallEmission;
|
|
90
|
+
},
|
|
91
|
+
get retryEligible() {
|
|
92
|
+
return retryEligible;
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Salvage the conversation to the last fully completed step after a stalled or
|
|
98
|
+
* failed stream: completed — possibly mutating — tool work is preserved so an
|
|
99
|
+
* idle retry (or a user resume) continues from there instead of re-running it.
|
|
100
|
+
*/
|
|
101
|
+
export function salvageConversationToLastStep(callbacks, salvage) {
|
|
102
|
+
if (salvage.accumulated.length > 0) {
|
|
103
|
+
callbacks.setConversation(compactToolHistory([...stripSyntheticControls(salvage.requestMessages), ...salvage.accumulated]).messages);
|
|
104
|
+
}
|
|
105
|
+
}
|