@denizokcu/haze 0.9.0 → 0.10.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 (158) hide show
  1. package/CHANGELOG.md +57 -17
  2. package/README.md +119 -64
  3. package/dist/cli/chat/chatMetrics.d.ts +17 -1
  4. package/dist/cli/chat/chatMetrics.js +22 -5
  5. package/dist/cli/chat/contextReport.d.ts +11 -0
  6. package/dist/cli/chat/contextReport.js +44 -0
  7. package/dist/cli/chat/fileMentionSuggestions.d.ts +29 -0
  8. package/dist/cli/chat/fileMentionSuggestions.js +91 -0
  9. package/dist/cli/chat/inputSuggestions.d.ts +5 -0
  10. package/dist/cli/chat/inputSuggestions.js +17 -3
  11. package/dist/cli/chat/sessionLifecycle.d.ts +58 -0
  12. package/dist/cli/chat/sessionLifecycle.js +155 -0
  13. package/dist/cli/chat/sessionRecorder.js +7 -9
  14. package/dist/cli/chat/startupInfo.d.ts +1 -0
  15. package/dist/cli/chat/startupInfo.js +11 -0
  16. package/dist/cli/chat/tips.d.ts +21 -0
  17. package/dist/cli/chat/tips.js +43 -0
  18. package/dist/cli/chat/wizardDispatch.d.ts +64 -0
  19. package/dist/cli/chat/wizardDispatch.js +645 -0
  20. package/dist/cli/commands/chat.d.ts +1 -0
  21. package/dist/cli/commands/chat.js +181 -700
  22. package/dist/cli/commands/chatModes.d.ts +1 -1
  23. package/dist/cli/commands/chatModes.js +7 -2
  24. package/dist/cli/commands/commandHelp.js +5 -3
  25. package/dist/cli/commands/commands.d.ts +3 -2
  26. package/dist/cli/commands/commands.js +12 -13
  27. package/dist/cli/commands/fleetCommand.d.ts +14 -0
  28. package/dist/cli/commands/fleetCommand.js +46 -0
  29. package/dist/cli/commands/formatters.d.ts +5 -0
  30. package/dist/cli/commands/formatters.js +33 -6
  31. package/dist/cli/commands/logsCommand.js +1 -7
  32. package/dist/cli/commands/modelCommand.js +1 -1
  33. package/dist/cli/commands/providerWizard.d.ts +1 -0
  34. package/dist/cli/commands/providerWizard.js +13 -0
  35. package/dist/cli/commands/runCommand.d.ts +1 -0
  36. package/dist/cli/commands/runCommand.js +25 -5
  37. package/dist/cli/commands/sessionPicker.d.ts +9 -0
  38. package/dist/cli/commands/sessionPicker.js +29 -0
  39. package/dist/cli/commands/settingsSummary.js +6 -4
  40. package/dist/cli/commands/skillConfirmRemove.js +4 -3
  41. package/dist/cli/commands/skillWizard.d.ts +2 -0
  42. package/dist/cli/commands/skillWizard.js +16 -6
  43. package/dist/cli/commands/streaming/idleTimer.d.ts +26 -0
  44. package/dist/cli/commands/streaming/idleTimer.js +24 -0
  45. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +2 -0
  46. package/dist/cli/commands/streaming/toolGroupRenderer.js +4 -2
  47. package/dist/cli/commands/streaming/turnRuntime.js +6 -4
  48. package/dist/cli/commands/streaming.d.ts +13 -1
  49. package/dist/cli/commands/streaming.js +42 -19
  50. package/dist/cli/commands/wizardActions.d.ts +6 -0
  51. package/dist/cli/commands/wizardActions.js +6 -0
  52. package/dist/cli/commands/wizardSuggestions.d.ts +8 -0
  53. package/dist/cli/commands/wizardSuggestions.js +60 -12
  54. package/dist/cli/commands/wizardTransition.d.ts +4 -0
  55. package/dist/cli/commands/wizardTransition.js +1 -2
  56. package/dist/cli/index.js +17 -3
  57. package/dist/cli/terminalTitle.d.ts +6 -0
  58. package/dist/cli/terminalTitle.js +36 -0
  59. package/dist/config/inputHistory.d.ts +3 -3
  60. package/dist/config/inputHistory.js +12 -18
  61. package/dist/config/modelDiscovery.d.ts +20 -0
  62. package/dist/config/modelDiscovery.js +51 -0
  63. package/dist/config/providerPresets.d.ts +16 -4
  64. package/dist/config/providerPresets.js +263 -34
  65. package/dist/config/providers.d.ts +2 -0
  66. package/dist/config/providers.js +7 -0
  67. package/dist/config/settings.d.ts +22 -0
  68. package/dist/config/settings.js +29 -1
  69. package/dist/config/skillSettings.d.ts +6 -13
  70. package/dist/config/skillSettings.js +20 -19
  71. package/dist/core/agent/budgets.d.ts +26 -0
  72. package/dist/core/agent/budgets.js +34 -0
  73. package/dist/core/agent/compaction.js +17 -3
  74. package/dist/core/agent/contextBudget.d.ts +8 -0
  75. package/dist/core/agent/contextBudget.js +29 -0
  76. package/dist/core/agent/errors.js +6 -2
  77. package/dist/core/agent/events.d.ts +12 -0
  78. package/dist/core/agent/toolOutputStore.d.ts +5 -0
  79. package/dist/core/agent/toolOutputStore.js +18 -1
  80. package/dist/core/agent/workState.d.ts +1 -1
  81. package/dist/core/agent/workState.js +0 -4
  82. package/dist/core/attachments/imageAttachments.d.ts +90 -0
  83. package/dist/core/attachments/imageAttachments.js +245 -0
  84. package/dist/core/attachments/readBlessings.d.ts +37 -0
  85. package/dist/core/attachments/readBlessings.js +79 -0
  86. package/dist/core/goal/requestClassifier.d.ts +0 -3
  87. package/dist/core/goal/requestClassifier.js +0 -13
  88. package/dist/core/io/boundedRead.js +76 -29
  89. package/dist/core/limits/byteBudgets.d.ts +5 -0
  90. package/dist/core/limits/byteBudgets.js +5 -0
  91. package/dist/core/limits/textBudgets.d.ts +23 -0
  92. package/dist/core/limits/textBudgets.js +23 -0
  93. package/dist/core/process/backgroundRegistry.d.ts +35 -0
  94. package/dist/core/process/backgroundRegistry.js +194 -0
  95. package/dist/core/process/runBoundedProcess.d.ts +3 -0
  96. package/dist/core/process/runBoundedProcess.js +65 -29
  97. package/dist/core/safety/urlGuard.d.ts +2 -1
  98. package/dist/core/safety/urlGuard.js +3 -2
  99. package/dist/core/session/sessionSlimming.js +47 -4
  100. package/dist/core/session/sessionStore.d.ts +37 -0
  101. package/dist/core/session/sessionStore.js +95 -9
  102. package/dist/core/subagent/contracts.d.ts +116 -0
  103. package/dist/core/subagent/contracts.js +54 -0
  104. package/dist/core/subagent/executionProfiles.d.ts +28 -0
  105. package/dist/core/subagent/executionProfiles.js +45 -0
  106. package/dist/core/subagent/subagentCoordinator.d.ts +74 -0
  107. package/dist/core/subagent/subagentCoordinator.js +134 -0
  108. package/dist/core/subagent/subagentRunner.d.ts +211 -145
  109. package/dist/core/subagent/subagentRunner.js +228 -98
  110. package/dist/core/subagent/workspaceMutationPolicy.d.ts +11 -0
  111. package/dist/core/subagent/workspaceMutationPolicy.js +52 -0
  112. package/dist/core/tasks/taskStorage.js +12 -1
  113. package/dist/llm/client.d.ts +20 -29
  114. package/dist/llm/client.js +29 -28
  115. package/dist/llm/hazeTools.d.ts +2013 -78
  116. package/dist/llm/hazeTools.js +16 -7
  117. package/dist/llm/lsp.d.ts +2 -0
  118. package/dist/llm/lsp.js +18 -3
  119. package/dist/llm/requestContext.d.ts +22 -1
  120. package/dist/llm/requestContext.js +45 -5
  121. package/dist/llm/systemPrompt.d.ts +4 -1
  122. package/dist/llm/systemPrompt.js +14 -4
  123. package/dist/llm/toolResultTypes.d.ts +1 -1
  124. package/dist/llm/tools/bashTool.d.ts +874 -32
  125. package/dist/llm/tools/bashTool.js +25 -4
  126. package/dist/llm/tools/fetchTool.d.ts +26 -26
  127. package/dist/llm/tools/fetchTool.js +1 -1
  128. package/dist/llm/tools/fileToolShared.d.ts +2 -1
  129. package/dist/llm/tools/fileToolShared.js +5 -5
  130. package/dist/llm/tools/grepRunner.d.ts +5 -0
  131. package/dist/llm/tools/grepRunner.js +52 -71
  132. package/dist/llm/tools/outputCap.d.ts +2 -6
  133. package/dist/llm/tools/outputCap.js +2 -6
  134. package/dist/llm/tools/processTool.d.ts +1077 -0
  135. package/dist/llm/tools/processTool.js +41 -0
  136. package/dist/llm/tools/toolContext.d.ts +8 -0
  137. package/dist/llm/tools/toolContext.js +22 -11
  138. package/dist/llm/tools/workspaceFile.d.ts +9 -1
  139. package/dist/llm/tools/workspaceFile.js +33 -4
  140. package/dist/llm/webFetch.js +24 -11
  141. package/dist/llm/workerContext.d.ts +18 -0
  142. package/dist/llm/workerContext.js +55 -0
  143. package/dist/skills/SkillLoader.d.ts +2 -2
  144. package/dist/skills/SkillRegistry.d.ts +3 -2
  145. package/dist/skills/SkillRegistry.js +43 -13
  146. package/dist/skills/builder/SkillBuilder.d.ts +3 -0
  147. package/dist/skills/builder/SkillBuilder.js +23 -5
  148. package/dist/skills/skillTools.js +11 -4
  149. package/dist/skills/types.d.ts +6 -1
  150. package/dist/ui/components/TextInput.d.ts +5 -2
  151. package/dist/ui/components/TextInput.js +76 -8
  152. package/dist/utils/format.d.ts +2 -0
  153. package/dist/utils/format.js +8 -0
  154. package/dist/utils/fs.d.ts +0 -1
  155. package/dist/utils/fs.js +0 -4
  156. package/dist/utils/openPath.d.ts +2 -0
  157. package/dist/utils/openPath.js +9 -0
  158. package/package.json +1 -1
@@ -1,127 +1,257 @@
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 { assembleWorkerContext, workerTaskMessage } from '../../llm/workerContext.js';
8
+ import { buildSubagentPrompt, projectContextSection } from '../../llm/systemPrompt.js';
4
9
  import { hazeTools } from '../../llm/hazeTools.js';
5
10
  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;
11
+ import { fallbackWorkerRuntime, normalizeSubagentInput, subagentInputSchema, withLegacyProjection, } from './contracts.js';
12
+ import { COMPATIBILITY_PROFILE, MODE_TOOL_NAMES } from './executionProfiles.js';
13
+ import { SubagentCoordinator } from './subagentCoordinator.js';
14
+ import { resolveWorkspacePath, workspaceRelativePath } from '../../utils/path.js';
15
+ 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.';
16
+ const TOOL_BUDGET_BLOCKED = '__hazeSubagentToolBudgetBlocked';
17
+ function withToolExecutionBudget(tools, maxToolCalls, state) {
18
+ return Object.fromEntries(Object.entries(tools).map(([name, definition]) => {
19
+ if (typeof definition.execute !== 'function')
20
+ return [name, definition];
21
+ const execute = definition.execute;
22
+ return [name, {
23
+ ...definition,
24
+ execute: (...args) => {
25
+ // This check is at the actual execute boundary. Concurrent calls from
26
+ // one emitted batch enter synchronously, so no more than the remaining
27
+ // budget can reach an underlying tool implementation.
28
+ if (state.started >= maxToolCalls) {
29
+ state.exceeded = true;
30
+ return { ok: false, [TOOL_BUDGET_BLOCKED]: true, error: `Subagent tool-call budget of ${maxToolCalls} exhausted; execution was blocked.` };
31
+ }
32
+ state.started++;
33
+ return execute(...args);
34
+ },
35
+ }];
36
+ }));
37
+ }
11
38
  function toolSummary(output) {
12
39
  if (typeof output !== 'object' || output == null)
13
40
  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)
41
+ const value = output;
42
+ if (typeof value.totalMatches === 'number')
43
+ return value.totalMatches === 0 ? 'no matches' : `${value.matchCountIsLowerBound === true ? 'at least ' : ''}${value.totalMatches} matches`;
44
+ if (typeof value.code === 'number')
45
+ return `exit ${value.code}`;
46
+ if (value.ok === true)
20
47
  return 'completed';
21
- if (o.ok === false && typeof o.error === 'string')
22
- return `failed: ${o.error.slice(0, 120)}`;
48
+ if (value.ok === false && typeof value.error === 'string')
49
+ return `failed: ${value.error.slice(0, 120)}`;
23
50
  return 'completed';
24
51
  }
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];
52
+ function shouldForceSynthesis(steps, maxSteps, maxToolCalls = COMPATIBILITY_PROFILE.maxToolCalls) {
53
+ return toolOnlyStepCount(steps) >= SUBAGENT_TOOL_ONLY_LIMIT
54
+ || steps.flatMap(step => step.toolCalls).length >= maxToolCalls
55
+ || steps.length >= maxSteps - SUBAGENT_SYNTHESIS_RESERVE;
56
+ }
57
+ function pendingScopedControl(messages, context) {
58
+ const files = context.pendingContextFiles ?? [];
59
+ if (files.length === 0)
60
+ return messages;
61
+ context.pendingContextFiles = [];
62
+ return withSyntheticControl(messages, `Additional scoped project instructions now apply. Follow them before subsequent work.${projectContextSection(files)}`);
63
+ }
64
+ function changedPathFromOutput(name, output) {
65
+ if (!['editFile', 'replaceLines', 'writeFile'].includes(name) || typeof output !== 'object' || output == null)
66
+ return undefined;
67
+ const value = output;
68
+ if (value.ok !== true || typeof value.path !== 'string')
69
+ return undefined;
70
+ try {
71
+ return workspaceRelativePath(resolveWorkspacePath(value.path));
35
72
  }
73
+ catch {
74
+ return undefined;
75
+ }
76
+ }
77
+ function validationFromOutput(name, output) {
78
+ if (name !== 'bash' || typeof output !== 'object' || output == null)
79
+ return undefined;
80
+ const value = output;
81
+ if (typeof value.command !== 'string' || typeof value.validationSummary !== 'object' || value.validationSummary == null)
82
+ return undefined;
83
+ return { command: value.command, ok: value.ok === true };
84
+ }
85
+ function telemetryBase(runtime, profile, taskTokens, initialInputTokens, queueMs = 0) {
86
+ return { modelSelector: runtime.selector, profile: profile.name, durationMs: 0, queueMs, toolCallCount: 0, toolCalls: [], usage: {}, estimates: { taskCapsuleTokens: taskTokens, initialInputTokens, privateContextTokens: 0, resultCapsuleTokens: 0, mainContextTokensAvoided: 0 } };
87
+ }
88
+ function terminalResult(task, runtime, profile, termination, message, queueMs = 0) {
89
+ const capsule = { id: task.id, termination, usable: false, deliverable: message, changedPaths: [], validation: [], coverageGaps: [message], truncated: false };
90
+ const telemetry = telemetryBase(runtime, profile, estimateValueTokens(workerTaskMessage(task)), 0, queueMs);
91
+ telemetry.estimates.resultCapsuleTokens = estimateValueTokens(capsule);
92
+ return withLegacyProjection(capsule, telemetry, termination === 'provider_error' || termination === 'policy_blocked' ? message : undefined);
93
+ }
94
+ export async function runSubagent(taskInput, options) {
95
+ const profile = options.profile ?? COMPATIBILITY_PROFILE;
96
+ const runtime = options.runtime ?? fallbackWorkerRuntime(options.model);
97
+ const task = typeof taskInput === 'string'
98
+ ? { 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 }
99
+ : taskInput;
100
+ const requestedSteps = task.legacyMaxSteps ?? options.maxSteps;
101
+ if (requestedSteps != null && (requestedSteps < SUBAGENT_MIN_STEPS || requestedSteps > SUBAGENT_MAX_STEPS))
102
+ return terminalResult(task, runtime, profile, 'policy_blocked', `maxSteps must be from ${SUBAGENT_MIN_STEPS} to ${SUBAGENT_MAX_STEPS}.`);
103
+ const maxSteps = Math.min(requestedSteps ?? profile.maxSteps, profile.maxSteps);
104
+ const startedAt = performance.now();
105
+ const bundle = options.contextBundle ?? (options.contextFiles
106
+ ? await compatibilityBundle(task, profile, options.contextFiles, options.allowedTools, options.session)
107
+ : await assembleWorkerContext(task, profile, options.session));
108
+ if (bundle.policyBlock)
109
+ return terminalResult(task, runtime, profile, 'policy_blocked', bundle.policyBlock, options.queueMs);
36
110
  const toolCallLog = [];
37
- const toolExecutionContext = { inFlightToolCalls: new Map() };
38
- let tokensIn = 0;
39
- let tokensOut = 0;
40
- let lastStep = 0;
41
- let totalToolCalls = 0;
111
+ const changedPaths = new Set();
112
+ const validation = [];
113
+ let usageIn;
114
+ let usageOut;
115
+ const toolBudget = { started: 0, exceeded: false };
116
+ const budgetedTools = withToolExecutionBudget(bundle.tools, profile.maxToolCalls, toolBudget);
117
+ const mutationPolicy = options.mutationPolicy;
118
+ const mutationOwner = mutationPolicy?.createOwner();
119
+ const toolExecutionContext = {
120
+ isSubagent: true,
121
+ inFlightToolCalls: new Map(), loadedContextFilePaths: new Set(bundle.loadedPaths),
122
+ loadedContextFileSignatures: new Map(bundle.loadedSignatures),
123
+ ...(mutationPolicy && mutationOwner ? { mutationPolicy, mutationOwner } : {}),
124
+ };
125
+ const release = mutationPolicy && mutationOwner && (task.mode === 'implement' || task.mode === 'validate')
126
+ ? await mutationPolicy.acquire(mutationOwner, options.abortSignal).catch(() => undefined)
127
+ : undefined;
128
+ if (mutationPolicy && mutationOwner && (task.mode === 'implement' || task.mode === 'validate') && !release)
129
+ return terminalResult(task, runtime, profile, options.deadlineExpired?.() ? 'deadline_exceeded' : 'cancelled', 'Worker cancelled before workspace admission.', options.queueMs);
42
130
  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,
131
+ const result = await generateText({
132
+ model: runtime.model,
133
+ instructions: bundle.systemPrompt,
134
+ messages: [{ role: 'user', content: workerTaskMessage(task) }],
135
+ tools: budgetedTools,
49
136
  stopWhen: isStepCount(maxSteps),
137
+ maxOutputTokens: profile.maxOutputTokens,
138
+ maxRetries: profile.maxRetries,
139
+ ...runtime.requestOptions,
50
140
  abortSignal: options.abortSignal,
51
141
  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;
142
+ toolsContext: toolsContextFor(budgetedTools, toolExecutionContext),
143
+ prepareStep({ steps, messages }) {
144
+ const scopedMessages = pendingScopedControl(messages, toolExecutionContext);
145
+ if (!toolBudget.exceeded && toolBudget.started < profile.maxToolCalls && !shouldForceSynthesis(steps, maxSteps, profile.maxToolCalls))
146
+ return scopedMessages !== messages ? { messages: scopedMessages } : undefined;
147
+ return { toolChoice: 'none', messages: withSyntheticControl(scopedMessages, SYNTHESIS_DIRECTIVE) };
68
148
  },
69
- onEnd(event) {
70
- if (event.usage) {
71
- tokensIn = event.usage.inputTokens ?? 0;
72
- tokensOut = event.usage.outputTokens ?? 0;
73
- }
149
+ onStepEnd({ usage }) {
150
+ if (typeof usage?.inputTokens === 'number')
151
+ usageIn = (usageIn ?? 0) + usage.inputTokens;
152
+ if (typeof usage?.outputTokens === 'number')
153
+ usageOut = (usageOut ?? 0) + usage.outputTokens;
74
154
  },
75
155
  onToolExecutionEnd(event) {
76
156
  if (!event.toolCall)
77
157
  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
- });
158
+ const output = event.toolOutput.type === 'tool-result' ? event.toolOutput.output : undefined;
159
+ if (typeof output === 'object' && output != null && TOOL_BUDGET_BLOCKED in output)
160
+ return;
161
+ const toolError = 'error' in event.toolOutput ? event.toolOutput.error : 'tool execution failed';
162
+ if (toolCallLog.length < profile.maxToolCalls)
163
+ toolCallLog.push({ name: event.toolCall.toolName, summary: output === undefined ? `failed: ${String(toolError).slice(0, 120)}` : toolSummary(output), durationMs: event.toolExecutionMs });
164
+ const changedPath = changedPathFromOutput(event.toolCall.toolName, output);
165
+ if (changedPath)
166
+ changedPaths.add(changedPath);
167
+ const validationRecord = validationFromOutput(event.toolCall.toolName, output);
168
+ if (validationRecord)
169
+ validation.push(validationRecord);
84
170
  },
85
171
  });
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 };
172
+ usageIn = result.usage.inputTokens ?? usageIn;
173
+ usageOut = result.usage.outputTokens ?? usageOut;
174
+ const fullText = result.text.trim();
175
+ const truncated = fullText.length > profile.maxSummaryChars;
176
+ const resultHandle = truncated ? storeToolOutput(fullText) : undefined;
177
+ const deliverable = fullText
178
+ ? `${fullText.slice(0, profile.maxSummaryChars)}${truncated ? '\n\n[Result truncated; retrieve the non-durable resultHandle only if needed.]' : ''}`
179
+ : 'Subagent completed without text output.';
180
+ const totalToolCalls = toolBudget.started;
181
+ const toolLimited = toolBudget.exceeded || totalToolCalls >= profile.maxToolCalls;
182
+ const termination = options.deadlineExpired?.() ? 'deadline_exceeded'
183
+ : options.abortSignal?.aborted ? 'cancelled'
184
+ : toolLimited ? 'tool_limit'
185
+ : result.steps.length >= maxSteps && !fullText ? 'step_limit'
186
+ : !fullText ? 'no_output'
187
+ : 'completed';
188
+ const capsule = { id: task.id, termination, usable: fullText.length > 0, deliverable, changedPaths: [...changedPaths].sort(), validation, coverageGaps: [], truncated, ...(resultHandle ? { resultHandle } : {}) };
189
+ const durationMs = performance.now() - startedAt;
190
+ const telemetry = telemetryBase(runtime, profile, bundle.taskTokens, bundle.estimatedTokens, options.queueMs);
191
+ telemetry.durationMs = durationMs;
192
+ telemetry.toolCallCount = totalToolCalls;
193
+ telemetry.toolCalls = toolCallLog;
194
+ telemetry.usage = { inputTokens: usageIn, outputTokens: usageOut };
195
+ telemetry.estimates.privateContextTokens = (usageIn ?? bundle.estimatedTokens) + (usageOut ?? 0);
196
+ telemetry.estimates.resultCapsuleTokens = estimateValueTokens(capsule);
197
+ telemetry.estimates.mainContextTokensAvoided = Math.max(0, telemetry.estimates.privateContextTokens - telemetry.estimates.taskCapsuleTokens - telemetry.estimates.resultCapsuleTokens);
198
+ return withLegacyProjection(capsule, telemetry);
97
199
  }
98
200
  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
- };
201
+ const message = error instanceof Error ? error.message : String(error);
202
+ const termination = options.deadlineExpired?.() ? 'deadline_exceeded' : options.abortSignal?.aborted ? 'cancelled' : 'provider_error';
203
+ const result = terminalResult(task, runtime, profile, termination, message, options.queueMs);
204
+ result.telemetry.durationMs = performance.now() - startedAt;
205
+ result.durationMs = result.telemetry.durationMs;
206
+ result.telemetry.toolCalls = toolCallLog;
207
+ result.toolCalls = toolCallLog;
208
+ result.telemetry.toolCallCount = toolBudget.started;
209
+ result.toolCallCount = toolBudget.started;
210
+ result.telemetry.usage = { inputTokens: usageIn, outputTokens: usageOut };
211
+ result.tokens = { in: usageIn, out: usageOut };
212
+ return result;
213
+ }
214
+ finally {
215
+ release?.();
108
216
  }
109
217
  }
218
+ async function compatibilityBundle(task, profile, contextFiles, allowedTools, session) {
219
+ const instructions = contextFiles;
220
+ const systemPrompt = buildSubagentPrompt(instructions, session, task.mode, profile);
221
+ const tools = {};
222
+ for (const name of allowedTools ?? MODE_TOOL_NAMES[task.mode])
223
+ if (name in hazeTools)
224
+ tools[name] = hazeTools[name];
225
+ const taskTokens = estimateValueTokens(workerTaskMessage(task));
226
+ const estimatedTokens = estimateValueTokens(systemPrompt) + taskTokens + estimateToolSchemas(tools).reduce((sum, value) => sum + value.tokens, 0);
227
+ 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}.` } : {}) };
228
+ }
110
229
  export function createSubagentTool(options) {
230
+ const profile = options.profile ?? COMPATIBILITY_PROFILE;
231
+ const runtime = options.runtime ?? fallbackWorkerRuntime(options.model);
232
+ const coordinator = options.coordinator ?? new SubagentCoordinator(profile);
111
233
  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
- }),
234
+ 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.',
235
+ inputSchema: subagentInputSchema,
236
+ execute: async (rawInput, context) => {
237
+ const input = rawInput;
238
+ const id = coordinator.createId();
239
+ const normalized = normalizeSubagentInput(input, id);
240
+ const task = options.forceMode ? { ...normalized, mode: options.forceMode } : normalized;
241
+ if (options.blockedReason)
242
+ return terminalResult(task, runtime, profile, 'policy_blocked', options.blockedReason);
243
+ return await coordinator.submit({
244
+ id, mode: task.mode, signal: context.abortSignal,
245
+ run: ({ signal, queueMs, deadlineExpired }) => runSubagent(task, { runtime, profile, abortSignal: signal, deadlineExpired, queueMs, session: options.session, mutationPolicy: options.mutationPolicy, ...(options.contextFiles ? { contextFiles: options.contextFiles } : {}) }),
246
+ terminal: (termination, queueMs) => terminalResult(task, runtime, profile, termination, termination === 'cancelled'
247
+ ? 'Worker cancelled before completion.'
248
+ : termination === 'deadline_exceeded'
249
+ ? 'Worker deadline exceeded; underlying abort-ignoring work remains quarantined until it settles.'
250
+ : 'Worker execution failed unexpectedly.', queueMs),
251
+ terminationOf: result => result.capsule.termination,
252
+ });
253
+ },
254
+ toModelOutput: ({ output }) => ({ type: 'json', value: output.capsule }),
126
255
  });
127
256
  }
257
+ 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,10 +1,10 @@
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 } from '../config/settings.js';
2
+ import type { ProviderCapabilities, ProviderRequestOptions, WorkerRuntime } from '../core/subagent/contracts.js';
3
+ export type { ProviderCapabilities, ProviderRequestOptions } from '../core/subagent/contracts.js';
4
+ export interface ModelRuntimeSelection {
5
+ model: WorkerRuntime['model'];
6
+ config: ModelRuntimeConfig;
7
+ selector: string;
8
8
  }
9
9
  export interface ModelRuntimeConfig {
10
10
  providerName: string;
@@ -16,26 +16,17 @@ export interface ModelRuntimeConfig {
16
16
  export declare function modelWithConfig(session?: {
17
17
  cwd?: string;
18
18
  modelSelector?: string;
19
+ }, settings?: Awaited<ReturnType<typeof readSettings>>): Promise<ModelRuntimeSelection | undefined>;
20
+ export declare function resolveWorkerRuntime(input: {
21
+ active: ModelRuntimeSelection;
22
+ settings: Awaited<ReturnType<typeof readSettings>>;
23
+ selector?: string;
24
+ cwd?: string;
19
25
  }): 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
- };
26
+ status: 'found';
27
+ runtime: WorkerRuntime;
28
+ } | {
29
+ status: 'missing' | 'ambiguous';
30
+ message: string;
31
+ }>;
32
+ export declare function providerRequestSettings(config: ModelRuntimeConfig): ProviderRequestOptions;
@@ -1,7 +1,7 @@
1
1
  import { createOpenAI } from '@ai-sdk/openai';
2
2
  import crypto from 'node:crypto';
3
3
  import { readSettings } from '../config/settings.js';
4
- import { activeModel, resolveModelSelector } from '../config/providers.js';
4
+ import { activeModel, modelSelector, resolveModelSelector } from '../config/providers.js';
5
5
  import { assertCredentialedEndpointSecure } from '../config/endpointSecurity.js';
6
6
  const HAZE_SITE_URL = 'https://denizokcu.github.io/haze/';
7
7
  const HAZE_TITLE = 'Haze';
@@ -28,44 +28,45 @@ function capabilities(providerName, baseURL) {
28
28
  supportsTextVerbosity: directOpenAI,
29
29
  };
30
30
  }
31
- export async function modelWithConfig(session) {
32
- const settings = await readSettings();
33
- const override = session?.modelSelector?.trim();
34
- let selection;
35
- if (override) {
36
- const resolved = resolveModelSelector(settings, override);
37
- if (resolved.status === 'found')
38
- selection = { provider: resolved.provider, model: resolved.model };
39
- }
40
- else {
41
- selection = activeModel(settings);
42
- }
43
- if (!selection)
44
- return undefined;
31
+ function runtimeForSelection(settings, selection, cwd) {
45
32
  const baseURL = selection.provider.url;
46
33
  const configuredKey = selection.provider.key ?? settings.apiKey;
47
34
  assertCredentialedEndpointSecure(baseURL, configuredKey);
48
35
  const apiKey = configuredKey ?? 'not-needed';
49
36
  const name = selection.model;
50
- const cacheSeed = session?.cwd ?? process.cwd();
37
+ const cacheSeed = cwd ?? process.cwd();
51
38
  const cacheKey = crypto.createHash('sha256').update(`${cacheSeed}\0${name}`).digest('hex').slice(0, 32);
52
39
  return {
53
40
  model: createOpenAI({ apiKey, baseURL, headers: openRouterHeaders(selection.provider.name, baseURL) }).chat(name),
54
- config: {
55
- providerName: selection.provider.name,
56
- baseURL,
57
- modelName: name,
58
- cacheKey,
59
- capabilities: capabilities(selection.provider.name, baseURL),
60
- },
41
+ selector: modelSelector(selection.provider, name),
42
+ config: { providerName: selection.provider.name, baseURL, modelName: name, cacheKey, capabilities: capabilities(selection.provider.name, baseURL) },
61
43
  };
62
44
  }
63
- export async function model() {
64
- return (await modelWithConfig())?.model;
45
+ export async function modelWithConfig(session, settings) {
46
+ // Callers may pass pre-read settings so a turn performs a single settings
47
+ // read (CR-024); otherwise read fresh.
48
+ const resolvedSettings = settings ?? await readSettings();
49
+ const override = session?.modelSelector?.trim();
50
+ let selection;
51
+ if (override) {
52
+ const resolved = resolveModelSelector(resolvedSettings, override);
53
+ if (resolved.status === 'found')
54
+ selection = { provider: resolved.provider, model: resolved.model };
55
+ }
56
+ else
57
+ selection = activeModel(resolvedSettings);
58
+ return selection ? runtimeForSelection(resolvedSettings, selection, session?.cwd) : undefined;
65
59
  }
66
- export function cacheKeyFor(name, cwd) {
67
- const seed = cwd ?? process.cwd();
68
- return crypto.createHash('sha256').update(`${seed}\0${name}`).digest('hex').slice(0, 32);
60
+ export async function resolveWorkerRuntime(input) {
61
+ const requested = input.selector?.trim();
62
+ let selected = input.active;
63
+ if (requested) {
64
+ const resolved = resolveModelSelector(input.settings, requested);
65
+ if (resolved.status !== 'found')
66
+ return { status: resolved.status, message: resolved.status === 'ambiguous' ? `Worker model ${requested} is ambiguous; use provider:model.` : `Worker model ${requested} is not configured. Configure it via /provider or remove subagents.workerModel.` };
67
+ selected = runtimeForSelection(input.settings, { provider: resolved.provider, model: resolved.model }, input.cwd);
68
+ }
69
+ return { status: 'found', runtime: { model: selected.model, selector: selected.selector, providerName: selected.config.providerName, capabilities: selected.config.capabilities, requestOptions: providerRequestSettings(selected.config) } };
69
70
  }
70
71
  export function providerRequestSettings(config) {
71
72
  return {