@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,224 @@
|
|
|
1
|
+
import type { ValidationKind } from '../../llm/toolResultTypes.js';
|
|
2
|
+
import { type TurnBudget } from './budgets.js';
|
|
3
|
+
import { type ValidationOutcome, type WorkTaskProgress } from './workState.js';
|
|
4
|
+
import type { RequestIntent } from './goalPolicy.js';
|
|
5
|
+
/**
|
|
6
|
+
* Normalized reason a model stream finished. Derived from the AI SDK
|
|
7
|
+
* `finishReason` string so policy code never branches on raw provider strings.
|
|
8
|
+
*/
|
|
9
|
+
export type FinishCause = 'stop' | 'length' | 'tool-calls' | 'error' | 'content-filter' | 'unknown';
|
|
10
|
+
export declare function normalizeFinishReason(finishReason: string | undefined): FinishCause;
|
|
11
|
+
/**
|
|
12
|
+
* Turn-wide execution state, accumulated across provider retries and recovery
|
|
13
|
+
* slices. It is the single source of truth for "how much of the global budget
|
|
14
|
+
* has this whole turn consumed" and for completion evidence.
|
|
15
|
+
*
|
|
16
|
+
* Counters are turn-wide (never per-slice): a retry or recovery slice observes
|
|
17
|
+
* prior usage so the global budget cannot be reset or exceeded.
|
|
18
|
+
*/
|
|
19
|
+
export interface TurnExecutionState {
|
|
20
|
+
stepsUsed: number;
|
|
21
|
+
toolCallsUsed: number;
|
|
22
|
+
toolOnlyStepsUsed: number;
|
|
23
|
+
finishCause: FinishCause | undefined;
|
|
24
|
+
/** Length-continuation credit (Increment 2). */
|
|
25
|
+
lengthCreditUsed: boolean;
|
|
26
|
+
lengthRecoveriesAttempted: number;
|
|
27
|
+
/** Completion-rescue credit (Increment 2). */
|
|
28
|
+
rescueUsed: boolean;
|
|
29
|
+
/** Observable work evidence (Increment 3). */
|
|
30
|
+
mutationCount: number;
|
|
31
|
+
validationOutcome: ValidationOutcome;
|
|
32
|
+
validationKind: ValidationKind | undefined;
|
|
33
|
+
validationAfterMutation: boolean;
|
|
34
|
+
/** Request intent driving the validation policy (implement/fix/test expect validation). */
|
|
35
|
+
intent: RequestIntent;
|
|
36
|
+
/** Latest current-turn task-list evidence from a successful writeTasks call. */
|
|
37
|
+
taskProgress: WorkTaskProgress | undefined;
|
|
38
|
+
/** Goal-continuation cycles issued this turn (bounded by the global budget + progress guard). */
|
|
39
|
+
goalContinuationsUsed: number;
|
|
40
|
+
/** Whether the single focused post-edit validation-repair slice was admitted. */
|
|
41
|
+
validationContinuationUsed: boolean;
|
|
42
|
+
/** Work/task evidence signature recorded when the latest goal continuation was issued. */
|
|
43
|
+
goalContinuationProgress: string | undefined;
|
|
44
|
+
/** Whether the single allowed no-progress corrective nudge has been consumed. */
|
|
45
|
+
goalContinuationCorrectiveUsed: boolean;
|
|
46
|
+
budgetBoundary: boolean;
|
|
47
|
+
aborted: boolean;
|
|
48
|
+
}
|
|
49
|
+
export declare function createTurnExecutionState(): TurnExecutionState;
|
|
50
|
+
/**
|
|
51
|
+
* Bounded, safe completion evidence for headless/CI consumers. Contains only
|
|
52
|
+
* enums, booleans, and counts — never raw commands, tool inputs/outputs, or
|
|
53
|
+
* credentials. Additive on top of existing JSON/stream-JSON results.
|
|
54
|
+
*/
|
|
55
|
+
export interface TurnCompletionEvidence {
|
|
56
|
+
validationOutcome: ValidationOutcome;
|
|
57
|
+
validationKind?: ValidationKind;
|
|
58
|
+
validationAfterMutation: boolean;
|
|
59
|
+
mutationCount: number;
|
|
60
|
+
/** Current-turn task counts from writeTasks, when a task list was declared. */
|
|
61
|
+
taskProgress?: {
|
|
62
|
+
total: number;
|
|
63
|
+
pending: number;
|
|
64
|
+
inProgress: number;
|
|
65
|
+
completed: number;
|
|
66
|
+
};
|
|
67
|
+
finishCause: FinishCause | undefined;
|
|
68
|
+
recoveryUsed: {
|
|
69
|
+
length: boolean;
|
|
70
|
+
rescue: boolean;
|
|
71
|
+
goal: number;
|
|
72
|
+
};
|
|
73
|
+
budgetBoundary: boolean;
|
|
74
|
+
}
|
|
75
|
+
/** Project the turn-wide state into the safe evidence shape. */
|
|
76
|
+
export declare function toCompletionEvidence(state: TurnExecutionState): TurnCompletionEvidence;
|
|
77
|
+
/** Evidence snapshot the terminal-status decision consumes (decoupled from WorkState). */
|
|
78
|
+
export interface CompletionEvidence {
|
|
79
|
+
sawToolCall: boolean;
|
|
80
|
+
assistantText: string;
|
|
81
|
+
lastToolOk: boolean | undefined;
|
|
82
|
+
unresolvedToolInputError: boolean;
|
|
83
|
+
}
|
|
84
|
+
export type TurnStatus = 'complete' | 'aborted' | 'failed';
|
|
85
|
+
/**
|
|
86
|
+
* Reasoned completion readiness from structured current-turn evidence. A
|
|
87
|
+
* voluntary final is acceptable only when the declared work is actually done;
|
|
88
|
+
* prose alone is never evidence of completion (no semantic judge — task,
|
|
89
|
+
* mutation, validation, tool, and budget evidence is authoritative).
|
|
90
|
+
*/
|
|
91
|
+
export type CompletionReadiness = 'ready' | 'pending_tasks' | 'validation_failed' | 'validation_stale' | 'validation_absent_after_mutation' | 'tool_failure' | 'unresolved_tool_input' | 'aborted';
|
|
92
|
+
/** Inputs `assessCompletionReadiness` needs; matches the TurnExecutionState projection. */
|
|
93
|
+
export interface CompletionReadinessInput {
|
|
94
|
+
aborted: boolean;
|
|
95
|
+
intent: RequestIntent;
|
|
96
|
+
mutationCount: number;
|
|
97
|
+
validationOutcome: ValidationOutcome;
|
|
98
|
+
taskProgress: WorkTaskProgress | undefined;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Pure completion-readiness assessment. Priority: abort, unresolved tool
|
|
102
|
+
* input, failed tool, declared task progress, then intent-sensitive validation
|
|
103
|
+
* policy (implement/fix/test turns with successful mutations require fresh
|
|
104
|
+
* passing validation; plan/review/answer turns never do). A task list is
|
|
105
|
+
* enforced only when this turn declared one via a successful writeTasks call.
|
|
106
|
+
*/
|
|
107
|
+
export declare function assessCompletionReadiness(state: CompletionReadinessInput, evidence: Pick<CompletionEvidence, 'lastToolOk' | 'unresolvedToolInputError'>): CompletionReadiness;
|
|
108
|
+
/** Human-readable, safe (no commands/content) description of a readiness result. */
|
|
109
|
+
export declare function describeCompletionReadiness(readiness: CompletionReadiness, taskProgress?: WorkTaskProgress): string;
|
|
110
|
+
/**
|
|
111
|
+
* True when the turn-wide budget is exhausted. Expressed against turn-wide
|
|
112
|
+
* counters so a retry or recovery slice observes prior usage and the global
|
|
113
|
+
* budget cannot be reset or exceeded. A `length` finish counts as exhausted
|
|
114
|
+
* for the *terminal* status (the output was truncated); recovery uses
|
|
115
|
+
* `hasRemainingRecoveryBudget` instead, because a length finish often leaves
|
|
116
|
+
* plenty of step/tool budget.
|
|
117
|
+
*/
|
|
118
|
+
export declare function isBudgetExhausted(state: Pick<TurnExecutionState, 'stepsUsed' | 'toolCallsUsed' | 'toolOnlyStepsUsed' | 'finishCause'>, budget: TurnBudget): boolean;
|
|
119
|
+
/** Whether step/tool-call resources remain for a recovery slice (length finish excluded). */
|
|
120
|
+
export declare function hasRemainingRecoveryBudget(state: Pick<TurnExecutionState, 'stepsUsed' | 'toolCallsUsed'>, budget: TurnBudget): boolean;
|
|
121
|
+
/**
|
|
122
|
+
* Authoritative terminal turn status. This is the pure, unit-testable core of
|
|
123
|
+
* the old inline `terminalTurnStatus` in the CLI layer; the CLI wrapper still
|
|
124
|
+
* owns the single call site.
|
|
125
|
+
*
|
|
126
|
+
* `budgetExhausted` is supplied by the caller (typically via `isBudgetExhausted`)
|
|
127
|
+
* so this function stays free of budget-wiring details and a turn-wide caller
|
|
128
|
+
* and a per-slice caller can share one decision.
|
|
129
|
+
*
|
|
130
|
+
* Increment 1 reproduces historical behavior exactly: a `length` finish is a
|
|
131
|
+
* failure (length-continuation lands in Increment 2 and only flips on when a
|
|
132
|
+
* recovery credit is both available and warranted).
|
|
133
|
+
*/
|
|
134
|
+
export declare function decideTerminalStatus(state: TurnExecutionState, evidence: CompletionEvidence, budgetExhausted: boolean): TurnStatus;
|
|
135
|
+
type RecoveryAction = 'continue' | 'stop';
|
|
136
|
+
interface RecoverySlice {
|
|
137
|
+
steps: number;
|
|
138
|
+
toolCalls: number;
|
|
139
|
+
}
|
|
140
|
+
export interface LengthRecoveryDecision {
|
|
141
|
+
action: RecoveryAction;
|
|
142
|
+
reason: string;
|
|
143
|
+
/** Slice size to request when action is 'continue'. */
|
|
144
|
+
slice: RecoverySlice;
|
|
145
|
+
}
|
|
146
|
+
export interface RescueRecoveryDecision {
|
|
147
|
+
action: RecoveryAction;
|
|
148
|
+
reason: string;
|
|
149
|
+
slice: RecoverySlice;
|
|
150
|
+
}
|
|
151
|
+
/** Tool-only boundary at which rescue becomes eligible (normal exploration stops here). */
|
|
152
|
+
export declare const RESCUE_BOUNDARY: number;
|
|
153
|
+
/**
|
|
154
|
+
* Length-continuation decision. Fires once per turn when an output-length finish
|
|
155
|
+
* truncates the response, the turn is not aborted, the credit is unused, the
|
|
156
|
+
* global budget still has room, and the work is not already satisfactorily
|
|
157
|
+
* validated (a fresh passing validation means the artifact landed). A repeated
|
|
158
|
+
* length finish terminates cleanly because the credit is single-use.
|
|
159
|
+
*/
|
|
160
|
+
export declare function decideLengthRecovery(state: TurnExecutionState, budget: TurnBudget): LengthRecoveryDecision;
|
|
161
|
+
/**
|
|
162
|
+
* Whether a request intent has a deliverable the rescue slice could apply or
|
|
163
|
+
* validate. Deliberately matches `intentExpectsValidation` so a test-orchestration
|
|
164
|
+
* turn (F-04) gets the same bounded rescue as implement/fix: a `test` finish is
|
|
165
|
+
* driven by tool runs exactly like the intents `decideRescue` already serves.
|
|
166
|
+
*/
|
|
167
|
+
export declare function rescueEligibleRequest(intent: RequestIntent): boolean;
|
|
168
|
+
/**
|
|
169
|
+
* Completion-rescue decision near the tool-only boundary. Fires once when normal
|
|
170
|
+
* exploration exhausted the (reserved) tool-only slots without producing a
|
|
171
|
+
* substantive answer, the turn is not aborted, the rescue credit is unused, and
|
|
172
|
+
* the global budget still has room. Rescue never reopens discovery and never
|
|
173
|
+
* extends the global budget.
|
|
174
|
+
*/
|
|
175
|
+
export declare function decideRescue(state: TurnExecutionState, evidence: CompletionEvidence, budget: TurnBudget, isMutatingRequest: boolean): RescueRecoveryDecision;
|
|
176
|
+
export interface GoalContinuationDecision {
|
|
177
|
+
action: RecoveryAction;
|
|
178
|
+
reason: string;
|
|
179
|
+
/** Slice size to request when action is 'continue'. */
|
|
180
|
+
slice: RecoverySlice;
|
|
181
|
+
}
|
|
182
|
+
/** Readiness reasons a bounded continuation can plausibly resolve with more work. */
|
|
183
|
+
/** Readiness reasons a bounded continuation can plausibly resolve with more work. */
|
|
184
|
+
export declare function goalContinuationRecoverable(readiness: CompletionReadiness): boolean;
|
|
185
|
+
/**
|
|
186
|
+
* Terminal classification of a finished attempt against the logical goal.
|
|
187
|
+
* - `goal-complete`: readiness satisfied, substantive answer, clean stop.
|
|
188
|
+
* - `recoverable-incomplete`: structured readiness shows declared work
|
|
189
|
+
* remaining (pending tasks, missing/stale/failed validation after edits)
|
|
190
|
+
* and the finish shape can still be continued — regardless of turn
|
|
191
|
+
* budget. A budget boundary ends a physical turn, not the goal.
|
|
192
|
+
* - `hard-blocked`: concrete tool/input failure, provider error, or a
|
|
193
|
+
* readiness that more work cannot resolve.
|
|
194
|
+
* - `user-aborted`.
|
|
195
|
+
*/
|
|
196
|
+
export type TerminalClassification = 'goal-complete' | 'recoverable-incomplete' | 'hard-blocked' | 'user-aborted';
|
|
197
|
+
export declare function classifyTerminalOutcome(state: TurnExecutionState, evidence: CompletionEvidence): TerminalClassification;
|
|
198
|
+
/** Compact signature of measurable work: mutations, validation outcome/kind, task counts. */
|
|
199
|
+
export declare function goalProgressSignature(state: Pick<TurnExecutionState, 'mutationCount' | 'validationOutcome' | 'validationKind' | 'taskProgress'>): string;
|
|
200
|
+
/**
|
|
201
|
+
* Record that a goal-continuation slice was issued. Progress since the previous
|
|
202
|
+
* continuation (work/task signature comparison) decides whether this issuance
|
|
203
|
+
* is the single allowed corrective nudge; a second no-progress stop then
|
|
204
|
+
* terminates as failed (see `decideGoalContinuation`). Never resets counters.
|
|
205
|
+
*/
|
|
206
|
+
export declare function recordGoalContinuation(state: TurnExecutionState): void;
|
|
207
|
+
/**
|
|
208
|
+
* Goal-continuation decision for a `recoverable-incomplete` attempt with a
|
|
209
|
+
* substantive answer to reject: continue in-turn with a slice when the global
|
|
210
|
+
* budget and progress guard allow it. Any other outcome is the caller's signal
|
|
211
|
+
* to end the physical turn — the goal-level invariant (failed + recoverable +
|
|
212
|
+
* no same-turn recovery → `incomplete-goal` checkpoint) is enforced by the
|
|
213
|
+
* caller via `classifyTerminalOutcome`, not here. Never resets budgets.
|
|
214
|
+
*/
|
|
215
|
+
export declare function decideGoalContinuation(state: TurnExecutionState, evidence: CompletionEvidence, budget: TurnBudget): GoalContinuationDecision;
|
|
216
|
+
/**
|
|
217
|
+
* Does the turn have a satisfactory terminal outcome that should stop recovery?
|
|
218
|
+
* A substantive assistant answer is satisfactory only when the structured
|
|
219
|
+
* completion evidence agrees: declared tasks finished, no unresolved tool
|
|
220
|
+
* failure, and (for validation-bearing intents) fresh validation after edits.
|
|
221
|
+
* Used by recovery guards so a normal successful turn makes no extra model call.
|
|
222
|
+
*/
|
|
223
|
+
export declare function hasSatisfactoryTerminalOutcome(state: TurnExecutionState, evidence: CompletionEvidence): boolean;
|
|
224
|
+
export {};
|
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
import { MAIN_TOOL_ONLY_STEP_LIMIT } from './budgets.js';
|
|
2
|
+
import { intentExpectsValidation } from './workState.js';
|
|
3
|
+
export function normalizeFinishReason(finishReason) {
|
|
4
|
+
switch (finishReason) {
|
|
5
|
+
case 'stop': return 'stop';
|
|
6
|
+
case 'length': return 'length';
|
|
7
|
+
case 'tool-calls': return 'tool-calls';
|
|
8
|
+
case 'error': return 'error';
|
|
9
|
+
case 'content-filter': return 'content-filter';
|
|
10
|
+
default: return 'unknown';
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
export function createTurnExecutionState() {
|
|
14
|
+
return {
|
|
15
|
+
stepsUsed: 0,
|
|
16
|
+
toolCallsUsed: 0,
|
|
17
|
+
toolOnlyStepsUsed: 0,
|
|
18
|
+
finishCause: undefined,
|
|
19
|
+
lengthCreditUsed: false,
|
|
20
|
+
lengthRecoveriesAttempted: 0,
|
|
21
|
+
rescueUsed: false,
|
|
22
|
+
mutationCount: 0,
|
|
23
|
+
validationOutcome: 'absent',
|
|
24
|
+
validationKind: undefined,
|
|
25
|
+
validationAfterMutation: false,
|
|
26
|
+
intent: 'unknown',
|
|
27
|
+
taskProgress: undefined,
|
|
28
|
+
goalContinuationsUsed: 0,
|
|
29
|
+
validationContinuationUsed: false,
|
|
30
|
+
goalContinuationProgress: undefined,
|
|
31
|
+
goalContinuationCorrectiveUsed: false,
|
|
32
|
+
budgetBoundary: false,
|
|
33
|
+
aborted: false,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/** Project the turn-wide state into the safe evidence shape. */
|
|
37
|
+
export function toCompletionEvidence(state) {
|
|
38
|
+
return {
|
|
39
|
+
validationOutcome: state.validationOutcome,
|
|
40
|
+
...(state.validationKind ? { validationKind: state.validationKind } : {}),
|
|
41
|
+
validationAfterMutation: state.validationAfterMutation,
|
|
42
|
+
mutationCount: state.mutationCount,
|
|
43
|
+
...(state.taskProgress ? { taskProgress: { total: state.taskProgress.total, pending: state.taskProgress.pending, inProgress: state.taskProgress.inProgress, completed: state.taskProgress.completed } } : {}),
|
|
44
|
+
finishCause: state.finishCause,
|
|
45
|
+
recoveryUsed: { length: state.lengthCreditUsed, rescue: state.rescueUsed, goal: state.goalContinuationsUsed },
|
|
46
|
+
budgetBoundary: state.budgetBoundary,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Pure completion-readiness assessment. Priority: abort, unresolved tool
|
|
51
|
+
* input, failed tool, declared task progress, then intent-sensitive validation
|
|
52
|
+
* policy (implement/fix/test turns with successful mutations require fresh
|
|
53
|
+
* passing validation; plan/review/answer turns never do). A task list is
|
|
54
|
+
* enforced only when this turn declared one via a successful writeTasks call.
|
|
55
|
+
*/
|
|
56
|
+
export function assessCompletionReadiness(state, evidence) {
|
|
57
|
+
if (state.aborted)
|
|
58
|
+
return 'aborted';
|
|
59
|
+
if (evidence.unresolvedToolInputError)
|
|
60
|
+
return 'unresolved_tool_input';
|
|
61
|
+
if (evidence.lastToolOk === false)
|
|
62
|
+
return 'tool_failure';
|
|
63
|
+
if (state.taskProgress && (state.taskProgress.pending > 0 || state.taskProgress.inProgress > 0))
|
|
64
|
+
return 'pending_tasks';
|
|
65
|
+
if (intentExpectsValidation(state.intent)) {
|
|
66
|
+
if (state.validationOutcome === 'failed')
|
|
67
|
+
return 'validation_failed';
|
|
68
|
+
if (state.validationOutcome === 'stale')
|
|
69
|
+
return 'validation_stale';
|
|
70
|
+
if (state.validationOutcome === 'absent' && state.mutationCount > 0)
|
|
71
|
+
return 'validation_absent_after_mutation';
|
|
72
|
+
}
|
|
73
|
+
return 'ready';
|
|
74
|
+
}
|
|
75
|
+
/** Human-readable, safe (no commands/content) description of a readiness result. */
|
|
76
|
+
export function describeCompletionReadiness(readiness, taskProgress) {
|
|
77
|
+
switch (readiness) {
|
|
78
|
+
case 'pending_tasks': {
|
|
79
|
+
const open = taskProgress ? taskProgress.pending + taskProgress.inProgress : 0;
|
|
80
|
+
return `${open} declared task${open === 1 ? '' : 's'} still pending or in progress`;
|
|
81
|
+
}
|
|
82
|
+
case 'validation_failed': return 'the latest validation failed and remains unresolved';
|
|
83
|
+
case 'validation_stale': return 'edits landed after the latest validation';
|
|
84
|
+
case 'validation_absent_after_mutation': return 'edits landed without any relevant validation';
|
|
85
|
+
case 'tool_failure': return 'the last tool call failed';
|
|
86
|
+
case 'unresolved_tool_input': return 'a tool call never executed because its input was invalid';
|
|
87
|
+
case 'aborted': return 'the turn was aborted';
|
|
88
|
+
case 'ready': return 'declared work is complete';
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* True when the turn-wide budget is exhausted. Expressed against turn-wide
|
|
93
|
+
* counters so a retry or recovery slice observes prior usage and the global
|
|
94
|
+
* budget cannot be reset or exceeded. A `length` finish counts as exhausted
|
|
95
|
+
* for the *terminal* status (the output was truncated); recovery uses
|
|
96
|
+
* `hasRemainingRecoveryBudget` instead, because a length finish often leaves
|
|
97
|
+
* plenty of step/tool budget.
|
|
98
|
+
*/
|
|
99
|
+
export function isBudgetExhausted(state, budget) {
|
|
100
|
+
return state.finishCause === 'length'
|
|
101
|
+
|| state.stepsUsed >= budget.stepLimit
|
|
102
|
+
|| state.toolCallsUsed >= budget.toolCallLimit
|
|
103
|
+
|| state.toolOnlyStepsUsed >= budget.toolOnlyStepLimit;
|
|
104
|
+
}
|
|
105
|
+
/** Whether step/tool-call resources remain for a recovery slice (length finish excluded). */
|
|
106
|
+
export function hasRemainingRecoveryBudget(state, budget) {
|
|
107
|
+
return state.stepsUsed < budget.stepLimit && state.toolCallsUsed < budget.toolCallLimit;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Authoritative terminal turn status. This is the pure, unit-testable core of
|
|
111
|
+
* the old inline `terminalTurnStatus` in the CLI layer; the CLI wrapper still
|
|
112
|
+
* owns the single call site.
|
|
113
|
+
*
|
|
114
|
+
* `budgetExhausted` is supplied by the caller (typically via `isBudgetExhausted`)
|
|
115
|
+
* so this function stays free of budget-wiring details and a turn-wide caller
|
|
116
|
+
* and a per-slice caller can share one decision.
|
|
117
|
+
*
|
|
118
|
+
* Increment 1 reproduces historical behavior exactly: a `length` finish is a
|
|
119
|
+
* failure (length-continuation lands in Increment 2 and only flips on when a
|
|
120
|
+
* recovery credit is both available and warranted).
|
|
121
|
+
*/
|
|
122
|
+
export function decideTerminalStatus(state, evidence, budgetExhausted) {
|
|
123
|
+
if (state.aborted)
|
|
124
|
+
return 'aborted';
|
|
125
|
+
if (budgetExhausted || state.finishCause === 'length' || state.finishCause === 'error')
|
|
126
|
+
return 'failed';
|
|
127
|
+
if (assessCompletionReadiness(state, evidence) !== 'ready')
|
|
128
|
+
return 'failed';
|
|
129
|
+
if (evidence.sawToolCall && evidence.assistantText.trim().length === 0)
|
|
130
|
+
return 'failed';
|
|
131
|
+
return evidence.assistantText.trim().length > 0 ? 'complete' : 'failed';
|
|
132
|
+
}
|
|
133
|
+
/** Length-continuation slice cap: four model steps / four tool calls (global). */
|
|
134
|
+
const LENGTH_RECOVERY_SLICE = { steps: 4, toolCalls: 4 };
|
|
135
|
+
/** Completion-rescue slice: one tool-bearing step (≤2 calls) + one synthesis step. */
|
|
136
|
+
const RESCUE_SLICE = { steps: 2, toolCalls: 2 };
|
|
137
|
+
/** Number of trailing tool-only slots reserved for the rescue slice. */
|
|
138
|
+
const RESCUE_RESERVE = 1;
|
|
139
|
+
/** Tool-only boundary at which rescue becomes eligible (normal exploration stops here). */
|
|
140
|
+
export const RESCUE_BOUNDARY = MAIN_TOOL_ONLY_STEP_LIMIT - RESCUE_RESERVE;
|
|
141
|
+
/**
|
|
142
|
+
* Length-continuation decision. Fires once per turn when an output-length finish
|
|
143
|
+
* truncates the response, the turn is not aborted, the credit is unused, the
|
|
144
|
+
* global budget still has room, and the work is not already satisfactorily
|
|
145
|
+
* validated (a fresh passing validation means the artifact landed). A repeated
|
|
146
|
+
* length finish terminates cleanly because the credit is single-use.
|
|
147
|
+
*/
|
|
148
|
+
export function decideLengthRecovery(state, budget) {
|
|
149
|
+
const stop = (reason) => ({ action: 'stop', reason, slice: LENGTH_RECOVERY_SLICE });
|
|
150
|
+
if (state.aborted)
|
|
151
|
+
return stop('turn aborted');
|
|
152
|
+
if (state.finishCause !== 'length')
|
|
153
|
+
return stop('finish is not a length truncation');
|
|
154
|
+
if (state.lengthCreditUsed)
|
|
155
|
+
return stop('length-continuation credit already used');
|
|
156
|
+
if (!hasRemainingRecoveryBudget(state, budget))
|
|
157
|
+
return stop('global budget exhausted');
|
|
158
|
+
if (state.validationOutcome === 'passed')
|
|
159
|
+
return stop('fresh passing validation already observed');
|
|
160
|
+
return { action: 'continue', reason: 'output-length finish with budget remaining', slice: LENGTH_RECOVERY_SLICE };
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Whether a request intent has a deliverable the rescue slice could apply or
|
|
164
|
+
* validate. Deliberately matches `intentExpectsValidation` so a test-orchestration
|
|
165
|
+
* turn (F-04) gets the same bounded rescue as implement/fix: a `test` finish is
|
|
166
|
+
* driven by tool runs exactly like the intents `decideRescue` already serves.
|
|
167
|
+
*/
|
|
168
|
+
export function rescueEligibleRequest(intent) {
|
|
169
|
+
return intentExpectsValidation(intent);
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Completion-rescue decision near the tool-only boundary. Fires once when normal
|
|
173
|
+
* exploration exhausted the (reserved) tool-only slots without producing a
|
|
174
|
+
* substantive answer, the turn is not aborted, the rescue credit is unused, and
|
|
175
|
+
* the global budget still has room. Rescue never reopens discovery and never
|
|
176
|
+
* extends the global budget.
|
|
177
|
+
*/
|
|
178
|
+
export function decideRescue(state, evidence, budget, isMutatingRequest) {
|
|
179
|
+
const stop = (reason) => ({ action: 'stop', reason, slice: RESCUE_SLICE });
|
|
180
|
+
if (state.aborted)
|
|
181
|
+
return stop('turn aborted');
|
|
182
|
+
if (state.rescueUsed)
|
|
183
|
+
return stop('rescue credit already used');
|
|
184
|
+
if (state.finishCause !== 'stop' && state.finishCause !== 'tool-calls' && state.finishCause !== 'length')
|
|
185
|
+
return stop('finish is not a normal/tool boundary stop');
|
|
186
|
+
if (!isMutatingRequest)
|
|
187
|
+
return stop('request has no deliverable to apply');
|
|
188
|
+
if (state.toolOnlyStepsUsed < RESCUE_BOUNDARY)
|
|
189
|
+
return stop('not near the tool-only boundary');
|
|
190
|
+
if (hasSatisfactoryTerminalOutcome(state, evidence))
|
|
191
|
+
return stop('substantive terminal outcome already present');
|
|
192
|
+
if (!hasRemainingRecoveryBudget(state, budget))
|
|
193
|
+
return stop('global budget exhausted');
|
|
194
|
+
return { action: 'continue', reason: 'near tool-only boundary with no substantive answer', slice: RESCUE_SLICE };
|
|
195
|
+
}
|
|
196
|
+
/** Pending-task continuation keeps room for implementation; evidence repair is deliberately smaller. */
|
|
197
|
+
const GOAL_CONTINUATION_SLICE = { steps: 6, toolCalls: 12 };
|
|
198
|
+
const VALIDATION_CONTINUATION_SLICE = { steps: 3, toolCalls: 3 };
|
|
199
|
+
/** Readiness reasons a bounded continuation can plausibly resolve with more work. */
|
|
200
|
+
/** Readiness reasons a bounded continuation can plausibly resolve with more work. */
|
|
201
|
+
export function goalContinuationRecoverable(readiness) {
|
|
202
|
+
return readiness === 'pending_tasks'
|
|
203
|
+
|| readiness === 'validation_failed'
|
|
204
|
+
|| readiness === 'validation_stale'
|
|
205
|
+
|| readiness === 'validation_absent_after_mutation';
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Normal provider finishes that can still represent recoverable unfinished
|
|
209
|
+
* work. `stop` is a voluntary final; `tool-calls` is a step/slice budget
|
|
210
|
+
* boundary (often with a runtime-forced progress line); `length` is output
|
|
211
|
+
* truncation; `unknown` is an unmapped but non-erroneous finish. `error` and
|
|
212
|
+
* `content-filter` stay hard: they are provider failures, not work states.
|
|
213
|
+
*/
|
|
214
|
+
const RECOVERABLE_FINISH_CAUSES = new Set(['stop', 'tool-calls', 'length', 'unknown']);
|
|
215
|
+
function isRecoverableFinishCause(finishCause) {
|
|
216
|
+
return finishCause != null && RECOVERABLE_FINISH_CAUSES.has(finishCause);
|
|
217
|
+
}
|
|
218
|
+
export function classifyTerminalOutcome(state, evidence) {
|
|
219
|
+
if (state.aborted)
|
|
220
|
+
return 'user-aborted';
|
|
221
|
+
const readiness = assessCompletionReadiness(state, evidence);
|
|
222
|
+
if (readiness === 'ready') {
|
|
223
|
+
return evidence.assistantText.trim().length > 0 && state.finishCause === 'stop' ? 'goal-complete' : 'hard-blocked';
|
|
224
|
+
}
|
|
225
|
+
if (!goalContinuationRecoverable(readiness))
|
|
226
|
+
return 'hard-blocked';
|
|
227
|
+
return isRecoverableFinishCause(state.finishCause) ? 'recoverable-incomplete' : 'hard-blocked';
|
|
228
|
+
}
|
|
229
|
+
/** Compact signature of measurable work: mutations, validation outcome/kind, task counts. */
|
|
230
|
+
export function goalProgressSignature(state) {
|
|
231
|
+
const tasks = state.taskProgress;
|
|
232
|
+
// Mutation counters and task revisions are monotonic activity signals, not
|
|
233
|
+
// proof of net progress: edit→revert and rewriting identical task counts must
|
|
234
|
+
// not keep an unfinished goal alive. Track only whether work exists plus
|
|
235
|
+
// validation/task outcomes that can actually move toward readiness.
|
|
236
|
+
return JSON.stringify([state.mutationCount > 0, state.validationOutcome, state.validationKind ?? '', tasks ? [tasks.pending, tasks.inProgress, tasks.completed] : null]);
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Record that a goal-continuation slice was issued. Progress since the previous
|
|
240
|
+
* continuation (work/task signature comparison) decides whether this issuance
|
|
241
|
+
* is the single allowed corrective nudge; a second no-progress stop then
|
|
242
|
+
* terminates as failed (see `decideGoalContinuation`). Never resets counters.
|
|
243
|
+
*/
|
|
244
|
+
export function recordGoalContinuation(state) {
|
|
245
|
+
const signature = goalProgressSignature(state);
|
|
246
|
+
state.goalContinuationCorrectiveUsed = state.goalContinuationProgress != null && signature === state.goalContinuationProgress;
|
|
247
|
+
state.goalContinuationProgress = signature;
|
|
248
|
+
state.goalContinuationsUsed += 1;
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Goal-continuation decision for a `recoverable-incomplete` attempt with a
|
|
252
|
+
* substantive answer to reject: continue in-turn with a slice when the global
|
|
253
|
+
* budget and progress guard allow it. Any other outcome is the caller's signal
|
|
254
|
+
* to end the physical turn — the goal-level invariant (failed + recoverable +
|
|
255
|
+
* no same-turn recovery → `incomplete-goal` checkpoint) is enforced by the
|
|
256
|
+
* caller via `classifyTerminalOutcome`, not here. Never resets budgets.
|
|
257
|
+
*/
|
|
258
|
+
export function decideGoalContinuation(state, evidence, budget) {
|
|
259
|
+
const stop = (reason) => ({ action: 'stop', reason, slice: GOAL_CONTINUATION_SLICE });
|
|
260
|
+
if (state.aborted)
|
|
261
|
+
return stop('turn aborted');
|
|
262
|
+
if (!isRecoverableFinishCause(state.finishCause))
|
|
263
|
+
return stop('finish shape is not recoverable');
|
|
264
|
+
if (evidence.assistantText.trim().length === 0)
|
|
265
|
+
return stop('no substantive final to reject');
|
|
266
|
+
if (evidence.lastToolOk === false || evidence.unresolvedToolInputError)
|
|
267
|
+
return stop('unresolved tool failure');
|
|
268
|
+
const readiness = assessCompletionReadiness(state, evidence);
|
|
269
|
+
if (readiness === 'ready')
|
|
270
|
+
return stop('completion readiness satisfied');
|
|
271
|
+
if (!goalContinuationRecoverable(readiness))
|
|
272
|
+
return stop(`readiness '${readiness}' is not autonomously recoverable`);
|
|
273
|
+
const validationRepair = readiness === 'validation_failed' || readiness === 'validation_stale' || readiness === 'validation_absent_after_mutation';
|
|
274
|
+
if (validationRepair && state.validationContinuationUsed)
|
|
275
|
+
return stop('focused validation-repair continuation already used');
|
|
276
|
+
if (!hasRemainingRecoveryBudget(state, budget))
|
|
277
|
+
return stop('global budget exhausted');
|
|
278
|
+
if (state.goalContinuationProgress != null && goalProgressSignature(state) === state.goalContinuationProgress && state.goalContinuationCorrectiveUsed) {
|
|
279
|
+
return stop('no measurable progress after the corrective nudge');
|
|
280
|
+
}
|
|
281
|
+
return { action: 'continue', reason: `premature final rejected: ${readiness}`, slice: validationRepair ? VALIDATION_CONTINUATION_SLICE : GOAL_CONTINUATION_SLICE };
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Does the turn have a satisfactory terminal outcome that should stop recovery?
|
|
285
|
+
* A substantive assistant answer is satisfactory only when the structured
|
|
286
|
+
* completion evidence agrees: declared tasks finished, no unresolved tool
|
|
287
|
+
* failure, and (for validation-bearing intents) fresh validation after edits.
|
|
288
|
+
* Used by recovery guards so a normal successful turn makes no extra model call.
|
|
289
|
+
*/
|
|
290
|
+
export function hasSatisfactoryTerminalOutcome(state, evidence) {
|
|
291
|
+
if (state.aborted)
|
|
292
|
+
return true;
|
|
293
|
+
if (evidence.assistantText.trim().length === 0)
|
|
294
|
+
return false;
|
|
295
|
+
return assessCompletionReadiness(state, evidence) === 'ready';
|
|
296
|
+
}
|
|
@@ -1,6 +1,17 @@
|
|
|
1
1
|
import type { ModelMessage } from 'ai';
|
|
2
2
|
import type { ContextFile } from '../../config/contextFiles.js';
|
|
3
|
-
|
|
3
|
+
/**
|
|
4
|
+
* Conservative fallback context window for a hosted model with no metadata
|
|
5
|
+
* (RH-005). 128K is the floor for current capable hosted models (GPT-4o class,
|
|
6
|
+
* older Claude, fine-tunes); assuming more risks hard request failures on
|
|
7
|
+
* exactly-128K models, while assuming less only compacts earlier. Local
|
|
8
|
+
* servers use a smaller fallback (see FALLBACK_LOCAL_CONTEXT_TOKENS) because
|
|
9
|
+
* their effective window is set by server configuration (often 4–32K), not the
|
|
10
|
+
* model, and silent truncation there is undetectable.
|
|
11
|
+
*/
|
|
12
|
+
export declare const FALLBACK_CONTEXT_WINDOW_TOKENS = 128000;
|
|
13
|
+
/** Fallback window for unknown models on local (localhost) inference servers. */
|
|
14
|
+
export declare const FALLBACK_LOCAL_CONTEXT_TOKENS = 32768;
|
|
4
15
|
/**
|
|
5
16
|
* Rough vision estimate for attached images: providers bill images by
|
|
6
17
|
* resolution, not by serialized bytes. ~750 bytes per token matches common
|
|
@@ -25,8 +36,10 @@ export interface ContextBreakdown {
|
|
|
25
36
|
syntheticControl: number;
|
|
26
37
|
}
|
|
27
38
|
export declare function estimateTextTokens(text: string): number;
|
|
28
|
-
export declare function estimateImagePartTokens(part: unknown): number;
|
|
29
39
|
export declare function estimateValueTokens(value: unknown): number;
|
|
40
|
+
export declare function estimateModelMessageTokens(message: ModelMessage): number;
|
|
41
|
+
/** Sum of per-message estimates for a history array, memoized per message object. */
|
|
42
|
+
export declare function estimateMessagesTokens(messages: readonly ModelMessage[]): number;
|
|
30
43
|
export declare function estimateToolSchemas(tools?: Record<string, unknown>): {
|
|
31
44
|
name: string;
|
|
32
45
|
tokens: number;
|
|
@@ -39,3 +52,24 @@ export declare function contextBreakdown(input: {
|
|
|
39
52
|
}): ContextBreakdown;
|
|
40
53
|
export declare function effectiveNonCachedInput(inputTokens: number | undefined, cacheReadTokens: number): number | undefined;
|
|
41
54
|
export declare function cacheHitRatio(inputTokens: number | undefined, cacheReadTokens: number | undefined): number | undefined;
|
|
55
|
+
export interface RequestTokenBudget {
|
|
56
|
+
contextWindowTokens: number;
|
|
57
|
+
systemTokens: number;
|
|
58
|
+
toolSchemaTokens: number;
|
|
59
|
+
outputReserveTokens: number;
|
|
60
|
+
safetyMarginTokens: number;
|
|
61
|
+
/** Tokens available for the message history. */
|
|
62
|
+
messageTokens: number;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Compute the message-token allowance for a request from the full input
|
|
66
|
+
* breakdown: context window minus system prompt, tool schemas, output reserve,
|
|
67
|
+
* and a safety margin (RH-005). Falls back to a conservative window when a
|
|
68
|
+
* model declares no capacity metadata.
|
|
69
|
+
*/
|
|
70
|
+
export declare function calculateRequestTokenBudget(input: {
|
|
71
|
+
contextWindowTokens?: number;
|
|
72
|
+
requestedOutputTokens: number;
|
|
73
|
+
system: string;
|
|
74
|
+
tools: Record<string, unknown>;
|
|
75
|
+
}): RequestTokenBudget;
|