@denizokcu/haze 0.9.0 → 0.11.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 (241) hide show
  1. package/CHANGELOG.md +133 -17
  2. package/README.md +164 -68
  3. package/SECURITY.md +22 -0
  4. package/bin/haze.js +102 -1
  5. package/dist/buildInfo.json +7 -0
  6. package/dist/cli/chat/TaskBar.d.ts +2 -1
  7. package/dist/cli/chat/TaskBar.js +7 -4
  8. package/dist/cli/chat/chatMetrics.d.ts +17 -1
  9. package/dist/cli/chat/chatMetrics.js +22 -5
  10. package/dist/cli/chat/contextReport.d.ts +11 -0
  11. package/dist/cli/chat/contextReport.js +46 -0
  12. package/dist/cli/chat/fileMentionSuggestions.d.ts +29 -0
  13. package/dist/cli/chat/fileMentionSuggestions.js +92 -0
  14. package/dist/cli/chat/inputSuggestions.d.ts +5 -0
  15. package/dist/cli/chat/inputSuggestions.js +17 -3
  16. package/dist/cli/chat/liveRegion.d.ts +25 -0
  17. package/dist/cli/chat/liveRegion.js +48 -0
  18. package/dist/cli/chat/messages.d.ts +33 -2
  19. package/dist/cli/chat/messages.js +216 -33
  20. package/dist/cli/chat/sessionLifecycle.d.ts +67 -0
  21. package/dist/cli/chat/sessionLifecycle.js +205 -0
  22. package/dist/cli/chat/sessionRecorder.js +80 -14
  23. package/dist/cli/chat/startupInfo.js +11 -4
  24. package/dist/cli/chat/tips.d.ts +21 -0
  25. package/dist/cli/chat/tips.js +43 -0
  26. package/dist/cli/chat/wizardDispatch.d.ts +64 -0
  27. package/dist/cli/chat/wizardDispatch.js +744 -0
  28. package/dist/cli/commands/chat.d.ts +6 -0
  29. package/dist/cli/commands/chat.js +373 -790
  30. package/dist/cli/commands/chatModes.d.ts +1 -1
  31. package/dist/cli/commands/chatModes.js +7 -2
  32. package/dist/cli/commands/commandHelp.js +5 -3
  33. package/dist/cli/commands/commands.d.ts +5 -2
  34. package/dist/cli/commands/commands.js +22 -18
  35. package/dist/cli/commands/doctor.d.ts +19 -0
  36. package/dist/cli/commands/doctor.js +76 -0
  37. package/dist/cli/commands/fleetCommand.d.ts +14 -0
  38. package/dist/cli/commands/fleetCommand.js +46 -0
  39. package/dist/cli/commands/formatters.d.ts +5 -0
  40. package/dist/cli/commands/formatters.js +35 -6
  41. package/dist/cli/commands/logsCommand.js +1 -7
  42. package/dist/cli/commands/modelCommand.js +1 -1
  43. package/dist/cli/commands/ndjsonSink.d.ts +23 -0
  44. package/dist/cli/commands/ndjsonSink.js +38 -0
  45. package/dist/cli/commands/providerWizard.d.ts +10 -2
  46. package/dist/cli/commands/providerWizard.js +50 -4
  47. package/dist/cli/commands/runCommand.d.ts +4 -0
  48. package/dist/cli/commands/runCommand.js +142 -16
  49. package/dist/cli/commands/sessionPicker.d.ts +9 -0
  50. package/dist/cli/commands/sessionPicker.js +29 -0
  51. package/dist/cli/commands/settingsSummary.js +6 -4
  52. package/dist/cli/commands/skillConfirmRemove.js +4 -3
  53. package/dist/cli/commands/skillWizard.d.ts +2 -0
  54. package/dist/cli/commands/skillWizard.js +16 -6
  55. package/dist/cli/commands/streaming/abortCause.d.ts +24 -0
  56. package/dist/cli/commands/streaming/abortCause.js +16 -0
  57. package/dist/cli/commands/streaming/assistantText.js +9 -2
  58. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +65 -0
  59. package/dist/cli/commands/streaming/goalCheckpoint.js +23 -0
  60. package/dist/cli/commands/streaming/goalSupervisor.d.ts +64 -0
  61. package/dist/cli/commands/streaming/goalSupervisor.js +127 -0
  62. package/dist/cli/commands/streaming/idleTimer.d.ts +26 -0
  63. package/dist/cli/commands/streaming/idleTimer.js +24 -0
  64. package/dist/cli/commands/streaming/toolCallRecovery.d.ts +2 -0
  65. package/dist/cli/commands/streaming/toolCallRecovery.js +24 -0
  66. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +31 -0
  67. package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -2
  68. package/dist/cli/commands/streaming/toolResultState.d.ts +6 -1
  69. package/dist/cli/commands/streaming/toolResultState.js +29 -7
  70. package/dist/cli/commands/streaming/turnOutcome.d.ts +17 -0
  71. package/dist/cli/commands/streaming/turnOutcome.js +27 -11
  72. package/dist/cli/commands/streaming/turnRuntime.js +6 -4
  73. package/dist/cli/commands/streaming.d.ts +82 -3
  74. package/dist/cli/commands/streaming.js +528 -91
  75. package/dist/cli/commands/wizardActions.d.ts +7 -0
  76. package/dist/cli/commands/wizardActions.js +7 -0
  77. package/dist/cli/commands/wizardPrompts.js +7 -1
  78. package/dist/cli/commands/wizardSuggestions.d.ts +8 -0
  79. package/dist/cli/commands/wizardSuggestions.js +64 -14
  80. package/dist/cli/commands/wizardTransition.d.ts +4 -0
  81. package/dist/cli/commands/wizardTransition.js +1 -2
  82. package/dist/cli/index.js +82 -22
  83. package/dist/cli/terminalTitle.d.ts +6 -0
  84. package/dist/cli/terminalTitle.js +36 -0
  85. package/dist/config/inputHistory.d.ts +3 -3
  86. package/dist/config/inputHistory.js +12 -18
  87. package/dist/config/modelDiscovery.d.ts +71 -0
  88. package/dist/config/modelDiscovery.js +214 -0
  89. package/dist/config/privateStorage.js +28 -2
  90. package/dist/config/providerAuth.d.ts +14 -0
  91. package/dist/config/providerAuth.js +49 -0
  92. package/dist/config/providerPresets.d.ts +49 -5
  93. package/dist/config/providerPresets.js +573 -73
  94. package/dist/config/providers.d.ts +2 -0
  95. package/dist/config/providers.js +9 -0
  96. package/dist/config/settings.d.ts +58 -0
  97. package/dist/config/settings.js +38 -1
  98. package/dist/config/skillSettings.d.ts +6 -13
  99. package/dist/config/skillSettings.js +20 -19
  100. package/dist/core/agent/budgets.d.ts +36 -0
  101. package/dist/core/agent/budgets.js +44 -0
  102. package/dist/core/agent/compaction.d.ts +38 -0
  103. package/dist/core/agent/compaction.js +108 -19
  104. package/dist/core/agent/completionController.d.ts +230 -0
  105. package/dist/core/agent/completionController.js +287 -0
  106. package/dist/core/agent/contextBudget.d.ts +46 -0
  107. package/dist/core/agent/contextBudget.js +89 -7
  108. package/dist/core/agent/errors.js +6 -2
  109. package/dist/core/agent/events.d.ts +86 -0
  110. package/dist/core/agent/reasoningPolicy.d.ts +31 -0
  111. package/dist/core/agent/reasoningPolicy.js +27 -0
  112. package/dist/core/agent/toolCapabilities.d.ts +27 -0
  113. package/dist/core/agent/toolCapabilities.js +58 -0
  114. package/dist/core/agent/toolExecutionBudget.d.ts +35 -0
  115. package/dist/core/agent/toolExecutionBudget.js +49 -0
  116. package/dist/core/agent/toolOutputStore.d.ts +13 -0
  117. package/dist/core/agent/toolOutputStore.js +27 -10
  118. package/dist/core/agent/toolResults.d.ts +12 -0
  119. package/dist/core/agent/toolResults.js +38 -0
  120. package/dist/core/agent/turnBudget.d.ts +35 -0
  121. package/dist/core/agent/turnBudget.js +27 -0
  122. package/dist/core/agent/turnPolicy.d.ts +11 -0
  123. package/dist/core/agent/turnPolicy.js +19 -0
  124. package/dist/core/agent/workState.d.ts +76 -1
  125. package/dist/core/agent/workState.js +120 -13
  126. package/dist/core/attachments/imageAttachments.d.ts +90 -0
  127. package/dist/core/attachments/imageAttachments.js +245 -0
  128. package/dist/core/attachments/readBlessings.d.ts +37 -0
  129. package/dist/core/attachments/readBlessings.js +79 -0
  130. package/dist/core/deadline.d.ts +33 -0
  131. package/dist/core/deadline.js +74 -0
  132. package/dist/core/goal/completionPolicy.d.ts +27 -0
  133. package/dist/core/goal/completionPolicy.js +37 -1
  134. package/dist/core/goal/requestClassifier.d.ts +0 -3
  135. package/dist/core/goal/requestClassifier.js +0 -13
  136. package/dist/core/io/boundedRead.js +76 -29
  137. package/dist/core/limits/byteBudgets.d.ts +7 -0
  138. package/dist/core/limits/byteBudgets.js +7 -0
  139. package/dist/core/limits/textBudgets.d.ts +25 -0
  140. package/dist/core/limits/textBudgets.js +25 -0
  141. package/dist/core/log/llmLog.js +7 -0
  142. package/dist/core/persistence/orderedFileWriter.d.ts +10 -0
  143. package/dist/core/persistence/orderedFileWriter.js +16 -2
  144. package/dist/core/process/backgroundRegistry.d.ts +35 -0
  145. package/dist/core/process/backgroundRegistry.js +195 -0
  146. package/dist/core/process/runBoundedProcess.d.ts +9 -0
  147. package/dist/core/process/runBoundedProcess.js +74 -29
  148. package/dist/core/safety/missingExecutable.d.ts +42 -0
  149. package/dist/core/safety/missingExecutable.js +77 -0
  150. package/dist/core/safety/urlGuard.d.ts +2 -1
  151. package/dist/core/safety/urlGuard.js +3 -2
  152. package/dist/core/session/sessionSlimming.js +47 -4
  153. package/dist/core/session/sessionStore.d.ts +74 -0
  154. package/dist/core/session/sessionStore.js +268 -18
  155. package/dist/core/subagent/contracts.d.ts +120 -0
  156. package/dist/core/subagent/contracts.js +55 -0
  157. package/dist/core/subagent/executionProfiles.d.ts +28 -0
  158. package/dist/core/subagent/executionProfiles.js +45 -0
  159. package/dist/core/subagent/subagentCoordinator.d.ts +78 -0
  160. package/dist/core/subagent/subagentCoordinator.js +164 -0
  161. package/dist/core/subagent/subagentRunner.d.ts +211 -145
  162. package/dist/core/subagent/subagentRunner.js +208 -98
  163. package/dist/core/subagent/workspaceMutationPolicy.d.ts +11 -0
  164. package/dist/core/subagent/workspaceMutationPolicy.js +52 -0
  165. package/dist/core/tasks/taskStorage.js +12 -1
  166. package/dist/llm/client.d.ts +36 -29
  167. package/dist/llm/client.js +102 -33
  168. package/dist/llm/hazeTools.d.ts +2559 -150
  169. package/dist/llm/hazeTools.js +119 -31
  170. package/dist/llm/lsp.d.ts +26 -4
  171. package/dist/llm/lsp.js +90 -14
  172. package/dist/llm/lspTools.d.ts +2366 -0
  173. package/dist/llm/lspTools.js +87 -79
  174. package/dist/llm/openaiCodex.d.ts +3 -0
  175. package/dist/llm/openaiCodex.js +47 -0
  176. package/dist/llm/openaiCodexOAuth.d.ts +54 -0
  177. package/dist/llm/openaiCodexOAuth.js +214 -0
  178. package/dist/llm/requestContext.d.ts +25 -1
  179. package/dist/llm/requestContext.js +51 -8
  180. package/dist/llm/systemPrompt.d.ts +15 -1
  181. package/dist/llm/systemPrompt.js +24 -8
  182. package/dist/llm/toolResultTypes.d.ts +8 -1
  183. package/dist/llm/tools/bashTool.d.ts +906 -32
  184. package/dist/llm/tools/bashTool.js +30 -4
  185. package/dist/llm/tools/editMatch.d.ts +14 -0
  186. package/dist/llm/tools/editMatch.js +72 -0
  187. package/dist/llm/tools/failures.d.ts +2 -0
  188. package/dist/llm/tools/failures.js +1 -0
  189. package/dist/llm/tools/fetchTool.d.ts +42 -26
  190. package/dist/llm/tools/fetchTool.js +1 -1
  191. package/dist/llm/tools/fileToolShared.d.ts +6 -4
  192. package/dist/llm/tools/fileToolShared.js +18 -23
  193. package/dist/llm/tools/gitIgnore.d.ts +49 -0
  194. package/dist/llm/tools/gitIgnore.js +129 -0
  195. package/dist/llm/tools/grepRunner.d.ts +5 -0
  196. package/dist/llm/tools/grepRunner.js +52 -71
  197. package/dist/llm/tools/outputCap.d.ts +2 -6
  198. package/dist/llm/tools/outputCap.js +2 -6
  199. package/dist/llm/tools/processTool.d.ts +1077 -0
  200. package/dist/llm/tools/processTool.js +41 -0
  201. package/dist/llm/tools/readRecovery.d.ts +10 -0
  202. package/dist/llm/tools/readRecovery.js +135 -0
  203. package/dist/llm/tools/toolContext.d.ts +9 -1
  204. package/dist/llm/tools/toolContext.js +83 -43
  205. package/dist/llm/tools/workspaceFile.d.ts +9 -1
  206. package/dist/llm/tools/workspaceFile.js +33 -4
  207. package/dist/llm/webFetch.d.ts +17 -0
  208. package/dist/llm/webFetch.js +66 -86
  209. package/dist/llm/workerContext.d.ts +18 -0
  210. package/dist/llm/workerContext.js +55 -0
  211. package/dist/skills/SkillLoader.d.ts +2 -2
  212. package/dist/skills/SkillRegistry.d.ts +3 -2
  213. package/dist/skills/SkillRegistry.js +43 -13
  214. package/dist/skills/builder/SkillBuilder.d.ts +3 -0
  215. package/dist/skills/builder/SkillBuilder.js +23 -5
  216. package/dist/skills/skillTools.js +11 -4
  217. package/dist/skills/types.d.ts +6 -1
  218. package/dist/ui/codeHighlight.d.ts +4 -0
  219. package/dist/ui/codeHighlight.js +31 -0
  220. package/dist/ui/components/Header.d.ts +1 -1
  221. package/dist/ui/components/MarkdownText.d.ts +16 -2
  222. package/dist/ui/components/MarkdownText.js +244 -34
  223. package/dist/ui/components/TextInput.d.ts +12 -2
  224. package/dist/ui/components/TextInput.js +80 -8
  225. package/dist/ui/theme.d.ts +4 -3
  226. package/dist/ui/theme.js +5 -4
  227. package/dist/utils/buildInfo.d.ts +104 -0
  228. package/dist/utils/buildInfo.js +253 -0
  229. package/dist/utils/format.d.ts +2 -0
  230. package/dist/utils/format.js +8 -0
  231. package/dist/utils/fs.d.ts +9 -1
  232. package/dist/utils/fs.js +87 -29
  233. package/dist/utils/openPath.d.ts +2 -0
  234. package/dist/utils/openPath.js +22 -0
  235. package/dist/utils/path.d.ts +2 -0
  236. package/dist/utils/path.js +5 -1
  237. package/dist/utils/utf8.d.ts +22 -0
  238. package/dist/utils/utf8.js +54 -0
  239. package/dist/utils/version.d.ts +9 -3
  240. package/dist/utils/version.js +28 -2
  241. package/package.json +24 -19
@@ -1,127 +1,237 @@
1
- import { streamText, isStepCount, tool } from 'ai';
2
- import { z } from 'zod';
3
- import { buildSubagentPrompt } from '../../llm/systemPrompt.js';
1
+ import { generateText, isStepCount, tool } from 'ai';
2
+ import { estimateToolSchemas, estimateValueTokens } from '../agent/contextBudget.js';
3
+ import { SUBAGENT_MAX_STEPS, SUBAGENT_MIN_STEPS, SUBAGENT_SYNTHESIS_RESERVE, SUBAGENT_TOOL_ONLY_LIMIT, } from '../agent/budgets.js';
4
+ import { storeToolOutput } from '../agent/toolOutputStore.js';
5
+ import { withSyntheticControl } from '../agent/requestAssembly.js';
6
+ import { toolOnlyStepCount } from '../agent/turnPolicy.js';
7
+ import { createToolExecutionBudget, isToolBudgetBlocked, withToolExecutionBudget } from '../agent/toolExecutionBudget.js';
8
+ import { assembleWorkerContext, workerTaskMessage } from '../../llm/workerContext.js';
9
+ import { buildSubagentPrompt, projectContextSection } from '../../llm/systemPrompt.js';
4
10
  import { hazeTools } from '../../llm/hazeTools.js';
5
11
  import { toolsContextFor } from '../../llm/tools/toolContext.js';
6
- import { toolOnlyStepCount } from '../agent/turnPolicy.js';
7
- const ALL_TOOLS = ['listFiles', 'readFile', 'grep', 'bash', 'readToolOutput', 'editFile', 'replaceLines', 'writeFile', 'fetch'];
8
- const STEP_LIMIT = 25;
9
- const MAX_SUMMARY = 4000;
10
- const TOOL_ONLY_LIMIT = 12;
12
+ import { fallbackWorkerRuntime, normalizeSubagentInput, subagentInputSchema, withLegacyProjection, } from './contracts.js';
13
+ import { COMPATIBILITY_PROFILE, MODE_TOOL_NAMES } from './executionProfiles.js';
14
+ import { SubagentCoordinator } from './subagentCoordinator.js';
15
+ import { resolveWorkspacePath, workspaceRelativePath } from '../../utils/path.js';
16
+ const SYNTHESIS_DIRECTIVE = 'You have reached your tool/step budget. Stop calling tools. Return the requested self-contained deliverable now, including evidence, coverage gaps, changed paths, validation, and precise remaining work. A concise partial deliverable is mandatory and better than an empty response.';
11
17
  function toolSummary(output) {
12
18
  if (typeof output !== 'object' || output == null)
13
19
  return 'completed';
14
- const o = output;
15
- if (typeof o.totalMatches === 'number')
16
- return o.totalMatches === 0 ? 'no matches' : `${o.matchCountIsLowerBound === true ? 'at least ' : ''}${o.totalMatches} matches`;
17
- if (typeof o.code === 'number')
18
- return `exit ${o.code}`;
19
- if (o.ok === true)
20
+ const value = output;
21
+ if (typeof value.totalMatches === 'number')
22
+ return value.totalMatches === 0 ? 'no matches' : `${value.matchCountIsLowerBound === true ? 'at least ' : ''}${value.totalMatches} matches`;
23
+ if (typeof value.code === 'number')
24
+ return `exit ${value.code}`;
25
+ if (value.ok === true)
20
26
  return 'completed';
21
- if (o.ok === false && typeof o.error === 'string')
22
- return `failed: ${o.error.slice(0, 120)}`;
27
+ if (value.ok === false && typeof value.error === 'string')
28
+ return `failed: ${value.error.slice(0, 120)}`;
23
29
  return 'completed';
24
30
  }
25
- export const internals = { toolSummary, toolOnlyStepCount };
26
- export async function runSubagent(task, options) {
27
- const start = performance.now();
28
- const toolNames = (options.allowedTools ?? ALL_TOOLS).filter(t => ALL_TOOLS.includes(t));
29
- const maxSteps = Math.min(options.maxSteps ?? STEP_LIMIT, STEP_LIMIT);
30
- const scopedTools = {};
31
- for (const name of toolNames) {
32
- const key = name;
33
- if (key in hazeTools)
34
- scopedTools[name] = hazeTools[key];
31
+ function shouldForceSynthesis(steps, maxSteps, maxToolCalls = COMPATIBILITY_PROFILE.maxToolCalls) {
32
+ return toolOnlyStepCount(steps) >= SUBAGENT_TOOL_ONLY_LIMIT
33
+ || steps.flatMap(step => step.toolCalls).length >= maxToolCalls
34
+ || steps.length >= maxSteps - SUBAGENT_SYNTHESIS_RESERVE;
35
+ }
36
+ function pendingScopedControl(messages, context) {
37
+ const files = context.pendingContextFiles ?? [];
38
+ if (files.length === 0)
39
+ return messages;
40
+ context.pendingContextFiles = [];
41
+ return withSyntheticControl(messages, `Additional scoped project instructions now apply. Follow them before subsequent work.${projectContextSection(files)}`);
42
+ }
43
+ function changedPathFromOutput(name, output) {
44
+ if (!['editFile', 'replaceLines', 'writeFile'].includes(name) || typeof output !== 'object' || output == null)
45
+ return undefined;
46
+ const value = output;
47
+ if (value.ok !== true || typeof value.path !== 'string')
48
+ return undefined;
49
+ try {
50
+ return workspaceRelativePath(resolveWorkspacePath(value.path));
51
+ }
52
+ catch {
53
+ return undefined;
35
54
  }
55
+ }
56
+ function validationFromOutput(name, output) {
57
+ if (name !== 'bash' || typeof output !== 'object' || output == null)
58
+ return undefined;
59
+ const value = output;
60
+ if (typeof value.command !== 'string' || typeof value.validationSummary !== 'object' || value.validationSummary == null)
61
+ return undefined;
62
+ return { command: value.command, ok: value.ok === true };
63
+ }
64
+ function telemetryBase(runtime, profile, taskTokens, initialInputTokens, queueMs = 0) {
65
+ return { modelSelector: runtime.selector, profile: profile.name, durationMs: 0, queueMs, toolCallCount: 0, toolCalls: [], usage: {}, estimates: { taskCapsuleTokens: taskTokens, initialInputTokens, privateContextTokens: 0, resultCapsuleTokens: 0, mainContextTokensAvoided: 0 } };
66
+ }
67
+ function terminalResult(task, runtime, profile, termination, message, queueMs = 0) {
68
+ const capsule = { id: task.id, termination, usable: false, deliverable: message, changedPaths: [], validation: [], coverageGaps: [message], truncated: false };
69
+ const telemetry = telemetryBase(runtime, profile, estimateValueTokens(workerTaskMessage(task)), 0, queueMs);
70
+ telemetry.estimates.resultCapsuleTokens = estimateValueTokens(capsule);
71
+ return withLegacyProjection(capsule, telemetry, termination === 'provider_error' || termination === 'policy_blocked' ? message : undefined);
72
+ }
73
+ export async function runSubagent(taskInput, options) {
74
+ const profile = options.profile ?? COMPATIBILITY_PROFILE;
75
+ const runtime = options.runtime ?? fallbackWorkerRuntime(options.model);
76
+ const task = typeof taskInput === 'string'
77
+ ? { id: 'worker', objective: taskInput, deliverable: 'Return a concise self-contained result.', mode: options.allowedTools ? (options.allowedTools.some(name => ['editFile', 'replaceLines', 'writeFile'].includes(name)) ? 'implement' : options.allowedTools.includes('bash') ? 'validate' : options.allowedTools.includes('fetch') ? 'research' : 'inspect') : 'implement', scope: [], acceptanceCriteria: [], legacyMaxSteps: options.maxSteps }
78
+ : taskInput;
79
+ const requestedSteps = task.legacyMaxSteps ?? options.maxSteps;
80
+ if (requestedSteps != null && (requestedSteps < SUBAGENT_MIN_STEPS || requestedSteps > SUBAGENT_MAX_STEPS))
81
+ return terminalResult(task, runtime, profile, 'policy_blocked', `maxSteps must be from ${SUBAGENT_MIN_STEPS} to ${SUBAGENT_MAX_STEPS}.`);
82
+ const maxSteps = Math.min(requestedSteps ?? profile.maxSteps, profile.maxSteps);
83
+ const startedAt = performance.now();
84
+ const bundle = options.contextBundle ?? (options.contextFiles
85
+ ? await compatibilityBundle(task, profile, options.contextFiles, options.allowedTools, options.session)
86
+ : await assembleWorkerContext(task, profile, options.session));
87
+ if (bundle.policyBlock)
88
+ return terminalResult(task, runtime, profile, 'policy_blocked', bundle.policyBlock, options.queueMs);
36
89
  const toolCallLog = [];
37
- const toolExecutionContext = { inFlightToolCalls: new Map() };
38
- let tokensIn = 0;
39
- let tokensOut = 0;
40
- let lastStep = 0;
41
- let totalToolCalls = 0;
90
+ const changedPaths = new Set();
91
+ const validation = [];
92
+ let usageIn;
93
+ let usageOut;
94
+ const toolBudget = createToolExecutionBudget();
95
+ const budgetedTools = withToolExecutionBudget(bundle.tools, { state: toolBudget, limit: profile.maxToolCalls });
96
+ const mutationPolicy = options.mutationPolicy;
97
+ const mutationOwner = mutationPolicy?.createOwner();
98
+ const toolExecutionContext = {
99
+ isSubagent: true,
100
+ inFlightToolCalls: new Map(), loadedContextFilePaths: new Set(bundle.loadedPaths),
101
+ loadedContextFileSignatures: new Map(bundle.loadedSignatures),
102
+ ...(mutationPolicy && mutationOwner ? { mutationPolicy, mutationOwner } : {}),
103
+ };
104
+ const release = mutationPolicy && mutationOwner && (task.mode === 'implement' || task.mode === 'validate')
105
+ ? await mutationPolicy.acquire(mutationOwner, options.abortSignal).catch(() => undefined)
106
+ : undefined;
107
+ if (mutationPolicy && mutationOwner && (task.mode === 'implement' || task.mode === 'validate') && !release)
108
+ return terminalResult(task, runtime, profile, options.deadlineExpired?.() ? 'deadline_exceeded' : 'cancelled', 'Worker cancelled before workspace admission.', options.queueMs);
42
109
  try {
43
- const result = streamText({
44
- model: options.model,
45
- maxOutputTokens: 4096,
46
- instructions: buildSubagentPrompt(options.contextFiles, options.session),
47
- messages: [{ role: 'user', content: task }],
48
- tools: scopedTools,
110
+ const { omitMaxOutputTokens, ...providerRequestOptions } = runtime.requestOptions;
111
+ const result = await generateText({
112
+ model: runtime.model,
113
+ instructions: bundle.systemPrompt,
114
+ messages: [{ role: 'user', content: workerTaskMessage(task) }],
115
+ tools: budgetedTools,
49
116
  stopWhen: isStepCount(maxSteps),
117
+ ...(!omitMaxOutputTokens ? { maxOutputTokens: profile.maxOutputTokens } : {}),
118
+ maxRetries: profile.maxRetries,
119
+ ...providerRequestOptions,
50
120
  abortSignal: options.abortSignal,
51
121
  runtimeContext: toolExecutionContext,
52
- toolsContext: toolsContextFor(scopedTools, toolExecutionContext),
53
- prepareStep({ steps }) {
54
- const calls = steps.flatMap(step => step.toolCalls);
55
- const consecutiveToolOnly = toolOnlyStepCount(steps);
56
- if (consecutiveToolOnly >= TOOL_ONLY_LIMIT || calls.length >= maxSteps * 2) {
57
- return {
58
- toolChoice: 'none',
59
- messages: [
60
- { role: 'user', content: 'Tool budget reached for this subtask. Summarize what you found or changed, validation evidence, and the exact remaining action if incomplete. Do not claim tools are unavailable.' },
61
- ],
62
- };
63
- }
64
- return undefined;
65
- },
66
- onStepEnd({ stepNumber }) {
67
- lastStep = stepNumber;
122
+ toolsContext: toolsContextFor(budgetedTools, toolExecutionContext),
123
+ prepareStep({ steps, messages }) {
124
+ const scopedMessages = pendingScopedControl(messages, toolExecutionContext);
125
+ if (!toolBudget.exceeded && toolBudget.started < profile.maxToolCalls && !shouldForceSynthesis(steps, maxSteps, profile.maxToolCalls))
126
+ return scopedMessages !== messages ? { messages: scopedMessages } : undefined;
127
+ return { toolChoice: 'none', messages: withSyntheticControl(scopedMessages, SYNTHESIS_DIRECTIVE) };
68
128
  },
69
- onEnd(event) {
70
- if (event.usage) {
71
- tokensIn = event.usage.inputTokens ?? 0;
72
- tokensOut = event.usage.outputTokens ?? 0;
73
- }
129
+ onStepEnd({ usage }) {
130
+ if (typeof usage?.inputTokens === 'number')
131
+ usageIn = (usageIn ?? 0) + usage.inputTokens;
132
+ if (typeof usage?.outputTokens === 'number')
133
+ usageOut = (usageOut ?? 0) + usage.outputTokens;
74
134
  },
75
135
  onToolExecutionEnd(event) {
76
136
  if (!event.toolCall)
77
137
  return;
78
- totalToolCalls += 1;
79
- toolCallLog.push({
80
- name: event.toolCall.toolName,
81
- summary: event.toolOutput.type === 'tool-result' ? toolSummary(event.toolOutput.output) : `failed: ${String(event.toolOutput.error).slice(0, 120)}`,
82
- durationMs: event.toolExecutionMs,
83
- });
138
+ const output = event.toolOutput.type === 'tool-result' ? event.toolOutput.output : undefined;
139
+ if (!isToolBudgetBlocked(output)) {
140
+ const toolError = 'error' in event.toolOutput ? event.toolOutput.error : 'tool execution failed';
141
+ if (toolCallLog.length < profile.maxToolCalls)
142
+ toolCallLog.push({ name: event.toolCall.toolName, summary: output === undefined ? `failed: ${String(toolError).slice(0, 120)}` : toolSummary(output), durationMs: event.toolExecutionMs });
143
+ const changedPath = changedPathFromOutput(event.toolCall.toolName, output);
144
+ if (changedPath)
145
+ changedPaths.add(changedPath);
146
+ const validationRecord = validationFromOutput(event.toolCall.toolName, output);
147
+ if (validationRecord)
148
+ validation.push(validationRecord);
149
+ }
84
150
  },
85
151
  });
86
- let text = '';
87
- for await (const delta of result.textStream) {
88
- text += delta;
89
- }
90
- await result.response;
91
- const summary = (text.trim() || 'Subagent completed without text output.').slice(0, MAX_SUMMARY);
92
- const durationMs = performance.now() - start;
93
- const status = options.abortSignal?.aborted ? 'cancelled'
94
- : lastStep >= maxSteps ? 'timeout'
95
- : 'ok';
96
- return { status, summary, toolCalls: toolCallLog, toolCallCount: totalToolCalls, tokens: { in: tokensIn, out: tokensOut }, durationMs };
152
+ usageIn = result.usage.inputTokens ?? usageIn;
153
+ usageOut = result.usage.outputTokens ?? usageOut;
154
+ const fullText = result.text.trim();
155
+ const truncated = fullText.length > profile.maxSummaryChars;
156
+ const resultHandle = truncated ? storeToolOutput(fullText) : undefined;
157
+ const deliverable = fullText
158
+ ? `${fullText.slice(0, profile.maxSummaryChars)}${truncated ? '\n\n[Result truncated; retrieve the non-durable resultHandle only if needed.]' : ''}`
159
+ : 'Subagent completed without text output.';
160
+ const totalToolCalls = toolBudget.started;
161
+ const toolLimited = toolBudget.exceeded || totalToolCalls >= profile.maxToolCalls;
162
+ const termination = options.deadlineExpired?.() ? 'deadline_exceeded'
163
+ : options.abortSignal?.aborted ? 'cancelled'
164
+ : toolLimited ? 'tool_limit'
165
+ : result.steps.length >= maxSteps && !fullText ? 'step_limit'
166
+ : !fullText ? 'no_output'
167
+ : 'completed';
168
+ const capsule = { id: task.id, termination, usable: fullText.length > 0, deliverable, changedPaths: [...changedPaths].sort(), validation, coverageGaps: [], truncated, ...(resultHandle ? { resultHandle } : {}) };
169
+ const durationMs = performance.now() - startedAt;
170
+ const telemetry = telemetryBase(runtime, profile, bundle.taskTokens, bundle.estimatedTokens, options.queueMs);
171
+ telemetry.durationMs = durationMs;
172
+ telemetry.toolCallCount = totalToolCalls;
173
+ telemetry.toolCalls = toolCallLog;
174
+ telemetry.usage = { inputTokens: usageIn, outputTokens: usageOut };
175
+ telemetry.estimates.privateContextTokens = (usageIn ?? bundle.estimatedTokens) + (usageOut ?? 0);
176
+ telemetry.estimates.resultCapsuleTokens = estimateValueTokens(capsule);
177
+ telemetry.estimates.mainContextTokensAvoided = Math.max(0, telemetry.estimates.privateContextTokens - telemetry.estimates.taskCapsuleTokens - telemetry.estimates.resultCapsuleTokens);
178
+ return withLegacyProjection(capsule, telemetry);
97
179
  }
98
180
  catch (error) {
99
- return {
100
- status: options.abortSignal?.aborted ? 'cancelled' : 'error',
101
- summary: error instanceof Error ? error.message : String(error),
102
- toolCalls: toolCallLog,
103
- toolCallCount: totalToolCalls,
104
- tokens: { in: tokensIn, out: tokensOut },
105
- durationMs: performance.now() - start,
106
- error: error instanceof Error ? error.message : String(error),
107
- };
181
+ const message = error instanceof Error ? error.message : String(error);
182
+ const termination = options.deadlineExpired?.() ? 'deadline_exceeded' : options.abortSignal?.aborted ? 'cancelled' : 'provider_error';
183
+ const result = terminalResult(task, runtime, profile, termination, message, options.queueMs);
184
+ result.telemetry.durationMs = performance.now() - startedAt;
185
+ result.durationMs = result.telemetry.durationMs;
186
+ result.telemetry.toolCalls = toolCallLog;
187
+ result.toolCalls = toolCallLog;
188
+ result.telemetry.toolCallCount = toolBudget.started;
189
+ result.toolCallCount = toolBudget.started;
190
+ result.telemetry.usage = { inputTokens: usageIn, outputTokens: usageOut };
191
+ result.tokens = { in: usageIn, out: usageOut };
192
+ return result;
108
193
  }
194
+ finally {
195
+ release?.();
196
+ }
197
+ }
198
+ async function compatibilityBundle(task, profile, contextFiles, allowedTools, session) {
199
+ const instructions = contextFiles;
200
+ const systemPrompt = buildSubagentPrompt(instructions, session, task.mode, profile);
201
+ const tools = {};
202
+ for (const name of allowedTools ?? MODE_TOOL_NAMES[task.mode])
203
+ if (name in hazeTools)
204
+ tools[name] = hazeTools[name];
205
+ const taskTokens = estimateValueTokens(workerTaskMessage(task));
206
+ const estimatedTokens = estimateValueTokens(systemPrompt) + taskTokens + estimateToolSchemas(tools).reduce((sum, value) => sum + value.tokens, 0);
207
+ return { instructions, systemPrompt, tools, taskTokens, estimatedTokens, validatedScope: [], loadedPaths: new Set(instructions.map(file => file.path)), loadedSignatures: new Map(instructions.flatMap(file => file.signature ? [[file.path, file.signature]] : [])), ...(estimatedTokens > profile.maxInputTokens ? { policyBlock: `Worker input estimate ${estimatedTokens} exceeds profile ${profile.name} limit ${profile.maxInputTokens}.` } : {}) };
109
208
  }
110
209
  export function createSubagentTool(options) {
210
+ const profile = options.profile ?? COMPATIBILITY_PROFILE;
211
+ const runtime = options.runtime ?? fallbackWorkerRuntime(options.model);
212
+ const coordinator = options.coordinator ?? new SubagentCoordinator(profile);
111
213
  return tool({
112
- description: 'Spawn subagents to run independent tasks in parallel. ONLY use when a request clearly decomposes into 2+ independent subtasks that can run concurrently — spawn all of them in one step. Do NOT use for single tasks, sequential work, or anything that benefits from conversation context; do those directly instead. Subagents have no conversation history and return a summary.',
113
- inputSchema: z.object({
114
- task: z.string().min(1).describe('Clear, specific task for the subagent to complete.'),
115
- tools: z.array(z.enum(['listFiles', 'readFile', 'grep', 'bash', 'readToolOutput', 'editFile', 'replaceLines', 'writeFile', 'fetch'])).optional().describe('Tools the subagent can use. Defaults to all tools.'),
116
- maxSteps: z.number().int().positive().max(50).optional().describe('Maximum tool-call rounds. Default 25.'),
117
- }),
118
- execute: async ({ task, tools, maxSteps }, context) => runSubagent(task, {
119
- model: options.model,
120
- contextFiles: options.contextFiles,
121
- allowedTools: tools,
122
- maxSteps,
123
- abortSignal: context.abortSignal,
124
- session: options.session,
125
- }),
214
+ description: 'Run independent work in a fresh disposable context and return only its deliverable. Always provide objective, deliverable, and mode (inspect, research, implement, or validate); keep objective under 1000 characters; scope and acceptanceCriteria are optional. Use when private repository/log/docs/audit/debugging work would add much more context than the result needed here; one substantial task is enough. Use multiple calls for genuinely independent work. Do not use for trivial, sequential, user-interactive, shared-mutation, or unsummarized conversation-dependent work.',
215
+ inputSchema: subagentInputSchema,
216
+ execute: async (rawInput, context) => {
217
+ const input = rawInput;
218
+ const id = coordinator.createId();
219
+ const normalized = normalizeSubagentInput(input, id);
220
+ const task = options.forceMode ? { ...normalized, mode: options.forceMode } : normalized;
221
+ if (options.blockedReason)
222
+ return terminalResult(task, runtime, profile, 'policy_blocked', options.blockedReason);
223
+ return await coordinator.submit({
224
+ id, mode: task.mode, signal: context.abortSignal,
225
+ run: ({ signal, queueMs, deadlineExpired }) => runSubagent(task, { runtime, profile, abortSignal: signal, deadlineExpired, queueMs, session: options.session, mutationPolicy: options.mutationPolicy, ...(options.contextFiles ? { contextFiles: options.contextFiles } : {}) }),
226
+ terminal: (termination, queueMs) => terminalResult(task, runtime, profile, termination, termination === 'cancelled'
227
+ ? 'Worker cancelled before completion.'
228
+ : termination === 'deadline_exceeded'
229
+ ? 'Worker deadline exceeded; underlying abort-ignoring work remains quarantined until it settles.'
230
+ : 'Worker execution failed unexpectedly.', queueMs),
231
+ terminationOf: result => result.capsule.termination,
232
+ });
233
+ },
234
+ toModelOutput: ({ output }) => ({ type: 'json', value: output.capsule }),
126
235
  });
127
236
  }
237
+ export const internals = { toolSummary, toolOnlyStepCount, shouldForceSynthesis, validationFromOutput, SYNTHESIS_DIRECTIVE };
@@ -0,0 +1,11 @@
1
+ export type WorkspaceMutationOwner = symbol;
2
+ /** Turn-scoped, reentrant workspace-wide mutation lease. It coordinates work;
3
+ * it is not a shell sandbox or authorization boundary. */
4
+ export declare class WorkspaceMutationPolicy {
5
+ private owner?;
6
+ private depth;
7
+ private readonly waiters;
8
+ createOwner(): WorkspaceMutationOwner;
9
+ acquire(owner: WorkspaceMutationOwner, signal?: AbortSignal): Promise<() => void>;
10
+ private releaseFor;
11
+ }
@@ -0,0 +1,52 @@
1
+ /** Turn-scoped, reentrant workspace-wide mutation lease. It coordinates work;
2
+ * it is not a shell sandbox or authorization boundary. */
3
+ export class WorkspaceMutationPolicy {
4
+ owner;
5
+ depth = 0;
6
+ waiters = [];
7
+ createOwner() { return Symbol('workspace-mutation-owner'); }
8
+ async acquire(owner, signal) {
9
+ if (signal?.aborted)
10
+ throw new Error('Workspace mutation cancelled before admission.');
11
+ if (!this.owner || this.owner === owner) {
12
+ this.owner = owner;
13
+ this.depth++;
14
+ return this.releaseFor(owner);
15
+ }
16
+ return await new Promise((resolve, reject) => {
17
+ const waiter = { owner, resolve, reject, ...(signal ? { signal } : {}) };
18
+ if (signal) {
19
+ waiter.onAbort = () => {
20
+ const index = this.waiters.indexOf(waiter);
21
+ if (index >= 0)
22
+ this.waiters.splice(index, 1);
23
+ reject(new Error('Workspace mutation cancelled while queued.'));
24
+ };
25
+ signal.addEventListener('abort', waiter.onAbort, { once: true });
26
+ }
27
+ this.waiters.push(waiter);
28
+ });
29
+ }
30
+ releaseFor(owner) {
31
+ let released = false;
32
+ return () => {
33
+ if (released)
34
+ return;
35
+ released = true;
36
+ if (this.owner !== owner)
37
+ return;
38
+ this.depth--;
39
+ if (this.depth > 0)
40
+ return;
41
+ this.owner = undefined;
42
+ const next = this.waiters.shift();
43
+ if (!next)
44
+ return;
45
+ if (next.signal && next.onAbort)
46
+ next.signal.removeEventListener('abort', next.onAbort);
47
+ this.owner = next.owner;
48
+ this.depth = 1;
49
+ next.resolve(this.releaseFor(next.owner));
50
+ };
51
+ }
52
+ }
@@ -1,7 +1,18 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import fs from 'node:fs/promises';
3
3
  import path from 'node:path';
4
+ import { z } from 'zod';
4
5
  import { resolveWorkspacePath } from '../../utils/path.js';
6
+ const taskSchema = z.object({
7
+ id: z.string(),
8
+ title: z.string(),
9
+ status: z.enum(['pending', 'in_progress', 'completed']),
10
+ createdAt: z.string(),
11
+ updatedAt: z.string(),
12
+ });
13
+ // Corrupt or structurally invalid files fall back to an empty list, matching
14
+ // the documented "loading errors return an empty list" contract (CR-012).
15
+ const tasksSchema = z.array(taskSchema);
5
16
  const TASKS_DIR = '.haze';
6
17
  const TASKS_FILE = 'tasks.json';
7
18
  export function getTasksFilePath() {
@@ -13,7 +24,7 @@ export function generateTaskId() {
13
24
  export async function loadTasks() {
14
25
  try {
15
26
  const content = await fs.readFile(getTasksFilePath(), 'utf-8');
16
- return JSON.parse(content);
27
+ return tasksSchema.parse(JSON.parse(content));
17
28
  }
18
29
  catch {
19
30
  return [];
@@ -1,41 +1,48 @@
1
- export interface ProviderCapabilities {
2
- reportsCacheUsage: boolean;
3
- supportsPromptCacheKey: boolean;
4
- supportsExtendedCacheRetention: boolean;
5
- supportsStickySessionId: boolean;
6
- supportsServerCompaction: boolean;
7
- supportsTextVerbosity: boolean;
1
+ import { readSettings, type HazeProviderSettings } from '../config/settings.js';
2
+ import type { ProviderCapabilities, ProviderRequestOptions, WorkerRuntime } from '../core/subagent/contracts.js';
3
+ import { type ResolvedReasoningPolicy } from '../core/agent/reasoningPolicy.js';
4
+ export type { ProviderCapabilities, ProviderRequestOptions } from '../core/subagent/contracts.js';
5
+ export interface ModelRuntimeSelection {
6
+ model: WorkerRuntime['model'];
7
+ config: ModelRuntimeConfig;
8
+ selector: string;
8
9
  }
9
10
  export interface ModelRuntimeConfig {
10
11
  providerName: string;
12
+ providerKind?: HazeProviderSettings['kind'];
11
13
  baseURL: string;
12
14
  modelName: string;
13
15
  cacheKey: string;
14
16
  capabilities: ProviderCapabilities;
17
+ /** Resolved reasoning policy (requested vs effective); observable, no secrets. */
18
+ reasoningPolicy: ResolvedReasoningPolicy;
19
+ /**
20
+ * Effective context window for request budgeting (RH-005). Always set: the
21
+ * user-configured value when present, otherwise a class-aware fallback
22
+ * (128K hosted / 32K local) so `contextWindowSource` can flag the guess.
23
+ */
24
+ contextWindowTokens: number;
25
+ /** Where contextWindowTokens came from: per-model settings, a user-set fallback, or the built-in default. */
26
+ contextWindowSource: 'settings' | 'user-fallback' | 'default-fallback';
27
+ /** Optional output-token limit metadata for request budgeting (RH-005). */
28
+ maxOutputTokens?: number;
15
29
  }
30
+ /** True for loopback/local inference servers, whose effective window is server-configured (often far below the model's). */
31
+ export declare function isLocalProviderUrl(url: string): boolean;
16
32
  export declare function modelWithConfig(session?: {
17
33
  cwd?: string;
18
34
  modelSelector?: string;
35
+ }, settings?: Awaited<ReturnType<typeof readSettings>>): Promise<ModelRuntimeSelection | undefined>;
36
+ export declare function resolveWorkerRuntime(input: {
37
+ active: ModelRuntimeSelection;
38
+ settings: Awaited<ReturnType<typeof readSettings>>;
39
+ selector?: string;
40
+ cwd?: string;
19
41
  }): Promise<{
20
- model: import("@ai-sdk/provider").LanguageModelV4;
21
- config: {
22
- providerName: string;
23
- baseURL: string;
24
- modelName: string;
25
- cacheKey: string;
26
- capabilities: ProviderCapabilities;
27
- };
28
- } | undefined>;
29
- export declare function model(): Promise<import("@ai-sdk/provider").LanguageModelV4 | undefined>;
30
- export declare function cacheKeyFor(name: string, cwd?: string): string;
31
- export declare function providerRequestSettings(config: ModelRuntimeConfig): {
32
- headers?: {
33
- 'x-session-id': string;
34
- } | undefined;
35
- providerOptions?: {
36
- openai: {
37
- textVerbosity?: "low" | undefined;
38
- promptCacheKey?: string | undefined;
39
- };
40
- } | undefined;
41
- };
42
+ status: 'found';
43
+ runtime: WorkerRuntime;
44
+ } | {
45
+ status: 'missing' | 'ambiguous';
46
+ message: string;
47
+ }>;
48
+ export declare function providerRequestSettings(config: ModelRuntimeConfig): ProviderRequestOptions;