@denizokcu/haze 1.5.1 → 1.6.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 (87) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +61 -3
  3. package/SECURITY.md +1 -1
  4. package/dist/buildInfo.json +3 -3
  5. package/dist/cli/chat/DynamicFrame.d.ts +0 -13
  6. package/dist/cli/chat/DynamicFrame.js +1 -1
  7. package/dist/cli/chat/inputSuggestions.js +2 -0
  8. package/dist/cli/chat/terminalControl.d.ts +4 -2
  9. package/dist/cli/chat/terminalControl.js +16 -5
  10. package/dist/cli/chat/wizard/pluginHandlers.d.ts +10 -0
  11. package/dist/cli/chat/wizard/pluginHandlers.js +156 -0
  12. package/dist/cli/chat/wizard/skillsHandlers.js +2 -2
  13. package/dist/cli/chat/wizard/types.d.ts +20 -0
  14. package/dist/cli/chat/wizard/uiState.d.ts +25 -1
  15. package/dist/cli/chat/wizard/uiState.js +3 -1
  16. package/dist/cli/chat/wizardDispatch.js +6 -0
  17. package/dist/cli/commands/chat.js +18 -3
  18. package/dist/cli/commands/commandHelp.js +7 -2
  19. package/dist/cli/commands/commands.d.ts +5 -0
  20. package/dist/cli/commands/commands.js +17 -3
  21. package/dist/cli/commands/initCommand.js +3 -2
  22. package/dist/cli/commands/pluginCommand.d.ts +16 -0
  23. package/dist/cli/commands/pluginCommand.js +127 -0
  24. package/dist/cli/commands/reasoningCommand.d.ts +0 -15
  25. package/dist/cli/commands/reasoningCommand.js +1 -3
  26. package/dist/cli/commands/skillsWizard.js +4 -0
  27. package/dist/cli/commands/streaming/agentAttempt.js +2 -1
  28. package/dist/cli/commands/streaming/attemptOutcome.d.ts +2 -0
  29. package/dist/cli/commands/streaming/attemptOutcome.js +4 -3
  30. package/dist/cli/commands/streaming/attemptSetup.d.ts +2 -0
  31. package/dist/cli/commands/streaming/attemptSetup.js +3 -2
  32. package/dist/cli/commands/streaming/stallRecovery.d.ts +6 -0
  33. package/dist/cli/commands/streaming/stallRecovery.js +6 -5
  34. package/dist/cli/commands/streaming/turnRuntime.js +2 -4
  35. package/dist/cli/commands/wizardFlow.d.ts +59 -0
  36. package/dist/cli/commands/wizardFlow.js +40 -0
  37. package/dist/cli/contextReportCli.js +4 -3
  38. package/dist/cli/index.js +19 -2
  39. package/dist/config/contextFiles.js +3 -2
  40. package/dist/config/inputHistory.js +3 -3
  41. package/dist/config/paths.d.ts +1 -0
  42. package/dist/config/paths.js +1 -0
  43. package/dist/config/providerAuth.js +3 -3
  44. package/dist/config/settings.d.ts +10 -1
  45. package/dist/config/settings.js +7 -4
  46. package/dist/config/updateCheck.js +3 -3
  47. package/dist/core/agent/budgets.d.ts +17 -0
  48. package/dist/core/agent/budgets.js +19 -0
  49. package/dist/core/agent/reasoningPolicy.js +1 -1
  50. package/dist/core/agent/workState.d.ts +0 -2
  51. package/dist/core/agent/workState.js +1 -1
  52. package/dist/core/log/llmLog.js +1 -1
  53. package/dist/core/session/sessionStore.js +4 -3
  54. package/dist/core/subagent/contracts.d.ts +1 -11
  55. package/dist/core/subagent/contracts.js +0 -22
  56. package/dist/llm/client.js +1 -1
  57. package/dist/llm/subagentRunner.d.ts +1 -6
  58. package/dist/llm/subagentRunner.js +11 -23
  59. package/dist/llm/tools/fileTools.js +2 -3
  60. package/dist/llm/tools/gitIgnore.js +1 -1
  61. package/dist/llm/tools/grepRunner.d.ts +10 -0
  62. package/dist/llm/tools/grepRunner.js +24 -0
  63. package/dist/llm/tools/toolContext.d.ts +2 -3
  64. package/dist/llm/tools/toolContext.js +2 -3
  65. package/dist/llm/tools/toolContextState.d.ts +0 -1
  66. package/dist/llm/tools/toolContextState.js +1 -4
  67. package/dist/llm/workerContext.d.ts +0 -7
  68. package/dist/llm/workerContext.js +0 -17
  69. package/dist/skills/SkillLoader.js +3 -2
  70. package/dist/skills/SkillRegistry.js +7 -4
  71. package/dist/skills/builder/SkillBuilder.js +11 -10
  72. package/dist/skills/plugins/installer.d.ts +25 -0
  73. package/dist/skills/plugins/installer.js +272 -0
  74. package/dist/skills/plugins/package.d.ts +41 -0
  75. package/dist/skills/plugins/package.js +275 -0
  76. package/dist/skills/plugins/runtime.d.ts +3 -0
  77. package/dist/skills/plugins/runtime.js +108 -0
  78. package/dist/skills/skillTools.js +10 -5
  79. package/dist/skills/types.d.ts +4 -0
  80. package/dist/ui/codeHighlight.d.ts +1 -1
  81. package/dist/ui/codeHighlight.js +112 -4
  82. package/dist/ui/components/StreamingMarkdownText.d.ts +0 -2
  83. package/dist/ui/components/StreamingMarkdownText.js +1 -1
  84. package/dist/ui/components/TextInput.d.ts +1 -1
  85. package/dist/utils/fs.d.ts +10 -0
  86. package/dist/utils/fs.js +37 -2
  87. package/package.json +17 -20
package/dist/cli/index.js CHANGED
@@ -1,7 +1,5 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command, Option } from 'commander';
3
- import { chatCommand } from './commands/chat.js';
4
- import { runHeadless } from './commands/runCommand.js';
5
3
  import { installTerminalTitle, terminalTitleLabel } from './terminalTitle.js';
6
4
  import { findSession, latestSession, readSessionEntries } from '../core/session/sessionStore.js';
7
5
  import { formatSessionReport, summarizeSessionEntries } from '../core/session/sessionReport.js';
@@ -10,6 +8,7 @@ import { STDIN_PROMPT_BYTES } from '../core/limits.js';
10
8
  import { readPackageVersion } from '../utils/version.js';
11
9
  import { formatVersionVerbose, readBuildInfo } from '../utils/buildInfo.js';
12
10
  import { runDoctor } from './commands/doctor.js';
11
+ import { runPluginCommand } from './commands/pluginCommand.js';
13
12
  installBackgroundProcessSignalHandlers();
14
13
  const version = readPackageVersion() ?? '0.0.0';
15
14
  const program = new Command();
@@ -101,6 +100,20 @@ program.command('doctor')
101
100
  .action(async () => {
102
101
  process.exitCode = await runDoctor();
103
102
  });
103
+ const plugins = program.command('plugin').alias('kit')
104
+ .description('inspect and install local Claude/Agent Plugins packages and collections (skills only)');
105
+ plugins.command('inspect <directory> [name]').action(async (directory, name) => {
106
+ process.stdout.write(`${await runPluginCommand(['inspect', directory, ...(name ? [name] : [])])}\n`);
107
+ });
108
+ plugins.command('install <directory> [name]').action(async (directory, name) => {
109
+ process.stdout.write(`${await runPluginCommand(['install', directory, ...(name ? [name] : [])])}\n`);
110
+ });
111
+ plugins.command('list').action(async () => {
112
+ process.stdout.write(`${await runPluginCommand(['list'])}\n`);
113
+ });
114
+ plugins.command('remove <name>').action(async (name) => {
115
+ process.stdout.write(`${await runPluginCommand(['remove', name])}\n`);
116
+ });
104
117
  program.command('report [id]')
105
118
  .description('summarize a saved session without exposing prompts or tool output (defaults to the latest session in this workspace)')
106
119
  .option('--json', 'print the structured report')
@@ -132,6 +145,7 @@ program.action(async () => {
132
145
  }
133
146
  if (prompt) {
134
147
  // One-shot runs are always fresh and non-durable; --continue is ignored in this mode.
148
+ const { runHeadless } = await import('./commands/runCommand.js');
135
149
  const code = await runHeadless({
136
150
  prompt,
137
151
  modelOverride: opts.model,
@@ -149,6 +163,9 @@ program.action(async () => {
149
163
  process.exitCode = code;
150
164
  return;
151
165
  }
166
+ // Chat and headless pull the full React/Ink/AI-SDK graph; import them only
167
+ // when a turn actually runs so --help/report/doctor stay fast to boot.
168
+ const { chatCommand } = await import('./commands/chat.js');
152
169
  await chatCommand({ debug: Boolean(opts.debug), continueSession: Boolean(opts.continue), resumeSessionId: opts.resume, noSession: opts.session === false, version, build: sessionBuildProvenance() });
153
170
  });
154
171
  /** Safe build provenance recorded into session headers (commit + build time only). */
@@ -1,4 +1,5 @@
1
- import fs from 'fs-extra';
1
+ import fs from 'node:fs/promises';
2
+ import { pathExists } from '../utils/fs.js';
2
3
  import os from 'node:os';
3
4
  import path from 'node:path';
4
5
  import crypto from 'node:crypto';
@@ -45,7 +46,7 @@ async function readContextCandidates(candidates, seen = new Set(), options = {},
45
46
  if (seen.has(absolute))
46
47
  continue;
47
48
  seen.add(absolute);
48
- if (!await fs.pathExists(absolute))
49
+ if (!await pathExists(absolute))
49
50
  continue;
50
51
  const stat = await fs.stat(absolute).catch(() => null);
51
52
  if (!stat?.isFile())
@@ -1,4 +1,4 @@
1
- import fs from 'fs-extra';
1
+ import { pathExists, readJson } from '../utils/fs.js';
2
2
  import path from 'node:path';
3
3
  import { HAZE_DIR } from './paths.js';
4
4
  import { tightenPrivateFile, writePrivateJsonAtomic } from './privateStorage.js';
@@ -13,9 +13,9 @@ function normalizeHistory(value) {
13
13
  // The storage path is injectable so tests isolate via temp files instead of
14
14
  // production switches on test-env globals (CR-011).
15
15
  export async function readInputHistory(file = INPUT_HISTORY_FILE) {
16
- if (await fs.pathExists(file))
16
+ if (await pathExists(file))
17
17
  await tightenPrivateFile(file);
18
- const data = await fs.readJson(file).catch(() => []);
18
+ const data = await readJson(file).catch(() => []);
19
19
  return normalizeHistory(data).slice(-MAX_HISTORY_ITEMS);
20
20
  }
21
21
  export async function writeInputHistory(history, file = INPUT_HISTORY_FILE) {
@@ -1,2 +1,3 @@
1
1
  export declare const HAZE_DIR: string;
2
2
  export declare const GLOBAL_SKILLS_DIR: string;
3
+ export declare const GLOBAL_PLUGINS_DIR: string;
@@ -2,3 +2,4 @@ import os from 'node:os';
2
2
  import path from 'node:path';
3
3
  export const HAZE_DIR = path.join(os.homedir(), '.haze');
4
4
  export const GLOBAL_SKILLS_DIR = path.join(HAZE_DIR, 'skills');
5
+ export const GLOBAL_PLUGINS_DIR = path.join(HAZE_DIR, 'plugins');
@@ -1,4 +1,4 @@
1
- import fs from 'fs-extra';
1
+ import { pathExists, readJson } from '../utils/fs.js';
2
2
  import path from 'node:path';
3
3
  import { z } from 'zod';
4
4
  import { HAZE_DIR } from './paths.js';
@@ -18,9 +18,9 @@ function authReadError(error) {
18
18
  }
19
19
  export async function readProviderAuthStore() {
20
20
  try {
21
- if (await fs.pathExists(PROVIDER_AUTH_FILE))
21
+ if (await pathExists(PROVIDER_AUTH_FILE))
22
22
  await tightenPrivateFile(PROVIDER_AUTH_FILE);
23
- const raw = await fs.readJson(PROVIDER_AUTH_FILE);
23
+ const raw = await readJson(PROVIDER_AUTH_FILE);
24
24
  return providerAuthStoreSchema.parse(raw);
25
25
  }
26
26
  catch (error) {
@@ -84,7 +84,7 @@ export interface HazeSettings {
84
84
  mcpServers?: HazeMcpServer[];
85
85
  skills?: HazeSkillSetting[];
86
86
  subagents?: HazeSubagentSettings;
87
- /** Optional reasoning depth; absent means the built-in default (`high`), the `provider-default` sentinel sends no parameter. */
87
+ /** Optional reasoning depth; absent means the built-in default (`low`), the `provider-default` sentinel sends no parameter. */
88
88
  reasoning?: StoredReasoningSetting;
89
89
  /** `compact` keeps working context small for models with limited reliable context/tool calling. Default: `standard`. */
90
90
  steeringProfile?: 'standard' | 'compact';
@@ -112,6 +112,15 @@ export interface HazeSettings {
112
112
  * successful step, so intermittent blips never exhaust it.
113
113
  */
114
114
  retryBaseDelayMs?: number;
115
+ /**
116
+ * Idle-stream stall window in milliseconds: how long the model stream may
117
+ * emit nothing before the attempt is aborted (and retried while the shared
118
+ * model-retry pool lasts). Unset means the built-in class-aware default —
119
+ * 5 minutes for hosted endpoints, 30 minutes for loopback/local inference
120
+ * servers, whose prompt ingestion and hidden reasoning can emit no bytes
121
+ * (no SSE keepalives) for many minutes.
122
+ */
123
+ streamIdleTimeoutMs?: number;
115
124
  /**
116
125
  * Manual `/compact` mode (F-09): `llm-summary` (default) asks the active
117
126
  * model to summarize the older history; `heuristic` keeps the bounded
@@ -1,4 +1,4 @@
1
- import fs from 'fs-extra';
1
+ import { pathExists, readJson } from '../utils/fs.js';
2
2
  import path from 'node:path';
3
3
  import { z } from 'zod';
4
4
  import { HAZE_DIR } from './paths.js';
@@ -7,7 +7,7 @@ import { customProfileSchema } from '../core/subagent/executionProfiles.js';
7
7
  import { REASONING_LEVELS, REASONING_PROVIDER_DEFAULT } from '../core/agent/reasoningPolicy.js';
8
8
  /**
9
9
  * Optional, explicitly user-controlled reasoning depth (provider/protocol
10
- * gated). Absent means the built-in default (`high`); the `provider-default`
10
+ * gated). Absent means the built-in default (`low`); the `provider-default`
11
11
  * sentinel stores an explicit "send no parameter" opt-out.
12
12
  */
13
13
  const storedReasoningValues = [...REASONING_LEVELS, REASONING_PROVIDER_DEFAULT];
@@ -56,6 +56,8 @@ const contextWindowFallbackSchema = z.number().int().min(1_000).max(10_000_000);
56
56
  const modelRetriesSchema = z.number().int().min(0).max(10);
57
57
  /** Retry backoff base must be a plausible delay (not fractions/junk). */
58
58
  const retryBaseDelaySchema = z.number().int().min(250).max(60_000);
59
+ /** Idle-stall window must be a plausible wait (≥ 1s for tests, capped at the 24h turn-deadline ceiling). */
60
+ const streamIdleTimeoutSchema = z.number().int().min(1_000).max(24 * 60 * 60_000);
59
61
  /**
60
62
  * An escalation model is an explicit `provider:model` selector (KISS: shape
61
63
  * only — whether the provider/model actually resolves is checked by the
@@ -77,6 +79,7 @@ const settingsSchema = z.object({
77
79
  localContextWindowFallbackTokens: contextWindowFallbackSchema.optional(),
78
80
  modelRetries: modelRetriesSchema.optional(),
79
81
  retryBaseDelayMs: retryBaseDelaySchema.optional(),
82
+ streamIdleTimeoutMs: streamIdleTimeoutSchema.optional(),
80
83
  manualCompaction: z.enum(['llm-summary', 'heuristic']).optional(),
81
84
  tips: z.object({ enabled: z.boolean().optional() }).optional(),
82
85
  theme: z.string().optional(),
@@ -89,9 +92,9 @@ function settingsReadError(error) {
89
92
  }
90
93
  export async function readSettings() {
91
94
  try {
92
- if (await fs.pathExists(SETTINGS_FILE))
95
+ if (await pathExists(SETTINGS_FILE))
93
96
  await tightenPrivateFile(SETTINGS_FILE);
94
- const raw = await fs.readJson(SETTINGS_FILE);
97
+ const raw = await readJson(SETTINGS_FILE);
95
98
  return settingsSchema.parse(raw);
96
99
  }
97
100
  catch (error) {
@@ -1,6 +1,6 @@
1
1
  import { execFile as execFileCallback } from 'node:child_process';
2
2
  import { promisify } from 'node:util';
3
- import fs from 'fs-extra';
3
+ import { pathExists, readJson } from '../utils/fs.js';
4
4
  import path from 'node:path';
5
5
  import { HAZE_DIR } from './paths.js';
6
6
  import { isNewer } from '../utils/version.js';
@@ -14,9 +14,9 @@ async function defaultExecVersion(packageName, options) {
14
14
  return stdout;
15
15
  }
16
16
  async function defaultReadStore(file) {
17
- if (await fs.pathExists(file))
17
+ if (await pathExists(file))
18
18
  await tightenPrivateFile(file);
19
- return fs.readJson(file).catch(() => ({}));
19
+ return readJson(file).catch(() => ({}));
20
20
  }
21
21
  async function defaultWriteStore(file, store) {
22
22
  await writePrivateJsonAtomic(file, store);
@@ -2,7 +2,24 @@ import type { ToolSet } from 'ai';
2
2
  export declare const DEFAULT_MAX_OUTPUT_TOKENS = 16384;
3
3
  /** Keep generated file payloads comfortably below a model's output-token ceiling. */
4
4
  export declare const WRITE_FILE_CHUNK_BYTES: number;
5
+ /** Built-in idle-stream stall window for hosted endpoints (`streamIdleTimeoutMs` setting overrides). */
5
6
  export declare const IDLE_TIMEOUT_MS: number;
7
+ /**
8
+ * Built-in idle-stream stall window for loopback/local inference servers.
9
+ * Their time-to-first-token includes prompt ingestion and hidden reasoning
10
+ * with zero bytes emitted — LM Studio and Ollama send no SSE keepalives — so
11
+ * a healthy local model is indistinguishable from a dead stream for minutes.
12
+ * Aborting and retrying would discard the prefill work and re-do it, so the
13
+ * local default is deliberately patient; a genuine local hang is better
14
+ * resolved by the user than by three wasted re-prefills.
15
+ */
16
+ export declare const LOCAL_IDLE_TIMEOUT_MS: number;
17
+ /**
18
+ * Effective idle-stream stall window: the explicit `streamIdleTimeoutMs`
19
+ * setting wins; otherwise local inference servers get the patient local
20
+ * default and hosted endpoints the hosted one.
21
+ */
22
+ export declare function resolveStreamIdleTimeoutMs(setting: number | undefined, localProvider: boolean): number;
6
23
  /** Default per-tool execution deadline; an uncooperative tool cannot defer the turn indefinitely (RH-004). */
7
24
  export declare const DEFAULT_TOOL_DEADLINE_MS: number;
8
25
  /** Subagents legitimately run long; give their wrapper a larger deadline. */
@@ -1,7 +1,26 @@
1
1
  export const DEFAULT_MAX_OUTPUT_TOKENS = 16384;
2
2
  /** Keep generated file payloads comfortably below a model's output-token ceiling. */
3
3
  export const WRITE_FILE_CHUNK_BYTES = 16 * 1024;
4
+ /** Built-in idle-stream stall window for hosted endpoints (`streamIdleTimeoutMs` setting overrides). */
4
5
  export const IDLE_TIMEOUT_MS = 5 * 60_000;
6
+ /**
7
+ * Built-in idle-stream stall window for loopback/local inference servers.
8
+ * Their time-to-first-token includes prompt ingestion and hidden reasoning
9
+ * with zero bytes emitted — LM Studio and Ollama send no SSE keepalives — so
10
+ * a healthy local model is indistinguishable from a dead stream for minutes.
11
+ * Aborting and retrying would discard the prefill work and re-do it, so the
12
+ * local default is deliberately patient; a genuine local hang is better
13
+ * resolved by the user than by three wasted re-prefills.
14
+ */
15
+ export const LOCAL_IDLE_TIMEOUT_MS = 30 * 60_000;
16
+ /**
17
+ * Effective idle-stream stall window: the explicit `streamIdleTimeoutMs`
18
+ * setting wins; otherwise local inference servers get the patient local
19
+ * default and hosted endpoints the hosted one.
20
+ */
21
+ export function resolveStreamIdleTimeoutMs(setting, localProvider) {
22
+ return setting ?? (localProvider ? LOCAL_IDLE_TIMEOUT_MS : IDLE_TIMEOUT_MS);
23
+ }
5
24
  /** Default per-tool execution deadline; an uncooperative tool cannot defer the turn indefinitely (RH-004). */
6
25
  export const DEFAULT_TOOL_DEADLINE_MS = 10 * 60_000;
7
26
  /** Subagents legitimately run long; give their wrapper a larger deadline. */
@@ -5,7 +5,7 @@ export const REASONING_LEVELS = ['none', 'minimal', 'low', 'medium', 'high', 'xh
5
5
  * `none` (reasoning off) or the stored `provider-default` sentinel (written by
6
6
  * `/reasoning unset`); key-absent means this default.
7
7
  */
8
- export const DEFAULT_REASONING_LEVEL = 'medium';
8
+ export const DEFAULT_REASONING_LEVEL = 'low';
9
9
  /** Stored sentinel meaning "send no reasoning parameter at all". */
10
10
  export const REASONING_PROVIDER_DEFAULT = 'provider-default';
11
11
  export function isStoredReasoning(value) {
@@ -22,8 +22,6 @@ export declare function intentExpectsValidation(intent: RequestIntent): boolean;
22
22
  * a lone line-continuation backslash, and a trailing `--` separator are noise.
23
23
  */
24
24
  export declare function validationCommandKey(command: string): string;
25
- /** Stable, non-reversible identity safe to carry in a goal checkpoint. */
26
- export declare function validationCheckId(command: string): string;
27
25
  /**
28
26
  * Opportunistic red→green state for fix intents: no failing repro is required,
29
27
  * but when a pre-mutation validation did fail, that same check must pass after
@@ -114,7 +114,7 @@ function failedCheckScope(command) {
114
114
  return `direct@${workspacePathKey('.')}:${executable}`;
115
115
  }
116
116
  /** Stable, non-reversible identity safe to carry in a goal checkpoint. */
117
- export function validationCheckId(command) {
117
+ function validationCheckId(command) {
118
118
  return crypto.createHash('sha256').update(validationCommandKey(command)).digest('hex').slice(0, 16);
119
119
  }
120
120
  /** Encode check identity as `scope:kind:hash`. Self-describing so a pass can pair against carried ids without keeping raw commands. */
@@ -1,5 +1,5 @@
1
1
  import path from 'node:path';
2
- import fs from 'fs-extra';
2
+ import fs from 'node:fs/promises';
3
3
  import { HAZE_DIR } from '../../config/paths.js';
4
4
  import { appendPrivateFile, ensurePrivateFile, ensurePrivateDir, tightenPrivateFile } from '../../config/privateStorage.js';
5
5
  import { OrderedFileWriter } from '../persistence/orderedFileWriter.js';
@@ -1,6 +1,7 @@
1
1
  import crypto from 'node:crypto';
2
2
  import path from 'node:path';
3
- import fs from 'fs-extra';
3
+ import fs from 'node:fs/promises';
4
+ import { pathExists } from '../../utils/fs.js';
4
5
  import { HAZE_DIR } from '../../config/paths.js';
5
6
  import { prepareSessionEntryForWrite, repairRestoredConversation } from './sessionSlimming.js';
6
7
  import { appendPrivateFile, ensurePrivateDir, tightenPrivateFile, writePrivateFileAtomic } from '../../config/privateStorage.js';
@@ -68,7 +69,7 @@ export async function findSession(id, cwd = process.cwd(), sessionsDir = DEFAULT
68
69
  if (!normalizedId || normalizedId !== id || normalizedId === '.' || normalizedId === '..' || normalizedId.includes('/') || normalizedId.includes('\\') || path.isAbsolute(normalizedId))
69
70
  return undefined;
70
71
  const file = sessionFile(normalizedId, cwd, sessionsDir);
71
- if (!await fs.pathExists(file))
72
+ if (!await pathExists(file))
72
73
  return undefined;
73
74
  return { id: normalizedId, file, cwd: path.resolve(cwd), sessionsDir: path.resolve(sessionsDir) };
74
75
  }
@@ -293,7 +294,7 @@ function parseSessionEntry(value) {
293
294
  }
294
295
  async function scanSessionEntries(session, onEntry) {
295
296
  const file = validatedSessionFile(session);
296
- if (session.deferredWrite && !await fs.pathExists(file))
297
+ if (session.deferredWrite && !await pathExists(file))
297
298
  return [];
298
299
  await tightenPrivateFile(file);
299
300
  const parseErrors = [];
@@ -24,7 +24,6 @@ export interface SubagentTaskCapsule {
24
24
  mode: WorkerMode;
25
25
  scope: string[];
26
26
  acceptanceCriteria: string[];
27
- legacyMaxSteps?: number;
28
27
  }
29
28
  export type WorkerTermination = 'completed' | 'no_output' | 'step_limit' | 'tool_limit' | 'deadline_exceeded' | 'cancelled' | 'provider_error' | 'policy_blocked';
30
29
  export interface SubagentResultCapsule {
@@ -67,15 +66,7 @@ export interface SubagentTelemetry {
67
66
  export interface SubagentExecutionResult {
68
67
  capsule: SubagentResultCapsule;
69
68
  telemetry: SubagentTelemetry;
70
- status: 'ok' | 'error' | 'timeout' | 'cancelled';
71
- summary: string;
72
- toolCalls: SubagentTelemetry['toolCalls'];
73
- toolCallCount: number;
74
- tokens: {
75
- in?: number;
76
- out?: number;
77
- };
78
- durationMs: number;
69
+ /** Raw provider message on provider errors; kept for machine consumers (RT-03). */
79
70
  error?: string;
80
71
  }
81
72
  export interface WorkerRuntime {
@@ -90,4 +81,3 @@ export declare function fallbackProviderCapabilities(): ProviderCapabilities;
90
81
  /** Single source for the placeholder runtime used when only a bare model is available (CR-018). */
91
82
  export declare function fallbackWorkerRuntime(model: WorkerRuntime['model'], selector?: string, providerName?: string): WorkerRuntime;
92
83
  export declare function normalizeSubagentInput(input: SubagentToolInput, id: string): SubagentTaskCapsule;
93
- export declare function withLegacyProjection(capsule: SubagentResultCapsule, telemetry: SubagentTelemetry, error?: string): SubagentExecutionResult;
@@ -31,25 +31,3 @@ export function fallbackWorkerRuntime(model, selector = 'active-model', provider
31
31
  export function normalizeSubagentInput(input, id) {
32
32
  return { id, objective: input.objective, deliverable: input.deliverable, mode: input.mode, scope: input.scope ?? [], acceptanceCriteria: input.acceptanceCriteria ?? [] };
33
33
  }
34
- function legacyStatus(termination) {
35
- if (termination === 'completed' || termination === 'no_output')
36
- return 'ok';
37
- if (termination === 'cancelled')
38
- return 'cancelled';
39
- if (termination === 'step_limit' || termination === 'tool_limit' || termination === 'deadline_exceeded')
40
- return 'timeout';
41
- return 'error';
42
- }
43
- export function withLegacyProjection(capsule, telemetry, error) {
44
- return {
45
- capsule,
46
- telemetry,
47
- status: legacyStatus(capsule.termination),
48
- summary: capsule.deliverable,
49
- toolCalls: telemetry.toolCalls,
50
- toolCallCount: telemetry.toolCallCount,
51
- tokens: { in: telemetry.usage.inputTokens, out: telemetry.usage.outputTokens },
52
- durationMs: telemetry.durationMs,
53
- ...(error ? { error } : {}),
54
- };
55
- }
@@ -83,7 +83,7 @@ function runtimeForSelection(settings, selection, cwd, reasoningOverride, sessio
83
83
  const selector = modelSelector(selection.provider, name);
84
84
  // The full precedence chain lives in one pure resolver
85
85
  // (`resolveAttemptReasoning`): run-scoped override → session per-model map →
86
- // global settings → built-in default (medium). The stored or session
86
+ // global settings → built-in default (low). The stored or session
87
87
  // `provider-default` sentinel sends no parameter at all. The capability gate
88
88
  // in resolveReasoningPolicy is unchanged — nothing forces the parameter onto
89
89
  // an unsupported protocol.
@@ -1,4 +1,3 @@
1
- import type { ContextFile } from '../config/contextFiles.js';
2
1
  import { toolOnlyStepCount } from '../core/agent/turnPolicy.js';
3
2
  import { type HazeToolContext } from './tools/toolContext.js';
4
3
  import { type WorkerContextBundle } from './workerContext.js';
@@ -18,14 +17,11 @@ declare function validationFromOutput(name: string, output: unknown): {
18
17
  ok: boolean;
19
18
  } | undefined;
20
19
  export type SubagentResult = SubagentExecutionResult;
21
- export declare function runSubagent(taskInput: string | SubagentTaskCapsule, options: {
20
+ export declare function runSubagent(task: SubagentTaskCapsule, options: {
22
21
  model?: WorkerRuntime['model'];
23
22
  runtime?: WorkerRuntime;
24
23
  profile?: SubagentExecutionProfile;
25
- contextFiles?: ContextFile[];
26
24
  contextBundle?: WorkerContextBundle;
27
- allowedTools?: readonly string[];
28
- maxSteps?: number;
29
25
  abortSignal?: AbortSignal;
30
26
  deadlineExpired?: () => boolean;
31
27
  queueMs?: number;
@@ -40,7 +36,6 @@ export declare function createSubagentTool(options: {
40
36
  mutationPolicy?: WorkspaceMutationPolicy;
41
37
  blockedReason?: string;
42
38
  forceMode?: 'inspect';
43
- contextFiles?: ContextFile[];
44
39
  session?: PromptSession;
45
40
  }): ({
46
41
  deferLoading?: boolean;
@@ -1,13 +1,13 @@
1
1
  import { isStepCount, streamText, tool } from 'ai';
2
2
  import { estimateValueTokens } from '../core/agent/contextBudget.js';
3
- import { SUBAGENT_MAX_STEPS, SUBAGENT_MIN_STEPS, SUBAGENT_SYNTHESIS_RESERVE, SUBAGENT_TOOL_ONLY_LIMIT, createToolExecutionBudget, isToolBudgetBlocked, withToolExecutionBudget, } from '../core/agent/budgets.js';
3
+ import { SUBAGENT_SYNTHESIS_RESERVE, SUBAGENT_TOOL_ONLY_LIMIT, createToolExecutionBudget, isToolBudgetBlocked, withToolExecutionBudget, } from '../core/agent/budgets.js';
4
4
  import { storeToolOutput } from '../core/agent/toolOutputStore.js';
5
5
  import { changedPathsFromTool } from '../core/agent/toolCapabilities.js';
6
6
  import { withSyntheticControl } from '../core/agent/requestAssembly.js';
7
7
  import { toolOnlyStepCount } from '../core/agent/turnPolicy.js';
8
8
  import { toolsContextFor } from './tools/toolContext.js';
9
- import { assembleWorkerContext, compatibilityBundle, workerTaskMessage } from './workerContext.js';
10
- import { fallbackWorkerRuntime, normalizeSubagentInput, subagentInputSchema, withLegacyProjection, } from '../core/subagent/contracts.js';
9
+ import { assembleWorkerContext, workerTaskMessage } from './workerContext.js';
10
+ import { fallbackWorkerRuntime, normalizeSubagentInput, subagentInputSchema, } from '../core/subagent/contracts.js';
11
11
  import { COMPATIBILITY_PROFILE } from '../core/subagent/executionProfiles.js';
12
12
  import { SubagentCoordinator } from '../core/subagent/subagentCoordinator.js';
13
13
  import { projectContextSection } from './systemPrompt.js';
@@ -54,22 +54,14 @@ function terminalResult(task, runtime, profile, termination, message, queueMs =
54
54
  const capsule = { id: task.id, termination, usable: false, deliverable: message, changedPaths: [], validation: [], coverageGaps: [message], truncated: false };
55
55
  const telemetry = telemetryBase(runtime, profile, estimateValueTokens(workerTaskMessage(task)), 0, queueMs);
56
56
  telemetry.estimates.resultCapsuleTokens = estimateValueTokens(capsule);
57
- return withLegacyProjection(capsule, telemetry, termination === 'provider_error' || termination === 'policy_blocked' ? message : undefined);
57
+ return { capsule, telemetry, ...(termination === 'provider_error' || termination === 'policy_blocked' ? { error: message } : {}) };
58
58
  }
59
- export async function runSubagent(taskInput, options) {
59
+ export async function runSubagent(task, options) {
60
60
  const profile = options.profile ?? COMPATIBILITY_PROFILE;
61
61
  const runtime = options.runtime ?? fallbackWorkerRuntime(options.model);
62
- const task = typeof taskInput === 'string'
63
- ? { 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('shell') ? 'validate' : options.allowedTools.includes('fetch') ? 'research' : 'inspect') : 'implement', scope: [], acceptanceCriteria: [], legacyMaxSteps: options.maxSteps }
64
- : taskInput;
65
- const requestedSteps = task.legacyMaxSteps ?? options.maxSteps;
66
- if (requestedSteps != null && (requestedSteps < SUBAGENT_MIN_STEPS || requestedSteps > SUBAGENT_MAX_STEPS))
67
- return terminalResult(task, runtime, profile, 'policy_blocked', `maxSteps must be from ${SUBAGENT_MIN_STEPS} to ${SUBAGENT_MAX_STEPS}.`);
68
- const maxSteps = Math.min(requestedSteps ?? profile.maxSteps, profile.maxSteps);
62
+ const maxSteps = profile.maxSteps;
69
63
  const startedAt = performance.now();
70
- const bundle = options.contextBundle ?? (options.contextFiles
71
- ? await compatibilityBundle(task, profile, options.contextFiles, options.allowedTools, options.session)
72
- : await assembleWorkerContext(task, profile, options.session));
64
+ const bundle = options.contextBundle ?? await assembleWorkerContext(task, profile, options.session);
73
65
  if (bundle.policyBlock)
74
66
  return terminalResult(task, runtime, profile, 'policy_blocked', bundle.policyBlock, options.queueMs);
75
67
  const toolCallLog = [];
@@ -177,7 +169,7 @@ export async function runSubagent(taskInput, options) {
177
169
  telemetry.estimates.privateContextTokens = (usageIn ?? bundle.estimatedTokens) + (usageOut ?? 0);
178
170
  telemetry.estimates.resultCapsuleTokens = estimateValueTokens(capsule);
179
171
  telemetry.estimates.mainContextTokensAvoided = Math.max(0, telemetry.estimates.privateContextTokens - telemetry.estimates.taskCapsuleTokens - telemetry.estimates.resultCapsuleTokens);
180
- return withLegacyProjection(capsule, telemetry);
172
+ return { capsule, telemetry };
181
173
  }
182
174
  catch (error) {
183
175
  // Bounded, actionable provider-failure capsule (RT-03): a worker that dies
@@ -190,20 +182,16 @@ export async function runSubagent(taskInput, options) {
190
182
  const capsuleMessage = `${boundedMessage}. No usable worker output was produced; retry this subagent once with the same task, or do the work directly in the main conversation.`;
191
183
  const termination = options.deadlineExpired?.() ? 'deadline_exceeded' : options.abortSignal?.aborted ? 'cancelled' : 'provider_error';
192
184
  const result = terminalResult(task, runtime, profile, termination, capsuleMessage, options.queueMs);
193
- // Keep the raw provider message on the legacy `error` field so machine
194
- // consumers see exactly what the provider said (unchanged contract).
185
+ // Keep the raw provider message on `error` so machine consumers see exactly
186
+ // what the provider said (unchanged contract).
195
187
  result.error = rawMessage;
196
188
  result.capsule.changedPaths = [...changedPaths].sort();
197
189
  result.capsule.validation = [...validation];
198
190
  result.telemetry.estimates.resultCapsuleTokens = estimateValueTokens(result.capsule);
199
191
  result.telemetry.durationMs = performance.now() - startedAt;
200
- result.durationMs = result.telemetry.durationMs;
201
192
  result.telemetry.toolCalls = toolCallLog;
202
- result.toolCalls = toolCallLog;
203
193
  result.telemetry.toolCallCount = toolBudget.started;
204
- result.toolCallCount = toolBudget.started;
205
194
  result.telemetry.usage = { inputTokens: usageIn, outputTokens: usageOut };
206
- result.tokens = { in: usageIn, out: usageOut };
207
195
  return result;
208
196
  }
209
197
  finally {
@@ -226,7 +214,7 @@ export function createSubagentTool(options) {
226
214
  return terminalResult(task, runtime, profile, 'policy_blocked', options.blockedReason);
227
215
  return await coordinator.submit({
228
216
  id, mode: task.mode, signal: context.abortSignal,
229
- run: ({ signal, queueMs, deadlineExpired }) => runSubagent(task, { runtime, profile, abortSignal: signal, deadlineExpired, queueMs, session: options.session, mutationPolicy: options.mutationPolicy, ...(options.contextFiles ? { contextFiles: options.contextFiles } : {}) }),
217
+ run: ({ signal, queueMs, deadlineExpired }) => runSubagent(task, { runtime, profile, abortSignal: signal, deadlineExpired, queueMs, session: options.session, mutationPolicy: options.mutationPolicy }),
230
218
  terminal: (termination, queueMs) => terminalResult(task, runtime, profile, termination, termination === 'cancelled'
231
219
  ? 'Worker cancelled before completion.'
232
220
  : termination === 'deadline_exceeded'
@@ -1,7 +1,6 @@
1
1
  import fs from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { tool } from 'ai';
4
- import { rgPath } from '@vscode/ripgrep';
5
4
  import { z } from 'zod';
6
5
  import { walkDir } from '../../utils/fs.js';
7
6
  import { workspaceRoot } from '../../utils/path.js';
@@ -15,7 +14,7 @@ import { runDedupedTool, discoverScopedContext, withScopedContext, hazeToolConte
15
14
  import { prepareWorkspaceMutation, prepareWorkspaceRead, prepareWorkspaceWritePath } from './workspaceFile.js';
16
15
  import { DEFAULT_READ_LINES, INLINE_DIFF_LINE_LIMIT, MAX_OUTPUT_CHARS, sourceOutlineEntries } from './fileToolShared.js';
17
16
  import { createIgnoreClassifier } from './gitIgnore.js';
18
- import { runRipgrepBounded } from './grepRunner.js';
17
+ import { runRipgrepBounded, resolveRipgrepExecutable } from './grepRunner.js';
19
18
  import { secretSearchExcludeGlobs } from '../../core/safety/secretPaths.js';
20
19
  import { EXACT_MUTATION_BYTES } from '../../core/limits.js';
21
20
  import { WRITE_FILE_CHUNK_BYTES } from '../../core/agent/budgets.js';
@@ -218,7 +217,7 @@ export const fileTools = {
218
217
  args.push('--iglob', secretGlob);
219
218
  args.push('--glob', '!**/.git/**', '--glob', '!**/node_modules/**');
220
219
  args.push('--', pattern, absolutePath);
221
- const result = await runRipgrepBounded({ executable: rgPath, args, cwd: workspaceRoot(), maxMatches, signal: context.abortSignal });
220
+ const result = await runRipgrepBounded({ executable: resolveRipgrepExecutable(), args, cwd: workspaceRoot(), maxMatches, signal: context.abortSignal });
222
221
  const stdout = result.stdout;
223
222
  if (result.aborted)
224
223
  throw new Error('ripgrep aborted');
@@ -1,4 +1,4 @@
1
- import fs from 'fs-extra';
1
+ import fs from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import ignoreFactory from 'ignore';
4
4
  import { workspaceRelativePath, workspaceRoot } from '../../utils/path.js';
@@ -1,3 +1,13 @@
1
+ /**
2
+ * Prefer the bundled ripgrep binary; fall back to a system `rg` on PATH when
3
+ * the bundled download is absent (installs where dependency lifecycle scripts
4
+ * are blocked never materialize `@vscode/ripgrep/bin/rg`). Returns the bundled
5
+ * path unchanged when no system rg exists so spawn errors still name the
6
+ * expected binary. Injectable for deterministic tests.
7
+ */
8
+ export declare function resolveRipgrepExecutable(options?: {
9
+ bundledPath?: string;
10
+ }): string;
1
11
  /**
2
12
  * Line-oriented bounded ripgrep runner built on the shared bounded-process
3
13
  * primitive, so spawn/timeout/abort/process-group teardown behavior is
@@ -1,6 +1,30 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { delimiter, join } from 'node:path';
1
3
  import { StringDecoder } from 'node:string_decoder';
4
+ import { rgPath } from '@vscode/ripgrep';
2
5
  import { runBoundedProcess } from '../../core/process/runBoundedProcess.js';
3
6
  import { GREP_STREAM_BYTES, PROCESS_STDERR_BYTES, TEXT_LINE_BYTES } from '../../core/limits.js';
7
+ /**
8
+ * Prefer the bundled ripgrep binary; fall back to a system `rg` on PATH when
9
+ * the bundled download is absent (installs where dependency lifecycle scripts
10
+ * are blocked never materialize `@vscode/ripgrep/bin/rg`). Returns the bundled
11
+ * path unchanged when no system rg exists so spawn errors still name the
12
+ * expected binary. Injectable for deterministic tests.
13
+ */
14
+ export function resolveRipgrepExecutable(options) {
15
+ const bundled = options?.bundledPath ?? rgPath;
16
+ if (existsSync(bundled))
17
+ return bundled;
18
+ const name = process.platform === 'win32' ? 'rg.exe' : 'rg';
19
+ for (const dir of process.env.PATH?.split(delimiter) ?? []) {
20
+ if (!dir)
21
+ continue;
22
+ const candidate = join(dir, name);
23
+ if (existsSync(candidate))
24
+ return candidate;
25
+ }
26
+ return bundled;
27
+ }
4
28
  /**
5
29
  * Line-oriented bounded ripgrep runner built on the shared bounded-process
6
30
  * primitive, so spawn/timeout/abort/process-group teardown behavior is
@@ -2,7 +2,7 @@ import { z } from 'zod';
2
2
  import { type ContextFile } from '../../config/contextFiles.js';
3
3
  import { type HazeToolContext, type ToolExecutionContext } from './toolContextState.js';
4
4
  export type { HazeToolContext, PostMutationDiagnostics, ToolExecutionContext } from './toolContextState.js';
5
- export { hazeContext, isHazeToolContext } from './toolContextState.js';
5
+ export { hazeContext } from './toolContextState.js';
6
6
  /**
7
7
  * Turn-scoped tool-call orchestration shared by every built-in tool: in-flight
8
8
  * and completed-call deduplication, a mutation epoch that invalidates read
@@ -10,8 +10,7 @@ export { hazeContext, isHazeToolContext } from './toolContextState.js';
10
10
  * project instructions (CLAUDE.md / AGENTS.md below the cwd).
11
11
  *
12
12
  * All state lives on per-tool `context` values, which the agent turn owns and
13
- * passes to the AI SDK. Tests and older callers may still provide the legacy
14
- * `experimental_context` shape. Nothing here is persisted.
13
+ * passes to the AI SDK. Nothing here is persisted.
15
14
  */
16
15
  export declare const hazeToolContextSchema: z.ZodCustom<HazeToolContext, HazeToolContext>;
17
16
  export declare function toolsContextFor<T extends Record<string, unknown>>(tools: T, context: HazeToolContext): Partial<Record<keyof T, HazeToolContext>>;
@@ -5,7 +5,7 @@ import { workspacePathKey, workspaceRoot } from '../../utils/path.js';
5
5
  import { isFailedToolOutput, requiresReadFileRecovery, toolInputField } from '../../core/agent/toolResults.js';
6
6
  import { HazeToolError } from './failures.js';
7
7
  import { hazeContext, isHazeToolContext } from './toolContextState.js';
8
- export { hazeContext, isHazeToolContext } from './toolContextState.js';
8
+ export { hazeContext } from './toolContextState.js';
9
9
  /**
10
10
  * Turn-scoped tool-call orchestration shared by every built-in tool: in-flight
11
11
  * and completed-call deduplication, a mutation epoch that invalidates read
@@ -13,8 +13,7 @@ export { hazeContext, isHazeToolContext } from './toolContextState.js';
13
13
  * project instructions (CLAUDE.md / AGENTS.md below the cwd).
14
14
  *
15
15
  * All state lives on per-tool `context` values, which the agent turn owns and
16
- * passes to the AI SDK. Tests and older callers may still provide the legacy
17
- * `experimental_context` shape. Nothing here is persisted.
16
+ * passes to the AI SDK. Nothing here is persisted.
18
17
  */
19
18
  export const hazeToolContextSchema = z.custom(isHazeToolContext, 'Invalid haze tool context');
20
19
  export function toolsContextFor(tools, context) {