@denizokcu/haze 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/CHANGELOG.md +77 -1
  2. package/README.md +66 -25
  3. package/SECURITY.md +22 -0
  4. package/bin/haze.js +102 -1
  5. package/dist/buildInfo.json +7 -0
  6. package/dist/cli/chat/TaskBar.d.ts +2 -1
  7. package/dist/cli/chat/TaskBar.js +7 -4
  8. package/dist/cli/chat/contextReport.js +2 -0
  9. package/dist/cli/chat/fileMentionSuggestions.js +3 -2
  10. package/dist/cli/chat/liveRegion.d.ts +25 -0
  11. package/dist/cli/chat/liveRegion.js +48 -0
  12. package/dist/cli/chat/messages.d.ts +33 -2
  13. package/dist/cli/chat/messages.js +216 -33
  14. package/dist/cli/chat/sessionLifecycle.d.ts +9 -0
  15. package/dist/cli/chat/sessionLifecycle.js +64 -14
  16. package/dist/cli/chat/sessionRecorder.js +75 -7
  17. package/dist/cli/chat/startupInfo.d.ts +0 -1
  18. package/dist/cli/chat/startupInfo.js +11 -15
  19. package/dist/cli/chat/wizardDispatch.js +111 -12
  20. package/dist/cli/commands/chat.d.ts +5 -0
  21. package/dist/cli/commands/chat.js +203 -101
  22. package/dist/cli/commands/commands.d.ts +2 -0
  23. package/dist/cli/commands/commands.js +10 -5
  24. package/dist/cli/commands/doctor.d.ts +19 -0
  25. package/dist/cli/commands/doctor.js +76 -0
  26. package/dist/cli/commands/formatters.js +2 -0
  27. package/dist/cli/commands/ndjsonSink.d.ts +23 -0
  28. package/dist/cli/commands/ndjsonSink.js +38 -0
  29. package/dist/cli/commands/providerWizard.d.ts +9 -2
  30. package/dist/cli/commands/providerWizard.js +37 -4
  31. package/dist/cli/commands/runCommand.d.ts +3 -0
  32. package/dist/cli/commands/runCommand.js +117 -11
  33. package/dist/cli/commands/streaming/abortCause.d.ts +24 -0
  34. package/dist/cli/commands/streaming/abortCause.js +16 -0
  35. package/dist/cli/commands/streaming/assistantText.js +9 -2
  36. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +65 -0
  37. package/dist/cli/commands/streaming/goalCheckpoint.js +23 -0
  38. package/dist/cli/commands/streaming/goalSupervisor.d.ts +64 -0
  39. package/dist/cli/commands/streaming/goalSupervisor.js +127 -0
  40. package/dist/cli/commands/streaming/toolCallRecovery.d.ts +2 -0
  41. package/dist/cli/commands/streaming/toolCallRecovery.js +24 -0
  42. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +29 -0
  43. package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -4
  44. package/dist/cli/commands/streaming/toolResultState.d.ts +6 -1
  45. package/dist/cli/commands/streaming/toolResultState.js +29 -7
  46. package/dist/cli/commands/streaming/turnOutcome.d.ts +17 -0
  47. package/dist/cli/commands/streaming/turnOutcome.js +27 -11
  48. package/dist/cli/commands/streaming.d.ts +70 -3
  49. package/dist/cli/commands/streaming.js +491 -77
  50. package/dist/cli/commands/wizardActions.d.ts +1 -0
  51. package/dist/cli/commands/wizardActions.js +1 -0
  52. package/dist/cli/commands/wizardPrompts.js +7 -1
  53. package/dist/cli/commands/wizardSuggestions.js +5 -3
  54. package/dist/cli/index.js +68 -22
  55. package/dist/cli/terminalTitle.js +1 -1
  56. package/dist/config/modelDiscovery.d.ts +51 -0
  57. package/dist/config/modelDiscovery.js +164 -1
  58. package/dist/config/privateStorage.js +28 -2
  59. package/dist/config/providerAuth.d.ts +14 -0
  60. package/dist/config/providerAuth.js +49 -0
  61. package/dist/config/providerPresets.d.ts +39 -7
  62. package/dist/config/providerPresets.js +371 -100
  63. package/dist/config/providers.js +2 -0
  64. package/dist/config/settings.d.ts +36 -0
  65. package/dist/config/settings.js +9 -0
  66. package/dist/core/agent/budgets.d.ts +10 -0
  67. package/dist/core/agent/budgets.js +10 -0
  68. package/dist/core/agent/compaction.d.ts +38 -0
  69. package/dist/core/agent/compaction.js +92 -17
  70. package/dist/core/agent/completionController.d.ts +230 -0
  71. package/dist/core/agent/completionController.js +287 -0
  72. package/dist/core/agent/contextBudget.d.ts +38 -0
  73. package/dist/core/agent/contextBudget.js +60 -7
  74. package/dist/core/agent/events.d.ts +74 -0
  75. package/dist/core/agent/reasoningPolicy.d.ts +31 -0
  76. package/dist/core/agent/reasoningPolicy.js +27 -0
  77. package/dist/core/agent/toolCapabilities.d.ts +27 -0
  78. package/dist/core/agent/toolCapabilities.js +58 -0
  79. package/dist/core/agent/toolExecutionBudget.d.ts +35 -0
  80. package/dist/core/agent/toolExecutionBudget.js +49 -0
  81. package/dist/core/agent/toolOutputStore.d.ts +8 -0
  82. package/dist/core/agent/toolOutputStore.js +10 -10
  83. package/dist/core/agent/toolResults.d.ts +12 -0
  84. package/dist/core/agent/toolResults.js +38 -0
  85. package/dist/core/agent/turnBudget.d.ts +35 -0
  86. package/dist/core/agent/turnBudget.js +27 -0
  87. package/dist/core/agent/turnPolicy.d.ts +11 -0
  88. package/dist/core/agent/turnPolicy.js +19 -0
  89. package/dist/core/agent/workState.d.ts +75 -0
  90. package/dist/core/agent/workState.js +120 -9
  91. package/dist/core/deadline.d.ts +33 -0
  92. package/dist/core/deadline.js +74 -0
  93. package/dist/core/goal/completionPolicy.d.ts +27 -0
  94. package/dist/core/goal/completionPolicy.js +37 -1
  95. package/dist/core/limits/byteBudgets.d.ts +2 -0
  96. package/dist/core/limits/byteBudgets.js +2 -0
  97. package/dist/core/limits/textBudgets.d.ts +2 -0
  98. package/dist/core/limits/textBudgets.js +2 -0
  99. package/dist/core/log/llmLog.js +7 -0
  100. package/dist/core/persistence/orderedFileWriter.d.ts +10 -0
  101. package/dist/core/persistence/orderedFileWriter.js +16 -2
  102. package/dist/core/process/backgroundRegistry.js +8 -7
  103. package/dist/core/process/runBoundedProcess.d.ts +8 -2
  104. package/dist/core/process/runBoundedProcess.js +15 -6
  105. package/dist/core/safety/missingExecutable.d.ts +42 -0
  106. package/dist/core/safety/missingExecutable.js +77 -0
  107. package/dist/core/session/sessionStore.d.ts +37 -0
  108. package/dist/core/session/sessionStore.js +215 -51
  109. package/dist/core/subagent/contracts.d.ts +4 -0
  110. package/dist/core/subagent/contracts.js +1 -0
  111. package/dist/core/subagent/subagentCoordinator.d.ts +4 -0
  112. package/dist/core/subagent/subagentCoordinator.js +32 -2
  113. package/dist/core/subagent/subagentRunner.js +17 -37
  114. package/dist/llm/client.d.ts +17 -1
  115. package/dist/llm/client.js +82 -14
  116. package/dist/llm/hazeTools.d.ts +554 -80
  117. package/dist/llm/hazeTools.js +103 -24
  118. package/dist/llm/lsp.d.ts +24 -4
  119. package/dist/llm/lsp.js +72 -11
  120. package/dist/llm/lspTools.d.ts +2366 -0
  121. package/dist/llm/lspTools.js +87 -79
  122. package/dist/llm/openaiCodex.d.ts +3 -0
  123. package/dist/llm/openaiCodex.js +47 -0
  124. package/dist/llm/openaiCodexOAuth.d.ts +54 -0
  125. package/dist/llm/openaiCodexOAuth.js +214 -0
  126. package/dist/llm/requestContext.d.ts +3 -0
  127. package/dist/llm/requestContext.js +7 -4
  128. package/dist/llm/systemPrompt.d.ts +11 -0
  129. package/dist/llm/systemPrompt.js +12 -6
  130. package/dist/llm/toolResultTypes.d.ts +8 -1
  131. package/dist/llm/tools/bashTool.d.ts +48 -16
  132. package/dist/llm/tools/bashTool.js +5 -0
  133. package/dist/llm/tools/editMatch.d.ts +14 -0
  134. package/dist/llm/tools/editMatch.js +72 -0
  135. package/dist/llm/tools/failures.d.ts +2 -0
  136. package/dist/llm/tools/failures.js +1 -0
  137. package/dist/llm/tools/fetchTool.d.ts +16 -0
  138. package/dist/llm/tools/fileToolShared.d.ts +4 -3
  139. package/dist/llm/tools/fileToolShared.js +16 -21
  140. package/dist/llm/tools/gitIgnore.d.ts +49 -0
  141. package/dist/llm/tools/gitIgnore.js +129 -0
  142. package/dist/llm/tools/readRecovery.d.ts +10 -0
  143. package/dist/llm/tools/readRecovery.js +135 -0
  144. package/dist/llm/tools/toolContext.d.ts +1 -1
  145. package/dist/llm/tools/toolContext.js +61 -32
  146. package/dist/llm/webFetch.d.ts +17 -0
  147. package/dist/llm/webFetch.js +64 -97
  148. package/dist/ui/codeHighlight.d.ts +4 -0
  149. package/dist/ui/codeHighlight.js +31 -0
  150. package/dist/ui/components/Header.d.ts +1 -1
  151. package/dist/ui/components/MarkdownText.d.ts +16 -2
  152. package/dist/ui/components/MarkdownText.js +244 -34
  153. package/dist/ui/components/TextInput.d.ts +8 -1
  154. package/dist/ui/components/TextInput.js +6 -2
  155. package/dist/ui/theme.d.ts +4 -3
  156. package/dist/ui/theme.js +5 -4
  157. package/dist/utils/buildInfo.d.ts +104 -0
  158. package/dist/utils/buildInfo.js +253 -0
  159. package/dist/utils/fs.d.ts +9 -0
  160. package/dist/utils/fs.js +87 -25
  161. package/dist/utils/openPath.d.ts +2 -2
  162. package/dist/utils/openPath.js +19 -6
  163. package/dist/utils/path.d.ts +2 -0
  164. package/dist/utils/path.js +5 -1
  165. package/dist/utils/utf8.d.ts +22 -0
  166. package/dist/utils/utf8.js +54 -0
  167. package/dist/utils/version.d.ts +9 -3
  168. package/dist/utils/version.js +28 -2
  169. package/package.json +24 -19
@@ -122,6 +122,8 @@ export function toolResultSummary(event) {
122
122
  return compact(output.summary, 120);
123
123
  }
124
124
  if (output.ok) {
125
+ if (output.noChange === true)
126
+ return 'No changes made';
125
127
  if (typeof output.addedLines === 'number' || typeof output.removedLines === 'number') {
126
128
  const added = typeof output.addedLines === 'number' ? output.addedLines : 0;
127
129
  const removed = typeof output.removedLines === 'number' ? output.removedLines : 0;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Ordered, backpressure-aware NDJSON sink for headless `--output stream-json`
3
+ * (RH-006). Writes are serialized in arrival order and each line awaits stdout
4
+ * drain when the stream returns false, so a slow/redirected consumer cannot
5
+ * reorder or lose events and the final result line always lands after all
6
+ * streamed events.
7
+ */
8
+ export interface WritableSink {
9
+ write(chunk: string): boolean;
10
+ once(event: 'drain' | 'error', listener: () => void): unknown;
11
+ off?(event: 'drain' | 'error', listener: () => void): unknown;
12
+ }
13
+ export declare class NdjsonSink {
14
+ private readonly stream;
15
+ private tail;
16
+ private firstError;
17
+ constructor(stream: WritableSink);
18
+ /** Serialize one value as an NDJSON line, preserving order and awaiting drain. */
19
+ write(value: unknown): Promise<void>;
20
+ private writeLine;
21
+ /** Wait for every queued line to finish writing. Rejects on the first error. */
22
+ flush(): Promise<void>;
23
+ }
@@ -0,0 +1,38 @@
1
+ export class NdjsonSink {
2
+ stream;
3
+ tail = Promise.resolve();
4
+ firstError;
5
+ constructor(stream) {
6
+ this.stream = stream;
7
+ }
8
+ /** Serialize one value as an NDJSON line, preserving order and awaiting drain. */
9
+ write(value) {
10
+ const line = `${JSON.stringify(value)}\n`;
11
+ const next = this.tail.then(() => this.writeLine(line));
12
+ // Keep the chain draining even if one line fails; surface the first error on flush.
13
+ this.tail = next.catch(error => {
14
+ this.firstError ??= error instanceof Error ? error : new Error(String(error));
15
+ });
16
+ return next;
17
+ }
18
+ writeLine(line) {
19
+ return new Promise((resolve, reject) => {
20
+ if (this.stream.write(line))
21
+ return resolve();
22
+ const onDrain = () => { cleanup(); resolve(); };
23
+ const onError = (error) => { cleanup(); reject(error ?? new Error('stream error')); };
24
+ const cleanup = () => {
25
+ this.stream.off?.('drain', onDrain);
26
+ this.stream.off?.('error', onError);
27
+ };
28
+ this.stream.once('drain', onDrain);
29
+ this.stream.once('error', onError);
30
+ });
31
+ }
32
+ /** Wait for every queued line to finish writing. Rejects on the first error. */
33
+ async flush() {
34
+ await this.tail;
35
+ if (this.firstError)
36
+ throw this.firstError;
37
+ }
38
+ }
@@ -1,5 +1,12 @@
1
1
  import type { HazeProviderSettings, HazeSettings } from '../../config/settings.js';
2
2
  import type { Mode } from './chatModes.js';
3
+ import type { HarvestedModelLimits } from '../../config/modelDiscovery.js';
4
+ /**
5
+ * Warning when a `chatgpt-codex` provider's configured URL diverges from the
6
+ * canonical endpoint (F-14): requests always route to the registered OAuth
7
+ * client's endpoint, so a hand-edited URL (e.g. a proxy) is silently ignored.
8
+ */
9
+ export declare function chatgptCodexUrlWarning(provider: HazeProviderSettings): string | undefined;
3
10
  type WizardPatch = {
4
11
  settingsPatch?: Partial<HazeSettings>;
5
12
  message: string;
@@ -7,8 +14,8 @@ type WizardPatch = {
7
14
  providers?: HazeProviderSettings[];
8
15
  models?: string[];
9
16
  };
10
- export declare function providerAppendModels(settings: HazeSettings, providerName: string | undefined, modelsValue: string): WizardPatch;
11
- export declare function providerFinishAdd(settings: HazeSettings, draft: Partial<HazeProviderSettings>, modelsValue: string): WizardPatch;
17
+ export declare function providerAppendModels(settings: HazeSettings, providerName: string | undefined, modelsValue: string, discoveredLimits?: HarvestedModelLimits): WizardPatch;
18
+ export declare function providerFinishAdd(settings: HazeSettings, draft: Partial<HazeProviderSettings>, modelsValue: string, discoveredLimits?: HarvestedModelLimits): WizardPatch;
12
19
  export declare function providerRemoveModels(settings: HazeSettings, providerName: string | undefined, modelsValue: string): WizardPatch & {
13
20
  remaining?: string[];
14
21
  removed?: string[];
@@ -2,14 +2,42 @@ import { configuredProviders, findProvider, upsertProvider } from '../../config/
2
2
  import { PROVIDER_ACTIONS } from './wizardActions.js';
3
3
  import { commaList } from './wizardInput.js';
4
4
  import { assertCredentialedEndpointSecure } from '../../config/endpointSecurity.js';
5
- export function providerAppendModels(settings, providerName, modelsValue) {
5
+ import { presetModelLimitsForModels } from '../../config/providerPresets.js';
6
+ import { CHATGPT_CODEX_BASE_URL } from '../../llm/openaiCodexOAuth.js';
7
+ /**
8
+ * Warning when a `chatgpt-codex` provider's configured URL diverges from the
9
+ * canonical endpoint (F-14): requests always route to the registered OAuth
10
+ * client's endpoint, so a hand-edited URL (e.g. a proxy) is silently ignored.
11
+ */
12
+ export function chatgptCodexUrlWarning(provider) {
13
+ if (provider.kind !== 'chatgpt-codex' || provider.url === CHATGPT_CODEX_BASE_URL)
14
+ return undefined;
15
+ return `Note: ${provider.name} uses ChatGPT sign-in, which always sends requests to ${CHATGPT_CODEX_BASE_URL}. The configured URL (${provider.url}) is ignored for requests.`;
16
+ }
17
+ /** Merge order for per-model limits on add: preset-curated < live-discovered < existing user settings. */
18
+ function mergedModelLimits(curated, models, discovered, existing) {
19
+ const discoveredSubset = {};
20
+ for (const model of models)
21
+ if (discovered?.[model])
22
+ discoveredSubset[model] = discovered[model];
23
+ const merged = { ...curated, ...discoveredSubset, ...existing };
24
+ return Object.keys(merged).length > 0 ? merged : undefined;
25
+ }
26
+ export function providerAppendModels(settings, providerName, modelsValue, discoveredLimits) {
6
27
  const provider = providerName ? findProvider(settings, providerName) : undefined;
7
28
  const models = commaList(modelsValue);
8
29
  if (!provider)
9
30
  return { message: 'No provider selected.' };
10
31
  if (models.length === 0)
11
32
  return { provider, models, message: 'Enter at least one model name.' };
12
- const nextProvider = { ...provider, models: [...new Set([...provider.models, ...models])] };
33
+ // Preset-curated limits (models.dev) flow into settings so request budgeting
34
+ // uses the real window without the user configuring anything. Live values the
35
+ // provider itself reported in /models discovery win over the static catalog
36
+ // (this is the only source that knows a local server's configured window);
37
+ // existing user-configured keys always win over both.
38
+ const curatedLimits = presetModelLimitsForModels({ name: provider.name, url: provider.url }, models);
39
+ const modelLimits = mergedModelLimits(curatedLimits, models, discoveredLimits, provider.modelLimits);
40
+ const nextProvider = { ...provider, models: [...new Set([...provider.models, ...models])], ...(modelLimits ? { modelLimits } : {}) };
13
41
  return {
14
42
  provider,
15
43
  models,
@@ -17,7 +45,7 @@ export function providerAppendModels(settings, providerName, modelsValue) {
17
45
  message: `Added ${models.length} model${models.length === 1 ? '' : 's'} to ${provider.name}. Choose a model.`,
18
46
  };
19
47
  }
20
- export function providerFinishAdd(settings, draft, modelsValue) {
48
+ export function providerFinishAdd(settings, draft, modelsValue, discoveredLimits) {
21
49
  const models = commaList(modelsValue);
22
50
  if (!draft.name || !draft.url || models.length === 0) {
23
51
  return { models, message: 'Provider name, URL, and at least one model are required.' };
@@ -28,17 +56,22 @@ export function providerFinishAdd(settings, draft, modelsValue) {
28
56
  catch (error) {
29
57
  return { models, message: error instanceof Error ? error.message : String(error) };
30
58
  }
59
+ const curatedLimits = presetModelLimitsForModels({ name: draft.name, url: draft.url }, models);
60
+ const modelLimits = mergedModelLimits(curatedLimits, models, discoveredLimits, undefined);
31
61
  const provider = {
32
62
  name: draft.name,
33
63
  url: draft.url,
34
64
  ...(draft.key ? { key: draft.key } : {}),
65
+ ...(draft.kind ? { kind: draft.kind } : {}),
35
66
  models: [...new Set(models)],
67
+ ...(modelLimits ? { modelLimits } : {}),
36
68
  };
69
+ const divergence = chatgptCodexUrlWarning(provider);
37
70
  return {
38
71
  provider,
39
72
  models,
40
73
  settingsPatch: { providers: upsertProvider(settings, provider), provider: provider.name },
41
- message: `Added provider ${provider.name}. Choose a model.`,
74
+ message: `Added provider ${provider.name}. Choose a model.${divergence ? ` ${divergence}` : ''}`,
42
75
  };
43
76
  }
44
77
  export function providerRemoveModels(settings, providerName, modelsValue) {
@@ -5,6 +5,7 @@ export interface HeadlessOptions {
5
5
  resumeSessionId?: string;
6
6
  output: HeadlessOutput;
7
7
  debug?: boolean;
8
+ timeout?: string;
8
9
  }
9
10
  /** Pinned, documented usage shape emitted in `--output json` (avoids leaking internal estimates). */
10
11
  export interface HeadlessUsage {
@@ -14,4 +15,6 @@ export interface HeadlessUsage {
14
15
  cacheWriteTokens: number;
15
16
  reasoningTokens: number;
16
17
  }
18
+ /** Parse a `--timeout` duration like `30s`, `10m`, `2h`, or raw ms. Throws on invalid input. */
19
+ export declare function parseTurnTimeoutMs(raw: string | undefined): number | undefined;
17
20
  export declare function runHeadless(options: HeadlessOptions): Promise<number>;
@@ -1,11 +1,15 @@
1
1
  import { readContextFiles } from '../../config/contextFiles.js';
2
- import { runAgentTurn } from './streaming.js';
2
+ import { runAgentGoal } from './streaming/goalSupervisor.js';
3
3
  import { EMPTY_TOKEN_USAGE, accumulateTokenUsage } from '../chat/turnState.js';
4
4
  import { readSettings } from '../../config/settings.js';
5
5
  import { activeModel, modelSelector, resolveModelSelector } from '../../config/providers.js';
6
6
  import { createLog, endLog } from '../../core/log/llmLog.js';
7
7
  import { findSession, restoreSessionState } from '../../core/session/sessionStore.js';
8
+ import { compactModelMessages } from '../../core/agent/compaction.js';
9
+ import { FALLBACK_CONTEXT_WINDOW_TOKENS } from '../../core/agent/contextBudget.js';
8
10
  import { teardownBackgroundProcesses } from '../../core/process/backgroundRegistry.js';
11
+ import { MAX_TURN_DEADLINE_MS } from '../../core/agent/budgets.js';
12
+ import { NdjsonSink } from './ndjsonSink.js';
9
13
  function pinnedUsage(usage) {
10
14
  // Normalize every field to a number: TokenUsage seeds most fields to 0 but
11
15
  // inputTokens/outputTokens may be undefined until the first report. A uniform ?? 0
@@ -18,35 +22,84 @@ function pinnedUsage(usage) {
18
22
  reasoningTokens: usage.reasoningTokens ?? 0,
19
23
  };
20
24
  }
25
+ /** Parse a `--timeout` duration like `30s`, `10m`, `2h`, or raw ms. Throws on invalid input. */
26
+ export function parseTurnTimeoutMs(raw) {
27
+ if (raw === undefined || raw.trim() === '')
28
+ return undefined;
29
+ const match = /^(\d+(?:\.\d+)?)(ms|s|m|h)?$/.exec(raw.trim());
30
+ if (!match)
31
+ throw new Error(`Invalid --timeout '${raw}'. Use a number with optional ms/s/m/h units (e.g. 30s, 10m, 2h).`);
32
+ const value = Number(match[1]);
33
+ const unit = match[2] ?? 'ms';
34
+ const multiplier = unit === 'ms' ? 1 : unit === 's' ? 1000 : unit === 'm' ? 60_000 : 3_600_000;
35
+ const ms = Math.round(value * multiplier);
36
+ if (ms < 1000)
37
+ throw new Error(`--timeout must be at least 1 second (got ${ms}ms).`);
38
+ if (ms > MAX_TURN_DEADLINE_MS)
39
+ throw new Error(`--timeout must be at most 24 hours (got ${ms}ms).`);
40
+ return ms;
41
+ }
21
42
  function errorText(error) {
22
- return error instanceof Error ? error.message : String(error);
43
+ const value = error instanceof Error ? error.message : String(error);
44
+ const normalized = value.replace(/\p{Cc}+/gu, ' ').replace(/\s+/g, ' ').trim();
45
+ return normalized.length <= 500 ? normalized : `${normalized.slice(0, 499)}…`;
23
46
  }
24
47
  function toHeadlessStreamEvent(event) {
25
48
  switch (event.type) {
26
49
  case 'turn_start':
27
50
  return { type: 'turn_start', request: event.request, at: event.at };
28
51
  case 'turn_end':
29
- return { type: 'turn_end', request: event.request, status: event.status, at: event.at };
52
+ return { ...(event.evidence ? { evidence: event.evidence } : {}), type: 'turn_end', request: event.request, status: event.status, at: event.at };
53
+ case 'goal_start':
54
+ return { type: 'goal_start', goalId: event.goalId, request: event.request, at: event.at };
55
+ case 'goal_continue':
56
+ return { type: 'goal_continue', goalId: event.goalId, cycle: event.cycle, reason: event.reason, at: event.at };
57
+ case 'goal_end':
58
+ return { ...(event.stopReason ? { stopReason: event.stopReason } : {}), ...(event.evidence ? { evidence: event.evidence } : {}), type: 'goal_end', goalId: event.goalId, status: event.status, cycles: event.cycles, at: event.at };
59
+ case 'step_start':
60
+ return { type: 'step_start', attempt: event.attempt, step: event.step, at: event.at };
61
+ case 'step_end':
62
+ return { type: 'step_end', attempt: event.attempt, step: event.step, finishReason: event.finishReason, toolCallCount: event.toolCallCount, usage: event.usage, at: event.at };
30
63
  case 'message_start':
31
64
  return { type: 'message_start', id: event.id, role: event.role, at: event.at };
32
65
  case 'message_update':
33
- return { type: 'message_update', id: event.id, text: event.text, at: event.at };
66
+ // Handled directly in emitStreamEvent with delta tracking; this case is
67
+ // unreachable but kept for type exhaustiveness.
68
+ return undefined;
34
69
  case 'message_end':
35
70
  return { ...(event.hidden === undefined ? {} : { hidden: event.hidden }), type: 'message_end', id: event.id, text: event.text, at: event.at };
36
71
  case 'tool_start':
37
72
  // Intentionally omit raw tool input: stdout is often persisted by harnesses/CI.
38
73
  return { type: 'tool_start', id: event.id, name: event.name, at: event.at };
39
74
  case 'tool_end':
40
- return { type: 'tool_end', id: event.id, name: event.name, success: event.success, durationMs: event.durationMs, ...(event.error === undefined ? {} : { error: errorText(event.error) }), at: event.at };
75
+ return { type: 'tool_end', id: event.id, name: event.name, success: event.success, durationMs: event.durationMs, ...(event.errorCode === undefined ? {} : { errorCode: event.errorCode }), ...(event.error === undefined ? {} : { error: errorText(event.error) }), at: event.at };
41
76
  case 'retry':
42
77
  return { type: 'retry', attempt: event.attempt, maxAttempts: event.maxAttempts, delayMs: event.delayMs, error: event.error, at: event.at };
43
78
  case 'context_overflow':
44
79
  return { type: 'context_overflow', recovered: event.recovered, error: event.error, at: event.at };
80
+ case 'timeout':
81
+ return { type: 'timeout', phase: event.phase, timeoutMs: event.timeoutMs, at: event.at };
82
+ case 'reasoning_policy':
83
+ return { ...(event.requested ? { requested: event.requested } : {}), type: 'reasoning_policy', effective: event.effective, reason: event.reason, at: event.at };
84
+ case 'context_budget':
85
+ return { type: 'context_budget', contextWindowTokens: event.contextWindowTokens, source: event.source, at: event.at };
45
86
  }
46
87
  }
47
88
  function writeNdjson(value) {
48
89
  process.stdout.write(`${JSON.stringify(value)}\n`);
49
90
  }
91
+ /** Apply a cumulative-text message_update as a delta against the last emitted text for the segment. */
92
+ function messageUpdateDelta(event, emitted) {
93
+ const prev = emitted.get(event.id) ?? '';
94
+ // Delta from the last emitted text. If display sanitization reset the suffix,
95
+ // re-emit from offset 0 so consumers can reconstruct the exact final text.
96
+ const delta = event.text.startsWith(prev) ? event.text.slice(prev.length) : event.text;
97
+ const offset = event.text.startsWith(prev) ? prev.length : 0;
98
+ emitted.set(event.id, event.text);
99
+ if (delta.length === 0)
100
+ return undefined;
101
+ return { type: 'message_update', id: event.id, delta, offset, at: event.at };
102
+ }
50
103
  /**
51
104
  * Resolve the model the run will use *before* invoking the agent, so a bad `--model`
52
105
  * selector or a missing provider produces a precise error (not the generic no-provider
@@ -71,6 +124,14 @@ async function resolveModelOrError(modelOverride) {
71
124
  return undefined;
72
125
  }
73
126
  export async function runHeadless(options) {
127
+ let turnDeadlineMs;
128
+ try {
129
+ turnDeadlineMs = parseTurnTimeoutMs(options.timeout);
130
+ }
131
+ catch (error) {
132
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
133
+ return 2;
134
+ }
74
135
  const resumed = options.resumeSessionId ? await findSession(options.resumeSessionId) : undefined;
75
136
  if (options.resumeSessionId && !resumed) {
76
137
  process.stderr.write(`No session named ${options.resumeSessionId} exists for this workspace.\n`);
@@ -104,11 +165,23 @@ export async function runHeadless(options) {
104
165
  let log;
105
166
  if (options.debug)
106
167
  log = await createLog();
107
- const emitStreamEvent = options.output === 'stream-json'
168
+ const streamSink = options.output === 'stream-json' ? new NdjsonSink(process.stdout) : undefined;
169
+ // Last cumulative text emitted per segment, used to derive deltas (RH-006) so
170
+ // the total stream-json update payload is linear in the final text size.
171
+ const emittedSegmentText = new Map();
172
+ const emitStreamEvent = options.output === 'stream-json' && streamSink
108
173
  ? (event) => {
174
+ if (event.type === 'message_update') {
175
+ const delta = messageUpdateDelta(event, emittedSegmentText);
176
+ if (delta)
177
+ void streamSink.write(delta);
178
+ return;
179
+ }
180
+ if (event.type === 'message_end')
181
+ emittedSegmentText.delete(event.id);
109
182
  const headlessEvent = toHeadlessStreamEvent(event);
110
183
  if (headlessEvent)
111
- writeNdjson(headlessEvent);
184
+ void streamSink.write(headlessEvent);
112
185
  }
113
186
  : undefined;
114
187
  const callbacks = {
@@ -139,15 +212,39 @@ export async function runHeadless(options) {
139
212
  recordTokenUsage: (u) => {
140
213
  usage = accumulateTokenUsage(usage, u);
141
214
  },
215
+ compactConversation: (instructions) => {
216
+ // Headless context-overflow recovery (F-10): compact the in-scope
217
+ // conversation exactly like the interactive fallback path so a long CI
218
+ // run self-heals instead of dying on the first provider overflow.
219
+ const result = compactModelMessages(conversation, { instructions, tokenBudget: FALLBACK_CONTEXT_WINDOW_TOKENS });
220
+ if (!result.compacted)
221
+ return false;
222
+ conversation = result.messages;
223
+ return true;
224
+ },
142
225
  onEvent: emitStreamEvent,
143
226
  log,
144
227
  };
145
228
  let status;
146
229
  let result;
230
+ let evidence;
231
+ let goal;
147
232
  let persistenceError;
148
233
  let backgroundTeardownError;
149
234
  try {
150
- ({ status } = await runAgentTurn(options.prompt, options.prompt, contextFiles, callbacks, 0, false, false, session, options.modelOverride));
235
+ // The logical-goal supervisor owns the whole request: `--timeout` bounds
236
+ // the entire goal, and per-turn budgets merely end physical turns that
237
+ // continue automatically while recoverable work and progress remain.
238
+ const goalResult = await runAgentGoal({ request: options.prompt, displayValue: options.prompt, contextFiles, callbacks, session, modelOverride: options.modelOverride, ...(turnDeadlineMs != null ? { goalDeadlineMs: turnDeadlineMs } : {}) });
239
+ status = goalResult.status;
240
+ evidence = goalResult.evidence;
241
+ goal = {
242
+ cycles: goalResult.cycles,
243
+ stopReason: goalResult.stopReason,
244
+ mutations: goalResult.evidence?.mutationCount ?? 0,
245
+ ...(goalResult.evidence && goalResult.evidence.validationOutcome !== 'not_applicable' ? { validationOutcome: goalResult.evidence.validationOutcome } : {}),
246
+ ...(goalResult.evidence?.taskProgress ? { taskProgress: goalResult.evidence.taskProgress } : {}),
247
+ };
151
248
  result = segments.filter((s) => !s.hidden && s.text).map((s) => s.text).join('\n');
152
249
  }
153
250
  catch (error) {
@@ -168,9 +265,18 @@ export async function runHeadless(options) {
168
265
  if (persistenceError)
169
266
  process.stderr.write(`haze persistence warning: ${persistenceError}\n`);
170
267
  if (options.output === 'json' || options.output === 'stream-json') {
171
- // For stream-json the authoritative agent events have already streamed above; this is the terminal line.
172
- // It is byte-identical to the --output json envelope, so harnesses can parse the last line the same way.
173
- writeNdjson({ type: 'result', status, result, usage: pinnedUsage(usage) });
268
+ // For stream-json the authoritative agent events have already streamed; flush
269
+ // them before the terminal result so ordering is preserved under backpressure.
270
+ if (streamSink)
271
+ await streamSink.flush().catch(() => undefined);
272
+ // This terminal line is byte-identical to the --output json envelope, so harnesses can parse the last line the same way.
273
+ const resultLine = { type: 'result', status, result, usage: pinnedUsage(usage), ...(evidence ? { evidence } : {}), ...(goal ? { goal } : {}) };
274
+ if (streamSink)
275
+ await streamSink.write(resultLine).catch(() => undefined);
276
+ else
277
+ writeNdjson(resultLine);
278
+ if (streamSink)
279
+ await streamSink.flush().catch(() => undefined);
174
280
  }
175
281
  else if (status === 'complete') {
176
282
  process.stdout.write(result + (result.endsWith('\n') ? '' : '\n'));
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Why a turn's AbortController fired.
3
+ *
4
+ * One controller is shared by three abort sites: the model-stream idle timer,
5
+ * the absolute turn deadline (both in this subtree), and the user's cancel
6
+ * action (chat.tsx aborts the controller it holds). All three land in the same
7
+ * catch block in `runAgentAttempt`, so the *cause* is tracked in a per-turn
8
+ * mutable holder set by whichever internal site aborts first. A user abort
9
+ * never sets it and therefore stays `'user'` (the default).
10
+ */
11
+ export type TurnAbortCauseKind = 'user' | 'turn-deadline' | 'model-stream-idle';
12
+ export interface TurnAbortCause {
13
+ kind: TurnAbortCauseKind;
14
+ /** Window of the timer that fired (idle window or turn deadline), for messages and diagnostics. */
15
+ timeoutMs?: number;
16
+ }
17
+ /** Fresh per-turn cause tracker. An unset cause means the user aborted. */
18
+ export declare function createUserAbortCause(): TurnAbortCause;
19
+ /**
20
+ * Record `next` as the abort cause and abort `controller`. First aborter wins:
21
+ * a no-op once the controller already aborted, so a user Esc raced against an
22
+ * idle timeout keeps whichever cause actually fired first.
23
+ */
24
+ export declare function abortForTurn(cause: TurnAbortCause, next: TurnAbortCause, controller: AbortController, reason: string): void;
@@ -0,0 +1,16 @@
1
+ /** Fresh per-turn cause tracker. An unset cause means the user aborted. */
2
+ export function createUserAbortCause() {
3
+ return { kind: 'user' };
4
+ }
5
+ /**
6
+ * Record `next` as the abort cause and abort `controller`. First aborter wins:
7
+ * a no-op once the controller already aborted, so a user Esc raced against an
8
+ * idle timeout keeps whichever cause actually fired first.
9
+ */
10
+ export function abortForTurn(cause, next, controller, reason) {
11
+ if (controller.signal.aborted)
12
+ return;
13
+ cause.kind = next.kind;
14
+ cause.timeoutMs = next.timeoutMs;
15
+ controller.abort(reason);
16
+ }
@@ -64,8 +64,15 @@ function isLikelyUnfinishedMarkdownFragment(text) {
64
64
  const trimmed = text.trim();
65
65
  if (!trimmed.includes('\n'))
66
66
  return false;
67
- const last = trimmed.at(-1) ?? '';
68
- return last === '-' || last === '*' || last === '#' || last === '`' || last === '>';
67
+ // A dangling structural marker alone on the last line ("- ", "#", ">") means
68
+ // the model just opened a list/heading/blockquote and is about to continue.
69
+ const lastLine = trimmed.split('\n').pop()?.trim() ?? '';
70
+ if (lastLine.length === 1 && '-*#>'.includes(lastLine))
71
+ return true;
72
+ // An odd number of fence-open lines means a code block was opened but never
73
+ // closed. An even count (including a trailing closing fence) is balanced.
74
+ const fenceCount = (trimmed.match(/^`{3,}/gm) ?? []).length;
75
+ return fenceCount % 2 === 1;
69
76
  }
70
77
  // Procedural pre-tool lead-ins (e.g. "Confirmed:", "Files written.", "Now let me",
71
78
  // "I checked the tests.") are short preambles the model emits before calling a tool; they
@@ -0,0 +1,65 @@
1
+ import type { CompletionReadiness, TurnExecutionState } from '../../../core/agent/completionController.js';
2
+ import type { ValidationOutcome } from '../../../core/agent/workState.js';
3
+ /**
4
+ * Bounded continuation checkpoint for a logical goal whose work is recoverably
5
+ * unfinished. Safe metadata only — reasons, counts, enums — never commands,
6
+ * content, or credentials. Carried on `TurnResult.resume` so a goal supervisor
7
+ * (or the interactive resume affordance) can continue the same logical goal in
8
+ * a fresh physical turn without replaying completed work.
9
+ */
10
+ export interface IncompleteGoalResume {
11
+ kind: 'incomplete-goal';
12
+ request: string;
13
+ reason: CompletionReadiness;
14
+ /** Logical-goal id shared across physical turns. */
15
+ goalId: string;
16
+ /** Physical turns consumed so far (including the one producing this). */
17
+ cycle: number;
18
+ stepsUsed: number;
19
+ /** Cumulative successful mutations across the logical goal. */
20
+ mutationCount: number;
21
+ taskCounts?: {
22
+ total: number;
23
+ pending: number;
24
+ inProgress: number;
25
+ completed: number;
26
+ };
27
+ validationOutcome?: ValidationOutcome;
28
+ }
29
+ /** Supervisor-level checkpoint persisted between physical turns (in memory). */
30
+ export interface GoalCheckpoint {
31
+ goalId: string;
32
+ request: string;
33
+ cycle: number;
34
+ readiness: CompletionReadiness;
35
+ taskCounts?: {
36
+ total: number;
37
+ pending: number;
38
+ inProgress: number;
39
+ completed: number;
40
+ };
41
+ mutationCount: number;
42
+ validationOutcome: ValidationOutcome;
43
+ /** Cumulative progress signature used by the no-progress guard. */
44
+ progressSignature: string;
45
+ /** Consecutive physical turns without measurable progress. */
46
+ noProgressCount: number;
47
+ }
48
+ /** Cumulative progress signature: mutations, validation outcome, task counts. */
49
+ export declare function goalCheckpointSignature(input: {
50
+ mutationCount: number;
51
+ validationOutcome: ValidationOutcome;
52
+ taskCounts?: {
53
+ pending: number;
54
+ inProgress: number;
55
+ completed: number;
56
+ total: number;
57
+ };
58
+ }): string;
59
+ /**
60
+ * Build the checkpoint payload for a `recoverable-incomplete` attempt that no
61
+ * same-turn recovery can continue. Single construction site so every path
62
+ * (voluntary final, budget boundary, tool-calls finish, exhausted recovery
63
+ * slice) yields the same bounded shape.
64
+ */
65
+ export declare function buildIncompleteGoalResume(request: string, goalId: string, cycle: number, state: Pick<TurnExecutionState, 'stepsUsed' | 'mutationCount' | 'validationOutcome' | 'taskProgress'>, reason: CompletionReadiness): IncompleteGoalResume;
@@ -0,0 +1,23 @@
1
+ /** Cumulative progress signature: mutations, validation outcome, task counts. */
2
+ export function goalCheckpointSignature(input) {
3
+ return JSON.stringify([input.mutationCount, input.validationOutcome, input.taskCounts ? [input.taskCounts.total, input.taskCounts.pending, input.taskCounts.inProgress, input.taskCounts.completed] : null]);
4
+ }
5
+ /**
6
+ * Build the checkpoint payload for a `recoverable-incomplete` attempt that no
7
+ * same-turn recovery can continue. Single construction site so every path
8
+ * (voluntary final, budget boundary, tool-calls finish, exhausted recovery
9
+ * slice) yields the same bounded shape.
10
+ */
11
+ export function buildIncompleteGoalResume(request, goalId, cycle, state, reason) {
12
+ return {
13
+ kind: 'incomplete-goal',
14
+ request,
15
+ reason,
16
+ goalId,
17
+ cycle,
18
+ stepsUsed: state.stepsUsed,
19
+ mutationCount: state.mutationCount,
20
+ ...(state.taskProgress ? { taskCounts: { total: state.taskProgress.total, pending: state.taskProgress.pending, inProgress: state.taskProgress.inProgress, completed: state.taskProgress.completed } } : {}),
21
+ ...(state.validationOutcome !== 'not_applicable' ? { validationOutcome: state.validationOutcome } : {}),
22
+ };
23
+ }
@@ -0,0 +1,64 @@
1
+ import type { ContextFile } from '../../../config/contextFiles.js';
2
+ import type { TurnCompletionEvidence } from '../../../core/agent/completionController.js';
3
+ import type { PromptSession } from '../../../llm/systemPrompt.js';
4
+ import { type StreamCallbacks, type TurnExecutionOptions } from '../streaming.js';
5
+ import { type GoalCheckpoint } from './goalCheckpoint.js';
6
+ /** Why a logical goal stopped. `completed` is the only success. */
7
+ export type GoalStopReason = 'completed' | 'no-progress' | 'goal-deadline' | 'blocked' | 'model-error' | 'model-stream-idle' | 'user-aborted';
8
+ /** Authoritative outcome of a logical goal (one or more physical turns). */
9
+ export interface GoalRunResult {
10
+ status: 'complete' | 'failed' | 'aborted';
11
+ stopReason: GoalStopReason;
12
+ /** Physical turns consumed by the logical goal. */
13
+ cycles: number;
14
+ /** Last physical turn's bounded evidence. */
15
+ evidence?: TurnCompletionEvidence;
16
+ /**
17
+ * Present only for genuinely paused goals (no-progress, deadline, idle
18
+ * stall): what an explicit resume needs. Automatic continuation has already
19
+ * been attempted; this never rides a `completed` result.
20
+ */
21
+ resume?: {
22
+ kind: 'model-stream-idle';
23
+ request: string;
24
+ retryAttempt: number;
25
+ } | {
26
+ kind: 'incomplete-goal';
27
+ checkpoint: GoalCheckpoint;
28
+ };
29
+ }
30
+ export interface GoalRunOptions {
31
+ request: string;
32
+ displayValue?: string;
33
+ contextFiles: ContextFile[];
34
+ callbacks: StreamCallbacks;
35
+ session?: PromptSession;
36
+ modelOverride?: string;
37
+ /** Whole-logical-goal wall-clock budget (headless `--timeout`); unset means continue while progress. */
38
+ goalDeadlineMs?: number;
39
+ /** Base per-turn options (attachments, blessed paths); attachments apply to the first physical turn only. */
40
+ turnOptions?: TurnExecutionOptions;
41
+ /** Explicit resume of a paused goal: an idle-stalled turn pool or a stored goal checkpoint. */
42
+ resumeFrom?: {
43
+ kind: 'model-stream-idle';
44
+ retryAttempt: number;
45
+ } | {
46
+ kind: 'incomplete-goal';
47
+ checkpoint: GoalCheckpoint;
48
+ };
49
+ }
50
+ /**
51
+ * Logical-goal supervisor. Runs bounded physical turns (`runAgentTurn`) until
52
+ * the user's goal is structurally complete, autonomously starting the next
53
+ * physical turn whenever the previous one ended `recoverable-incomplete` —
54
+ * including at step/tool budget boundaries, which end a physical turn, not the
55
+ * goal. Per-turn limits stay safety boundaries; they no longer imply goal
56
+ * completion.
57
+ *
58
+ * Stops only for: structured completion, a concrete external blocker (hard
59
+ * tool/provider failure), user cancellation, the goal-level deadline, or
60
+ * repeated no-progress cycles. Conversation and completed tool results carry
61
+ * across turns, so mutations are never replayed. Emits exactly one `goal_start`
62
+ * and one terminal `goal_end`, plus `goal_continue` between physical turns.
63
+ */
64
+ export declare function runAgentGoal(options: GoalRunOptions): Promise<GoalRunResult>;