@denizokcu/haze 0.11.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 +23 -0
- package/README.md +23 -14
- package/SECURITY.md +3 -3
- package/dist/buildInfo.json +3 -3
- 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 +9 -41
- package/dist/cli/chat/messages.d.ts +0 -2
- package/dist/cli/chat/messages.js +2 -2
- 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 +250 -133
- package/dist/cli/commands/chat.js +14 -72
- package/dist/cli/commands/chatModes.d.ts +8 -1
- package/dist/cli/commands/chatModes.js +9 -44
- package/dist/cli/commands/doctor.js +1 -1
- package/dist/cli/commands/formatters.d.ts +3 -3
- package/dist/cli/commands/formatters.js +6 -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/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/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 +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 +7 -0
- package/dist/config/settings.js +3 -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/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 +14 -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 +13 -6
- package/dist/llm/toolResultTypes.d.ts +0 -14
- 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/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 +2 -2
- package/dist/llm/tools/{bashTool.d.ts → shellTool.d.ts} +123 -107
- package/dist/llm/tools/{bashTool.js → shellTool.js} +15 -14
- package/dist/llm/tools/toolContext.js +5 -5
- package/dist/llm/tools/workspaceFile.d.ts +0 -1
- package/dist/llm/tools/workspaceFile.js +1 -6
- 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/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,79 @@
|
|
|
1
|
+
import { closeMcpClients } from '../../../llm/mcp.js';
|
|
2
|
+
import { modelThinkingLabel } from '../../../utils/modelName.js';
|
|
3
|
+
import { normalizeAssistantText } from './assistantText.js';
|
|
4
|
+
import { createToolGroupRenderer } from './toolGroupRenderer.js';
|
|
5
|
+
import { prepareAttempt } from './attemptSetup.js';
|
|
6
|
+
import { createAttemptLoopState, runAttemptStream } from './streamLoop.js';
|
|
7
|
+
import { createStreamStallGuard } from './stallRecovery.js';
|
|
8
|
+
import { finalizeAttemptOutcome, handleAttemptFailure } from './attemptOutcome.js';
|
|
9
|
+
import { ATTEMPT_TEARDOWN_BOUND_MS } from './attemptLifecycle.js';
|
|
10
|
+
/**
|
|
11
|
+
* Run one agent attempt end to end: setup (`attemptSetup`), the stream loop
|
|
12
|
+
* (`streamLoop`), then terminal classification and recovery decisions
|
|
13
|
+
* (`attemptOutcome`). Failures are classified from the abort cause and error
|
|
14
|
+
* in one catch; MCP clients, the LSP pool, the stall guard, and the tool
|
|
15
|
+
* display are always torn down.
|
|
16
|
+
*/
|
|
17
|
+
export async function runAgentAttempt(input) {
|
|
18
|
+
const { value, contextFiles, callbacks, retryAttempt, retryingExistingRequest, contextOverflowRecovered, session, modelOverride, abortController, turnOptions, turnScope, turnState, turnBudget, globalBudget, sliceBudget, goal, abortCause, cleanup, remainingTurnDeadlineMs } = input;
|
|
19
|
+
callbacks.setBusyLabel?.(modelThinkingLabel(undefined));
|
|
20
|
+
let loadedMcp;
|
|
21
|
+
let lspPool;
|
|
22
|
+
let mcpClosed = false;
|
|
23
|
+
let lspClosed = false;
|
|
24
|
+
const toolDisplay = createToolGroupRenderer({ addMessage: callbacks.addMessage, updateMessage: callbacks.updateMessage, debugLog: callbacks.debugLog, onEvent: callbacks.onEvent, log: callbacks.log });
|
|
25
|
+
// Teardown is registered, not inline: whichever runs first — this attempt's
|
|
26
|
+
// own finally or the turn-level forced settlement after an abort-ignoring
|
|
27
|
+
// stream — performs it exactly once (bounded), the other becomes a no-op.
|
|
28
|
+
cleanup.register(async () => {
|
|
29
|
+
const closes = [];
|
|
30
|
+
if (loadedMcp?.clients.length && !mcpClosed) {
|
|
31
|
+
mcpClosed = true;
|
|
32
|
+
closes.push(closeMcpClients(loadedMcp.clients));
|
|
33
|
+
}
|
|
34
|
+
if (lspPool && !lspClosed) {
|
|
35
|
+
lspClosed = true;
|
|
36
|
+
closes.push(lspPool.close());
|
|
37
|
+
}
|
|
38
|
+
stallGuard?.clear();
|
|
39
|
+
toolDisplay.stopToolTimer();
|
|
40
|
+
await Promise.allSettled(closes);
|
|
41
|
+
});
|
|
42
|
+
const salvage = { requestMessages: [], accumulated: [] };
|
|
43
|
+
let stallGuard;
|
|
44
|
+
let setup;
|
|
45
|
+
try {
|
|
46
|
+
setup = await prepareAttempt({ value, contextFiles, callbacks, retryingExistingRequest, contextOverflowRecovered, session, modelOverride, abortController, turnOptions, turnScope, turnBudget, globalBudget, sliceBudget, goal, onContextFileRead: path => toolDisplay.addContextFileRead(path) });
|
|
47
|
+
if (!setup)
|
|
48
|
+
return { status: 'failed' };
|
|
49
|
+
const attemptSetupResult = setup;
|
|
50
|
+
loadedMcp = setup.loadedMcp;
|
|
51
|
+
lspPool = setup.lspPool;
|
|
52
|
+
salvage.requestMessages = setup.requestMessages;
|
|
53
|
+
const loopState = createAttemptLoopState(normalizeAssistantText(callbacks.getLastAssistantText()), setup.contextFiles, callbacks);
|
|
54
|
+
stallGuard = createStreamStallGuard({
|
|
55
|
+
controller: abortController,
|
|
56
|
+
abortCause,
|
|
57
|
+
retryAttempt,
|
|
58
|
+
maxRetries: attemptSetupResult.modelRetries,
|
|
59
|
+
classifyEmission: () => loopState.currentAssistantText.trim().length > 0 || loopState.assistantStarted ? 'text' : loopState.inFlightTools.size > 0 ? 'tool' : 'none',
|
|
60
|
+
isToolInFlight: () => loopState.inFlightTools.size > 0,
|
|
61
|
+
provider: () => attemptSetupResult.runtime.config.providerName,
|
|
62
|
+
model: () => attemptSetupResult.runtime.config.modelName,
|
|
63
|
+
workPhase: () => goal.phase,
|
|
64
|
+
stepsUsed: () => turnState.stepsUsed,
|
|
65
|
+
onEvent: callbacks.onEvent,
|
|
66
|
+
log: callbacks.log,
|
|
67
|
+
debugLog: callbacks.debugLog,
|
|
68
|
+
});
|
|
69
|
+
const stream = await runAttemptStream({ setup, callbacks, abortController, retryAttempt, recoverySlice: turnOptions.recoverySlice, turnState, turnBudget, globalBudget, goal, stallGuard, loopState, toolDisplay, salvage });
|
|
70
|
+
return finalizeAttemptOutcome({ value, callbacks, abortController, turnOptions, turnState, turnBudget, goal, remainingTurnDeadlineMs, stream });
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
return handleAttemptFailure({ value, callbacks, abortController, turnState, retryAttempt, contextOverflowRecovered, abortCause, stallGuard, salvage, error, maxRetries: setup?.modelRetries });
|
|
74
|
+
}
|
|
75
|
+
finally {
|
|
76
|
+
await cleanup.closeOnce(ATTEMPT_TEARDOWN_BOUND_MS);
|
|
77
|
+
toolDisplay.finalizeToolGroup();
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { StreamCallbacks } from '../streaming.js';
|
|
2
|
+
import type { AgentAttemptResult } from './attemptOutcome.js';
|
|
3
|
+
/** Upper bound for one forced teardown pass; the underlying closes continue even if it expires. */
|
|
4
|
+
export declare const ATTEMPT_TEARDOWN_BOUND_MS = 5000;
|
|
5
|
+
/**
|
|
6
|
+
* Exactly-once cleanup registry for one agent attempt. The attempt registers
|
|
7
|
+
* its resource cleanups (MCP clients, LSP pool, stall guard, tool display) as
|
|
8
|
+
* it acquires them; whichever of the attempt's own `finally` or the turn's
|
|
9
|
+
* forced settlement runs first performs the teardown, and the other becomes a
|
|
10
|
+
* no-op. `closeOnce` is bounded and reports truthfully whether every cleanup
|
|
11
|
+
* completed within `timeoutMs` (closes keep settling in the background).
|
|
12
|
+
*/
|
|
13
|
+
export interface AttemptCleanupRegistry {
|
|
14
|
+
/** Register a cleanup to run once at teardown. Ignored after teardown started. */
|
|
15
|
+
register: (cleanup: () => void | Promise<void>) => void;
|
|
16
|
+
/** Run all registered cleanups exactly once; resolves false when the bound expired. */
|
|
17
|
+
closeOnce: (timeoutMs: number) => Promise<boolean>;
|
|
18
|
+
/** True once teardown has started. */
|
|
19
|
+
readonly closed: boolean;
|
|
20
|
+
}
|
|
21
|
+
export declare function createAttemptCleanupRegistry(): AttemptCleanupRegistry;
|
|
22
|
+
/**
|
|
23
|
+
* Per-turn callback guard for the attempt machinery. After `quarantine()` —
|
|
24
|
+
* run at forced settlement — every state-mutating callback (messages,
|
|
25
|
+
* conversation, busy/goal/work state, events, token usage, logs) becomes a
|
|
26
|
+
* permanent no-op, so a still-running abort-ignoring stream cannot mutate the
|
|
27
|
+
* finished turn's UI, conversation, or session state if it ever wakes up.
|
|
28
|
+
* Diagnostics (`debugLog`) and read-only accessors stay live.
|
|
29
|
+
*/
|
|
30
|
+
export interface QuarantinableCallbacks {
|
|
31
|
+
callbacks: StreamCallbacks;
|
|
32
|
+
/** Permanently no-op all state-mutating callbacks. */
|
|
33
|
+
quarantine: () => void;
|
|
34
|
+
}
|
|
35
|
+
export declare function createQuarantinableCallbacks(callbacks: StreamCallbacks): QuarantinableCallbacks;
|
|
36
|
+
export interface ForcedSettlementDeps {
|
|
37
|
+
abortController: AbortController;
|
|
38
|
+
cleanup: AttemptCleanupRegistry;
|
|
39
|
+
quarantine: () => void;
|
|
40
|
+
/**
|
|
41
|
+
* Build the synthetic attempt result after forced teardown. Runs with the
|
|
42
|
+
* turn's live (unguarded) callbacks before the abandoned attempt's result
|
|
43
|
+
* (if it ever settles) is discarded.
|
|
44
|
+
*/
|
|
45
|
+
onForced: (tornDownCleanly: boolean) => AgentAttemptResult;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Await one agent attempt, but never let an abort-ignoring attempt defer the
|
|
49
|
+
* turn forever: once the shared controller aborts (user cancel or absolute
|
|
50
|
+
* deadline), the attempt gets a grace window to settle normally; if the grace
|
|
51
|
+
* expires, owned resources are torn down (bounded, exactly once), the attempt's
|
|
52
|
+
* callbacks are quarantined, and the turn resolves with `onForced`'s result.
|
|
53
|
+
* The abandoned attempt keeps running detached; its eventual settlement is
|
|
54
|
+
* discarded and its teardown is a no-op.
|
|
55
|
+
*/
|
|
56
|
+
export declare function awaitAttemptWithForcedSettlement(attempt: Promise<AgentAttemptResult>, deps: ForcedSettlementDeps): Promise<AgentAttemptResult>;
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Grace window for an aborted attempt to settle on its own (streams normally
|
|
3
|
+
* reject immediately on abort) before the turn forces settlement.
|
|
4
|
+
*/
|
|
5
|
+
const ATTEMPT_SETTLEMENT_GRACE_MS = 5000;
|
|
6
|
+
/** Upper bound for one forced teardown pass; the underlying closes continue even if it expires. */
|
|
7
|
+
export const ATTEMPT_TEARDOWN_BOUND_MS = 5000;
|
|
8
|
+
export function createAttemptCleanupRegistry() {
|
|
9
|
+
const cleanups = [];
|
|
10
|
+
let closePromise;
|
|
11
|
+
return {
|
|
12
|
+
register: cleanup => {
|
|
13
|
+
if (!closePromise)
|
|
14
|
+
cleanups.push(cleanup);
|
|
15
|
+
},
|
|
16
|
+
get closed() {
|
|
17
|
+
return closePromise != null;
|
|
18
|
+
},
|
|
19
|
+
closeOnce(timeoutMs) {
|
|
20
|
+
if (!closePromise) {
|
|
21
|
+
const settled = Promise.allSettled(cleanups.map(cleanup => cleanup()));
|
|
22
|
+
// The teardown continues even when the bound expires; its eventual
|
|
23
|
+
// settlement must never surface as an unhandled rejection.
|
|
24
|
+
void settled.then(() => undefined, () => undefined);
|
|
25
|
+
closePromise = Promise.race([
|
|
26
|
+
settled.then(() => true),
|
|
27
|
+
new Promise(resolve => setTimeout(() => resolve(false), timeoutMs)),
|
|
28
|
+
]);
|
|
29
|
+
}
|
|
30
|
+
return closePromise;
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
export function createQuarantinableCallbacks(callbacks) {
|
|
35
|
+
const state = { quarantined: false };
|
|
36
|
+
const whileLive = (fn) => (...args) => {
|
|
37
|
+
if (!state.quarantined)
|
|
38
|
+
fn(...args);
|
|
39
|
+
};
|
|
40
|
+
// `compactConversation`'s boolean return is consumed by overflow recovery;
|
|
41
|
+
// a quarantined call must answer "not compacted" instead of undefined.
|
|
42
|
+
const whileLiveBoolean = (fn) => (...args) => (state.quarantined ? false : fn(...args));
|
|
43
|
+
const guarded = {
|
|
44
|
+
...callbacks,
|
|
45
|
+
addMessage: whileLive(callbacks.addMessage),
|
|
46
|
+
updateMessage: whileLive(callbacks.updateMessage),
|
|
47
|
+
setConversation: whileLive(callbacks.setConversation),
|
|
48
|
+
setBusy: whileLive(callbacks.setBusy),
|
|
49
|
+
setLastAssistantText: whileLive(callbacks.setLastAssistantText),
|
|
50
|
+
...(callbacks.setBusyLabel ? { setBusyLabel: whileLive(callbacks.setBusyLabel) } : {}),
|
|
51
|
+
...(callbacks.setAbortController ? { setAbortController: whileLive(callbacks.setAbortController) } : {}),
|
|
52
|
+
...(callbacks.setGoalStatus ? { setGoalStatus: whileLive(callbacks.setGoalStatus) } : {}),
|
|
53
|
+
...(callbacks.onEvent ? { onEvent: whileLive(callbacks.onEvent) } : {}),
|
|
54
|
+
...(callbacks.compactConversation ? { compactConversation: whileLiveBoolean(callbacks.compactConversation) } : {}),
|
|
55
|
+
...(callbacks.recordTokenUsage ? { recordTokenUsage: whileLive(callbacks.recordTokenUsage) } : {}),
|
|
56
|
+
...(callbacks.setWorkState ? { setWorkState: whileLive(callbacks.setWorkState) } : {}),
|
|
57
|
+
...(callbacks.onTasksChanged ? { onTasksChanged: whileLive(callbacks.onTasksChanged) } : {}),
|
|
58
|
+
get log() {
|
|
59
|
+
return state.quarantined ? undefined : callbacks.log;
|
|
60
|
+
},
|
|
61
|
+
get contextFileSignatures() {
|
|
62
|
+
return callbacks.contextFileSignatures;
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
return { callbacks: guarded, quarantine: () => {
|
|
66
|
+
state.quarantined = true;
|
|
67
|
+
} };
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Await one agent attempt, but never let an abort-ignoring attempt defer the
|
|
71
|
+
* turn forever: once the shared controller aborts (user cancel or absolute
|
|
72
|
+
* deadline), the attempt gets a grace window to settle normally; if the grace
|
|
73
|
+
* expires, owned resources are torn down (bounded, exactly once), the attempt's
|
|
74
|
+
* callbacks are quarantined, and the turn resolves with `onForced`'s result.
|
|
75
|
+
* The abandoned attempt keeps running detached; its eventual settlement is
|
|
76
|
+
* discarded and its teardown is a no-op.
|
|
77
|
+
*/
|
|
78
|
+
export async function awaitAttemptWithForcedSettlement(attempt, deps) {
|
|
79
|
+
const { abortController, cleanup, quarantine, onForced } = deps;
|
|
80
|
+
return new Promise(resolve => {
|
|
81
|
+
let finished = false;
|
|
82
|
+
let graceTimer;
|
|
83
|
+
const finish = (result) => {
|
|
84
|
+
if (finished)
|
|
85
|
+
return;
|
|
86
|
+
finished = true;
|
|
87
|
+
if (graceTimer)
|
|
88
|
+
clearTimeout(graceTimer);
|
|
89
|
+
resolve(result);
|
|
90
|
+
};
|
|
91
|
+
// runAgentAttempt classifies its own errors, but never let a surprise
|
|
92
|
+
// rejection surface as unhandled after the turn moved on.
|
|
93
|
+
attempt.then(result => finish(result), () => finish({ status: 'failed' }));
|
|
94
|
+
const armGrace = () => {
|
|
95
|
+
if (finished || graceTimer)
|
|
96
|
+
return;
|
|
97
|
+
graceTimer = setTimeout(async () => {
|
|
98
|
+
if (finished)
|
|
99
|
+
return;
|
|
100
|
+
const tornDown = await cleanup.closeOnce(ATTEMPT_TEARDOWN_BOUND_MS);
|
|
101
|
+
quarantine();
|
|
102
|
+
finish(onForced(tornDown));
|
|
103
|
+
}, ATTEMPT_SETTLEMENT_GRACE_MS);
|
|
104
|
+
};
|
|
105
|
+
if (abortController.signal.aborted)
|
|
106
|
+
armGrace();
|
|
107
|
+
else
|
|
108
|
+
abortController.signal.addEventListener('abort', armGrace, { once: true });
|
|
109
|
+
});
|
|
110
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { type TurnExecutionState } from '../../../core/agent/completionController.js';
|
|
2
|
+
import { type SessionGoal } from '../../../core/agent/goalPolicy.js';
|
|
3
|
+
import { type TurnBudget } from '../../../core/agent/budgets.js';
|
|
4
|
+
import { type AttemptSalvage, type StreamStallGuard } from './stallRecovery.js';
|
|
5
|
+
import type { TurnAbortCause } from './abortCause.js';
|
|
6
|
+
import type { AttemptStreamOutcome } from './streamLoop.js';
|
|
7
|
+
import type { RequestIntent } from '../../../core/agent/goalPolicy.js';
|
|
8
|
+
import type { StreamCallbacks, TurnExecutionOptions, TurnResult, TurnStatus } from '../streaming.js';
|
|
9
|
+
import type { ValidationOutcome, WorkTaskProgress } from '../../../core/agent/workState.js';
|
|
10
|
+
/**
|
|
11
|
+
* CLI adapter for the authoritative turn-status decision. The pure policy
|
|
12
|
+
* lives in `core/agent/completionController.ts`; this keeps the single call site
|
|
13
|
+
* in the agent turn (see streaming/AGENTS.md) and preserves the documented
|
|
14
|
+
* field-based signature exercised by `tests/cli/commands/streaming/attemptOutcome.test.ts`.
|
|
15
|
+
*
|
|
16
|
+
* The optional work-evidence fields (intent, mutation/validation counts, task
|
|
17
|
+
* progress) project the turn-wide `TurnExecutionState`; when omitted, the
|
|
18
|
+
* defaults cannot reject a turn (unknown intent, no mutations, no task list).
|
|
19
|
+
*/
|
|
20
|
+
export declare function terminalTurnStatus(input: {
|
|
21
|
+
aborted: boolean;
|
|
22
|
+
error?: unknown;
|
|
23
|
+
assistantText: string;
|
|
24
|
+
sawToolCall: boolean;
|
|
25
|
+
lastToolOk?: boolean;
|
|
26
|
+
finishReason?: string;
|
|
27
|
+
budgetReached?: boolean;
|
|
28
|
+
unresolvedToolInputError?: boolean;
|
|
29
|
+
intent?: RequestIntent;
|
|
30
|
+
mutationCount?: number;
|
|
31
|
+
validationOutcome?: ValidationOutcome;
|
|
32
|
+
taskProgress?: WorkTaskProgress;
|
|
33
|
+
}): TurnStatus;
|
|
34
|
+
/** Bounded recovery slice an attempt proposes for the next agent call. */
|
|
35
|
+
type AttemptRecovery = {
|
|
36
|
+
kind: 'length' | 'rescue' | 'goal';
|
|
37
|
+
control: string;
|
|
38
|
+
slice: {
|
|
39
|
+
maxSteps: number;
|
|
40
|
+
maxToolCalls: number;
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
/** Internal per-attempt result: the turn outcome plus retry/recovery directives for `runAgentTurn`. */
|
|
44
|
+
export type AgentAttemptResult = TurnResult & {
|
|
45
|
+
retry?: {
|
|
46
|
+
attempt: number;
|
|
47
|
+
contextOverflowRecovered: boolean;
|
|
48
|
+
delayMs: number; /** The retry aborts the previous controller (idle stall); hand the loop a fresh one. */
|
|
49
|
+
freshController?: boolean;
|
|
50
|
+
};
|
|
51
|
+
/** When set, run one bounded recovery slice next (length-continuation, rescue, or goal continuation). */
|
|
52
|
+
recovery?: AttemptRecovery;
|
|
53
|
+
};
|
|
54
|
+
/** Keep terminal evidence truthful on normal, timeout, and forced-settlement paths. */
|
|
55
|
+
export declare function projectGoalEvidence(turnState: TurnExecutionState, goal: SessionGoal): void;
|
|
56
|
+
export interface AttemptOutcomeDeps {
|
|
57
|
+
value: string;
|
|
58
|
+
callbacks: StreamCallbacks;
|
|
59
|
+
abortController: AbortController;
|
|
60
|
+
turnOptions: TurnExecutionOptions;
|
|
61
|
+
turnState: TurnExecutionState;
|
|
62
|
+
turnBudget: TurnBudget;
|
|
63
|
+
goal: SessionGoal;
|
|
64
|
+
remainingTurnDeadlineMs: () => number;
|
|
65
|
+
stream: AttemptStreamOutcome;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Classify the finished attempt: project work evidence onto the turn state,
|
|
69
|
+
* decide the authoritative turn status and goal status, then propose bounded
|
|
70
|
+
* recovery (length-continuation, goal continuation, rescue) or an
|
|
71
|
+
* `incomplete-goal` checkpoint when no same-turn recovery can run. Never
|
|
72
|
+
* reports incomplete work as `complete`.
|
|
73
|
+
*/
|
|
74
|
+
export declare function finalizeAttemptOutcome(deps: AttemptOutcomeDeps): AgentAttemptResult;
|
|
75
|
+
export interface AttemptFailureDeps {
|
|
76
|
+
value: string;
|
|
77
|
+
callbacks: StreamCallbacks;
|
|
78
|
+
abortController: AbortController;
|
|
79
|
+
turnState: TurnExecutionState;
|
|
80
|
+
retryAttempt: number;
|
|
81
|
+
contextOverflowRecovered: boolean;
|
|
82
|
+
abortCause: TurnAbortCause;
|
|
83
|
+
stallGuard: StreamStallGuard | undefined;
|
|
84
|
+
salvage: AttemptSalvage;
|
|
85
|
+
error: unknown;
|
|
86
|
+
/** Retry-pool size for this turn (`modelRetries` setting); defaults to DEFAULT_MODEL_RETRIES. */
|
|
87
|
+
maxRetries?: number;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Classify a failed attempt from the recorded abort cause and the error:
|
|
91
|
+
* idle-stall retry/pause (shared bounded retry pool), absolute turn deadline,
|
|
92
|
+
* user abort, context-overflow compaction retry, transient model retry, or a
|
|
93
|
+
* hard model-call failure. Completed-step progress is always preserved.
|
|
94
|
+
*/
|
|
95
|
+
export declare function handleAttemptFailure(deps: AttemptFailureDeps): AgentAttemptResult;
|
|
96
|
+
export {};
|
|
@@ -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>;
|