@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
@@ -17,6 +17,7 @@ import { runDedupedTool, discoverScopedContext, withScopedContext, hazeToolConte
17
17
  import { prepareWorkspaceMutation, prepareWorkspaceRead, prepareWorkspaceWritePath } from './tools/workspaceFile.js';
18
18
  import { fetchTool } from './tools/fetchTool.js';
19
19
  import { bashTool } from './tools/bashTool.js';
20
+ import { processTool } from './tools/processTool.js';
20
21
  import { DEFAULT_READ_LINES, INLINE_DIFF_LINE_LIMIT, isGitIgnored, MAX_OUTPUT_CHARS, sourceOutlineEntries } from './tools/fileToolShared.js';
21
22
  import { runRipgrepBounded } from './tools/grepRunner.js';
22
23
  import { EXACT_MUTATION_BYTES } from '../core/limits/byteBudgets.js';
@@ -35,7 +36,7 @@ export const hazeTools = {
35
36
  }),
36
37
  execute: async ({ path: dirPath, recursive, maxEntries, cursor, includeIgnored, includeSizes }, context) => runDedupedTool('listFiles', { path: dirPath, recursive, maxEntries, cursor, includeIgnored, includeSizes }, context, async () => {
37
38
  try {
38
- const absolutePath = await prepareWorkspaceRead(dirPath, includeIgnored);
39
+ const absolutePath = await prepareWorkspaceRead(dirPath, includeIgnored, context);
39
40
  const entries = [];
40
41
  let ignoredSkipped = 0;
41
42
  const walked = await walkDir(absolutePath, { recursive, maxEntries: maxEntries + 1, cursor, filter: async (entry) => {
@@ -81,7 +82,7 @@ export const hazeTools = {
81
82
  }),
82
83
  execute: async ({ path: filePath, offset, limit, mode, allowIgnored }, context) => runDedupedTool('readFile', { path: filePath, offset, limit, mode, allowIgnored }, context, async () => {
83
84
  try {
84
- const absolutePath = await prepareWorkspaceRead(filePath, allowIgnored);
85
+ const absolutePath = await prepareWorkspaceRead(filePath, allowIgnored, context);
85
86
  const start = offset == null ? 0 : offset - 1;
86
87
  const pageLimit = limit ?? DEFAULT_READ_LINES;
87
88
  const page = await readUtf8LinesPage(absolutePath, start + 1, pageLimit);
@@ -118,9 +119,16 @@ export const hazeTools = {
118
119
  const endLine = mode === 'outline'
119
120
  ? displayLines[Math.max(0, includedLines - 1)]?.lineNumber ?? start + 1
120
121
  : start + includedLines;
122
+ const outlineDroppedEntries = mode === 'outline' ? displayLines.length - includedLines : 0;
121
123
  const hasMore = mode === 'outline'
122
- ? requestedEnd < totalLines
124
+ ? requestedEnd < totalLines || outlineDroppedEntries > 0
123
125
  : endLine < totalLines;
126
+ // Outline pages resume after the last *included* entry: the output cap can
127
+ // stop a page before requestedEnd, and jumping to requestedEnd + 1 would
128
+ // silently skip the entries in between (CR-028).
129
+ const nextOffset = hasMore
130
+ ? (mode === 'outline' && includedLines > 0 ? endLine + 1 : requestedEnd + 1)
131
+ : undefined;
124
132
  const scopedContext = await discoverScopedContext(filePath, context);
125
133
  return withScopedContext({
126
134
  path: filePath,
@@ -129,10 +137,10 @@ export const hazeTools = {
129
137
  endLine,
130
138
  totalLines,
131
139
  content: numberedLines.join('\n'),
132
- nextOffset: hasMore ? requestedEnd + 1 : undefined,
140
+ nextOffset,
133
141
  truncated: hasMore || lineTruncated,
134
142
  lineTruncated,
135
- ...(mode === 'outline' ? { outline: true, outlineEntries: includedLines, warning: 'Outline mode is lossy discovery output. Use exact readFile around relevant lines before editing.' } : {}),
143
+ ...(mode === 'outline' ? { outline: true, outlineEntries: includedLines, ...(outlineDroppedEntries > 0 ? { outlineDroppedEntries } : {}), warning: 'Outline mode is lossy discovery output. Use exact readFile around relevant lines before editing.' } : {}),
136
144
  }, scopedContext);
137
145
  }
138
146
  catch (error) {
@@ -148,13 +156,13 @@ export const hazeTools = {
148
156
  path: z.string().default('.').describe('Workspace-relative file or directory'),
149
157
  glob: z.string().optional().describe('Optional file glob, e.g. "*.ts"'),
150
158
  contextLines: z.number().int().nonnegative().max(5).default(2).describe('Context lines before/after each match'),
151
- maxMatches: z.number().int().positive().max(200).default(50).describe('Global match limit'),
159
+ maxMatches: z.number().int().positive().max(200).default(50).describe('Global match limit (enforced by the runner; ripgrep also applies it as a per-file cap)'),
152
160
  caseInsensitive: z.boolean().default(false).describe('Ignore case'),
153
161
  includeIgnored: z.boolean().default(false).describe('Search ignored paths only when explicitly needed'),
154
162
  }),
155
163
  execute: async ({ pattern, path: searchPath, glob, contextLines, maxMatches, caseInsensitive, includeIgnored }, context) => runDedupedTool('grep', { pattern, path: searchPath, glob, contextLines, maxMatches, caseInsensitive, includeIgnored }, context, async () => {
156
164
  try {
157
- const absolutePath = await prepareWorkspaceRead(searchPath, includeIgnored);
165
+ const absolutePath = await prepareWorkspaceRead(searchPath, includeIgnored, context);
158
166
  const args = [
159
167
  '--json', '--color=never',
160
168
  '--max-count', String(maxMatches),
@@ -374,4 +382,5 @@ export const hazeTools = {
374
382
  readToolOutput: readToolOutputTool,
375
383
  fetch: fetchTool,
376
384
  bash: bashTool,
385
+ process: processTool,
377
386
  };
package/dist/llm/lsp.d.ts CHANGED
@@ -62,9 +62,11 @@ export declare class StdioLspClient {
62
62
  private id;
63
63
  private buffer;
64
64
  private pending;
65
+ private terminating;
65
66
  constructor(server: HazeLspServer, child: ChildProcessWithoutNullStreams);
66
67
  static start(server: HazeLspServer): StdioLspClient;
67
68
  private rejectAll;
69
+ private terminate;
68
70
  private onData;
69
71
  private send;
70
72
  request(method: string, params?: Json, timeoutMs?: number): Promise<unknown>;
package/dist/llm/lsp.js CHANGED
@@ -5,6 +5,7 @@ import { assertRealPathInsideWorkspace, workspaceRelativePath, workspaceRoot } f
5
5
  import { prepareWorkspaceRead } from './tools/workspaceFile.js';
6
6
  import { LSP_BUFFER_BYTES, LSP_DOCUMENT_BYTES, LSP_FRAME_BYTES, LSP_HEADER_BYTES } from '../core/limits/byteBudgets.js';
7
7
  import { readUtf8Prefix } from '../core/io/boundedRead.js';
8
+ import { signalProcessTree } from '../core/process/runBoundedProcess.js';
8
9
  export class LspError extends Error {
9
10
  constructor(message) {
10
11
  super(message);
@@ -116,6 +117,7 @@ export class StdioLspClient {
116
117
  id = 0;
117
118
  buffer = Buffer.alloc(0);
118
119
  pending = new Map();
120
+ terminating = false;
119
121
  constructor(server, child) {
120
122
  this.server = server;
121
123
  this.child = child;
@@ -126,7 +128,7 @@ export class StdioLspClient {
126
128
  catch (error) {
127
129
  const lspError = error instanceof Error ? error : new LspError(String(error));
128
130
  this.rejectAll(lspError);
129
- this.child.kill('SIGTERM');
131
+ this.terminate();
130
132
  }
131
133
  });
132
134
  child.stderr.on('data', () => undefined);
@@ -136,7 +138,7 @@ export class StdioLspClient {
136
138
  static start(server) {
137
139
  if (!server.command)
138
140
  throw new LspError(`LSP server ${server.name} has no command.`);
139
- const child = spawn(server.command, server.args ?? [], { cwd: workspaceRoot(), stdio: ['pipe', 'pipe', 'pipe'] });
141
+ const child = spawn(server.command, server.args ?? [], { cwd: workspaceRoot(), detached: process.platform !== 'win32', stdio: ['pipe', 'pipe', 'pipe'] });
140
142
  return new StdioLspClient(server, child);
141
143
  }
142
144
  rejectAll(error) {
@@ -146,6 +148,17 @@ export class StdioLspClient {
146
148
  }
147
149
  this.pending.clear();
148
150
  }
151
+ terminate() {
152
+ if (this.terminating)
153
+ return;
154
+ this.terminating = true;
155
+ signalProcessTree(this.child, 'SIGTERM');
156
+ const forceTimer = setTimeout(() => signalProcessTree(this.child, 'SIGKILL'), 500);
157
+ forceTimer.unref?.();
158
+ this.child.stdin.destroy?.();
159
+ this.child.stdout.destroy?.();
160
+ this.child.stderr.destroy?.();
161
+ }
149
162
  onData(chunk) {
150
163
  if (this.buffer.length + chunk.length > LSP_BUFFER_BYTES)
151
164
  throw new LspError(`LSP receive buffer exceeds ${LSP_BUFFER_BYTES} bytes.`);
@@ -228,12 +241,14 @@ export class StdioLspClient {
228
241
  });
229
242
  }
230
243
  async close() {
244
+ if (this.terminating)
245
+ return;
231
246
  try {
232
247
  await this.request('shutdown', null, 2000).catch(() => undefined);
233
248
  this.notify('exit');
234
249
  }
235
250
  finally {
236
- this.child.kill('SIGTERM');
251
+ this.terminate();
237
252
  }
238
253
  }
239
254
  }
@@ -1,17 +1,32 @@
1
1
  import type { ToolSet } from 'ai';
2
2
  import { type PromptSession } from './systemPrompt.js';
3
+ import { readSettings } from '../config/settings.js';
4
+ import { type ModelRuntimeSelection } from './client.js';
5
+ import { SubagentCoordinator, type CoordinatorEvent } from '../core/subagent/subagentCoordinator.js';
6
+ import { WorkspaceMutationPolicy } from '../core/subagent/workspaceMutationPolicy.js';
3
7
  import { type LoadedMcpTools } from './mcp.js';
4
8
  import { createSubagentTool } from '../core/subagent/subagentRunner.js';
5
9
  import type { ContextFile } from '../config/contextFiles.js';
6
10
  export type ToolCategory = 'builtin' | 'lsp' | 'skill' | 'subagent' | 'mcp';
7
11
  /** Model type accepted by the subagent tool; derived so this module stays decoupled. */
8
- export type RequestModel = Parameters<typeof createSubagentTool>[0]['model'];
12
+ export type RequestModel = NonNullable<Parameters<typeof createSubagentTool>[0]['model']>;
13
+ export interface SubagentOverrides {
14
+ profile?: string;
15
+ workerModel?: string;
16
+ maxConcurrency?: number;
17
+ forceMode?: 'inspect';
18
+ }
19
+ export interface TurnExecutionScope {
20
+ coordinator: SubagentCoordinator;
21
+ mutationPolicy: WorkspaceMutationPolicy;
22
+ }
9
23
  export interface AssembledRequestContext {
10
24
  systemPrompt: string;
11
25
  availableTools: ToolSet;
12
26
  /** Tool name -> coarse origin bucket, used by /context to group token estimates. */
13
27
  toolCategories: Map<string, ToolCategory>;
14
28
  loadedMcp?: LoadedMcpTools;
29
+ executionScope: TurnExecutionScope;
15
30
  }
16
31
  /**
17
32
  * Assemble the system prompt and full tool set (built-in + LSP + subagent +
@@ -25,5 +40,11 @@ export declare function assembleRequestContext(input: {
25
40
  contextFiles: ContextFile[];
26
41
  session?: PromptSession;
27
42
  model: RequestModel;
43
+ modelRuntime?: ModelRuntimeSelection;
44
+ subagentOverrides?: SubagentOverrides;
45
+ onSubagentEvent?: (event: CoordinatorEvent) => void;
28
46
  abortSignal?: AbortSignal;
47
+ executionScope?: TurnExecutionScope;
48
+ /** Pre-read settings so a turn performs a single settings read (CR-024). */
49
+ settings?: Awaited<ReturnType<typeof readSettings>>;
29
50
  }): Promise<AssembledRequestContext>;
@@ -2,6 +2,11 @@ import { hazeTools } from './hazeTools.js';
2
2
  import { lspTools } from './lspTools.js';
3
3
  import { buildSystemPrompt } from './systemPrompt.js';
4
4
  import { readSettings } from '../config/settings.js';
5
+ import { resolveWorkerRuntime } from './client.js';
6
+ import { resolveExecutionProfile } from '../core/subagent/executionProfiles.js';
7
+ import { SubagentCoordinator } from '../core/subagent/subagentCoordinator.js';
8
+ import { WorkspaceMutationPolicy } from '../core/subagent/workspaceMutationPolicy.js';
9
+ import { fallbackProviderCapabilities, fallbackWorkerRuntime } from '../core/subagent/contracts.js';
5
10
  import { installedLspServers } from '../config/lspSettings.js';
6
11
  import { configuredMcpServers } from '../config/mcpSettings.js';
7
12
  import { loadMcpTools } from './mcp.js';
@@ -19,16 +24,51 @@ import { addCapabilityTools } from './capabilities.js';
19
24
  * close (`.close()`) once it is done with the assembled context.
20
25
  */
21
26
  export async function assembleRequestContext(input) {
22
- const settings = await readSettings();
27
+ const settings = input.settings ?? await readSettings();
23
28
  const skillRegistry = await loadSkillRegistry();
24
- const enabledSkills = new Map([...skillRegistry.skills.entries()].filter(([name]) => isSkillEnabled(settings, name)));
29
+ const enabledSkills = new Map(skillRegistry.skills);
30
+ if (skillRegistry.candidates) {
31
+ enabledSkills.clear();
32
+ for (const skill of skillRegistry.candidates) {
33
+ if (isSkillEnabled(settings, skill.name, skill.source) && !enabledSkills.has(skill.name))
34
+ enabledSkills.set(skill.name, skill);
35
+ }
36
+ }
37
+ else {
38
+ for (const [name, skill] of enabledSkills)
39
+ if (!isSkillEnabled(settings, name, skill.source))
40
+ enabledSkills.delete(name);
41
+ }
25
42
  const hasInstalledLsp = (await installedLspServers(settings)).length > 0;
43
+ const profileName = input.subagentOverrides?.profile ?? settings.subagents?.defaultProfile;
44
+ const profile = resolveExecutionProfile(profileName, settings.subagents?.profiles, input.subagentOverrides?.maxConcurrency);
45
+ const executionScope = input.executionScope ?? {
46
+ mutationPolicy: new WorkspaceMutationPolicy(),
47
+ coordinator: new SubagentCoordinator(profile ?? resolveExecutionProfile(undefined, undefined), input.onSubagentEvent),
48
+ };
49
+ const { coordinator, mutationPolicy } = executionScope;
50
+ let blockedReason = profile ? undefined : `Unknown subagent profile ${profileName}. Configure subagents.profiles or select a built-in profile.`;
51
+ let workerRuntime;
52
+ if (input.modelRuntime) {
53
+ const resolution = await resolveWorkerRuntime({ active: input.modelRuntime, settings, selector: input.subagentOverrides?.workerModel ?? settings.subagents?.workerModel, cwd: input.session?.cwd });
54
+ if (resolution.status === 'found')
55
+ workerRuntime = resolution.runtime;
56
+ else
57
+ blockedReason = resolution.message;
58
+ }
59
+ else if (settings.subagents?.workerModel || input.subagentOverrides?.workerModel) {
60
+ blockedReason = 'An explicit worker model could not be resolved for this request. Configure it via /provider and retry.';
61
+ }
62
+ workerRuntime ??= {
63
+ ...fallbackWorkerRuntime(input.model, input.modelRuntime?.selector, input.modelRuntime?.config.providerName),
64
+ capabilities: input.modelRuntime?.config.capabilities ?? fallbackProviderCapabilities(),
65
+ };
26
66
  const toolCategories = new Map();
27
67
  const availableTools = {};
28
68
  addCapabilityTools({ availableTools, toolCategories, loaded: { category: 'builtin', tools: hazeTools } });
29
69
  if (hasInstalledLsp)
30
70
  addCapabilityTools({ availableTools, toolCategories, loaded: { category: 'lsp', tools: lspTools } });
31
- addCapabilityTools({ availableTools, toolCategories, loaded: { category: 'subagent', tools: { subagent: createSubagentTool({ model: input.model, contextFiles: input.contextFiles, session: input.session }) } } });
71
+ addCapabilityTools({ availableTools, toolCategories, loaded: { category: 'subagent', tools: { subagent: createSubagentTool({ runtime: workerRuntime, profile: profile ?? undefined, coordinator, mutationPolicy, blockedReason, forceMode: input.subagentOverrides?.forceMode, session: input.session }) } } });
32
72
  addCapabilityTools({ availableTools, toolCategories, loaded: { category: 'skill', tools: buildSkillTools({ skills: enabledSkills, errors: skillRegistry.errors ?? [] }) } });
33
73
  const mcpServers = configuredMcpServers(settings).filter(server => server.enabled !== false);
34
74
  const loadedMcp = mcpServers.length > 0
@@ -38,7 +78,7 @@ export async function assembleRequestContext(input) {
38
78
  addCapabilityTools({ availableTools, toolCategories, loaded: { category: 'mcp', tools: loadedMcp.tools }, skipCollisions: true });
39
79
  }
40
80
  const mcpAvailable = Boolean(loadedMcp && Object.keys(loadedMcp.tools).length > 0);
41
- const skillErrors = (skillRegistry.errors ?? []).map(error => `${error.directory}: ${error.message}`);
81
+ const skillErrors = (skillRegistry.errors ?? []).map(error => `${error.source ? `${error.source}/` : ''}${error.directory}: ${error.message}`);
42
82
  const systemPrompt = `${buildSystemPrompt(input.contextFiles, input.session, { lspAvailable: hasInstalledLsp, mcpAvailable })}${skillErrors.length ? `\n\n<skill-load-errors>\nInvalid skills were isolated:\n${skillErrors.map(error => `- ${error}`).join('\n')}\n</skill-load-errors>` : ''}`;
43
- return { systemPrompt, availableTools, toolCategories, loadedMcp };
83
+ return { systemPrompt, availableTools, toolCategories, loadedMcp, executionScope };
44
84
  }
@@ -8,4 +8,7 @@ export declare function buildSystemPrompt(contextFiles?: ContextFile[], session?
8
8
  lspAvailable?: boolean;
9
9
  mcpAvailable?: boolean;
10
10
  }): string;
11
- export declare function buildSubagentPrompt(contextFiles?: ContextFile[], session?: PromptSession): string;
11
+ export declare function buildSubagentPrompt(contextFiles?: ContextFile[], session?: PromptSession, mode?: 'inspect' | 'research' | 'implement' | 'validate', budget?: {
12
+ maxToolCalls: number;
13
+ maxSteps: number;
14
+ }): string;
@@ -31,9 +31,9 @@ export function buildSystemPrompt(contextFiles = [], session, options = {}) {
31
31
  ## Tool use
32
32
  ${lspToolRule}${mcpToolRule}- grep locates text patterns and non-semantic matches. listFiles discovers structure. readFile returns bounded numbered lines with nextOffset for pagination.
33
33
  - editFile performs unique replacements. If an edit fails, read that exact file again before retrying; use replaceLines when current line numbers are safer.
34
- - writeFile creates files and only overwrites when explicitly requested. bash runs inspection, scripts, and validation. readToolOutput retrieves omitted oversized command output.
34
+ - writeFile creates files and only overwrites when explicitly requested. bash runs inspection, scripts, and validation; use background=true for dev servers/watchers, inspect them with process/readToolOutput, and kill every process you start when done. readToolOutput retrieves omitted oversized command output.
35
35
  - fetch reads a public URL and returns readable content (markdown for docs, pretty JSON, or text); use it for current docs, API references, and error lookups instead of guessing from memory. Private/loopback/metadata hosts and non-http(s) schemes are blocked; oversize output is retrievable with readToolOutput.
36
- - subagent is only for two or more independent tasks that benefit from separate context.
36
+ - Use subagent as a context-isolation boundary. Delegate an independent, self-contained task when its private reads/searches/tool output will likely be much larger than the compact deliverable needed here; one substantial task is sufficient. Keep trivial, conversation-coupled, user-interactive, sequentially dependent, or uncertain shared-mutation work here. Give a precise objective, deliverable, mode, and path scope—never paste chat history or file contents. Submit genuinely independent tasks together and let runtime limits schedule them.
37
37
  - skill loads one installed workflow by name. writeTasks is for substantial work, normally five or more steps; update it only at meaningful phase changes, blockers, or completion.
38
38
  - Prefer targeted reads and checks. Do not repeat unchanged reads or failing validation without a relevant change.
39
39
  - Ignored files require explicit need. Keep file mutations separate from validation commands when practical.
@@ -50,10 +50,20 @@ ${lspToolRule}${mcpToolRule}- grep locates text patterns and non-semantic matche
50
50
  Current date: ${date}
51
51
  Current working directory: ${cwd}`;
52
52
  }
53
- export function buildSubagentPrompt(contextFiles = [], session) {
53
+ export function buildSubagentPrompt(contextFiles = [], session, mode = 'implement', budget) {
54
54
  const date = (session?.start ?? new Date()).toISOString().slice(0, 10);
55
55
  const cwd = (session?.cwd ?? process.cwd()).replace(/\\/g, '/');
56
- return `You are a focused coding subagent. Complete only the assigned task with the available tools. Inspect narrowly, edit when requested, validate relevant changes, and return a concise handoff containing findings, changed paths, validation, blockers, and the exact next action if incomplete. Do not ask for routine command confirmation. After a failed edit, reread the affected file before retrying.${projectContextSection(contextFiles)}
56
+ const modeRule = mode === 'inspect'
57
+ ? 'Inspect only. You have no shell or mutation tools.'
58
+ : mode === 'research'
59
+ ? 'Research and inspect only. You may fetch public sources; you cannot run shell commands or mutate files.'
60
+ : mode === 'validate'
61
+ ? 'Inspect and run validation commands. Treat commands as potentially mutating; do not edit files directly.'
62
+ : 'Implement the bounded task, using targeted edits and relevant validation.';
63
+ const budgetRule = budget
64
+ ? ` You have at most ${budget.maxToolCalls} tool calls across ${budget.maxSteps} steps. Sample strategically rather than reading the whole repository; stop gathering evidence early enough to synthesize. A concise partial deliverable with explicit coverage gaps is mandatory and better than exhausting the budget with no output.`
65
+ : '';
66
+ return `You are a disposable ${mode} subagent in a fresh private context. Complete only the JSON task capsule in your single user message; you have no parent/sibling chat history. ${modeRule}${budgetRule} Investigate freely, but return only the requested self-contained deliverable with evidence, changed paths, validation, blockers, and coverage gaps. Do not ask the user questions or narrate your process. Follow newly surfaced scoped project instructions before continuing; after a failed edit, reread the file before retrying.${projectContextSection(contextFiles)}
57
67
 
58
68
  Current date: ${date}
59
69
  Current working directory: ${cwd}`;
@@ -1,4 +1,4 @@
1
- export type ToolFailureReasonCode = 'old_text_missing' | 'old_text_not_unique' | 'overlapping_edits' | 'ignored_path' | 'existing_file_requires_overwrite' | 'invalid_line_range' | 'io_error' | 'file_too_large' | 'blocked_url' | 'scoped_instructions_discovered';
1
+ export type ToolFailureReasonCode = 'old_text_missing' | 'old_text_not_unique' | 'overlapping_edits' | 'ignored_path' | 'existing_file_requires_overwrite' | 'invalid_line_range' | 'io_error' | 'file_too_large' | 'blocked_url' | 'background_limit' | 'background_not_allowed' | 'process_id_required' | 'process_not_found' | 'process_already_exited' | 'process_kill_failed' | 'output_expired' | 'aborted' | 'scoped_instructions_discovered';
2
2
  export type ToolDiffLine = {
3
3
  type: 'add' | 'remove' | 'context';
4
4
  oldLine?: number;