@denizokcu/haze 1.2.0 → 1.5.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 (179) hide show
  1. package/CHANGELOG.md +86 -1
  2. package/README.md +23 -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/BusyBar.d.ts +7 -0
  7. package/dist/cli/chat/BusyBar.js +8 -0
  8. package/dist/cli/chat/DynamicFrame.d.ts +37 -0
  9. package/dist/cli/chat/DynamicFrame.js +43 -0
  10. package/dist/cli/chat/busyIndicator.d.ts +3 -1
  11. package/dist/cli/chat/busyIndicator.js +11 -9
  12. package/dist/cli/chat/chatMetrics.d.ts +1 -1
  13. package/dist/cli/chat/chatMetrics.js +3 -3
  14. package/dist/cli/chat/inputSuggestions.js +4 -0
  15. package/dist/cli/chat/liveMessages.d.ts +36 -0
  16. package/dist/cli/chat/liveMessages.js +64 -0
  17. package/dist/cli/chat/liveRegion.js +1 -1
  18. package/dist/cli/chat/messages.js +27 -16
  19. package/dist/cli/chat/sessionLifecycle.d.ts +5 -2
  20. package/dist/cli/chat/sessionLifecycle.js +36 -4
  21. package/dist/cli/chat/sessionRecorder.d.ts +2 -1
  22. package/dist/cli/chat/sessionRecorder.js +8 -0
  23. package/dist/cli/chat/shutdown.d.ts +27 -0
  24. package/dist/cli/chat/shutdown.js +79 -0
  25. package/dist/cli/chat/terminalControl.d.ts +45 -0
  26. package/dist/cli/chat/terminalControl.js +107 -0
  27. package/dist/cli/chat/tips.js +1 -0
  28. package/dist/cli/chat/userInput.d.ts +43 -0
  29. package/dist/cli/chat/userInput.js +63 -0
  30. package/dist/cli/chat/wizard/sessionThemeHandlers.d.ts +1 -1
  31. package/dist/cli/chat/wizard/sessionThemeHandlers.js +24 -1
  32. package/dist/cli/chat/wizard/types.d.ts +8 -1
  33. package/dist/cli/chat/wizardDispatch.js +1 -1
  34. package/dist/cli/commands/chat.js +277 -193
  35. package/dist/cli/commands/commandHelp.js +6 -0
  36. package/dist/cli/commands/commands.d.ts +8 -0
  37. package/dist/cli/commands/commands.js +13 -0
  38. package/dist/cli/commands/formatters.d.ts +1 -1
  39. package/dist/cli/commands/formatters.js +25 -3
  40. package/dist/cli/commands/logsCommand.js +21 -2
  41. package/dist/cli/commands/ndjsonSink.d.ts +12 -0
  42. package/dist/cli/commands/ndjsonSink.js +29 -0
  43. package/dist/cli/commands/reasoningCommand.d.ts +44 -0
  44. package/dist/cli/commands/reasoningCommand.js +79 -0
  45. package/dist/cli/commands/runCommand.d.ts +14 -0
  46. package/dist/cli/commands/runCommand.js +56 -22
  47. package/dist/cli/commands/settingsSummary.js +2 -0
  48. package/dist/cli/commands/streaming/agentAttempt.d.ts +3 -0
  49. package/dist/cli/commands/streaming/agentAttempt.js +2 -2
  50. package/dist/cli/commands/streaming/assistantSegments.d.ts +0 -7
  51. package/dist/cli/commands/streaming/assistantSegments.js +1 -1
  52. package/dist/cli/commands/streaming/attemptLifecycle.js +13 -9
  53. package/dist/cli/commands/streaming/attemptOutcome.d.ts +2 -0
  54. package/dist/cli/commands/streaming/attemptOutcome.js +24 -9
  55. package/dist/cli/commands/streaming/attemptSetup.d.ts +4 -0
  56. package/dist/cli/commands/streaming/attemptSetup.js +21 -7
  57. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +14 -1
  58. package/dist/cli/commands/streaming/goalCheckpoint.js +4 -2
  59. package/dist/cli/commands/streaming/goalSupervisor.d.ts +9 -0
  60. package/dist/cli/commands/streaming/goalSupervisor.js +51 -10
  61. package/dist/cli/commands/streaming/prepareStep.d.ts +0 -3
  62. package/dist/cli/commands/streaming/prepareStep.js +14 -5
  63. package/dist/cli/commands/streaming/streamLoop.d.ts +5 -0
  64. package/dist/cli/commands/streaming/streamLoop.js +3 -0
  65. package/dist/cli/commands/streaming/toolPartHandlers.js +6 -0
  66. package/dist/cli/commands/streaming.d.ts +8 -3
  67. package/dist/cli/commands/streaming.js +46 -21
  68. package/dist/cli/commands/wizardFlow.d.ts +10 -0
  69. package/dist/cli/commands/wizardFlow.js +34 -5
  70. package/dist/cli/index.js +22 -2
  71. package/dist/config/contextFiles.d.ts +9 -0
  72. package/dist/config/contextFiles.js +21 -1
  73. package/dist/config/modelCatalog.d.ts +3 -0
  74. package/dist/config/modelCatalog.js +29 -0
  75. package/dist/config/modelDiscovery.js +68 -5
  76. package/dist/config/providerPresets.d.ts +1 -1
  77. package/dist/config/providerPresets.js +42 -3
  78. package/dist/config/settings.d.ts +14 -6
  79. package/dist/config/settings.js +16 -1
  80. package/dist/core/agent/budgets.d.ts +13 -17
  81. package/dist/core/agent/budgets.js +15 -19
  82. package/dist/core/agent/completionController.d.ts +14 -2
  83. package/dist/core/agent/completionController.js +48 -3
  84. package/dist/core/agent/events.d.ts +2 -1
  85. package/dist/core/agent/goalPolicy.d.ts +17 -0
  86. package/dist/core/agent/goalPolicy.js +53 -6
  87. package/dist/core/agent/projectPreflight.d.ts +2 -0
  88. package/dist/core/agent/projectPreflight.js +56 -0
  89. package/dist/core/agent/reasoningPolicy.d.ts +76 -10
  90. package/dist/core/agent/reasoningPolicy.js +72 -9
  91. package/dist/core/agent/toolCapabilities.d.ts +3 -3
  92. package/dist/core/agent/toolCapabilities.js +31 -7
  93. package/dist/core/agent/workState.d.ts +14 -4
  94. package/dist/core/agent/workState.js +229 -34
  95. package/dist/core/deadline.js +22 -24
  96. package/dist/core/providerContracts.d.ts +29 -0
  97. package/dist/core/providerContracts.js +1 -0
  98. package/dist/core/safety/secretPaths.js +10 -7
  99. package/dist/core/safety/shellClassifier.d.ts +2 -0
  100. package/dist/core/safety/shellClassifier.js +9 -1
  101. package/dist/core/session/sessionReport.d.ts +33 -0
  102. package/dist/core/session/sessionReport.js +121 -0
  103. package/dist/core/session/sessionSlimming.d.ts +2 -0
  104. package/dist/core/session/sessionSlimming.js +59 -4
  105. package/dist/core/session/sessionStore.d.ts +16 -8
  106. package/dist/core/session/sessionStore.js +71 -34
  107. package/dist/core/shellOutput/reducers/git.js +7 -2
  108. package/dist/core/shellOutput/reducers/validation.d.ts +1 -1
  109. package/dist/core/shellOutput/reducers/validation.js +14 -1
  110. package/dist/core/shellOutput/registry.js +3 -2
  111. package/dist/core/subagent/contracts.d.ts +3 -18
  112. package/dist/core/subagent/executionProfiles.js +4 -4
  113. package/dist/core/tasks/taskStorage.js +8 -1
  114. package/dist/core/validation/outputParser.d.ts +6 -1
  115. package/dist/core/validation/outputParser.js +30 -2
  116. package/dist/llm/client.d.ts +6 -3
  117. package/dist/llm/client.js +28 -11
  118. package/dist/llm/hazeTools.d.ts +9161 -7135
  119. package/dist/llm/hazeTools.js +6 -462
  120. package/dist/llm/lsp/client.d.ts +7 -1
  121. package/dist/llm/lsp/client.js +58 -9
  122. package/dist/llm/lsp/pool.d.ts +11 -0
  123. package/dist/llm/lsp/pool.js +61 -4
  124. package/dist/llm/lsp/protocol.d.ts +6 -23
  125. package/dist/llm/lsp/requests.d.ts +54 -60
  126. package/dist/llm/lsp/requests.js +152 -28
  127. package/dist/llm/lsp/symbols.d.ts +16 -0
  128. package/dist/llm/lsp/symbols.js +70 -0
  129. package/dist/llm/lsp/workspaceEdit.d.ts +43 -0
  130. package/dist/llm/lsp/workspaceEdit.js +117 -0
  131. package/dist/llm/lspTools.d.ts +7518 -2859
  132. package/dist/llm/lspTools.js +195 -110
  133. package/dist/llm/mcp.js +3 -0
  134. package/dist/llm/requestContext.d.ts +4 -3
  135. package/dist/llm/requestContext.js +9 -5
  136. package/dist/{core/subagent → llm}/subagentRunner.d.ts +13 -9
  137. package/dist/{core/subagent → llm}/subagentRunner.js +54 -49
  138. package/dist/llm/systemPrompt.d.ts +11 -1
  139. package/dist/llm/systemPrompt.js +4 -13
  140. package/dist/llm/tools/fetchTool.d.ts +34 -30
  141. package/dist/llm/tools/fileTools.d.ts +7768 -0
  142. package/dist/llm/tools/fileTools.js +510 -0
  143. package/dist/llm/tools/processTool.d.ts +34 -30
  144. package/dist/llm/tools/replaceInFiles.d.ts +105 -0
  145. package/dist/llm/tools/replaceInFiles.js +131 -0
  146. package/dist/llm/tools/shellTool.d.ts +34 -30
  147. package/dist/llm/tools/shellTool.js +8 -4
  148. package/dist/llm/tools/storedOutputTool.d.ts +4 -0
  149. package/dist/llm/tools/taskTool.d.ts +4 -0
  150. package/dist/llm/tools/toolContext.d.ts +3 -29
  151. package/dist/llm/tools/toolContext.js +56 -53
  152. package/dist/llm/tools/toolContextState.d.ts +40 -0
  153. package/dist/llm/tools/toolContextState.js +34 -0
  154. package/dist/llm/workerContext.d.ts +7 -0
  155. package/dist/llm/workerContext.js +18 -1
  156. package/dist/skills/SkillLoader.js +30 -4
  157. package/dist/skills/SkillRegistry.js +3 -3
  158. package/dist/skills/builder/SkillBuilder.js +3 -3
  159. package/dist/skills/confinement.d.ts +7 -0
  160. package/dist/skills/confinement.js +15 -0
  161. package/dist/ui/codeHighlight.js +4 -4
  162. package/dist/ui/components/MarkdownText.js +7 -8
  163. package/dist/ui/components/NativeIndicators.d.ts +15 -0
  164. package/dist/ui/components/NativeIndicators.js +32 -0
  165. package/dist/ui/components/StreamingMarkdownText.d.ts +9 -0
  166. package/dist/ui/components/StreamingMarkdownText.js +38 -0
  167. package/dist/ui/components/TextInput.d.ts +7 -2
  168. package/dist/ui/components/TextInput.js +103 -46
  169. package/dist/ui/components/WizardChoices.d.ts +18 -0
  170. package/dist/ui/components/WizardChoices.js +32 -0
  171. package/dist/ui/components/useInputSuggestions.js +18 -6
  172. package/dist/ui/inputBuffer.js +12 -6
  173. package/dist/ui/textGeometry.d.ts +14 -0
  174. package/dist/ui/textGeometry.js +31 -0
  175. package/dist/utils/buildInfo.js +29 -8
  176. package/dist/utils/fs.js +5 -1
  177. package/package.json +23 -22
  178. /package/dist/cli/{contextReport.d.ts → contextReportCli.d.ts} +0 -0
  179. /package/dist/cli/{contextReport.js → contextReportCli.js} +0 -0
@@ -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;
@@ -11,11 +11,21 @@ import { observeWorkToolEvent, type WorkState } from './workState.js';
11
11
  export type RequestIntent = 'implement' | 'fix' | 'test' | 'review' | 'plan' | 'answer' | 'unknown';
12
12
  export declare function isPlanOnlyRequest(value: string): boolean;
13
13
  export declare function classifyRequestIntent(value: string): RequestIntent;
14
+ /**
15
+ * Only broad implementation requests need a declared outcome ledger. Breadth
16
+ * needs two or more enumerated outcomes (bullet/numbered lines) — a single
17
+ * detailed item, however long, stays a quick focused edit.
18
+ */
19
+ export declare function requiresTaskLedger(request: string, intent: RequestIntent): boolean;
14
20
  export type SessionGoal = WorkState;
15
21
  export type GoalToolEvent = Parameters<typeof observeWorkToolEvent>[1];
16
22
  export declare function createSessionGoal(request: string, now?: number): SessionGoal;
17
23
  export declare function observeGoalToolEvent(goal: SessionGoal, event: GoalToolEvent, now?: number): WorkState;
18
24
  export declare function formatGoalStatus(goal: SessionGoal): string;
25
+ /** One-request direction for the active goal. The user request remains the source of truth. */
26
+ export declare function goalDirectionPrompt(intent: RequestIntent, compact: boolean): string;
27
+ /** A single mid-implementation nudge; the caller prevents repeats. */
28
+ export declare function earlyValidationPrompt(): string;
19
29
  export declare function toolLoopBudgetPrompt(): string;
20
30
  export declare function repeatedToolCallPrompt(toolNames: string[]): string;
21
31
  /**
@@ -32,6 +42,13 @@ export declare function lengthContinuationPrompt(): string;
32
42
  */
33
43
  export declare function completionRescuePrompt(): string;
34
44
  export declare function malformedToolCallPrompt(toolName: string, chunkBytes: number): string;
45
+ /**
46
+ * Ephemeral control for read-only edit recovery: a failed file mutation
47
+ * requested a fresh read before any further mutation. Names the exact path
48
+ * so the model re-reads it instead of retrying the stale edit. The tool set
49
+ * stays intact; the execution-time gate in toolContext is the enforcer.
50
+ */
51
+ export declare function editRecoveryReadPrompt(path: string): string;
35
52
  /**
36
53
  * Ephemeral control for a goal-continuation slice or a fresh continuation
37
54
  * turn. The model's stop was rejected (or its physical turn hit a budget
@@ -14,18 +14,36 @@ export function isPlanOnlyRequest(value) {
14
14
  export function classifyRequestIntent(value) {
15
15
  if (isPlanOnlyRequest(value))
16
16
  return 'plan';
17
- if (/\b(review|audit|inspect|analy[sz]e|compare)\b/i.test(value))
17
+ // A leading review request remains read-only unless it explicitly asks for
18
+ // follow-on changes. Incidental terms such as "how to build" are context.
19
+ if (/^\s*(?:please\s+)?(?:review|audit|inspect|analy[sz]e|compare)\b/i.test(value)
20
+ && !/\b(?:,|;|and|then)\s*(?:please\s+)?(?:fix|repair|implement|build|add|create|update|change)\b/i.test(value))
18
21
  return 'review';
19
22
  if (/\b(fix|repair|resolve|debug)\b/i.test(value))
20
23
  return 'fix';
21
- if (/\b(run|verify|check|validate)\b/i.test(value) || /\btests?\b/i.test(value) && !/\b(add|create|write)\b/i.test(value))
22
- return 'test';
23
- if (/\b(add|create|write|implement|update|change|support|wire|document|docs|documentation)\b/i.test(value))
24
+ // Creation verbs win over incidental words such as "run locally" or
25
+ // "test the app" in a larger implementation request.
26
+ if (/\b(add|create|write|implement|build|make|update|change|support|wire|document|docs|documentation|commit)\b/i.test(value))
24
27
  return 'implement';
28
+ if (/\b(review|audit|inspect|analy[sz]e|compare)\b/i.test(value))
29
+ return 'review';
30
+ if (/\b(run|verify|check|validate)\b/i.test(value) || /\btests?\b/i.test(value))
31
+ return 'test';
25
32
  if (/\b(what|why|how|explain|tell me)\b/i.test(value))
26
33
  return 'answer';
27
34
  return 'unknown';
28
35
  }
36
+ /**
37
+ * Only broad implementation requests need a declared outcome ledger. Breadth
38
+ * needs two or more enumerated outcomes (bullet/numbered lines) — a single
39
+ * detailed item, however long, stays a quick focused edit.
40
+ */
41
+ export function requiresTaskLedger(request, intent) {
42
+ if (intent !== 'implement' && intent !== 'fix')
43
+ return false;
44
+ const items = request.match(/(?:^|\n)\s*(?:[-*]|\d+[.)])\s+\S/g) ?? [];
45
+ return items.length >= 2;
46
+ }
29
47
  function shortRequest(value) {
30
48
  return value.replace(/\s+/g, ' ').trim().slice(0, 160) || 'current request';
31
49
  }
@@ -40,7 +58,9 @@ export function createSessionGoal(request, now = Date.now()) {
40
58
  : intent === 'answer'
41
59
  ? ['Answer the user using current project context when needed']
42
60
  : ['Inspect the relevant files', 'Make the requested change when needed', 'Validate the change when practical', 'Summarize only current-task changes and validation'];
43
- return createWorkState(request, intent, successCriteria, now);
61
+ const state = createWorkState(request, intent, successCriteria, now);
62
+ state.requiresTaskLedger = requiresTaskLedger(request, intent);
63
+ return state;
44
64
  }
45
65
  export function observeGoalToolEvent(goal, event, now = Date.now()) {
46
66
  return observeWorkToolEvent(goal, event, now);
@@ -54,6 +74,21 @@ export function formatGoalStatus(goal) {
54
74
  : 'done';
55
75
  return `Goal: ${shortRequest(goal.originalUserRequest)} · ${action}`;
56
76
  }
77
+ /** One-request direction for the active goal. The user request remains the source of truth. */
78
+ export function goalDirectionPrompt(intent, compact) {
79
+ if (intent === 'plan' || intent === 'review' || intent === 'answer')
80
+ return '';
81
+ return [
82
+ 'For this goal, turn the user\'s explicit requirements into observable outcomes. For substantial work, use writeTasks as the outcome ledger and keep it current.',
83
+ 'Implement one runnable slice, check it, then extend it. Run a relevant check before generating a large batch of dependent files. Keep failed checks open until the same check passes after the fix.',
84
+ 'For UI work, exercise a real interaction when a browser runner is available; otherwise name that coverage gap. Do not describe shadcn-style components as an installed shadcn system unless the project actually has one.',
85
+ compact ? 'Compact profile: handle a few files per slice, make one dependent tool decision at a time, prefer concise tool output and targeted reads, and keep the next action explicit.' : '',
86
+ ].filter(Boolean).join(' ');
87
+ }
88
+ /** A single mid-implementation nudge; the caller prevents repeats. */
89
+ export function earlyValidationPrompt() {
90
+ return 'Several files changed without a check. Run the smallest relevant build, test, typecheck, or direct artifact check now; use its result to guide the next slice.';
91
+ }
57
92
  // ── Completion/continuation control prompts ─────────────────────────────────
58
93
  // Keep these small and reusable; prefer one shared helper over embedding
59
94
  // near-identical model-facing control text in multiple loops. They are
@@ -88,6 +123,15 @@ export function malformedToolCallPrompt(toolName, chunkBytes) {
88
123
  : '';
89
124
  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
125
  }
126
+ /**
127
+ * Ephemeral control for read-only edit recovery: a failed file mutation
128
+ * requested a fresh read before any further mutation. Names the exact path
129
+ * so the model re-reads it instead of retrying the stale edit. The tool set
130
+ * stays intact; the execution-time gate in toolContext is the enforcer.
131
+ */
132
+ export function editRecoveryReadPrompt(path) {
133
+ 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.`;
134
+ }
91
135
  /**
92
136
  * Ephemeral control for a goal-continuation slice or a fresh continuation
93
137
  * turn. The model's stop was rejected (or its physical turn hit a budget
@@ -103,9 +147,12 @@ export function goalContinuationPrompt(reason, taskCounts, detail) {
103
147
  const validationLine = reason.includes('validation')
104
148
  ? ' No recognized post-edit validation was recorded. Run one standard test/build command, directly execute the changed artifact as one unchained command, or call shell with purpose=validation for a custom assertion check.'
105
149
  : '';
150
+ const ledgerLine = reason.includes('outcome list')
151
+ ? ' First call writeTasks with the concrete user-visible outcomes and their checks; keep the list until each outcome is complete.'
152
+ : '';
106
153
  const redLine = reason.includes('failing check')
107
154
  ? ' Rerun the same validation command that failed before the edit and resolve it; a different check does not close the captured red evidence.'
108
155
  : '';
109
156
  const detailLine = detail ? ` ${detail}` : '';
110
- return `Continue the active goal: haze rejected stopping because structured evidence shows this turn is not complete (${reason}).${validationLine}${redLine}${detailLine} Do not summarize again or restate what remains — resume the next concrete unfinished task now.${taskLine} If you declared a task list with writeTasks, its pending and in-progress items are commitments: complete them and update writeTasks at each meaningful phase change and at completion. After any further edits, run the smallest relevant validation and report its real outcome. Report a blocker only when it is a concrete external tool, permission, dependency, or environment failure; unfinished work is not a blocker.`;
157
+ return `Continue the active goal: haze rejected stopping because structured evidence shows this turn is not complete (${reason}).${validationLine}${ledgerLine}${redLine}${detailLine} Do not summarize again or restate what remains — resume the next concrete unfinished task now.${taskLine} If you declared a task list with writeTasks, its pending and in-progress items are commitments: complete them and update writeTasks at each meaningful phase change and at completion. After any further edits, run the smallest relevant validation and report its real outcome. Report a blocker only when it is a concrete external tool, permission, dependency, or environment failure; unfinished work is not a blocker.`;
111
158
  }
@@ -0,0 +1,2 @@
1
+ /** Read-only, bounded hints for a compact-profile model; never runs a command. */
2
+ export declare function projectPreflight(cwd: string): Promise<string>;
@@ -0,0 +1,56 @@
1
+ import fs from 'node:fs/promises';
2
+ import { constants } from 'node:fs';
3
+ import path from 'node:path';
4
+ const MAX_PACKAGE_BYTES = 64 * 1024;
5
+ const MAX_CHILD_DIRS = 12;
6
+ const MAX_SCRIPTS = 12;
7
+ async function scriptsAt(file) {
8
+ try {
9
+ // O_NOFOLLOW closes the lstat/read race for a symlinked package file on
10
+ // POSIX. Windows does not expose it, so the bounded read remains best
11
+ // effort there and the prompt still contains names only.
12
+ const noFollow = typeof constants.O_NOFOLLOW === 'number' ? constants.O_NOFOLLOW : 0;
13
+ const handle = await fs.open(file, constants.O_RDONLY | noFollow);
14
+ let content;
15
+ try {
16
+ const stat = await handle.stat();
17
+ if (!stat.isFile() || stat.size > MAX_PACKAGE_BYTES)
18
+ return undefined;
19
+ content = await handle.readFile('utf8');
20
+ }
21
+ finally {
22
+ await handle.close();
23
+ }
24
+ const parsed = JSON.parse(content);
25
+ if (typeof parsed !== 'object' || parsed === null || !('scripts' in parsed))
26
+ return [];
27
+ const scripts = parsed.scripts;
28
+ if (typeof scripts !== 'object' || scripts === null || Array.isArray(scripts))
29
+ return [];
30
+ return Object.entries(scripts).filter(([name, value]) => /^[A-Za-z0-9:._/-]{1,80}$/.test(name) && typeof value === 'string').map(([name]) => name).sort().slice(0, MAX_SCRIPTS);
31
+ }
32
+ catch {
33
+ return undefined;
34
+ }
35
+ }
36
+ /** Read-only, bounded hints for a compact-profile model; never runs a command. */
37
+ export async function projectPreflight(cwd) {
38
+ const packages = [];
39
+ const rootScripts = await scriptsAt(path.join(cwd, 'package.json'));
40
+ if (rootScripts)
41
+ packages.push(`.: ${rootScripts.join(', ') || '(no scripts)'}`);
42
+ try {
43
+ const children = (await fs.readdir(cwd, { withFileTypes: true }))
44
+ .filter(entry => entry.isDirectory() && entry.name.length <= 80 && !entry.name.startsWith('.') && entry.name !== 'node_modules')
45
+ .map(entry => entry.name).sort().slice(0, MAX_CHILD_DIRS);
46
+ for (const child of children) {
47
+ const scripts = await scriptsAt(path.join(cwd, child, 'package.json'));
48
+ if (scripts)
49
+ packages.push(`${child}: ${scripts.join(', ') || '(no scripts)'}`);
50
+ }
51
+ }
52
+ catch {
53
+ // A missing/unreadable workspace remains a normal tool error later.
54
+ }
55
+ return packages.length ? `<project_preflight>Package scripts by directory (names only; verify before running): ${packages.join(' | ')}</project_preflight>` : '';
56
+ }
@@ -1,10 +1,46 @@
1
- import type { ProviderCapabilities } from '../subagent/contracts.js';
1
+ import type { ProviderCapabilities } from '../providerContracts.js';
2
+ export type { ProviderCapabilities } from '../providerContracts.js';
2
3
  /**
3
- * Provider-neutral reasoning-depth setting. Unset by default; explicitly user
4
- * controlled. Mapped to a supported provider protocol (not a model name).
4
+ * Provider-neutral reasoning-depth levels (the AI SDK `reasoning` enum minus
5
+ * `provider-default`). `'none'` is an explicit request to disable reasoning;
6
+ * the stored `provider-default` sentinel means "send no parameter at all".
5
7
  */
6
- export type ReasoningLevel = 'low' | 'medium' | 'high';
8
+ export type ReasoningLevel = 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';
9
+ export declare const REASONING_LEVELS: readonly ReasoningLevel[];
10
+ /**
11
+ * Level applied when nothing more specific exists: no session per-model
12
+ * override and no `reasoning` settings key. Users opt out with an explicit
13
+ * `none` (reasoning off) or the stored `provider-default` sentinel (written by
14
+ * `/reasoning unset`); key-absent means this default.
15
+ */
16
+ export declare const DEFAULT_REASONING_LEVEL: ReasoningLevel;
17
+ /** Value the settings file may store: a level or the `provider-default` sentinel. */
18
+ export type StoredReasoningSetting = ReasoningLevel | 'provider-default';
19
+ /** Stored sentinel meaning "send no reasoning parameter at all". */
20
+ export declare const REASONING_PROVIDER_DEFAULT: "provider-default";
21
+ export declare function isStoredReasoning(value: unknown): value is StoredReasoningSetting;
22
+ /**
23
+ * The level a session actually requests: the stored setting when present, the
24
+ * default when the key is absent. The `provider-default` sentinel maps to
25
+ * undefined — no parameter is sent.
26
+ */
27
+ export declare function effectiveRequestedReasoning(setting: StoredReasoningSetting | undefined): ReasoningLevel | undefined;
7
28
  export type EffectiveReasoning = ReasoningLevel | 'disabled';
29
+ export type ReasoningSource = 'session' | 'settings' | 'default';
30
+ export interface ResolvedReasoningChoice {
31
+ /** The winning stored value, if any (undefined when nothing was set). */
32
+ setting: StoredReasoningSetting | undefined;
33
+ /** The level that will be requested; undefined when the sentinel means "send no parameter". */
34
+ level: ReasoningLevel | undefined;
35
+ /** Where the winner came from. */
36
+ source: ReasoningSource;
37
+ }
38
+ /**
39
+ * Resolve the reasoning choice for one model: the session per-model override
40
+ * (`/reasoning`, keyed `provider:model`) wins, then the global `reasoning`
41
+ * setting, then the built-in default. Pure; callers pass validated values.
42
+ */
43
+ export declare function resolveReasoningChoice(sessionOverride: StoredReasoningSetting | undefined, storedSetting: StoredReasoningSetting | undefined): ResolvedReasoningChoice;
8
44
  export interface ResolvedReasoningPolicy {
9
45
  /** What the user requested, if anything. */
10
46
  requested: ReasoningLevel | undefined;
@@ -15,17 +51,47 @@ export interface ResolvedReasoningPolicy {
15
51
  }
16
52
  /**
17
53
  * 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.
54
+ * capability based: only protocols that accept the reasoning parameter receive
55
+ * a level; everything else is disabled (the parameter is omitted entirely,
56
+ * never sent in a shape the protocol does not define). No model-name branching.
21
57
  */
22
58
  export declare function resolveReasoningPolicy(input: {
23
59
  requested: ReasoningLevel | undefined;
24
60
  capabilities: ProviderCapabilities;
25
61
  }): ResolvedReasoningPolicy;
26
62
  /**
27
- * The provider-option fragment to merge into request settings for a resolved
28
- * policy. Returns undefined when disabled so unsupported protocols send nothing.
63
+ * The AI SDK top-level `reasoning` call setting for a resolved policy.
64
+ * Returns undefined when disabled so unsupported or unrequested turns omit the
65
+ * parameter entirely. Never returns `'provider-default'` today; the sentinel
66
+ * stays in the return type for forward compatibility.
67
+ */
68
+ export declare function reasoningCallSetting(policy: ResolvedReasoningPolicy): ReasoningLevel | 'provider-default' | undefined;
69
+ /**
70
+ * The single pure resolver for the full reasoning precedence chain
71
+ * (AGENTS-documented order): run-scoped override → session per-model map
72
+ * (`provider:model`, in-memory only) → saved global `reasoning` setting →
73
+ * built-in default. `llm/client.ts` calls this; `/reasoning` and the status
74
+ * bar call `resolveReasoningChoice` on the same inputs.
29
75
  */
30
- export declare function reasoningProviderOptions(policy: ResolvedReasoningPolicy): Record<string, unknown> | undefined;
76
+ export declare function resolveAttemptReasoning(input: {
77
+ modelSelector: string;
78
+ runOverride?: StoredReasoningSetting;
79
+ sessionReasoningByModel?: Record<string, StoredReasoningSetting>;
80
+ globalSetting?: StoredReasoningSetting;
81
+ }): StoredReasoningSetting | undefined;
31
82
  export declare function isReasoningLevel(value: unknown): value is ReasoningLevel;
83
+ /** Aliases accepted by CLI paths (`/reasoning`, `--reasoning`) for "send no reasoning parameter". */
84
+ export declare function isReasoningUnsetAlias(value: string): boolean;
85
+ export type ParsedReasoningOverride = {
86
+ ok: true;
87
+ setting: StoredReasoningSetting;
88
+ } | {
89
+ ok: false;
90
+ error: string;
91
+ };
92
+ /**
93
+ * Parse a `--reasoning` CLI value (case-insensitive): a level maps directly,
94
+ * the unset aliases mean "send no reasoning parameter for this run". Shared by
95
+ * the commander flag surface and the headless option validation.
96
+ */
97
+ export declare function parseReasoningOverride(raw: string): ParsedReasoningOverride;
@@ -1,8 +1,43 @@
1
+ export const REASONING_LEVELS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh'];
2
+ /**
3
+ * Level applied when nothing more specific exists: no session per-model
4
+ * override and no `reasoning` settings key. Users opt out with an explicit
5
+ * `none` (reasoning off) or the stored `provider-default` sentinel (written by
6
+ * `/reasoning unset`); key-absent means this default.
7
+ */
8
+ export const DEFAULT_REASONING_LEVEL = 'medium';
9
+ /** Stored sentinel meaning "send no reasoning parameter at all". */
10
+ export const REASONING_PROVIDER_DEFAULT = 'provider-default';
11
+ export function isStoredReasoning(value) {
12
+ return isReasoningLevel(value) || value === REASONING_PROVIDER_DEFAULT;
13
+ }
14
+ /**
15
+ * The level a session actually requests: the stored setting when present, the
16
+ * default when the key is absent. The `provider-default` sentinel maps to
17
+ * undefined — no parameter is sent.
18
+ */
19
+ export function effectiveRequestedReasoning(setting) {
20
+ if (setting === REASONING_PROVIDER_DEFAULT)
21
+ return undefined;
22
+ return setting ?? DEFAULT_REASONING_LEVEL;
23
+ }
24
+ /**
25
+ * Resolve the reasoning choice for one model: the session per-model override
26
+ * (`/reasoning`, keyed `provider:model`) wins, then the global `reasoning`
27
+ * setting, then the built-in default. Pure; callers pass validated values.
28
+ */
29
+ export function resolveReasoningChoice(sessionOverride, storedSetting) {
30
+ if (sessionOverride !== undefined)
31
+ return { setting: sessionOverride, level: effectiveRequestedReasoning(sessionOverride), source: 'session' };
32
+ if (storedSetting !== undefined)
33
+ return { setting: storedSetting, level: effectiveRequestedReasoning(storedSetting), source: 'settings' };
34
+ return { setting: undefined, level: DEFAULT_REASONING_LEVEL, source: 'default' };
35
+ }
1
36
  /**
2
37
  * 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.
38
+ * capability based: only protocols that accept the reasoning parameter receive
39
+ * a level; everything else is disabled (the parameter is omitted entirely,
40
+ * never sent in a shape the protocol does not define). No model-name branching.
6
41
  */
7
42
  export function resolveReasoningPolicy(input) {
8
43
  const { requested, capabilities } = input;
@@ -13,15 +48,43 @@ export function resolveReasoningPolicy(input) {
13
48
  return { requested, effective: requested, reason: 'applied via supported provider protocol' };
14
49
  }
15
50
  /**
16
- * The provider-option fragment to merge into request settings for a resolved
17
- * policy. Returns undefined when disabled so unsupported protocols send nothing.
51
+ * The AI SDK top-level `reasoning` call setting for a resolved policy.
52
+ * Returns undefined when disabled so unsupported or unrequested turns omit the
53
+ * parameter entirely. Never returns `'provider-default'` today; the sentinel
54
+ * stays in the return type for forward compatibility.
18
55
  */
19
- export function reasoningProviderOptions(policy) {
56
+ export function reasoningCallSetting(policy) {
20
57
  if (policy.effective === 'disabled')
21
58
  return undefined;
22
- return { openai: { reasoningEffort: policy.effective } };
59
+ return policy.effective;
60
+ }
61
+ /**
62
+ * The single pure resolver for the full reasoning precedence chain
63
+ * (AGENTS-documented order): run-scoped override → session per-model map
64
+ * (`provider:model`, in-memory only) → saved global `reasoning` setting →
65
+ * built-in default. `llm/client.ts` calls this; `/reasoning` and the status
66
+ * bar call `resolveReasoningChoice` on the same inputs.
67
+ */
68
+ export function resolveAttemptReasoning(input) {
69
+ return input.runOverride ?? input.sessionReasoningByModel?.[input.modelSelector] ?? input.globalSetting;
23
70
  }
24
- const LEVELS = ['low', 'medium', 'high'];
25
71
  export function isReasoningLevel(value) {
26
- return typeof value === 'string' && LEVELS.includes(value);
72
+ return typeof value === 'string' && REASONING_LEVELS.includes(value);
73
+ }
74
+ /** Aliases accepted by CLI paths (`/reasoning`, `--reasoning`) for "send no reasoning parameter". */
75
+ export function isReasoningUnsetAlias(value) {
76
+ return value === 'unset' || value === 'off' || value === REASONING_PROVIDER_DEFAULT;
77
+ }
78
+ /**
79
+ * Parse a `--reasoning` CLI value (case-insensitive): a level maps directly,
80
+ * the unset aliases mean "send no reasoning parameter for this run". Shared by
81
+ * the commander flag surface and the headless option validation.
82
+ */
83
+ export function parseReasoningOverride(raw) {
84
+ const value = raw.trim().toLowerCase();
85
+ if (isReasoningUnsetAlias(value))
86
+ return { ok: true, setting: REASONING_PROVIDER_DEFAULT };
87
+ if (isReasoningLevel(value))
88
+ return { ok: true, setting: value };
89
+ return { ok: false, error: `Unknown reasoning level "${raw.trim()}". Valid levels: ${REASONING_LEVELS.join(', ')} — or unset for the provider default.` };
27
90
  }
@@ -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,9 +18,12 @@ 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;
25
+ /** Stable, non-reversible identity safe to carry in a goal checkpoint. */
26
+ export declare function validationCheckId(command: string): string;
24
27
  /**
25
28
  * Opportunistic red→green state for fix intents: no failing repro is required,
26
29
  * but when a pre-mutation validation did fail, that same check must pass after
@@ -35,6 +38,8 @@ export interface WorkState {
35
38
  intent: RequestIntent;
36
39
  normalizedIntent: RequestIntent;
37
40
  successCriteria: string[];
41
+ /** Broad requests must declare and finish an outcome list through writeTasks. */
42
+ requiresTaskLedger?: boolean;
38
43
  constraints: string[];
39
44
  decisions: Array<{
40
45
  decision: string;
@@ -76,12 +81,16 @@ export interface WorkState {
76
81
  * logical goal (see the goal supervisor). Used by `deriveValidationOutcome`
77
82
  * only while this turn itself has recorded no validation; a fresh
78
83
  * validation this turn supersedes it. Bounded to status/kind — never a
79
- * command or output.
84
+ * command or output. `kind` keeps cross-turn parity with the in-turn rule
85
+ * that a generic (self-declared) pass cannot clear a confirmed failure
86
+ * (R2-03).
80
87
  */
81
88
  carriedValidation?: {
82
89
  status: 'passed' | 'failed';
83
90
  kind?: ValidationKind;
84
91
  };
92
+ /** Failed confirmed checks from earlier physical turns, identified without persisting commands. */
93
+ carriedFailedCheckIds?: string[];
85
94
  /** Captured pre-mutation failing repro for fix goals. Optional, but same-check green is required when present. */
86
95
  redEvidence?: RedEvidence;
87
96
  /** Single source of truth for blockers; the most recent entry is the current one (CR-023). */
@@ -113,6 +122,8 @@ export declare function seedCarriedGoalEvidence(state: WorkState, carried: {
113
122
  validationOutcome: ValidationOutcome;
114
123
  taskProgress?: WorkTaskProgress;
115
124
  redEvidence?: RedEvidence;
125
+ validationKind?: ValidationKind;
126
+ failedCheckIds?: string[];
116
127
  }): void;
117
128
  export interface WorkToolEvent {
118
129
  toolName: string;
@@ -121,8 +132,6 @@ export interface WorkToolEvent {
121
132
  output?: unknown;
122
133
  duplicateSkipped?: boolean;
123
134
  }
124
- /** Strictly recognize direct execution of one file changed during this goal. */
125
- export declare function executedMutatedArtifact(command: string, state: WorkState): string | undefined;
126
135
  /** Extract a classifier-confirmed validation summary from a tool output, if any. */
127
136
  export declare function validationSummaryFromOutput(output: unknown): ValidationSummary | undefined;
128
137
  export declare function createWorkState(goal: string, intent: RequestIntent, successCriteria: string[], now?: number): WorkState;
@@ -135,5 +144,6 @@ export declare function taskProgressFromOutput(output: unknown, revision: number
135
144
  * ordering so a result that predates the latest mutation is `stale`.
136
145
  */
137
146
  export declare function deriveValidationOutcome(state: WorkState): ValidationOutcome;
147
+ export declare function unresolvedFailedCheckIds(state: WorkState): string[];
138
148
  export declare function workStatePrompt(state: WorkState): string;
139
149
  export {};