@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
@@ -12,7 +12,7 @@ export type TextInputSuggestion = {
12
12
  };
13
13
  /** Cursor-aware path completer for `@token` mentions; receives the token verbatim. */
14
14
  export type MentionSuggestionsProvider = (token: string) => Promise<TextInputSuggestion[]> | TextInputSuggestion[];
15
- export declare function TextInput({ placeholder, disabled, mask, historyItems, recordHistory, suggestions, suggestionMode, submitOnEmpty, width, getMentionSuggestions, onHistoryAdd, onCancel, onEscape, onToggleTasks, onSubmit }: {
15
+ export declare function TextInput({ placeholder, disabled, mask, historyItems, recordHistory, suggestions, suggestionMode, submitOnEmpty, width, getMentionSuggestions, onHistoryAdd, onCancel, onEscape, onToggleTasks, onResumeKey, onSubmit }: {
16
16
  placeholder?: string;
17
17
  disabled?: boolean;
18
18
  mask?: boolean;
@@ -27,6 +27,13 @@ export declare function TextInput({ placeholder, disabled, mask, historyItems, r
27
27
  onCancel?: () => void;
28
28
  onEscape?: () => void;
29
29
  onToggleTasks?: () => void;
30
+ /**
31
+ * One-key resume affordance: when provided and the input is empty, a bare
32
+ * R/R resumes the paused task instead of typing the character. The caller
33
+ * (chat) only provides it while a paused turn is pending and renders the
34
+ * matching hint line, so ordinary typing is unaffected.
35
+ */
36
+ onResumeKey?: () => void;
30
37
  onSubmit: (value: string) => void;
31
38
  }): React.JSX.Element;
32
39
  export {};
@@ -11,7 +11,7 @@ export function shouldInsertNewline(input, key) {
11
11
  || input === '\n'
12
12
  || CTRL_ENTER_ESCAPE_INPUTS.has(input);
13
13
  }
14
- export function TextInput({ placeholder, disabled, mask, historyItems = [], recordHistory = true, suggestions = [], suggestionMode = 'slash', submitOnEmpty = false, width = 80, getMentionSuggestions, onHistoryAdd, onCancel, onEscape, onToggleTasks, onSubmit }) {
14
+ export function TextInput({ placeholder, disabled, mask, historyItems = [], recordHistory = true, suggestions = [], suggestionMode = 'slash', submitOnEmpty = false, width = 80, getMentionSuggestions, onHistoryAdd, onCancel, onEscape, onToggleTasks, onResumeKey, onSubmit }) {
15
15
  const [value, setValue] = useState('');
16
16
  const [cursor, setCursor] = useState(0);
17
17
  const [pasteBlocks, setPasteBlocks] = useState([]);
@@ -140,6 +140,10 @@ export function TextInput({ placeholder, disabled, mask, historyItems = [], reco
140
140
  onEscape?.();
141
141
  return;
142
142
  }
143
+ if (onResumeKey && value.length === 0 && !key.ctrl && !key.meta && (input === 'r' || input === 'R')) {
144
+ onResumeKey();
145
+ return;
146
+ }
143
147
  if (key.tab && activeSuggestion) {
144
148
  if (inMentionMode && detectedMention) {
145
149
  // Partial replacement of the `@token` range, not the whole input —
@@ -280,7 +284,7 @@ export function TextInput({ placeholder, disabled, mask, historyItems = [], reco
280
284
  const visibleLines = wrappedLines.slice(firstVisibleLine, firstVisibleLine + maxVisibleLines);
281
285
  const displayList = inMentionMode ? mentionList : filteredSuggestions;
282
286
  const displayActiveIndex = inMentionMode ? activeMentionIndex : activeSuggestionIndex;
283
- return _jsxs(Box, { flexDirection: "column", width: "100%", children: [displayList.length > 0 && _jsx(Box, { flexDirection: "column", marginBottom: 1, children: displayList.map((suggestion, index) => _jsxs(Text, { color: index === displayActiveIndex ? theme.success : theme.muted, wrap: "truncate-end", children: [index === displayActiveIndex ? '› ' : ' ', suggestion.value, _jsxs(Text, { color: theme.muted, children: [" ", suggestion.kind ?? 'command', suggestion.description ? ` — ${suggestion.description}` : ''] })] }, suggestion.value)) }), value.length === 0 ? _jsxs(Text, { wrap: "truncate-end", children: [_jsx(Text, { color: theme.purple, children: "\u203A " }), _jsx(Text, { inverse: true, children: " " }), _jsxs(Text, { color: theme.muted, dimColor: true, children: [" ", placeholder ?? 'Type a message...'] })] }) : visibleLines.map((line, index) => {
287
+ return _jsxs(Box, { flexDirection: "column", width: "100%", children: [displayList.length > 0 && _jsx(Box, { flexDirection: "column", marginBottom: 1, children: displayList.map((suggestion, index) => _jsxs(Text, { color: index === displayActiveIndex ? theme.success : theme.muted, wrap: "truncate-end", children: [index === displayActiveIndex ? '› ' : ' ', suggestion.value, _jsxs(Text, { color: theme.muted, children: [" ", suggestion.kind ?? 'command', suggestion.description ? ` — ${suggestion.description}` : ''] })] }, suggestion.value)) }), value.length === 0 ? _jsxs(Text, { wrap: "truncate-end", children: [_jsx(Text, { color: theme.purple, children: "\u203A " }), _jsx(Text, { inverse: true, children: " " }), _jsxs(Text, { color: theme.muted, children: [" ", placeholder ?? 'Type a message...'] })] }) : visibleLines.map((line, index) => {
284
288
  const absoluteLineIndex = firstVisibleLine + index;
285
289
  const isCursorLine = absoluteLineIndex === currentCursorPosition.lineIndex;
286
290
  const lineCursor = isCursorLine ? Math.max(0, Math.min(displayCursor - line.start, line.text.length)) : -1;
@@ -1,7 +1,7 @@
1
1
  export declare const theme: {
2
+ foreground: string;
2
3
  purple: string;
3
4
  deepPurple: string;
4
- violet: string;
5
5
  blue: string;
6
6
  muted: string;
7
7
  danger: string;
@@ -9,7 +9,8 @@ export declare const theme: {
9
9
  success: string;
10
10
  successBg: string;
11
11
  warning: string;
12
- orange: string;
12
+ /** Slash commands, paths, and active terminal work; matches --command in docs/index.html. */
13
+ command: string;
14
+ surfaceBg: string;
13
15
  codeBg: string;
14
- quoteBg: string;
15
16
  };
package/dist/ui/theme.js CHANGED
@@ -1,7 +1,7 @@
1
1
  export const theme = {
2
+ foreground: 'white',
2
3
  purple: '#a78bfa',
3
4
  deepPurple: '#6d28d9',
4
- violet: '#8b5cf6',
5
5
  blue: '#60a5fa',
6
6
  muted: '#9ca3af',
7
7
  danger: '#fb7185',
@@ -9,7 +9,8 @@ export const theme = {
9
9
  success: '#39ff14',
10
10
  successBg: '#14331f',
11
11
  warning: '#fbbf24',
12
- orange: '#f59e0b',
13
- codeBg: '#1f1633',
14
- quoteBg: '#171127'
12
+ /** Slash commands, paths, and active terminal work; matches --command in docs/index.html. */
13
+ command: '#ffb86c',
14
+ surfaceBg: '#1f1633',
15
+ codeBg: '#202124',
15
16
  };
@@ -0,0 +1,104 @@
1
+ /** Package identity used to recognize a haze checkout near the working directory. */
2
+ export declare const HAZE_PACKAGE_NAME = "@denizokcu/haze";
3
+ /**
4
+ * Build provenance embedded by `npm run build` (dist/buildInfo.json). Safe
5
+ * metadata only — never environment, credentials, or conversation content.
6
+ */
7
+ export interface BuildInfo {
8
+ name: string;
9
+ version: string;
10
+ commit?: string;
11
+ builtAt?: string;
12
+ sourceRoot?: string;
13
+ }
14
+ /**
15
+ * Runtime capability registry: observable facts about the running build, so
16
+ * behavior can be diagnosed without inferring it from semantic versions.
17
+ * All three land together with the goal supervisor; a runtime missing its
18
+ * compiled artifact reports every supervisor capability as unavailable.
19
+ */
20
+ export interface RuntimeCapabilities {
21
+ logicalGoalSupervisor: boolean;
22
+ crossTurnCheckpoints: boolean;
23
+ automaticBudgetContinuation: boolean;
24
+ }
25
+ /** Compiled module whose presence proves the autonomous goal supervisor is in this build. */
26
+ export declare const GOAL_SUPERVISOR_ARTIFACT: string;
27
+ /** Parse a buildInfo.json payload defensively; malformed files read as absent. */
28
+ export declare function parseBuildInfo(value: unknown): BuildInfo | undefined;
29
+ /**
30
+ * Provenance of the running build, or undefined when no buildInfo.json is
31
+ * readable (source runs without a prior build). Cached per process; explicit
32
+ * candidate paths bypass the cache (tests, doctor probing another root).
33
+ */
34
+ export declare function readBuildInfo(candidates?: readonly string[]): BuildInfo | undefined;
35
+ /** Test seam: clear the default-path cache so the next `readBuildInfo()` reloads from disk. */
36
+ export declare function resetBuildInfoCache(): void;
37
+ /** Read the first parsable buildInfo.json among the candidate paths. */
38
+ export declare function loadBuildInfoFrom(candidates: readonly string[]): BuildInfo | undefined;
39
+ /** Read a package.json version from an explicit package root. */
40
+ export declare function readPackageVersionAt(root: string): string | undefined;
41
+ /** Read a package.json name from an explicit package root. */
42
+ export declare function readPackageNameAt(root: string): string | undefined;
43
+ /**
44
+ * Nearest ancestor directory (starting at `start`, default: this module's
45
+ * location) containing a package.json — i.e. the package root of the code
46
+ * that is actually executing.
47
+ */
48
+ export declare function resolvePackageRoot(start?: string): string | undefined;
49
+ /**
50
+ * Resolve the current git HEAD commit without spawning git: reads .git/HEAD
51
+ * (detached sha or symbolic ref), then the ref file or packed-refs. Returns
52
+ * undefined whenever the commit cannot be determined without guessing.
53
+ */
54
+ export declare function gitHeadCommit(root: string): string | undefined;
55
+ /** True when the goal-supervisor compiled module exists under this package root. */
56
+ export declare function goalSupervisorArtifactPresent(root: string): boolean;
57
+ /** Capabilities of the running build, verified against its compiled artifacts. */
58
+ export declare function runtimeCapabilities(root?: string): RuntimeCapabilities;
59
+ /** One-line capability summary for logs and doctor output. */
60
+ export declare function formatCapabilities(capabilities: RuntimeCapabilities): string;
61
+ /** Structured description of the executing runtime (used by --version --verbose and doctor). */
62
+ export interface RuntimeProvenance {
63
+ version: string;
64
+ build?: BuildInfo;
65
+ /** Package root of the executing code (contains package.json). */
66
+ runtimeRoot?: string;
67
+ /** Resolved entry executable (process.argv[1]); undefined in non-CLI contexts. */
68
+ executable?: string;
69
+ capabilities: RuntimeCapabilities;
70
+ }
71
+ /** Resolved entry executable (process.argv[1]); undefined in non-CLI contexts. */
72
+ export declare function resolveExecutable(): string | undefined;
73
+ export declare function describeRuntime(input?: {
74
+ runtimeRoot?: string;
75
+ }): RuntimeProvenance;
76
+ /** `haze --version --verbose` block: version, commit, runtime/executable paths, supervisor state. */
77
+ export declare function formatVersionVerbose(provenance?: RuntimeProvenance): string;
78
+ /** A nearby haze checkout whose version/commit diverges from the executing runtime. */
79
+ export interface CheckoutMismatch {
80
+ /** Package root of the executing runtime. */
81
+ executingRoot: string;
82
+ executingVersion: string;
83
+ executingCommit?: string;
84
+ /** Package root of the nearby checkout found from the working directory. */
85
+ checkoutRoot: string;
86
+ checkoutVersion: string;
87
+ checkoutCommit?: string;
88
+ /** True when the checkout's version string differs from the executing one. */
89
+ versionDiffers: boolean;
90
+ /** True when the checkout's version is strictly newer than the executing one. */
91
+ checkoutNewer: boolean;
92
+ }
93
+ /**
94
+ * Detect a haze source checkout at/above `cwd` that differs from the executing
95
+ * runtime — the classic failure where a globally installed haze (e.g. 0.10.0)
96
+ * silently serves requests while the checkout beside the workspace already
97
+ * contains the fix. Returns undefined when there is nothing to warn about.
98
+ */
99
+ export declare function detectCheckoutMismatch(input?: {
100
+ executingRoot?: string;
101
+ cwd?: string;
102
+ }): CheckoutMismatch | undefined;
103
+ /** Startup warning for a stale runtime executing next to a newer checkout. */
104
+ export declare function formatMismatchWarning(mismatch: CheckoutMismatch): string;
@@ -0,0 +1,253 @@
1
+ import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { compareVersions } from './version.js';
5
+ /** Package identity used to recognize a haze checkout near the working directory. */
6
+ export const HAZE_PACKAGE_NAME = '@denizokcu/haze';
7
+ /** Compiled module whose presence proves the autonomous goal supervisor is in this build. */
8
+ export const GOAL_SUPERVISOR_ARTIFACT = join('dist', 'cli', 'commands', 'streaming', 'goalSupervisor.js');
9
+ const MODULE_DIR = dirname(fileURLToPath(import.meta.url));
10
+ function isRecord(value) {
11
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
12
+ }
13
+ /** Parse a buildInfo.json payload defensively; malformed files read as absent. */
14
+ export function parseBuildInfo(value) {
15
+ if (!isRecord(value) || typeof value.name !== 'string' || typeof value.version !== 'string')
16
+ return undefined;
17
+ const info = { name: value.name, version: value.version };
18
+ if (typeof value.commit === 'string' && value.commit)
19
+ info.commit = value.commit;
20
+ if (typeof value.builtAt === 'string' && value.builtAt)
21
+ info.builtAt = value.builtAt;
22
+ if (typeof value.sourceRoot === 'string' && value.sourceRoot)
23
+ info.sourceRoot = value.sourceRoot;
24
+ return info;
25
+ }
26
+ /** Default candidate locations: dist/utils/../buildInfo.json (built) and <repo>/dist (running from src via tsx). */
27
+ function defaultBuildInfoCandidates() {
28
+ return [
29
+ join(MODULE_DIR, '..', 'buildInfo.json'),
30
+ join(MODULE_DIR, '..', '..', 'dist', 'buildInfo.json'),
31
+ ];
32
+ }
33
+ // Cache sentinel for the default-path lookup: `undefined` means "not loaded
34
+ // yet" and `null` means "loaded and absent" (a miss is cached too). Explicit
35
+ // candidate paths always bypass the cache.
36
+ let cachedBuildInfo;
37
+ /**
38
+ * Provenance of the running build, or undefined when no buildInfo.json is
39
+ * readable (source runs without a prior build). Cached per process; explicit
40
+ * candidate paths bypass the cache (tests, doctor probing another root).
41
+ */
42
+ export function readBuildInfo(candidates) {
43
+ if (!candidates) {
44
+ // `undefined` = never loaded (load now); `null` = cached miss.
45
+ if (cachedBuildInfo !== undefined)
46
+ return cachedBuildInfo ?? undefined;
47
+ const found = loadBuildInfoFrom(defaultBuildInfoCandidates());
48
+ cachedBuildInfo = found ?? null;
49
+ return found ?? undefined;
50
+ }
51
+ return loadBuildInfoFrom(candidates);
52
+ }
53
+ /** Test seam: clear the default-path cache so the next `readBuildInfo()` reloads from disk. */
54
+ export function resetBuildInfoCache() {
55
+ cachedBuildInfo = undefined;
56
+ }
57
+ /** Read the first parsable buildInfo.json among the candidate paths. */
58
+ export function loadBuildInfoFrom(candidates) {
59
+ for (const candidate of candidates) {
60
+ try {
61
+ return parseBuildInfo(JSON.parse(readFileSync(candidate, 'utf8')));
62
+ }
63
+ catch {
64
+ // Try the next candidate.
65
+ }
66
+ }
67
+ return undefined;
68
+ }
69
+ /** Read a package.json version from an explicit package root. */
70
+ export function readPackageVersionAt(root) {
71
+ try {
72
+ const parsed = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
73
+ return typeof parsed.version === 'string' ? parsed.version : undefined;
74
+ }
75
+ catch {
76
+ return undefined;
77
+ }
78
+ }
79
+ /** Read a package.json name from an explicit package root. */
80
+ export function readPackageNameAt(root) {
81
+ try {
82
+ const parsed = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
83
+ return typeof parsed.name === 'string' ? parsed.name : undefined;
84
+ }
85
+ catch {
86
+ return undefined;
87
+ }
88
+ }
89
+ /**
90
+ * Nearest ancestor directory (starting at `start`, default: this module's
91
+ * location) containing a package.json — i.e. the package root of the code
92
+ * that is actually executing.
93
+ */
94
+ export function resolvePackageRoot(start = MODULE_DIR) {
95
+ let dir = resolve(start);
96
+ while (true) {
97
+ if (existsSync(join(dir, 'package.json')))
98
+ return dir;
99
+ const parent = dirname(dir);
100
+ if (parent === dir)
101
+ return undefined;
102
+ dir = parent;
103
+ }
104
+ }
105
+ /**
106
+ * Resolve the current git HEAD commit without spawning git: reads .git/HEAD
107
+ * (detached sha or symbolic ref), then the ref file or packed-refs. Returns
108
+ * undefined whenever the commit cannot be determined without guessing.
109
+ */
110
+ export function gitHeadCommit(root) {
111
+ const sha = (value) => (/^[0-9a-f]{7,40}$/i.test((value ?? '').trim()) ? value.trim() : undefined);
112
+ try {
113
+ const dotGitPath = join(root, '.git');
114
+ const stat = statSync(dotGitPath);
115
+ const gitDir = stat.isDirectory()
116
+ ? dotGitPath
117
+ : /gitdir:\s*(\S+)/.exec(readFileSync(dotGitPath, 'utf8'))?.[1];
118
+ if (!gitDir)
119
+ return undefined;
120
+ const head = readFileSync(join(gitDir, 'HEAD'), 'utf8').trim();
121
+ if (!head.startsWith('ref:'))
122
+ return sha(head);
123
+ const ref = head.slice(4).trim();
124
+ const refPath = join(gitDir, ref);
125
+ if (existsSync(refPath))
126
+ return sha(readFileSync(refPath, 'utf8'));
127
+ const packed = readFileSync(join(gitDir, 'packed-refs'), 'utf8');
128
+ const escaped = ref.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
129
+ return sha(new RegExp(`^([0-9a-f]{40}) ${escaped}$`, 'm').exec(packed)?.[1]);
130
+ }
131
+ catch {
132
+ return undefined;
133
+ }
134
+ }
135
+ /** True when the goal-supervisor compiled module exists under this package root. */
136
+ export function goalSupervisorArtifactPresent(root) {
137
+ try {
138
+ return existsSync(join(root, GOAL_SUPERVISOR_ARTIFACT));
139
+ }
140
+ catch {
141
+ return false;
142
+ }
143
+ }
144
+ /** Capabilities of the running build, verified against its compiled artifacts. */
145
+ export function runtimeCapabilities(root = resolvePackageRoot() ?? process.cwd()) {
146
+ const supervisor = goalSupervisorArtifactPresent(root);
147
+ return {
148
+ logicalGoalSupervisor: supervisor,
149
+ crossTurnCheckpoints: supervisor,
150
+ automaticBudgetContinuation: supervisor,
151
+ };
152
+ }
153
+ /** One-line capability summary for logs and doctor output. */
154
+ export function formatCapabilities(capabilities) {
155
+ return [
156
+ `logical-goal-supervisor=${capabilities.logicalGoalSupervisor ? 'enabled' : 'disabled'}`,
157
+ `cross-turn-checkpoints=${capabilities.crossTurnCheckpoints ? 'enabled' : 'disabled'}`,
158
+ `automatic-budget-continuation=${capabilities.automaticBudgetContinuation ? 'enabled' : 'disabled'}`,
159
+ ].join(', ');
160
+ }
161
+ /** Resolved entry executable (process.argv[1]); undefined in non-CLI contexts. */
162
+ export function resolveExecutable() {
163
+ if (!process.argv[1])
164
+ return undefined;
165
+ try {
166
+ return realpathSync(process.argv[1]);
167
+ }
168
+ catch {
169
+ return process.argv[1];
170
+ }
171
+ }
172
+ export function describeRuntime(input = {}) {
173
+ const runtimeRoot = input.runtimeRoot ?? resolvePackageRoot();
174
+ const build = readBuildInfo(input.runtimeRoot ? [join(input.runtimeRoot, 'dist', 'buildInfo.json')] : undefined);
175
+ const version = build?.version ?? readPackageVersionAt(runtimeRoot ?? '') ?? '0.0.0';
176
+ return { version, build, runtimeRoot, executable: resolveExecutable(), capabilities: runtimeCapabilities(runtimeRoot ?? process.cwd()) };
177
+ }
178
+ /** `haze --version --verbose` block: version, commit, runtime/executable paths, supervisor state. */
179
+ export function formatVersionVerbose(provenance = describeRuntime()) {
180
+ const lines = [
181
+ `Haze ${provenance.version}`,
182
+ `commit: ${provenance.build?.commit ?? 'unknown'}`,
183
+ ...(provenance.build?.builtAt ? [`builtAt: ${provenance.build.builtAt}`] : []),
184
+ ];
185
+ if (provenance.runtimeRoot)
186
+ lines.push(`runtime: ${join(provenance.runtimeRoot, 'dist')}`);
187
+ if (provenance.executable)
188
+ lines.push(`executable: ${provenance.executable}`);
189
+ lines.push(`goal supervisor: ${provenance.capabilities.logicalGoalSupervisor ? 'enabled' : 'disabled'}`);
190
+ return lines.join('\n');
191
+ }
192
+ function sameRealPath(a, b) {
193
+ try {
194
+ return realpathSync(a) === realpathSync(b);
195
+ }
196
+ catch {
197
+ return resolve(a) === resolve(b);
198
+ }
199
+ }
200
+ /**
201
+ * Detect a haze source checkout at/above `cwd` that differs from the executing
202
+ * runtime — the classic failure where a globally installed haze (e.g. 0.10.0)
203
+ * silently serves requests while the checkout beside the workspace already
204
+ * contains the fix. Returns undefined when there is nothing to warn about.
205
+ */
206
+ export function detectCheckoutMismatch(input = {}) {
207
+ const executingRoot = input.executingRoot ?? resolvePackageRoot();
208
+ if (!executingRoot)
209
+ return undefined;
210
+ let dir = resolve(input.cwd ?? process.cwd());
211
+ let checkoutRoot;
212
+ while (true) {
213
+ if (readPackageNameAt(dir) === HAZE_PACKAGE_NAME) {
214
+ checkoutRoot = dir;
215
+ break;
216
+ }
217
+ const parent = dirname(dir);
218
+ if (parent === dir)
219
+ break;
220
+ dir = parent;
221
+ }
222
+ if (!checkoutRoot || sameRealPath(checkoutRoot, executingRoot))
223
+ return undefined;
224
+ const executingVersion = readPackageVersionAt(executingRoot) ?? readBuildInfo([join(executingRoot, 'dist', 'buildInfo.json')])?.version ?? 'unknown';
225
+ const checkoutVersion = readPackageVersionAt(checkoutRoot) ?? 'unknown';
226
+ const executingCommit = readBuildInfo([join(executingRoot, 'dist', 'buildInfo.json')])?.commit ?? gitHeadCommit(executingRoot);
227
+ const checkoutCommit = readBuildInfo([join(checkoutRoot, 'dist', 'buildInfo.json')])?.commit ?? gitHeadCommit(checkoutRoot);
228
+ const versionDiffers = executingVersion !== checkoutVersion;
229
+ const commitDiffers = executingCommit != null && checkoutCommit != null && executingCommit !== checkoutCommit;
230
+ if (!versionDiffers && !commitDiffers)
231
+ return undefined;
232
+ return {
233
+ executingRoot,
234
+ executingVersion,
235
+ ...(executingCommit ? { executingCommit } : {}),
236
+ checkoutRoot,
237
+ checkoutVersion,
238
+ ...(checkoutCommit ? { checkoutCommit } : {}),
239
+ versionDiffers,
240
+ checkoutNewer: compareVersions(checkoutVersion, executingVersion) > 0,
241
+ };
242
+ }
243
+ /** Startup warning for a stale runtime executing next to a newer checkout. */
244
+ export function formatMismatchWarning(mismatch) {
245
+ const head = mismatch.versionDiffers
246
+ ? `Running Haze ${mismatch.executingVersion} from ${mismatch.executingRoot}, but checkout ${mismatch.checkoutRoot} is ${mismatch.checkoutVersion}.`
247
+ : `Running Haze ${mismatch.executingVersion} (commit ${mismatch.executingCommit?.slice(0, 7) ?? '?'}) from ${mismatch.executingRoot}, but checkout ${mismatch.checkoutRoot} is at commit ${mismatch.checkoutCommit?.slice(0, 7) ?? '?'}.`;
248
+ return [
249
+ head,
250
+ mismatch.checkoutNewer || mismatch.versionDiffers ? 'The checkout contains newer runtime behavior than the binary serving this session.' : 'The checkout was rebuilt or moved ahead of the running binary.',
251
+ 'Run `npm run dev:link` inside the checkout (rebuild + relink), or start it directly with `npm run haze -- <args>`.',
252
+ ].join('\n');
253
+ }
@@ -9,6 +9,15 @@ export interface WalkOptions {
9
9
  recursive?: boolean;
10
10
  maxEntries?: number;
11
11
  cursor?: string;
12
+ /** Legacy per-entry filter applied after ignore pruning. Avoid for directory walks: it forces a check per entry. */
12
13
  filter?: (entry: WalkEntry) => boolean | Promise<boolean>;
14
+ /**
15
+ * Batched ignore classification over workspace-relative paths. Given a
16
+ * directory's children, return the subset that is Git-ignored. Ignored
17
+ * entries are dropped and ignored directories are not descended into, so a
18
+ * listing needs O(number of visited directories) Git subprocesses rather
19
+ * than one per entry (RH-001). Fails open: an empty set means "keep all".
20
+ */
21
+ ignoreBatch?: (relativePaths: string[]) => Promise<Set<string>>;
13
22
  }
14
23
  export declare function walkDir(root: string, options?: WalkOptions): Promise<WalkEntry[]>;
package/dist/utils/fs.js CHANGED
@@ -2,35 +2,97 @@ import fs from 'fs-extra';
2
2
  import path from 'node:path';
3
3
  const SKIP_ENTRIES = new Set(['node_modules', '.git']);
4
4
  export async function walkDir(root, options = {}) {
5
- const { recursive = false, maxEntries = Infinity, cursor, filter } = options;
5
+ const { recursive = false, maxEntries = Infinity, cursor, filter, ignoreBatch } = options;
6
6
  const result = [];
7
- let cursorSeen = cursor == null;
8
- async function walk(dir) {
9
- const entries = (await fs.readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name));
10
- for (const entry of entries) {
7
+ // Cursor semantics: the cursor is the last entry a previous page returned.
8
+ // This walk resumes strictly *after* that entry in depth-first traversal
9
+ // order, without re-checking or even descending into earlier subtrees.
10
+ const cursorSegments = cursor ? cursor.split(/[\\/]/).filter(Boolean) : [];
11
+ let collecting = cursor == null;
12
+ if (!(await fs.pathExists(root)))
13
+ return result;
14
+ async function readSortedChildren(dir) {
15
+ const entries = await fs.readdir(dir, { withFileTypes: true });
16
+ return entries.filter(entry => !SKIP_ENTRIES.has(entry.name)).sort((a, b) => a.name.localeCompare(b.name));
17
+ }
18
+ function toWalkEntry(dir, dirent) {
19
+ const absolutePath = path.join(dir, dirent.name);
20
+ return {
21
+ path: path.relative(root, absolutePath),
22
+ absolutePath,
23
+ name: dirent.name,
24
+ isDirectory: dirent.isDirectory(),
25
+ isFile: dirent.isFile(),
26
+ };
27
+ }
28
+ async function keepNonIgnored(entries) {
29
+ if (!ignoreBatch)
30
+ return entries;
31
+ if (entries.length === 0)
32
+ return entries;
33
+ const ignored = await ignoreBatch(entries.map(entry => entry.path));
34
+ if (ignored.size === 0)
35
+ return entries;
36
+ return entries.filter(entry => !ignored.has(entry.path));
37
+ }
38
+ async function walk(dir, depth) {
39
+ if (result.length >= maxEntries)
40
+ return;
41
+ const dirents = await readSortedChildren(dir);
42
+ const entries = dirents.map(dirent => toWalkEntry(dir, dirent));
43
+ if (collecting) {
44
+ const kept = await keepNonIgnored(entries);
45
+ for (const entry of kept) {
46
+ if (result.length >= maxEntries)
47
+ return;
48
+ const passesFilter = !filter || (await filter(entry));
49
+ if (passesFilter)
50
+ result.push(entry);
51
+ if (passesFilter && recursive && entry.isDirectory)
52
+ await walk(entry.absolutePath, depth + 1);
53
+ }
54
+ return;
55
+ }
56
+ // Pre-cursor region. The cursor's branch child at this depth splits the
57
+ // sorted children into three DFS-ordered groups: entries strictly before
58
+ // the branch (pre-cursor: skipped without classifying or descending), the
59
+ // branch child itself (descended into to resolve the cursor, never emitted),
60
+ // and entries after the branch (post-cursor: emitted normally). This keeps
61
+ // a later page from re-checking or re-walking earlier subtrees (RH-001).
62
+ const branchName = depth < cursorSegments.length ? cursorSegments[depth] : undefined;
63
+ const branchIndex = branchName ? entries.findIndex(entry => entry.name === branchName) : -1;
64
+ if (branchIndex === -1)
65
+ return; // stale cursor: emit nothing rather than duplicate earlier pages
66
+ const branch = entries[branchIndex];
67
+ const atCursorLevel = depth >= cursorSegments.length - 1;
68
+ if (atCursorLevel) {
69
+ // The branch child is the cursor entry itself; do not re-emit it. If it is
70
+ // a directory its children follow it in DFS order, so descend now that we
71
+ // are collecting.
72
+ if (branch.path === cursor) {
73
+ collecting = true;
74
+ if (recursive && branch.isDirectory)
75
+ await walk(branch.absolutePath, depth + 1);
76
+ }
77
+ }
78
+ else if (branch.isDirectory && recursive) {
79
+ // Ancestor directory: descend to resolve the cursor deeper in the tree.
80
+ await walk(branch.absolutePath, depth + 1);
81
+ }
82
+ if (!collecting)
83
+ return; // cursor was not found inside the branch (stale)
84
+ // Post-cursor siblings at this level are emitted and descended normally.
85
+ const keptPost = await keepNonIgnored(entries.slice(branchIndex + 1));
86
+ for (const entry of keptPost) {
11
87
  if (result.length >= maxEntries)
12
88
  return;
13
- if (SKIP_ENTRIES.has(entry.name))
14
- continue;
15
- const absolutePath = path.join(dir, entry.name);
16
- const relativePath = path.relative(root, absolutePath);
17
- const walkEntry = {
18
- path: relativePath,
19
- absolutePath,
20
- name: entry.name,
21
- isDirectory: entry.isDirectory(),
22
- isFile: entry.isFile(),
23
- };
24
- const passesFilter = !filter || await filter(walkEntry);
25
- if (passesFilter && cursorSeen)
26
- result.push(walkEntry);
27
- if (passesFilter && !cursorSeen && relativePath === cursor)
28
- cursorSeen = true;
29
- if (entry.isDirectory() && recursive && (!filter || passesFilter))
30
- await walk(absolutePath);
89
+ const passesFilter = !filter || (await filter(entry));
90
+ if (passesFilter)
91
+ result.push(entry);
92
+ if (passesFilter && recursive && entry.isDirectory)
93
+ await walk(entry.absolutePath, depth + 1);
31
94
  }
32
95
  }
33
- if (await fs.pathExists(root))
34
- await walk(root);
96
+ await walk(root, 0);
35
97
  return result;
36
98
  }
@@ -1,2 +1,2 @@
1
- /** Open a file with the platform default handler. Tests mock this module. */
2
- export declare function openPath(filePath: string): void;
1
+ /** Open a file or URL with the platform default handler. Tests mock this module. */
2
+ export declare function openPath(target: string, onError?: (error: Error) => void): Promise<boolean>;
@@ -1,9 +1,22 @@
1
1
  import { spawn } from 'node:child_process';
2
- /** Open a file with the platform default handler. Tests mock this module. */
3
- export function openPath(filePath) {
2
+ /** Open a file or URL with the platform default handler. Tests mock this module. */
3
+ export function openPath(target, onError) {
4
+ // Darwin: `open`. POSIX/Linux: `xdg-open`. Windows: `cmd /c start <title> url` —
5
+ // the empty string is the start command's title argument; without it, start
6
+ // would treat a quoted URL as the window title.
4
7
  const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
5
- const args = process.platform === 'win32' ? ['/c', 'start', '', filePath] : [filePath];
6
- const child = spawn(command, args, { stdio: 'ignore', detached: true });
7
- child.on('error', () => undefined);
8
- child.unref();
8
+ const args = process.platform === 'win32' ? ['/c', 'start', '', target] : [target];
9
+ return new Promise(resolve => {
10
+ const child = spawn(command, args, { stdio: 'ignore', detached: true, windowsHide: true });
11
+ child.once('error', error => {
12
+ // Callers like the OAuth wizard print the URL regardless, so a non-opening
13
+ // browser is recoverable; the optional callback lets debug builds log why.
14
+ onError?.(error);
15
+ resolve(false);
16
+ });
17
+ child.once('spawn', () => {
18
+ child.unref();
19
+ resolve(true);
20
+ });
21
+ });
9
22
  }
@@ -1,4 +1,6 @@
1
1
  export declare function workspaceRoot(): string;
2
+ /** Lexical identity for comparing model-supplied paths without touching the filesystem. */
3
+ export declare function workspacePathKey(inputPath: string): string;
2
4
  export declare function resolveWorkspacePath(inputPath: string): string;
3
5
  export declare function workspaceRelativePath(absolutePath: string): string;
4
6
  export declare function assertPathInsideRoot(root: string, candidate: string, inputPath: string, label?: string): void;
@@ -3,9 +3,13 @@ import path from 'node:path';
3
3
  export function workspaceRoot() {
4
4
  return process.cwd();
5
5
  }
6
+ /** Lexical identity for comparing model-supplied paths without touching the filesystem. */
7
+ export function workspacePathKey(inputPath) {
8
+ return path.resolve(workspaceRoot(), inputPath);
9
+ }
6
10
  export function resolveWorkspacePath(inputPath) {
7
11
  const root = workspaceRoot();
8
- const resolved = path.resolve(root, inputPath);
12
+ const resolved = workspacePathKey(inputPath);
9
13
  const relative = path.relative(root, resolved);
10
14
  if (relative.startsWith('..') || path.isAbsolute(relative)) {
11
15
  throw new Error(`Path is outside the workspace: ${inputPath}`);