@denizokcu/haze 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/README.md +18 -10
  3. package/SECURITY.md +1 -1
  4. package/bin/haze.js +27 -7
  5. package/dist/buildInfo.json +3 -3
  6. package/dist/cli/chat/inputSuggestions.js +3 -0
  7. package/dist/cli/chat/liveMessages.d.ts +36 -0
  8. package/dist/cli/chat/liveMessages.js +64 -0
  9. package/dist/cli/chat/sessionLifecycle.d.ts +2 -1
  10. package/dist/cli/chat/sessionLifecycle.js +23 -2
  11. package/dist/cli/chat/wizard/sessionThemeHandlers.d.ts +1 -1
  12. package/dist/cli/chat/wizard/sessionThemeHandlers.js +16 -1
  13. package/dist/cli/commands/chat.js +39 -34
  14. package/dist/cli/commands/commandHelp.js +2 -0
  15. package/dist/cli/commands/commands.js +2 -0
  16. package/dist/cli/commands/formatters.js +5 -1
  17. package/dist/cli/commands/ndjsonSink.d.ts +12 -0
  18. package/dist/cli/commands/ndjsonSink.js +29 -0
  19. package/dist/cli/commands/reasoningCommand.d.ts +35 -0
  20. package/dist/cli/commands/reasoningCommand.js +46 -0
  21. package/dist/cli/commands/runCommand.d.ts +14 -0
  22. package/dist/cli/commands/runCommand.js +37 -11
  23. package/dist/cli/commands/settingsSummary.js +2 -0
  24. package/dist/cli/commands/streaming/agentAttempt.d.ts +3 -0
  25. package/dist/cli/commands/streaming/agentAttempt.js +2 -2
  26. package/dist/cli/commands/streaming/assistantSegments.d.ts +0 -7
  27. package/dist/cli/commands/streaming/assistantSegments.js +1 -1
  28. package/dist/cli/commands/streaming/attemptLifecycle.js +13 -9
  29. package/dist/cli/commands/streaming/attemptOutcome.js +13 -3
  30. package/dist/cli/commands/streaming/attemptSetup.d.ts +3 -0
  31. package/dist/cli/commands/streaming/attemptSetup.js +11 -3
  32. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +6 -0
  33. package/dist/cli/commands/streaming/goalCheckpoint.js +1 -0
  34. package/dist/cli/commands/streaming/goalSupervisor.d.ts +5 -0
  35. package/dist/cli/commands/streaming/goalSupervisor.js +9 -4
  36. package/dist/cli/commands/streaming/prepareStep.d.ts +0 -3
  37. package/dist/cli/commands/streaming/prepareStep.js +8 -3
  38. package/dist/cli/commands/streaming.d.ts +7 -2
  39. package/dist/cli/commands/streaming.js +24 -5
  40. package/dist/cli/commands/wizardFlow.d.ts +7 -0
  41. package/dist/cli/commands/wizardFlow.js +22 -0
  42. package/dist/cli/index.js +5 -1
  43. package/dist/config/modelDiscovery.js +68 -5
  44. package/dist/config/settings.d.ts +8 -4
  45. package/dist/config/settings.js +8 -1
  46. package/dist/core/agent/budgets.d.ts +0 -2
  47. package/dist/core/agent/budgets.js +0 -2
  48. package/dist/core/agent/completionController.d.ts +8 -0
  49. package/dist/core/agent/completionController.js +32 -0
  50. package/dist/core/agent/events.d.ts +2 -1
  51. package/dist/core/agent/goalPolicy.d.ts +7 -0
  52. package/dist/core/agent/goalPolicy.js +9 -0
  53. package/dist/core/agent/reasoningPolicy.d.ts +45 -9
  54. package/dist/core/agent/reasoningPolicy.js +49 -9
  55. package/dist/core/agent/toolCapabilities.d.ts +3 -3
  56. package/dist/core/agent/toolCapabilities.js +31 -7
  57. package/dist/core/agent/workState.d.ts +6 -4
  58. package/dist/core/agent/workState.js +40 -28
  59. package/dist/core/deadline.js +22 -24
  60. package/dist/core/safety/secretPaths.js +10 -7
  61. package/dist/core/safety/shellClassifier.d.ts +2 -0
  62. package/dist/core/safety/shellClassifier.js +9 -1
  63. package/dist/core/session/sessionSlimming.d.ts +2 -0
  64. package/dist/core/session/sessionSlimming.js +50 -1
  65. package/dist/core/session/sessionStore.d.ts +4 -8
  66. package/dist/core/session/sessionStore.js +53 -32
  67. package/dist/core/shellOutput/reducers/git.js +7 -2
  68. package/dist/core/shellOutput/reducers/validation.d.ts +1 -1
  69. package/dist/core/shellOutput/reducers/validation.js +14 -1
  70. package/dist/core/shellOutput/registry.js +3 -2
  71. package/dist/core/subagent/contracts.d.ts +8 -1
  72. package/dist/core/subagent/subagentRunner.d.ts +4 -0
  73. package/dist/core/subagent/subagentRunner.js +33 -25
  74. package/dist/core/tasks/taskStorage.js +8 -1
  75. package/dist/core/validation/outputParser.js +24 -0
  76. package/dist/llm/client.d.ts +2 -1
  77. package/dist/llm/client.js +20 -10
  78. package/dist/llm/hazeTools.d.ts +2039 -16
  79. package/dist/llm/hazeTools.js +43 -2
  80. package/dist/llm/lsp/client.d.ts +7 -1
  81. package/dist/llm/lsp/client.js +58 -9
  82. package/dist/llm/lsp/pool.d.ts +11 -0
  83. package/dist/llm/lsp/pool.js +61 -4
  84. package/dist/llm/lsp/protocol.d.ts +6 -23
  85. package/dist/llm/lsp/requests.d.ts +54 -60
  86. package/dist/llm/lsp/requests.js +152 -28
  87. package/dist/llm/lsp/symbols.d.ts +16 -0
  88. package/dist/llm/lsp/symbols.js +70 -0
  89. package/dist/llm/lsp/workspaceEdit.d.ts +43 -0
  90. package/dist/llm/lsp/workspaceEdit.js +117 -0
  91. package/dist/llm/lspTools.d.ts +7518 -2859
  92. package/dist/llm/lspTools.js +195 -110
  93. package/dist/llm/requestContext.d.ts +3 -2
  94. package/dist/llm/requestContext.js +8 -4
  95. package/dist/llm/systemPrompt.js +2 -2
  96. package/dist/llm/tools/fetchTool.d.ts +4 -0
  97. package/dist/llm/tools/processTool.d.ts +4 -0
  98. package/dist/llm/tools/replaceInFiles.d.ts +105 -0
  99. package/dist/llm/tools/replaceInFiles.js +131 -0
  100. package/dist/llm/tools/shellTool.d.ts +4 -0
  101. package/dist/llm/tools/storedOutputTool.d.ts +4 -0
  102. package/dist/llm/tools/taskTool.d.ts +4 -0
  103. package/dist/llm/tools/toolContext.d.ts +3 -0
  104. package/dist/llm/tools/toolContext.js +26 -4
  105. package/dist/skills/SkillLoader.js +27 -1
  106. package/dist/ui/components/useInputSuggestions.js +18 -6
  107. package/dist/utils/buildInfo.js +29 -8
  108. package/dist/utils/fs.js +5 -1
  109. package/package.json +19 -19
@@ -1,10 +1,14 @@
1
1
  import { z } from 'zod';
2
- /** Optional, explicitly user-controlled reasoning depth (provider/protocol gated). */
3
- export type ReasoningLevel = 'low' | 'medium' | 'high';
2
+ import { type ReasoningLevel, type StoredReasoningSetting } from '../core/agent/reasoningPolicy.js';
3
+ export type { ReasoningLevel, StoredReasoningSetting };
4
4
  export declare const reasoningLevelSchema: z.ZodEnum<{
5
5
  high: "high";
6
6
  medium: "medium";
7
7
  low: "low";
8
+ none: "none";
9
+ minimal: "minimal";
10
+ xhigh: "xhigh";
11
+ "provider-default": "provider-default";
8
12
  }>;
9
13
  export interface HazeProviderSettings {
10
14
  name: string;
@@ -77,8 +81,8 @@ export interface HazeSettings {
77
81
  mcpServers?: HazeMcpServer[];
78
82
  skills?: HazeSkillSetting[];
79
83
  subagents?: HazeSubagentSettings;
80
- /** Optional reasoning depth; unset by default, mapped by supported provider protocol. */
81
- reasoning?: ReasoningLevel;
84
+ /** Optional reasoning depth; absent means the built-in default (`high`), the `provider-default` sentinel sends no parameter. */
85
+ reasoning?: StoredReasoningSetting;
82
86
  /**
83
87
  * Context-window fallback for models without `modelLimits` metadata, in
84
88
  * tokens. Unset means the built-in default (128K hosted / 32K local —
@@ -4,7 +4,14 @@ import { z } from 'zod';
4
4
  import { HAZE_DIR } from './paths.js';
5
5
  import { tightenPrivateFile, writePrivateJsonAtomic } from './privateStorage.js';
6
6
  import { customProfileSchema } from '../core/subagent/executionProfiles.js';
7
- export const reasoningLevelSchema = z.enum(['low', 'medium', 'high']);
7
+ import { REASONING_LEVELS, REASONING_PROVIDER_DEFAULT } from '../core/agent/reasoningPolicy.js';
8
+ /**
9
+ * Optional, explicitly user-controlled reasoning depth (provider/protocol
10
+ * gated). Absent means the built-in default (`high`); the `provider-default`
11
+ * sentinel stores an explicit "send no parameter" opt-out.
12
+ */
13
+ const storedReasoningValues = [...REASONING_LEVELS, REASONING_PROVIDER_DEFAULT];
14
+ export const reasoningLevelSchema = z.enum(storedReasoningValues);
8
15
  export const SETTINGS_FILE = path.join(HAZE_DIR, 'settings.json');
9
16
  const providerCapabilitiesSchema = z.object({
10
17
  images: z.boolean().optional(),
@@ -42,8 +42,6 @@ export declare const SUBAGENT_MAX_CONCURRENCY = 10;
42
42
  export declare const SUBAGENT_MAX_RETRIES = 5;
43
43
  /** Default size of the shared bounded model-retry pool for transient model errors and idle-stream stalls, per turn. Configurable via the `modelRetries` setting (0 disables automatic retries). */
44
44
  export declare const DEFAULT_MODEL_RETRIES = 2;
45
- /** Upper bound accepted for the `modelRetries` setting (mirrors the settings schema). */
46
- export declare const MAX_MODEL_RETRIES_SETTING = 10;
47
45
  /** Default base delay for the shared model-retry pool backoff (`base * 2^attempt`, capped at 4× the base). Configurable via the `retryBaseDelayMs` setting. */
48
46
  export declare const DEFAULT_RETRY_BASE_DELAY_MS = 1000;
49
47
  /** Each context-overflow retry multiplies the message-token budget by this factor (Pillar 1.4: 0.6 → 0.36 → checkpoint). */
@@ -49,8 +49,6 @@ export const SUBAGENT_MAX_CONCURRENCY = 10;
49
49
  export const SUBAGENT_MAX_RETRIES = 5;
50
50
  /** Default size of the shared bounded model-retry pool for transient model errors and idle-stream stalls, per turn. Configurable via the `modelRetries` setting (0 disables automatic retries). */
51
51
  export const DEFAULT_MODEL_RETRIES = 2;
52
- /** Upper bound accepted for the `modelRetries` setting (mirrors the settings schema). */
53
- export const MAX_MODEL_RETRIES_SETTING = 10;
54
52
  /** Default base delay for the shared model-retry pool backoff (`base * 2^attempt`, capped at 4× the base). Configurable via the `retryBaseDelayMs` setting. */
55
53
  export const DEFAULT_RETRY_BASE_DELAY_MS = 1_000;
56
54
  /** Each context-overflow retry multiplies the message-token budget by this factor (Pillar 1.4: 0.6 → 0.36 → checkpoint). */
@@ -141,6 +141,14 @@ export declare function hasRemainingRecoveryBudget(state: Pick<TurnExecutionStat
141
141
  * failure (length-continuation lands in Increment 2 and only flips on when a
142
142
  * recovery credit is both available and warranted).
143
143
  */
144
+ /**
145
+ * Explicit, persisted cause for a failed turn (RT-05): the live session's
146
+ * second goal failed in 20s with zero assistant output and no timeout/retry
147
+ * events, and with `--debug` off the ledger held nothing diagnosable. Pure and
148
+ * bounded; safe metadata only. Undefined when the finish explains itself
149
+ * (normal failed readiness with a substantive answer).
150
+ */
151
+ export declare function describeTurnFailure(state: Pick<TurnExecutionState, 'finishCause' | 'aborted' | 'budgetBoundary'>, lastAssistantText: string): string | undefined;
144
152
  export declare function decideTerminalStatus(state: TurnExecutionState, evidence: CompletionEvidence, budgetExhausted: boolean): TurnStatus;
145
153
  type RecoveryAction = 'continue' | 'stop';
146
154
  interface RecoverySlice {
@@ -126,9 +126,41 @@ export function hasRemainingRecoveryBudget(state, budget) {
126
126
  * failure (length-continuation lands in Increment 2 and only flips on when a
127
127
  * recovery credit is both available and warranted).
128
128
  */
129
+ /**
130
+ * Explicit, persisted cause for a failed turn (RT-05): the live session's
131
+ * second goal failed in 20s with zero assistant output and no timeout/retry
132
+ * events, and with `--debug` off the ledger held nothing diagnosable. Pure and
133
+ * bounded; safe metadata only. Undefined when the finish explains itself
134
+ * (normal failed readiness with a substantive answer).
135
+ */
136
+ export function describeTurnFailure(state, lastAssistantText) {
137
+ if (!state.aborted && state.finishCause === 'stop' && lastAssistantText.trim().length === 0)
138
+ return 'model-returned-no-output';
139
+ if (state.finishCause === 'length')
140
+ return 'output-length-truncation';
141
+ if (state.finishCause === 'error')
142
+ return 'model-error';
143
+ if (state.finishCause === 'content-filter')
144
+ return 'content-filter';
145
+ if (state.finishCause === 'tool-calls' && state.budgetBoundary)
146
+ return 'tool-budget-boundary';
147
+ if (state.finishCause === 'unknown')
148
+ return 'unknown-finish';
149
+ return undefined;
150
+ }
129
151
  export function decideTerminalStatus(state, evidence, budgetExhausted) {
130
152
  if (state.aborted)
131
153
  return 'aborted';
154
+ // A voluntary `stop` final whose structured completion evidence is ready is
155
+ // complete even at a budget boundary: a turn that finished its declared work
156
+ // and answered substantively must not be reported failed merely because it
157
+ // also used its whole budget (RT-02 — the review session's goal 1 ended
158
+ // failed/blocked with finishCause 'stop', 5/5 tasks, and a delivered report).
159
+ // `classifyTerminalOutcome` already treats this exact shape as goal-complete;
160
+ // keep the two authorities aligned. Non-stop finishes (length/error) and
161
+ // non-ready evidence still fail as before.
162
+ if (state.finishCause === 'stop' && evidence.assistantText.trim().length > 0 && assessCompletionReadiness(state, evidence) === 'ready')
163
+ return 'complete';
132
164
  if (budgetExhausted || state.finishCause === 'length' || state.finishCause === 'error')
133
165
  return 'failed';
134
166
  if (assessCompletionReadiness(state, evidence) !== 'ready')
@@ -16,7 +16,8 @@ export type AgentEvent = {
16
16
  request: string;
17
17
  at: string;
18
18
  status: 'complete' | 'aborted' | 'failed';
19
- evidence?: TurnCompletionEvidence;
19
+ evidence?: TurnCompletionEvidence; /** Explicit cause when the outcome is otherwise unexplained (RT-05): persisted without --debug so silent failures are diagnosable from the ledger. */
20
+ reason?: string;
20
21
  } | {
21
22
  type: 'goal_start';
22
23
  goalId: string;
@@ -32,6 +32,13 @@ export declare function lengthContinuationPrompt(): string;
32
32
  */
33
33
  export declare function completionRescuePrompt(): string;
34
34
  export declare function malformedToolCallPrompt(toolName: string, chunkBytes: number): string;
35
+ /**
36
+ * Ephemeral control for read-only edit recovery: a failed file mutation
37
+ * requested a fresh read before any further mutation. Names the exact path
38
+ * so the model re-reads it instead of retrying the stale edit. The tool set
39
+ * stays intact; the execution-time gate in toolContext is the enforcer.
40
+ */
41
+ export declare function editRecoveryReadPrompt(path: string): string;
35
42
  /**
36
43
  * Ephemeral control for a goal-continuation slice or a fresh continuation
37
44
  * turn. The model's stop was rejected (or its physical turn hit a budget
@@ -88,6 +88,15 @@ export function malformedToolCallPrompt(toolName, chunkBytes) {
88
88
  : '';
89
89
  return `The ${toolName} call had invalid, malformed, or truncated JSON input and did not execute. Retry it now with valid smaller arguments; do not merely announce that you will retry.${chunkGuidance}`;
90
90
  }
91
+ /**
92
+ * Ephemeral control for read-only edit recovery: a failed file mutation
93
+ * requested a fresh read before any further mutation. Names the exact path
94
+ * so the model re-reads it instead of retrying the stale edit. The tool set
95
+ * stays intact; the execution-time gate in toolContext is the enforcer.
96
+ */
97
+ export function editRecoveryReadPrompt(path) {
98
+ return `A file mutation on ${path} failed and its content may be stale. Read ${path} with readFile now to get fresh content and current line numbers; the edit tools will reject any retry on ${path} until that read completes. Then retry the mutation once with corrected, fresh content. Do not retry the failed edit first and do not announce tool calls.`;
99
+ }
91
100
  /**
92
101
  * Ephemeral control for a goal-continuation slice or a fresh continuation
93
102
  * turn. The model's stop was rejected (or its physical turn hit a budget
@@ -1,9 +1,28 @@
1
1
  import type { ProviderCapabilities } from '../subagent/contracts.js';
2
2
  /**
3
- * Provider-neutral reasoning-depth setting. Unset by default; explicitly user
4
- * controlled. Mapped to a supported provider protocol (not a model name).
3
+ * Provider-neutral reasoning-depth levels (the AI SDK `reasoning` enum minus
4
+ * `provider-default`). `'none'` is an explicit request to disable reasoning;
5
+ * the stored `provider-default` sentinel means "send no parameter at all".
5
6
  */
6
- export type ReasoningLevel = 'low' | 'medium' | 'high';
7
+ export type ReasoningLevel = 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';
8
+ export declare const REASONING_LEVELS: readonly ReasoningLevel[];
9
+ /**
10
+ * Level applied when settings carry no `reasoning` key. Users opt out with an
11
+ * explicit `none` (reasoning off) or the stored `provider-default` sentinel
12
+ * (written by `/reasoning unset`); key-absent means this default.
13
+ */
14
+ export declare const DEFAULT_REASONING_LEVEL: ReasoningLevel;
15
+ /** Value the settings file may store: a level or the `provider-default` sentinel. */
16
+ export type StoredReasoningSetting = ReasoningLevel | 'provider-default';
17
+ /** Stored sentinel meaning "send no reasoning parameter at all". */
18
+ export declare const REASONING_PROVIDER_DEFAULT: "provider-default";
19
+ export declare function isStoredReasoning(value: unknown): value is StoredReasoningSetting;
20
+ /**
21
+ * The level a session actually requests: the stored setting when present, the
22
+ * default when the key is absent. The `provider-default` sentinel maps to
23
+ * undefined — no parameter is sent.
24
+ */
25
+ export declare function effectiveRequestedReasoning(setting: StoredReasoningSetting | undefined): ReasoningLevel | undefined;
7
26
  export type EffectiveReasoning = ReasoningLevel | 'disabled';
8
27
  export interface ResolvedReasoningPolicy {
9
28
  /** What the user requested, if anything. */
@@ -15,17 +34,34 @@ export interface ResolvedReasoningPolicy {
15
34
  }
16
35
  /**
17
36
  * Resolve a requested reasoning level against provider capabilities. Pure and
18
- * capability based: only protocols that accept the OpenAI `reasoningEffort`
19
- * provider option receive a level; everything else is disabled (never silently
20
- * passed in a shape the protocol does not define). No model-name branching.
37
+ * capability based: only protocols that accept the reasoning parameter receive
38
+ * a level; everything else is disabled (the parameter is omitted entirely,
39
+ * never sent in a shape the protocol does not define). No model-name branching.
21
40
  */
22
41
  export declare function resolveReasoningPolicy(input: {
23
42
  requested: ReasoningLevel | undefined;
24
43
  capabilities: ProviderCapabilities;
25
44
  }): ResolvedReasoningPolicy;
26
45
  /**
27
- * The provider-option fragment to merge into request settings for a resolved
28
- * policy. Returns undefined when disabled so unsupported protocols send nothing.
46
+ * The AI SDK top-level `reasoning` call setting for a resolved policy.
47
+ * Returns undefined when disabled so unsupported or unrequested turns omit the
48
+ * parameter entirely. Never returns `'provider-default'` today; the sentinel
49
+ * stays in the return type for forward compatibility.
29
50
  */
30
- export declare function reasoningProviderOptions(policy: ResolvedReasoningPolicy): Record<string, unknown> | undefined;
51
+ export declare function reasoningCallSetting(policy: ResolvedReasoningPolicy): ReasoningLevel | 'provider-default' | undefined;
31
52
  export declare function isReasoningLevel(value: unknown): value is ReasoningLevel;
53
+ /** Aliases accepted by CLI paths (`/reasoning`, `--reasoning`) for "send no reasoning parameter". */
54
+ export declare function isReasoningUnsetAlias(value: string): boolean;
55
+ export type ParsedReasoningOverride = {
56
+ ok: true;
57
+ setting: StoredReasoningSetting;
58
+ } | {
59
+ ok: false;
60
+ error: string;
61
+ };
62
+ /**
63
+ * Parse a `--reasoning` CLI value (case-insensitive): a level maps directly,
64
+ * the unset aliases mean "send no reasoning parameter for this run". Shared by
65
+ * the commander flag surface and the headless option validation.
66
+ */
67
+ export declare function parseReasoningOverride(raw: string): ParsedReasoningOverride;
@@ -1,8 +1,30 @@
1
+ export const REASONING_LEVELS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh'];
2
+ /**
3
+ * Level applied when settings carry no `reasoning` key. Users opt out with an
4
+ * explicit `none` (reasoning off) or the stored `provider-default` sentinel
5
+ * (written by `/reasoning unset`); key-absent means this default.
6
+ */
7
+ export const DEFAULT_REASONING_LEVEL = 'high';
8
+ /** Stored sentinel meaning "send no reasoning parameter at all". */
9
+ export const REASONING_PROVIDER_DEFAULT = 'provider-default';
10
+ export function isStoredReasoning(value) {
11
+ return isReasoningLevel(value) || value === REASONING_PROVIDER_DEFAULT;
12
+ }
13
+ /**
14
+ * The level a session actually requests: the stored setting when present, the
15
+ * default when the key is absent. The `provider-default` sentinel maps to
16
+ * undefined — no parameter is sent.
17
+ */
18
+ export function effectiveRequestedReasoning(setting) {
19
+ if (setting === REASONING_PROVIDER_DEFAULT)
20
+ return undefined;
21
+ return setting ?? DEFAULT_REASONING_LEVEL;
22
+ }
1
23
  /**
2
24
  * Resolve a requested reasoning level against provider capabilities. Pure and
3
- * capability based: only protocols that accept the OpenAI `reasoningEffort`
4
- * provider option receive a level; everything else is disabled (never silently
5
- * passed in a shape the protocol does not define). No model-name branching.
25
+ * capability based: only protocols that accept the reasoning parameter receive
26
+ * a level; everything else is disabled (the parameter is omitted entirely,
27
+ * never sent in a shape the protocol does not define). No model-name branching.
6
28
  */
7
29
  export function resolveReasoningPolicy(input) {
8
30
  const { requested, capabilities } = input;
@@ -13,15 +35,33 @@ export function resolveReasoningPolicy(input) {
13
35
  return { requested, effective: requested, reason: 'applied via supported provider protocol' };
14
36
  }
15
37
  /**
16
- * The provider-option fragment to merge into request settings for a resolved
17
- * policy. Returns undefined when disabled so unsupported protocols send nothing.
38
+ * The AI SDK top-level `reasoning` call setting for a resolved policy.
39
+ * Returns undefined when disabled so unsupported or unrequested turns omit the
40
+ * parameter entirely. Never returns `'provider-default'` today; the sentinel
41
+ * stays in the return type for forward compatibility.
18
42
  */
19
- export function reasoningProviderOptions(policy) {
43
+ export function reasoningCallSetting(policy) {
20
44
  if (policy.effective === 'disabled')
21
45
  return undefined;
22
- return { openai: { reasoningEffort: policy.effective } };
46
+ return policy.effective;
23
47
  }
24
- const LEVELS = ['low', 'medium', 'high'];
25
48
  export function isReasoningLevel(value) {
26
- return typeof value === 'string' && LEVELS.includes(value);
49
+ return typeof value === 'string' && REASONING_LEVELS.includes(value);
50
+ }
51
+ /** Aliases accepted by CLI paths (`/reasoning`, `--reasoning`) for "send no reasoning parameter". */
52
+ export function isReasoningUnsetAlias(value) {
53
+ return value === 'unset' || value === 'off' || value === REASONING_PROVIDER_DEFAULT;
54
+ }
55
+ /**
56
+ * Parse a `--reasoning` CLI value (case-insensitive): a level maps directly,
57
+ * the unset aliases mean "send no reasoning parameter for this run". Shared by
58
+ * the commander flag surface and the headless option validation.
59
+ */
60
+ export function parseReasoningOverride(raw) {
61
+ const value = raw.trim().toLowerCase();
62
+ if (isReasoningUnsetAlias(value))
63
+ return { ok: true, setting: REASONING_PROVIDER_DEFAULT };
64
+ if (isReasoningLevel(value))
65
+ return { ok: true, setting: value };
66
+ return { ok: false, error: `Unknown reasoning level "${raw.trim()}". Valid levels: ${REASONING_LEVELS.join(', ')} — or unset for the provider default.` };
27
67
  }
@@ -11,7 +11,7 @@
11
11
  * Kept provider/UI-agnostic (no `ai`/Ink imports) so it is unit-testable in
12
12
  * `tests/core/**` and reusable by the subagent flow.
13
13
  */
14
- export type ToolCapability = 'discovery' | 'read' | 'mutate' | 'validate' | 'process' | 'coordinate';
14
+ export type ToolCapability = 'discovery' | 'read' | 'mutate' | 'process' | 'coordinate';
15
15
  /**
16
16
  * Capability set for a built-in tool name. Unknown/third-party tool names
17
17
  * (MCP) return an empty set: their effects are not statically knowable, so
@@ -21,7 +21,7 @@ export declare function toolCapability(name: string): readonly ToolCapability[];
21
21
  export declare function hasCapability(name: string, capability: ToolCapability): boolean;
22
22
  /** Tools whose successful call introduces a workspace mutation. */
23
23
  export declare function isMutatingCapability(name: string): boolean;
24
+ /** Confirmed effects, including completed writes from failed multi-file/worker calls. */
25
+ export declare function changedPathsFromTool(toolName: string, input: unknown, output: unknown, success?: boolean): string[];
24
26
  /** Tools that can act as a validation step (runtime-classifier dependent). */
25
27
  export declare function isValidationCapable(name: string): boolean;
26
- /** Read/discovery-only built-in tools (no mutation side effects). */
27
- export declare function isReadOrDiscoveryCapability(name: string): boolean;
@@ -22,6 +22,9 @@ const CAPABILITY_MAP = {
22
22
  writeFile: ['mutate'],
23
23
  editFile: ['mutate'],
24
24
  replaceLines: ['mutate'],
25
+ replaceInFiles: ['mutate'],
26
+ lspRenameSymbol: ['mutate'],
27
+ lspSafeDeleteSymbol: ['mutate'],
25
28
  // Process execution. A shell call becomes validation only when its command is
26
29
  // a classifier-confirmed validation command (see work state); that runtime
27
30
  // fact is tracked separately as a validation event, not as a static trait.
@@ -30,7 +33,6 @@ const CAPABILITY_MAP = {
30
33
  // Coordination / durable state.
31
34
  writeTasks: ['coordinate'],
32
35
  subagent: ['coordinate'],
33
- // LSP diagnostic reads.
34
36
  };
35
37
  /**
36
38
  * Capability set for a built-in tool name. Unknown/third-party tool names
@@ -47,12 +49,34 @@ export function hasCapability(name, capability) {
47
49
  export function isMutatingCapability(name) {
48
50
  return hasCapability(name, 'mutate');
49
51
  }
52
+ /** Confirmed effects, including completed writes from failed multi-file/worker calls. */
53
+ export function changedPathsFromTool(toolName, input, output, success = true) {
54
+ if (output !== undefined && output !== null && typeof output !== 'object')
55
+ return [];
56
+ const result = (output ?? {});
57
+ if (result.duplicateSkipped === true || result.dryRun === true || result.noChange === true)
58
+ return [];
59
+ const strings = (value) => Array.isArray(value) ? value.filter((path) => typeof path === 'string' && path.length > 0).slice(0, 20_000) : [];
60
+ if (toolName === 'subagent') {
61
+ const capsule = typeof result.capsule === 'object' && result.capsule !== null ? result.capsule : result;
62
+ return [...new Set(strings(capsule.changedPaths))];
63
+ }
64
+ if (!isMutatingCapability(toolName))
65
+ return [];
66
+ if (Array.isArray(result.changedPaths))
67
+ return [...new Set(strings(result.changedPaths))];
68
+ if (result.ok === false || !success)
69
+ return [];
70
+ if (Array.isArray(result.files))
71
+ return [...new Set(result.files.flatMap(file => typeof file === 'object' && file !== null && 'path' in file && typeof file.path === 'string' && !('noChange' in file && file.noChange === true) ? [file.path] : []))];
72
+ // Single-file tools confirm their effect from success plus the input path;
73
+ // a null output is tolerated for callers that report only a success flag.
74
+ if (!['writeFile', 'editFile', 'replaceLines'].includes(toolName))
75
+ return [];
76
+ const path = typeof result.path === 'string' ? result.path : typeof input === 'object' && input !== null && 'path' in input ? input.path : undefined;
77
+ return typeof path === 'string' && path.length > 0 ? [path] : [];
78
+ }
50
79
  /** Tools that can act as a validation step (runtime-classifier dependent). */
51
80
  export function isValidationCapable(name) {
52
- return hasCapability(name, 'validate') || name === 'shell';
53
- }
54
- /** Read/discovery-only built-in tools (no mutation side effects). */
55
- export function isReadOrDiscoveryCapability(name) {
56
- const caps = toolCapability(name);
57
- return caps.length > 0 && caps.every(capability => capability === 'read' || capability === 'discovery');
81
+ return name === 'shell';
58
82
  }
@@ -18,7 +18,8 @@ export declare function intentExpectsValidation(intent: RequestIntent): boolean;
18
18
  /**
19
19
  * Normalize a validation command into a matching key so a green run can be
20
20
  * bound to the red repro it must supersede (P4). Whitespace-insensitive; a
21
- * leading `time`/`env`/`nice` prefix and a trailing `--` separator are noise.
21
+ * leading `time`/`nice` prefix, `env` with or without `VAR=value` assignments,
22
+ * a lone line-continuation backslash, and a trailing `--` separator are noise.
22
23
  */
23
24
  export declare function validationCommandKey(command: string): string;
24
25
  /**
@@ -76,7 +77,9 @@ export interface WorkState {
76
77
  * logical goal (see the goal supervisor). Used by `deriveValidationOutcome`
77
78
  * only while this turn itself has recorded no validation; a fresh
78
79
  * validation this turn supersedes it. Bounded to status/kind — never a
79
- * command or output.
80
+ * command or output. `kind` keeps cross-turn parity with the in-turn rule
81
+ * that a generic (self-declared) pass cannot clear a confirmed failure
82
+ * (R2-03).
80
83
  */
81
84
  carriedValidation?: {
82
85
  status: 'passed' | 'failed';
@@ -113,6 +116,7 @@ export declare function seedCarriedGoalEvidence(state: WorkState, carried: {
113
116
  validationOutcome: ValidationOutcome;
114
117
  taskProgress?: WorkTaskProgress;
115
118
  redEvidence?: RedEvidence;
119
+ validationKind?: ValidationKind;
116
120
  }): void;
117
121
  export interface WorkToolEvent {
118
122
  toolName: string;
@@ -121,8 +125,6 @@ export interface WorkToolEvent {
121
125
  output?: unknown;
122
126
  duplicateSkipped?: boolean;
123
127
  }
124
- /** Strictly recognize direct execution of one file changed during this goal. */
125
- export declare function executedMutatedArtifact(command: string, state: WorkState): string | undefined;
126
128
  /** Extract a classifier-confirmed validation summary from a tool output, if any. */
127
129
  export declare function validationSummaryFromOutput(output: unknown): ValidationSummary | undefined;
128
130
  export declare function createWorkState(goal: string, intent: RequestIntent, successCriteria: string[], now?: number): WorkState;
@@ -1,6 +1,8 @@
1
1
  import { isValidationSummary } from '../../llm/toolResultTypes.js';
2
2
  import { toolInputField, toolOutputOk } from './toolResults.js';
3
3
  import { workspacePathKey } from '../../utils/path.js';
4
+ import { isSingleForegroundCommand } from '../safety/shellClassifier.js';
5
+ import { changedPathsFromTool } from './toolCapabilities.js';
4
6
  /** Request intents where a missing validation is itself meaningful evidence. */
5
7
  export function intentExpectsValidation(intent) {
6
8
  return intent === 'implement' || intent === 'fix' || intent === 'test';
@@ -8,12 +10,24 @@ export function intentExpectsValidation(intent) {
8
10
  /**
9
11
  * Normalize a validation command into a matching key so a green run can be
10
12
  * bound to the red repro it must supersede (P4). Whitespace-insensitive; a
11
- * leading `time`/`env`/`nice` prefix and a trailing `--` separator are noise.
13
+ * leading `time`/`nice` prefix, `env` with or without `VAR=value` assignments,
14
+ * a lone line-continuation backslash, and a trailing `--` separator are noise.
12
15
  */
13
16
  export function validationCommandKey(command) {
14
17
  const words = command.replace(/\s+/g, ' ').trim().split(' ').filter(Boolean);
15
- while (words.length > 1 && ['time', 'env', 'nice', '\\'].includes(words[0]))
18
+ while (words.length > 1 && ['time', 'nice', '\\'].includes(words[0]))
16
19
  words.shift();
20
+ // `env` — bare, with flags, or with `VAR=value` assignments — is wrapper
21
+ // noise for pair matching (R2-06): drop it together with any flag tokens
22
+ // and assignments, keeping at least the command word. `env` is handled here
23
+ // only (not in the loop above) so its assignments are stripped too.
24
+ if (words[0] === 'env') {
25
+ let i = 1;
26
+ while (i < words.length && (words[i].startsWith('-') || /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i])))
27
+ i++;
28
+ if (i < words.length)
29
+ words.splice(0, i);
30
+ }
17
31
  while (words.length > 1 && words.at(-1) === '--')
18
32
  words.pop();
19
33
  return words.join(' ');
@@ -45,7 +59,9 @@ export function seedCarriedGoalEvidence(state, carried) {
45
59
  }
46
60
  if (carried.validationOutcome === 'passed' || carried.validationOutcome === 'failed') {
47
61
  state.validationSeq = 1;
48
- state.carriedValidation = carried.validationOutcome === 'passed' ? { status: 'passed' } : { status: 'failed' };
62
+ state.carriedValidation = carried.validationOutcome === 'passed'
63
+ ? { status: 'passed', ...(carried.validationKind ? { kind: carried.validationKind } : {}) }
64
+ : { status: 'failed', ...(carried.validationKind ? { kind: carried.validationKind } : {}) };
49
65
  }
50
66
  // Red→green evidence is goal-scoped and rides the checkpoint across
51
67
  // physical turns so a continuation cannot complete while a carried pair
@@ -80,16 +96,11 @@ function outputSummary(output) {
80
96
  return '';
81
97
  }
82
98
  function upsertValidation(state, command, status, summary, kind, revision) {
83
- const existing = state.validations.find(validation => validation.command === command);
84
- if (existing)
85
- Object.assign(existing, { status, summary, revision, ...(kind ? { kind } : {}) });
86
- else
87
- state.validations.push({ command, status, summary, revision, ...(kind ? { kind } : {}) });
88
- const existingCommand = state.validationCommands.find(item => item.command === command);
89
- if (existingCommand)
90
- existingCommand.status = status;
91
- else
92
- state.validationCommands.push({ command, status });
99
+ // Keep both evidence and status display in execution order when a check reruns.
100
+ state.validations = state.validations.filter(validation => validation.command !== command);
101
+ state.validations.push({ command, status, summary, revision, ...(kind ? { kind } : {}) });
102
+ state.validationCommands = state.validationCommands.filter(item => item.command !== command);
103
+ state.validationCommands.push({ command, status });
93
104
  }
94
105
  const ARTIFACT_LAUNCHERS = new Set(['node', 'python', 'python3', 'ruby', 'php', 'perl', 'sh', 'bash', 'zsh', 'fish', 'csh', 'tcsh', 'tsx', 'ts-node', 'rscript', 'lua']);
95
106
  function shellWords(command) {
@@ -97,9 +108,9 @@ function shellWords(command) {
97
108
  .map(word => ((word.startsWith('"') && word.endsWith('"')) || (word.startsWith("'") && word.endsWith("'")) ? word.slice(1, -1) : word));
98
109
  }
99
110
  /** Strictly recognize direct execution of one file changed during this goal. */
100
- export function executedMutatedArtifact(command, state) {
111
+ function executedMutatedArtifact(command, state) {
101
112
  // Chaining and pipelines can mask the artifact's exit status, so they are not evidence.
102
- if (/&&|\|\||[;|]/.test(command))
113
+ if (!isSingleForegroundCommand(command))
103
114
  return undefined;
104
115
  const words = shellWords(command.trim());
105
116
  if (words.length === 0)
@@ -188,19 +199,20 @@ export function observeWorkToolEvent(state, event, now = Date.now()) {
188
199
  state.phase = 'inspecting';
189
200
  state.lastProgressAt = now;
190
201
  }
191
- if (path && ['editFile', 'replaceLines', 'writeFile'].includes(event.toolName)) {
192
- if (ok) {
193
- upsertFile(state, path, event.toolName === 'writeFile' ? 'created' : 'modified');
194
- state.phase = 'editing';
195
- state.lastProgressAt = now;
196
- state.blockers = state.blockers.filter(blocker => !blocker.includes(path));
197
- state.mutationCount += 1;
198
- state.mutationSeq = seq;
199
- }
200
- else {
201
- state.blockers = [...new Set([...state.blockers, `Edit failed for ${path}: ${outputSummary(event.output) || 'fresh read required'}`])];
202
- state.nextAction = `Read ${path}, then retry the edit with current content.`;
203
- }
202
+ const changedPaths = changedPathsFromTool(event.toolName, event.input, event.output, event.success);
203
+ for (const changedPath of changedPaths) {
204
+ upsertFile(state, changedPath, event.toolName === 'writeFile' ? 'created' : 'modified');
205
+ state.blockers = state.blockers.filter(blocker => !blocker.includes(changedPath));
206
+ }
207
+ if (changedPaths.length > 0) {
208
+ state.phase = 'editing';
209
+ state.lastProgressAt = now;
210
+ state.mutationCount += changedPaths.length;
211
+ state.mutationSeq = seq;
212
+ }
213
+ if (!ok && path && ['editFile', 'replaceLines', 'writeFile'].includes(event.toolName)) {
214
+ state.blockers = [...new Set([...state.blockers, `Edit failed for ${path}: ${outputSummary(event.output) || 'fresh read required'}`])];
215
+ state.nextAction = `Read ${path}, then retry the edit with current content.`;
204
216
  }
205
217
  // Classifier-confirmed test/build commands are validation. A direct execution
206
218
  // of a file changed during this goal is also bounded runtime evidence, provided
@@ -24,37 +24,41 @@ export function withToolDeadline(execute, timeoutMs, signal) {
24
24
  settled = true;
25
25
  if (handle.timer)
26
26
  clearTimeout(handle.timer);
27
+ signal?.removeEventListener('abort', onAbort);
27
28
  action();
28
29
  };
29
- const quarantineLate = () => {
30
- // Swallow the eventual resolution/rejection of an abort-ignoring tool so
31
- // it cannot surface as an unhandled rejection after the wrapper returned.
32
- work.catch(() => undefined);
33
- };
34
30
  const fire = (message) => settle(() => {
35
- quarantineLate();
36
31
  resolve({ ok: false, [TOOL_DEADLINE_EXCEEDED]: true, error: message });
37
32
  });
38
- const work = execute();
33
+ const onAbort = () => fire('Tool execution was aborted.');
34
+ if (signal?.aborted)
35
+ return onAbort();
36
+ signal?.addEventListener('abort', onAbort, { once: true });
39
37
  handle.timer = setTimeout(() => fire(`Tool execution exceeded the ${timeoutMs}ms deadline.`), timeoutMs);
40
- if (signal) {
41
- if (signal.aborted)
42
- return fire('Tool execution was aborted.');
43
- signal.addEventListener('abort', () => fire('Tool execution was aborted.'), { once: true });
38
+ // Attach both handlers even when cancellation wins; late rejection is handled.
39
+ try {
40
+ execute().then(value => settle(() => resolve(value)), error => settle(() => reject(error)));
41
+ }
42
+ catch (error) {
43
+ settle(() => reject(error));
44
44
  }
45
- work.then(value => settle(() => resolve(value)), error => settle(() => reject(error)));
46
45
  });
47
46
  }
48
47
  export function createAbsoluteDeadline(input) {
49
48
  const { timeoutMs, signal, onTimeout } = input;
50
- let fired = false;
49
+ let disposed = false;
51
50
  let timer;
52
- const fire = () => {
53
- if (fired)
54
- return;
55
- fired = true;
51
+ const clear = () => {
52
+ disposed = true;
56
53
  if (timer)
57
54
  clearTimeout(timer);
55
+ timer = undefined;
56
+ signal?.removeEventListener('abort', fire);
57
+ };
58
+ const fire = () => {
59
+ if (disposed)
60
+ return;
61
+ clear();
58
62
  onTimeout();
59
63
  };
60
64
  timer = setTimeout(fire, timeoutMs);
@@ -64,11 +68,5 @@ export function createAbsoluteDeadline(input) {
64
68
  else
65
69
  signal.addEventListener('abort', fire, { once: true });
66
70
  }
67
- return {
68
- clear: () => {
69
- if (timer)
70
- clearTimeout(timer);
71
- timer = undefined;
72
- },
73
- };
71
+ return { clear };
74
72
  }