@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
@@ -41,20 +41,24 @@ export function createQuarantinableCallbacks(callbacks) {
41
41
  // a quarantined call must answer "not compacted" instead of undefined.
42
42
  const whileLiveBoolean = (fn) => (...args) => (state.quarantined ? false : fn(...args));
43
43
  const guarded = {
44
- ...callbacks,
44
+ // Enumerate every callback so new fields require an explicit quarantine decision.
45
+ debugLog: callbacks.debugLog,
46
+ getConversation: callbacks.getConversation,
47
+ getLastAssistantText: callbacks.getLastAssistantText,
45
48
  addMessage: whileLive(callbacks.addMessage),
46
49
  updateMessage: whileLive(callbacks.updateMessage),
47
50
  setConversation: whileLive(callbacks.setConversation),
48
51
  setBusy: whileLive(callbacks.setBusy),
49
52
  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) } : {}),
53
+ setBusyLabel: callbacks.setBusyLabel && whileLive(callbacks.setBusyLabel),
54
+ setAbortController: callbacks.setAbortController && whileLive(callbacks.setAbortController),
55
+ setGoalStatus: callbacks.setGoalStatus && whileLive(callbacks.setGoalStatus),
56
+ onEvent: callbacks.onEvent && whileLive(callbacks.onEvent),
57
+ compactConversation: callbacks.compactConversation && whileLiveBoolean(callbacks.compactConversation),
58
+ recordCompaction: callbacks.recordCompaction && whileLive(callbacks.recordCompaction),
59
+ recordTokenUsage: callbacks.recordTokenUsage && whileLive(callbacks.recordTokenUsage),
60
+ setWorkState: callbacks.setWorkState && whileLive(callbacks.setWorkState),
61
+ onTasksChanged: callbacks.onTasksChanged && whileLive(callbacks.onTasksChanged),
58
62
  get log() {
59
63
  return state.quarantined ? undefined : callbacks.log;
60
64
  },
@@ -1,8 +1,7 @@
1
- import { createTurnExecutionState, decideTerminalStatus, normalizeFinishReason } from '../../../core/agent/completionController.js';
1
+ import { assessCompletionReadiness, classifyTerminalOutcome, createTurnExecutionState, decideGoalContinuation, decideLengthRecovery, decideRescue, decideTerminalStatus, describeCompletionReadiness, goalContinuationRecoverable, isBudgetExhausted, normalizeFinishReason, rescueEligibleRequest } from '../../../core/agent/completionController.js';
2
2
  import { agentEvent } from '../../../core/agent/events.js';
3
3
  import { isContextOverflowError, isRetryableModelError } from '../../../core/agent/errors.js';
4
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
5
  import { clampSlice, DEFAULT_MODEL_RETRIES, DEFAULT_RETRY_BASE_DELAY_MS, MAX_OVERFLOW_RETRIES, OVERFLOW_SHRINK_FACTOR, remainingSteps, remainingToolCalls, DEFAULT_TURN_DEADLINE_MS, IDLE_TIMEOUT_MS } from '../../../core/agent/budgets.js';
7
6
  import { deriveValidationOutcome, redPairStatus } from '../../../core/agent/workState.js';
8
7
  import { withoutRejectedAssistantFinal } from '../../../core/agent/requestAssembly.js';
@@ -116,6 +115,7 @@ export function finalizeAttemptOutcome(deps) {
116
115
  // Carry red evidence until the same check passes after the mutation. This
117
116
  // includes boundaries reached after red capture but before the first edit.
118
117
  ...(turnState.redPair !== 'satisfied' && goal.redEvidence ? { redEvidence: { ...goal.redEvidence } } : {}),
118
+ ...(turnState.validationKind ? { validationKind: turnState.validationKind } : {}),
119
119
  };
120
120
  const discardRejectedFinal = () => callbacks.setConversation(withoutRejectedAssistantFinal(callbacks.getConversation()));
121
121
  const checkpointResult = () => {
@@ -227,7 +227,17 @@ export function handleAttemptFailure(deps) {
227
227
  if (overflowRetries >= MAX_OVERFLOW_RETRIES && isContextOverflowError(error)) {
228
228
  callbacks.onEvent?.(agentEvent({ type: 'context_overflow', recovered: false, error: text }));
229
229
  callbacks.addMessage({ role: 'system', text: 'Context overflow persisted after bounded compaction retries; pausing the goal with a checkpoint. Completed work is preserved in the conversation. Press R to resume after compacting or clearing context, or switch to a larger-context model.' });
230
- return { status: 'failed', resume: buildIncompleteGoalResume(value, turnOptions.goalContext?.goalId ?? goal.id, turnOptions.goalContext?.cycle ?? 1, turnState, 'context_exhausted', {}) };
230
+ // Project the goal's evidence before checkpointing: the failing attempt
231
+ // threw before finalizeAttemptOutcome, so its validation outcome/kind and
232
+ // unresolved red evidence would otherwise be lost from the checkpoint
233
+ // (R2-02) — a resumed goal must still owe the same checks.
234
+ projectGoalEvidence(turnState, goal);
235
+ const carried = {
236
+ ...(turnOptions.goalContext?.requestHash ? { requestHash: turnOptions.goalContext.requestHash } : {}),
237
+ ...(redPairStatus(goal) !== 'satisfied' && goal.redEvidence ? { redEvidence: { ...goal.redEvidence } } : {}),
238
+ ...(turnState.validationKind ? { validationKind: turnState.validationKind } : {}),
239
+ };
240
+ return { status: 'failed', resume: buildIncompleteGoalResume(value, turnOptions.goalContext?.goalId ?? goal.id, turnOptions.goalContext?.cycle ?? 1, turnState, 'context_exhausted', carried) };
231
241
  }
232
242
  if (isContextOverflowError(error)) {
233
243
  const canCompact = typeof callbacks.compactConversation === 'function';
@@ -4,6 +4,7 @@ import { type ToolExecutionBudgetState, type TurnBudget } from '../../../core/ag
4
4
  import { type SessionGoal } from '../../../core/agent/goalPolicy.js';
5
5
  import { calculateRequestTokenBudget, type ContextUsageAnchor } from '../../../core/agent/contextBudget.js';
6
6
  import { providerRequestSettings, type ModelRuntimeSelection } from '../../../llm/client.js';
7
+ import type { StoredReasoningSetting } from '../../../core/agent/reasoningPolicy.js';
7
8
  import { type ToolCategory, type TurnExecutionScope } from '../../../llm/requestContext.js';
8
9
  import type { LoadedMcpTools } from '../../../llm/mcp.js';
9
10
  import type { LspPool } from '../../../llm/lsp/pool.js';
@@ -59,6 +60,8 @@ export interface AttemptSetupDeps {
59
60
  overflowShrinkFactor: number;
60
61
  session: PromptSession | undefined;
61
62
  modelOverride: string | undefined;
63
+ /** Run-scoped reasoning level/sentinel (CLI `--reasoning`); overrides the stored setting for this run. */
64
+ reasoningOverride: StoredReasoningSetting | undefined;
62
65
  abortController: AbortController;
63
66
  turnOptions: TurnExecutionOptions;
64
67
  turnScope: {
@@ -39,13 +39,13 @@ export function restrictToRescueTools(tools) {
39
39
  * configured (the caller-reported failure path).
40
40
  */
41
41
  export async function prepareAttempt(deps) {
42
- const { value, contextFiles, callbacks, retryingExistingRequest, session, modelOverride, abortController, turnOptions, turnScope, turnBudget, goal, globalBudget, sliceBudget, onContextFileRead, usageAnchor } = deps;
42
+ const { value, contextFiles, callbacks, retryingExistingRequest, session, modelOverride, reasoningOverride, abortController, turnOptions, turnScope, turnBudget, goal, globalBudget, sliceBudget, onContextFileRead, usageAnchor } = deps;
43
43
  // Single choke point: one fresh settings read per attempt, shared by model
44
44
  // resolution and request assembly (CR-024, relaxed in Pillar 1.9 so a
45
45
  // provider/model switch mid-goal applies from the next attempt — the first
46
46
  // attempt of each physical turn keeps the original read).
47
47
  const turnSettings = await readSettings();
48
- const runtime = await modelWithConfig({ cwd: session?.cwd, modelSelector: modelOverride }, turnSettings);
48
+ const runtime = await modelWithConfig({ cwd: session?.cwd, modelSelector: modelOverride, reasoningOverride }, turnSettings);
49
49
  if (!runtime?.model) {
50
50
  callbacks.addMessage({ role: 'assistant', text: 'No model provider configured. Run /provider to choose or add a provider. haze cannot hallucinate without a model. Progress.' });
51
51
  return undefined;
@@ -129,7 +129,15 @@ export async function prepareAttempt(deps) {
129
129
  logEntry(callbacks.log, { at: new Date().toISOString(), type: 'request', stream: 'main', system: systemPrompt, messages: requestMessages, tools: Object.keys(availableTools), context: inputBreakdown.breakdown });
130
130
  const contextFileSignatures = callbacks.contextFileSignatures ?? new Map(activeContextFiles.flatMap(file => file.signature ? [[file.path, file.signature]] : []));
131
131
  const mutationPolicy = assembled.executionScope?.mutationPolicy ?? new WorkspaceMutationPolicy();
132
- const toolExecutionContext = { inFlightToolCalls: new Map(), loadedContextFilePaths: new Set(activeContextFiles.map(file => file.path)), loadedContextFileSignatures: contextFileSignatures, onContextFileRead, mutationPolicy, blessedPaths: turnOptions.blessedPaths };
132
+ const toolExecutionContext = {
133
+ inFlightToolCalls: new Map(),
134
+ loadedContextFilePaths: new Set(activeContextFiles.map(file => file.path)),
135
+ loadedContextFileSignatures: contextFileSignatures,
136
+ onContextFileRead,
137
+ mutationPolicy,
138
+ blessedPaths: turnOptions.blessedPaths,
139
+ postMutationDiagnostics: assembled.postMutationDiagnostics,
140
+ };
133
141
  const recoverySlice = turnOptions.recoverySlice;
134
142
  const stepCap = recoverySlice?.maxSteps ?? MAIN_STEP_LIMIT;
135
143
  // Rescue exposes only mutation + validation-capable built-in tools so
@@ -1,6 +1,7 @@
1
1
  import type { CompletionReadiness, TurnExecutionState } from '../../../core/agent/completionController.js';
2
2
  import type { RequestIntent } from '../../../core/agent/goalPolicy.js';
3
3
  import type { RedEvidence, ValidationOutcome, WorkTaskProgress } from '../../../core/agent/workState.js';
4
+ import type { ValidationKind } from '../../../llm/toolResultTypes.js';
4
5
  import type { GoalLedgerFrontier } from '../../../core/session/sessionStore.js';
5
6
  /**
6
7
  * Bounded continuation checkpoint for a logical goal whose work is recoverably
@@ -32,6 +33,8 @@ export interface IncompleteGoalResume {
32
33
  requestHash?: string;
33
34
  /** Unresolved pre-mutation failing repro for fix goals. */
34
35
  redEvidence?: RedEvidence;
36
+ /** Kind of the carried validation, when one rode the checkpoint (R2-03). */
37
+ validationKind?: ValidationKind;
35
38
  }
36
39
  /** Supervisor-level checkpoint persisted between physical turns (in memory and, via the goal ledger, in the session JSONL). */
37
40
  export interface GoalCheckpoint {
@@ -60,6 +63,8 @@ export interface GoalCheckpoint {
60
63
  requestHash?: string;
61
64
  intent?: RequestIntent;
62
65
  redEvidence?: RedEvidence;
66
+ /** Kind of the carried validation, when one rode the checkpoint (R2-03). */
67
+ validationKind?: ValidationKind;
63
68
  }
64
69
  /** Durable goal-ledger append (P1): one entry per supervisor boundary; the writer stamps `type`/`at`. Shared by the supervisor and the session recorder. */
65
70
  export interface GoalLedgerAppend {
@@ -100,6 +105,7 @@ export interface CarriedGoalEvidence {
100
105
  requestHash?: string;
101
106
  intent?: RequestIntent;
102
107
  redEvidence?: RedEvidence;
108
+ validationKind?: ValidationKind;
103
109
  }
104
110
  /**
105
111
  * Build the checkpoint payload for a `recoverable-incomplete` attempt that no
@@ -54,5 +54,6 @@ export function checkpointFromGoalFrontier(frontier) {
54
54
  ...(frontier.intent ? { intent: frontier.intent } : {}),
55
55
  ...(frontier.taskCounts ? { taskCounts: frontier.taskCounts } : {}),
56
56
  ...(frontier.redEvidence ? { redEvidence: { ...frontier.redEvidence } } : {}),
57
+ ...(frontier.validationKind ? { validationKind: frontier.validationKind } : {}),
57
58
  };
58
59
  }
@@ -1,6 +1,7 @@
1
1
  import type { ContextFile } from '../../../config/contextFiles.js';
2
2
  import type { TurnCompletionEvidence } from '../../../core/agent/completionController.js';
3
3
  import type { PromptSession } from '../../../llm/systemPrompt.js';
4
+ import type { StoredReasoningSetting } from '../../../core/agent/reasoningPolicy.js';
4
5
  import { type StreamCallbacks, type TurnExecutionOptions } from '../streaming.js';
5
6
  import { type GoalCheckpoint, type GoalLedgerAppend } from './goalCheckpoint.js';
6
7
  /** Why a logical goal stopped. `completed` is the only success. */
@@ -23,6 +24,7 @@ export interface GoalRunResult {
23
24
  kind: 'model-stream-idle';
24
25
  request: string;
25
26
  retryAttempt: number;
27
+ checkpoint?: GoalCheckpoint;
26
28
  } | {
27
29
  kind: 'incomplete-goal';
28
30
  checkpoint: GoalCheckpoint;
@@ -35,6 +37,8 @@ export interface GoalRunOptions {
35
37
  callbacks: StreamCallbacks;
36
38
  session?: PromptSession;
37
39
  modelOverride?: string;
40
+ /** Run-scoped reasoning level/sentinel (CLI `--reasoning`); applies to every attempt of the goal. */
41
+ reasoningOverride?: StoredReasoningSetting;
38
42
  /** Whole-logical-goal wall-clock budget (headless `--timeout`); unset means continue while progress. */
39
43
  goalDeadlineMs?: number;
40
44
  /** Base per-turn options (attachments, blessed paths); attachments apply to the first physical turn only. */
@@ -43,6 +47,7 @@ export interface GoalRunOptions {
43
47
  resumeFrom?: {
44
48
  kind: 'model-stream-idle';
45
49
  retryAttempt: number;
50
+ checkpoint?: GoalCheckpoint;
46
51
  } | {
47
52
  kind: 'incomplete-goal';
48
53
  checkpoint: GoalCheckpoint;
@@ -20,6 +20,7 @@ function checkpointFromResume(resume, noProgressCount) {
20
20
  noProgressCount,
21
21
  ...(resume.requestHash ? { requestHash: resume.requestHash } : {}),
22
22
  ...(resume.redEvidence ? { redEvidence: { ...resume.redEvidence } } : {}),
23
+ ...(resume.validationKind ? { validationKind: resume.validationKind } : {}),
23
24
  };
24
25
  }
25
26
  function countsToTaskProgress(counts) {
@@ -38,6 +39,7 @@ function carriedOf(checkpoint) {
38
39
  validationOutcome: checkpoint.validationOutcome,
39
40
  ...(checkpoint.taskCounts ? { taskProgress: countsToTaskProgress(checkpoint.taskCounts) } : {}),
40
41
  ...(checkpoint.redEvidence ? { redEvidence: { ...checkpoint.redEvidence } } : {}),
42
+ ...(checkpoint.validationKind ? { validationKind: checkpoint.validationKind } : {}),
41
43
  }
42
44
  : { mutationCount: 0, validationOutcome: 'not_applicable' };
43
45
  }
@@ -63,7 +65,7 @@ function carriedOf(checkpoint) {
63
65
  export async function runAgentGoal(options) {
64
66
  const { request, contextFiles, callbacks } = options;
65
67
  const startedAt = Date.now();
66
- const resumedCheckpoint = options.resumeFrom?.kind === 'incomplete-goal' || options.resumeFrom?.kind === 'stored-goal' ? options.resumeFrom.checkpoint : undefined;
68
+ const resumedCheckpoint = options.resumeFrom?.checkpoint;
67
69
  const goalId = resumedCheckpoint?.goalId ?? `goal-${startedAt}-${Math.random().toString(36).slice(2)}`;
68
70
  const requestHash = resumedCheckpoint?.requestHash ?? hashRequest(request);
69
71
  const intent = resumedCheckpoint?.intent ?? classifyRequestIntent(request);
@@ -92,6 +94,7 @@ export async function runAgentGoal(options) {
92
94
  // Unresolved red evidence keeps crash resumes at parity with in-process
93
95
  // continuation; satisfied pairs are deliberately not carried.
94
96
  ...(source?.redEvidence ? { redEvidence: { ...source.redEvidence } } : {}),
97
+ ...(source?.validationKind ? { validationKind: source.validationKind } : {}),
95
98
  ...extra,
96
99
  });
97
100
  };
@@ -136,10 +139,12 @@ export async function runAgentGoal(options) {
136
139
  sharedTurnScope,
137
140
  ...(remainingMs != null ? { turnDeadlineMs: Math.min(remainingMs, DEFAULT_TURN_DEADLINE_MS) } : {}),
138
141
  };
139
- const result = await runAgentTurn(request, continuing ? undefined : options.displayValue, contextFiles, callbacks, initialRetryAttempt, continuing, false, options.session, options.modelOverride, turnOptions);
142
+ const result = await runAgentTurn(request, continuing ? undefined : options.displayValue, contextFiles, callbacks, initialRetryAttempt, continuing, false, options.session, options.modelOverride, turnOptions, options.reasoningOverride);
140
143
  initialRetryAttempt = 0;
141
144
  cycle += 1;
142
145
  lastEvidence = result.evidence;
146
+ if (result.checkpoint)
147
+ checkpoint = result.checkpoint;
143
148
  if (result.status === 'complete')
144
149
  return finish('complete', 'completed');
145
150
  if (result.status === 'aborted') {
@@ -180,10 +185,10 @@ export async function runAgentGoal(options) {
180
185
  if (result.resume?.kind === 'model-stream-idle') {
181
186
  // Bounded in-turn retries are exhausted; a transport stall is a concrete
182
187
  // external blocker — pause with the existing one-key resume path.
183
- return finish('failed', 'model-stream-idle', { kind: 'model-stream-idle', request: result.resume.request, retryAttempt: result.resume.retryAttempt });
188
+ return finish('failed', 'model-stream-idle', { kind: 'model-stream-idle', request: result.resume.request, retryAttempt: result.resume.retryAttempt, ...(checkpoint ? { checkpoint } : {}) });
184
189
  }
185
190
  // Failed without a checkpoint: hard blocker (failed tool, invalid input,
186
191
  // provider error) or an unresolved synthesis failure.
187
- return finish('failed', result.evidence?.finishCause === 'error' ? 'model-error' : 'blocked');
192
+ return finish('failed', result.evidence?.finishCause === 'error' ? 'model-error' : 'blocked', checkpoint ? { kind: 'incomplete-goal', checkpoint } : undefined);
188
193
  }
189
194
  }
@@ -1,7 +1,5 @@
1
- import type { ModelMessage } from 'ai';
2
1
  import { type SessionGoal } from '../../../core/agent/goalPolicy.js';
3
2
  import { type ContextUsageAnchor } from '../../../core/agent/contextBudget.js';
4
- import type { HazeToolContext } from '../../../llm/tools/toolContext.js';
5
3
  import type { StreamCallbacks, TurnExecutionOptions } from '../streaming.js';
6
4
  import type { AttemptSetup } from './attemptSetup.js';
7
5
  import type { AttemptLoopState } from './streamLoop.js';
@@ -18,7 +16,6 @@ type AgentOptions = NonNullable<ConstructorParameters<typeof import('ai').ToolLo
18
16
  type RepairToolCallFn = NonNullable<AgentOptions['experimental_repairToolCall']>;
19
17
  type PrepareStepFn = NonNullable<AgentOptions['prepareStep']>;
20
18
  type SyncPrepareStepResult = Exclude<ReturnType<PrepareStepFn>, PromiseLike<unknown>>;
21
- export declare function withScopedContextControl(messages: ModelMessage[], context: HazeToolContext): ModelMessage[];
22
19
  export declare function createRepairToolCall(deps: {
23
20
  callbacks: StreamCallbacks;
24
21
  loopState: AttemptLoopState;
@@ -1,5 +1,5 @@
1
1
  import { agentEvent } from '../../../core/agent/events.js';
2
- import { malformedToolCallPrompt, repeatedToolCallPrompt, toolLoopBudgetPrompt } from '../../../core/agent/goalPolicy.js';
2
+ import { editRecoveryReadPrompt, malformedToolCallPrompt, repeatedToolCallPrompt, toolLoopBudgetPrompt } from '../../../core/agent/goalPolicy.js';
3
3
  import { estimateConversationTokens } from '../../../core/agent/contextBudget.js';
4
4
  import { compactModelMessages } from '../../../core/agent/compaction.js';
5
5
  import { appendSyntheticControl, stripSyntheticControls } from '../../../core/agent/requestAssembly.js';
@@ -8,7 +8,7 @@ import { RESCUE_BOUNDARY } from '../../../core/agent/completionController.js';
8
8
  import { MAIN_TOOL_CALL_LIMIT, WRITE_FILE_CHUNK_BYTES } from '../../../core/agent/budgets.js';
9
9
  import { projectContextSection } from '../../../llm/systemPrompt.js';
10
10
  import { clampOutOfBoundsToolNumbers, isMalformedToolInputError } from './toolCallRecovery.js';
11
- export function withScopedContextControl(messages, context) {
11
+ function withScopedContextControl(messages, context) {
12
12
  const files = context.pendingContextFiles ?? [];
13
13
  if (files.length === 0)
14
14
  return messages;
@@ -96,8 +96,13 @@ export function createPrepareStep(deps) {
96
96
  return { activeTools: [toolName], toolChoice: 'required', messages: appendSyntheticControl(scopedMessages, malformedToolCallPrompt(String(toolName), WRITE_FILE_CHUNK_BYTES)) };
97
97
  }
98
98
  if (loopState.toolResultState.editRecoveryPath && !loopState.toolResultState.editRecoveryReadSatisfied) {
99
+ // Instruct, do not restrict: the execution-time gate in toolContext
100
+ // (failed-mutation path requires a fresh read) is the structural
101
+ // enforcer and returns a recoverable structured error. Narrowing the
102
+ // request tool set here would downgrade that to a step-fatal
103
+ // AI_NoSuchToolError when a model retries the edit anyway.
99
104
  if ('readFile' in sliceTools)
100
- return messagesChanged ? { activeTools: ['readFile'], messages: scopedMessages } : { activeTools: ['readFile'] };
105
+ return { messages: appendSyntheticControl(scopedMessages, editRecoveryReadPrompt(loopState.toolResultState.editRecoveryPath)) };
101
106
  return { toolChoice: 'none', messages: appendSyntheticControl(scopedMessages, `The failed mutation of ${loopState.toolResultState.editRecoveryPath} requires a fresh read, but readFile is unavailable in this bounded recovery slice. Report the unfinished edit as blocked; do not claim it succeeded.`) };
102
107
  }
103
108
  if (repeatedToolNames.length > 0) {
@@ -5,10 +5,12 @@ import type { ImageAttachment } from '../../core/attachments/imageAttachments.js
5
5
  import { type BlessedPath } from '../../core/attachments/readBlessings.js';
6
6
  import type { TurnCompletionEvidence } from '../../core/agent/completionController.js';
7
7
  import type { RedEvidence, ValidationOutcome, WorkTaskProgress, WorkState } from '../../core/agent/workState.js';
8
+ import type { ValidationKind } from '../../llm/toolResultTypes.js';
8
9
  import type { SubagentOverrides, TurnExecutionScope } from '../../llm/requestContext.js';
9
10
  import type { PromptSession } from '../../llm/systemPrompt.js';
11
+ import type { StoredReasoningSetting } from '../../core/agent/reasoningPolicy.js';
10
12
  import type { ContextFile } from '../../config/contextFiles.js';
11
- import type { IncompleteGoalResume } from './streaming/goalCheckpoint.js';
13
+ import { type GoalCheckpoint, type IncompleteGoalResume } from './streaming/goalCheckpoint.js';
12
14
  import { type TokenUsage } from './streaming/turnRuntime.js';
13
15
  import type { ToolDisplayDiff } from './streaming/toolGroupRenderer.js';
14
16
  export type Message = {
@@ -32,6 +34,8 @@ export interface TurnResult {
32
34
  abortReason?: 'user' | 'turn-deadline';
33
35
  /** Bounded, safe completion evidence (no raw commands/output). Additive. */
34
36
  evidence?: TurnCompletionEvidence;
37
+ /** Goal-scoped obligations survive every failed exit, including transport failures. */
38
+ checkpoint?: GoalCheckpoint;
35
39
  /**
36
40
  * The turn paused with recoverable work unfinished; this carries what a
37
41
  * one-key/automatic resume needs instead of forcing the user to restate the
@@ -65,6 +69,7 @@ interface TurnGoalContext {
65
69
  validationOutcome: ValidationOutcome;
66
70
  taskProgress?: WorkTaskProgress;
67
71
  redEvidence?: RedEvidence;
72
+ validationKind?: ValidationKind;
68
73
  };
69
74
  /** Consecutive no-progress physical turns at goal level (diagnostics). */
70
75
  noProgressCount: number;
@@ -121,5 +126,5 @@ export interface StreamCallbacks {
121
126
  log?: LlmLog;
122
127
  contextFileSignatures?: Map<string, string>;
123
128
  }
124
- export declare function runAgentTurn(value: string, displayValue: string | undefined, contextFiles: ContextFile[], callbacks: StreamCallbacks, retryAttempt?: number, retryingExistingRequest?: boolean, contextOverflowRecovered?: boolean, session?: PromptSession, modelOverride?: string, turnOptions?: TurnExecutionOptions): Promise<TurnResult>;
129
+ export declare function runAgentTurn(value: string, displayValue: string | undefined, contextFiles: ContextFile[], callbacks: StreamCallbacks, retryAttempt?: number, retryingExistingRequest?: boolean, contextOverflowRecovered?: boolean, session?: PromptSession, modelOverride?: string, turnOptions?: TurnExecutionOptions, reasoningOverride?: StoredReasoningSetting): Promise<TurnResult>;
125
130
  export {};
@@ -1,10 +1,11 @@
1
1
  import { agentEvent } from '../../core/agent/events.js';
2
- import { createTurnExecutionState, toCompletionEvidence } from '../../core/agent/completionController.js';
2
+ import { createTurnExecutionState, describeTurnFailure, toCompletionEvidence } from '../../core/agent/completionController.js';
3
3
  import { createSessionGoal } from '../../core/agent/goalPolicy.js';
4
4
  import { seedCarriedGoalEvidence } from '../../core/agent/workState.js';
5
5
  import { createToolExecutionBudget, mainTurnBudget, DEFAULT_TURN_DEADLINE_MS, OVERFLOW_SHRINK_FACTOR } from '../../core/agent/budgets.js';
6
6
  import { createAbsoluteDeadline } from '../../core/deadline.js';
7
7
  import { modelThinkingLabel } from '../../utils/modelName.js';
8
+ import { goalCheckpointSignature, taskCountsOf } from './streaming/goalCheckpoint.js';
8
9
  import { abortableDelay } from './streaming/turnRuntime.js';
9
10
  import { abortForTurn, createUserAbortCause } from './streaming/abortCause.js';
10
11
  import { runAgentAttempt } from './streaming/agentAttempt.js';
@@ -12,7 +13,7 @@ import { projectGoalEvidence } from './streaming/attemptOutcome.js';
12
13
  import { awaitAttemptWithForcedSettlement, createAttemptCleanupRegistry, createQuarantinableCallbacks } from './streaming/attemptLifecycle.js';
13
14
  import { startRecoverySlice } from './streaming/recoverySlices.js';
14
15
  import { formatIdleMinutes } from '../../utils/format.js';
15
- export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session, modelOverride, turnOptions = {}) {
16
+ export async function runAgentTurn(value, displayValue, contextFiles, callbacks, retryAttempt = 0, retryingExistingRequest = false, contextOverflowRecovered = false, session, modelOverride, turnOptions = {}, reasoningOverride) {
16
17
  // The controller is replaced when an idle-stall retry needs a live signal
17
18
  // after aborting a hung stream, so both it and the cause are mutable.
18
19
  let abortController = new AbortController();
@@ -86,7 +87,7 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
86
87
  },
87
88
  });
88
89
  const cleanup = createAttemptCleanupRegistry();
89
- const result = await awaitAttemptWithForcedSettlement(runAgentAttempt({ value, contextFiles, callbacks: attemptCallbacks, retryAttempt: attempt, retryingExistingRequest: retrying, overflowShrinkFactor, overflowRetries, progressSinceLastRetry: turnState.stepsUsed > stepsUsedAtLastRetry, session, modelOverride, abortController, turnOptions: activeOptions, turnScope, turnState, turnBudget, globalBudget, sliceBudget, goal, abortCause, cleanup, remainingTurnDeadlineMs: () => Math.max(0, turnDeadlineMs - (Date.now() - turnStartedAt)), usageAnchor }), {
90
+ const result = await awaitAttemptWithForcedSettlement(runAgentAttempt({ value, contextFiles, callbacks: attemptCallbacks, retryAttempt: attempt, retryingExistingRequest: retrying, overflowShrinkFactor, overflowRetries, progressSinceLastRetry: turnState.stepsUsed > stepsUsedAtLastRetry, session, modelOverride, reasoningOverride, abortController, turnOptions: activeOptions, turnScope, turnState, turnBudget, globalBudget, sliceBudget, goal, abortCause, cleanup, remainingTurnDeadlineMs: () => Math.max(0, turnDeadlineMs - (Date.now() - turnStartedAt)), usageAnchor }), {
90
91
  abortController,
91
92
  cleanup,
92
93
  quarantine,
@@ -141,11 +142,29 @@ export async function runAgentTurn(value, displayValue, contextFiles, callbacks,
141
142
  }
142
143
  projectGoalEvidence(turnState, goal);
143
144
  const evidence = toCompletionEvidence(turnState);
144
- return { status, evidence, ...(abortReason ? { abortReason } : {}), ...(resume ? { resume } : {}) };
145
+ const checkpoint = {
146
+ goalId: turnOptions.goalContext?.goalId ?? goal.id, request: value,
147
+ cycle: turnOptions.goalContext?.cycle ?? 1, mutationCount: goal.mutationCount,
148
+ validationOutcome: turnState.validationOutcome, taskCounts: taskCountsOf(goal.taskProgress),
149
+ progressSignature: goalCheckpointSignature({ mutationCount: goal.mutationCount, validationOutcome: turnState.validationOutcome, taskCounts: taskCountsOf(goal.taskProgress) }),
150
+ noProgressCount: turnOptions.goalContext?.noProgressCount ?? 0,
151
+ requestHash: turnOptions.goalContext?.requestHash, intent: goal.normalizedIntent,
152
+ ...(turnState.redPair !== 'satisfied' && goal.redEvidence ? { redEvidence: { ...goal.redEvidence } } : {}),
153
+ ...(turnState.validationKind ? { validationKind: turnState.validationKind } : {}),
154
+ };
155
+ return { status, evidence, ...(status !== 'complete' ? { checkpoint } : {}), ...(abortReason ? { abortReason } : {}), ...(resume ? { resume } : {}) };
145
156
  }
146
157
  finally {
147
158
  turnDeadline?.clear();
148
- callbacks.onEvent?.(agentEvent({ type: 'turn_end', request: value, status, evidence: toCompletionEvidence(turnState) }));
159
+ // RT-05: persist an explicit cause for unexplained outcomes in the ledger
160
+ // (no --debug required) and tell the user when a turn dies silently — the
161
+ // live session saw a 20s goal fail with zero assistant output and no
162
+ // timeout/retry events, forcing the user to re-send the prompt.
163
+ const turnEndReason = status === 'failed' ? describeTurnFailure(turnState, callbacks.getLastAssistantText()) : undefined;
164
+ if (turnEndReason === 'model-returned-no-output') {
165
+ callbacks.addMessage({ role: 'system', text: 'The model returned no output for this turn. Send the request again, or retry after a moment; completed work is preserved in the conversation.' });
166
+ }
167
+ callbacks.onEvent?.(agentEvent({ type: 'turn_end', request: value, status, evidence: toCompletionEvidence(turnState), ...(turnEndReason ? { reason: turnEndReason } : {}) }));
149
168
  callbacks.setAbortController?.(null);
150
169
  callbacks.setBusyLabel?.(modelThinkingLabel(undefined));
151
170
  callbacks.setBusy(false);
@@ -108,6 +108,8 @@ export declare function skillScopeSuggestions(): TextInputSuggestion[];
108
108
  export declare function skillsActionSuggestions(settings: HazeSettings, skills: LoadedSkill[], selectedSkillName: string | undefined): TextInputSuggestion[];
109
109
  /** Every built-in theme with its palette brightness and the active one marked (`resolveTheme` validates names). */
110
110
  export declare function themeSuggestions(settings: HazeSettings): TextInputSuggestion[];
111
+ /** Reasoning-effort picker values: every level plus the unset action. */
112
+ export declare function reasoningSuggestions(settings: HazeSettings): TextInputSuggestion[];
111
113
  type WizardStepKind = 'pick' | 'input' | 'masked-input' | 'confirm';
112
114
  /** Inputs available to a step's suggestion builder (mirrors the picker state). */
113
115
  export interface WizardSuggestionState {
@@ -334,6 +336,11 @@ export declare const WIZARD_STEPS: readonly [{
334
336
  readonly kind: "pick";
335
337
  readonly placeholder: "Choose a theme";
336
338
  readonly suggestions: (s: WizardSuggestionState) => TextInputSuggestion[];
339
+ }, {
340
+ readonly id: "reasoning";
341
+ readonly kind: "pick";
342
+ readonly placeholder: "Choose a reasoning effort level";
343
+ readonly suggestions: (s: WizardSuggestionState) => TextInputSuggestion[];
337
344
  }];
338
345
  export type WizardStepId = (typeof WIZARD_STEPS)[number]['id'];
339
346
  /** Suggestions for a wizard mode, or undefined when the mode is not a wizard step ('chat'). */
@@ -4,6 +4,7 @@ import { configuredMcpServers, findMcpServer, findMcpPreset, presetIds } from '.
4
4
  import { isSkillEnabled } from '../../config/skillSettings.js';
5
5
  import { PROVIDER_PRESETS } from '../../config/providerPresets.js';
6
6
  import { CHATGPT_CODEX_BASE_URL } from '../../llm/openaiCodexOAuth.js';
7
+ import { DEFAULT_REASONING_LEVEL, REASONING_LEVELS } from '../../core/agent/reasoningPolicy.js';
7
8
  import { BUILT_IN_THEME_SPECS, DEFAULT_THEME_NAME, resolveTheme } from '../../ui/theme.js';
8
9
  import { sessionActionSuggestions, sessionSuggestions } from './sessionPicker.js';
9
10
  /**
@@ -342,6 +343,25 @@ export function themeSuggestions(settings) {
342
343
  kind: 'theme',
343
344
  }));
344
345
  }
346
+ /** Reasoning-effort picker values: every level plus the unset action. */
347
+ export function reasoningSuggestions(settings) {
348
+ const descriptions = {
349
+ none: 'disable reasoning',
350
+ minimal: 'least reasoning',
351
+ low: 'light reasoning',
352
+ medium: 'moderate reasoning',
353
+ high: 'deep reasoning',
354
+ xhigh: 'maximum reasoning',
355
+ };
356
+ return [
357
+ ...REASONING_LEVELS.map(level => ({
358
+ value: level,
359
+ description: `${descriptions[level] ?? 'reasoning level'}${settings.reasoning === level || (settings.reasoning === undefined && level === DEFAULT_REASONING_LEVEL) ? ' · active' : ''}`,
360
+ kind: 'command',
361
+ })),
362
+ { value: 'unset', description: 'provider default — sends no reasoning parameter', kind: 'command' },
363
+ ];
364
+ }
345
365
  export const WIZARD_STEPS = [
346
366
  // Sessions
347
367
  { id: 'sessions', kind: 'pick', placeholder: 'Choose a saved session', suggestions: (s) => sessionSuggestions(s.sessions ?? []) },
@@ -388,6 +408,8 @@ export const WIZARD_STEPS = [
388
408
  { id: 'mcpConfirmRemove', kind: 'confirm', placeholder: 'Type "yes" to confirm', suggestions: () => [] },
389
409
  // Themes
390
410
  { id: 'themes', kind: 'pick', placeholder: 'Choose a theme', suggestions: (s) => themeSuggestions(s.settings) },
411
+ // Reasoning effort
412
+ { id: 'reasoning', kind: 'pick', placeholder: 'Choose a reasoning effort level', suggestions: (s) => reasoningSuggestions(s.settings) },
391
413
  ];
392
414
  const WIZARD_STEP_BY_ID = Object.fromEntries(WIZARD_STEPS.map(step => [step.id, step]));
393
415
  /** Suggestions for a wizard mode, or undefined when the mode is not a wizard step ('chat'). */
package/dist/cli/index.js CHANGED
@@ -23,6 +23,7 @@ program
23
23
  .option('--no-session', 'run without saving or resuming a durable session')
24
24
  .option('-p, --prompt <text>', 'print mode: run a single non-interactive turn and print the result (falls back to piped stdin)')
25
25
  .option('-m, --model <selector>', 'override the model for this run only — a registered model name or provider:name')
26
+ .addOption(new Option('--reasoning <level>', 'print-mode reasoning effort for this run only — none, minimal, low, medium, high, xhigh, or unset (no parameter sent; provider default)').choices(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'unset', 'off']))
26
27
  .addOption(new Option('--output <format>', 'print-mode output: plain text, a single JSON result envelope, or a stream-json NDJSON event stream').choices(['text', 'json', 'stream-json']).default('text'))
27
28
  .option('--timeout <duration>', 'print-mode absolute turn deadline (e.g. 30s, 10m, 2h); bounds total elapsed time so a busy tool cannot run indefinitely')
28
29
  .option('--until-done', 'print mode: relaunch the goal after transient model failures (with backoff) until it structurally completes, the --timeout deadline hits, or repeated relaunches make no progress');
@@ -34,6 +35,7 @@ Examples:
34
35
  $ haze -p "list the top 3 bugs" --output json emit a JSON envelope { type, status, result, usage }
35
36
  $ haze -p "audit src/" --output stream-json stream NDJSON events live, then the final result envelope
36
37
  $ haze -p "summarize" --model openai:gpt-4o-mini override the model for this run only
38
+ $ haze -p "audit src/" --reasoning xhigh run with maximum reasoning effort (unset = provider default)
37
39
  $ haze --resume <id> -p "continue the review" load a saved context for one print-mode turn
38
40
  $ haze -p "audit auth.ts" --debug also write a detailed JSONL log to ~/.haze/logs/
39
41
 
@@ -48,7 +50,8 @@ Print mode (-p):
48
50
  harnesses live progress, per-step usage, bounded tool-failure diagnostics, and stagnation
49
51
  detection without raw tool inputs or outputs. --model overrides the model for this
50
52
  run only (no settings change) and must already be registered under a provider (add it once via
51
- the /provider picker). Print-mode runs are non-durable: --continue is ignored and no session is
53
+ the /provider picker). --reasoning overrides the reasoning effort for this run only (levels
54
+ none–xhigh; unset sends no reasoning parameter, provider default). Print-mode runs are non-durable: --continue is ignored and no session is
52
55
  saved. --resume <id> loads saved context for the turn without changing that session. On a
53
56
  provider context overflow, haze compacts the conversation and retries at a progressively smaller
54
57
  message budget (up to twice); exhausted retries pause with a context_exhausted checkpoint, and
@@ -116,6 +119,7 @@ program.action(async () => {
116
119
  const code = await runHeadless({
117
120
  prompt,
118
121
  modelOverride: opts.model,
122
+ reasoning: opts.reasoning,
119
123
  resumeSessionId: opts.resume,
120
124
  // commander validates --output against the choices above, so opts.output is one of
121
125
  // 'text' | 'json' | 'stream-json'; default to text for piped/stdin runs without the flag.
@@ -1,6 +1,45 @@
1
+ import { assertCredentialedEndpointSecure } from './endpointSecurity.js';
1
2
  const DEFAULT_TIMEOUT_MS = 5000;
2
3
  /** Discovery feeds a type-filtered picker; cap the stored list, not the UX. */
3
4
  const MAX_DISCOVERED_MODELS = 500;
5
+ /** Redirect hops followed; each hop re-validates the credential transport policy. */
6
+ const MAX_DISCOVERY_REDIRECTS = 2;
7
+ /** CI-04: bound the JSON body before parsing so an oversized response fails loudly. */
8
+ const MAX_DISCOVERY_BODY_BYTES = 1_000_000;
9
+ /** Read a discovery response body as bounded UTF-8; an oversized body fails. */
10
+ async function readBodyBounded(response) {
11
+ if (response.body == null)
12
+ return await response.json();
13
+ const read = await readUtf8PrefixFromStream(response.body, MAX_DISCOVERY_BODY_BYTES);
14
+ if (read.truncated)
15
+ throw new Error(`endpoint response exceeds ${MAX_DISCOVERY_BODY_BYTES} bytes`);
16
+ return JSON.parse(read.content);
17
+ }
18
+ function readUtf8PrefixFromStream(stream, maxBytes) {
19
+ const reader = stream.getReader();
20
+ const chunks = [];
21
+ let received = 0;
22
+ return new Promise((resolve, reject) => {
23
+ const pump = () => {
24
+ reader.read().then(({ done, value }) => {
25
+ if (done) {
26
+ resolve({ content: Buffer.concat(chunks).toString('utf8'), truncated: false });
27
+ return;
28
+ }
29
+ received += value.byteLength;
30
+ if (received > maxBytes) {
31
+ // Cancel and resolve truncated; the caller decides what that means.
32
+ void reader.cancel().catch(() => undefined);
33
+ resolve({ content: '', truncated: true });
34
+ return;
35
+ }
36
+ chunks.push(value);
37
+ pump();
38
+ }, reject);
39
+ };
40
+ pump();
41
+ });
42
+ }
4
43
  export function modelsEndpointUrl(baseUrl) {
5
44
  return `${baseUrl.trim().replace(/\/+$/, '')}/models`;
6
45
  }
@@ -187,12 +226,36 @@ function describeFetchError(error) {
187
226
  export async function discoverProviderModels(provider, options = {}) {
188
227
  const fetchImpl = options.fetchImpl ?? fetch;
189
228
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
229
+ let url = modelsEndpointUrl(provider.url);
230
+ // CI-01: validate before the first network call — a draft key must never be
231
+ // transmitted to a remote plaintext endpoint just because the user is still
232
+ // in a wizard. Re-checked on every redirect hop (downgrades are refused).
233
+ try {
234
+ assertCredentialedEndpointSecure(url, provider.key);
235
+ }
236
+ catch (error) {
237
+ return { status: 'failed', error: error instanceof Error ? error.message : String(error) };
238
+ }
190
239
  let response;
191
240
  try {
192
- response = await fetchImpl(modelsEndpointUrl(provider.url), {
193
- headers: { accept: 'application/json', ...(provider.key ? { authorization: `Bearer ${provider.key}` } : {}) },
194
- signal: AbortSignal.timeout(timeoutMs),
195
- });
241
+ for (let hop = 0;; hop += 1) {
242
+ response = await fetchImpl(url, {
243
+ headers: { accept: 'application/json', ...(provider.key ? { authorization: `Bearer ${provider.key}` } : {}) },
244
+ redirect: 'manual',
245
+ signal: AbortSignal.timeout(timeoutMs),
246
+ });
247
+ const location = response.status >= 300 && response.status < 400 ? response.headers?.get('location') : null;
248
+ if (!location)
249
+ break;
250
+ if (hop >= MAX_DISCOVERY_REDIRECTS)
251
+ return { status: 'failed', error: `endpoint redirected more than ${MAX_DISCOVERY_REDIRECTS} times` };
252
+ const nextUrl = new URL(location, url).toString();
253
+ if (provider.key && new URL(nextUrl).origin !== new URL(url).origin) {
254
+ return { status: 'failed', error: 'credentialed endpoint redirected to a different origin' };
255
+ }
256
+ url = nextUrl;
257
+ assertCredentialedEndpointSecure(url, provider.key);
258
+ }
196
259
  }
197
260
  catch (error) {
198
261
  return { status: 'failed', error: describeFetchError(error) };
@@ -201,7 +264,7 @@ export async function discoverProviderModels(provider, options = {}) {
201
264
  return { status: 'failed', error: `endpoint returned HTTP ${response.status}` };
202
265
  let body;
203
266
  try {
204
- body = await response.json();
267
+ body = await readBodyBounded(response);
205
268
  }
206
269
  catch {
207
270
  return { status: 'failed', error: 'endpoint returned no JSON' };