@denizokcu/haze 0.9.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 (241) hide show
  1. package/CHANGELOG.md +133 -17
  2. package/README.md +164 -68
  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/chatMetrics.d.ts +17 -1
  9. package/dist/cli/chat/chatMetrics.js +22 -5
  10. package/dist/cli/chat/contextReport.d.ts +11 -0
  11. package/dist/cli/chat/contextReport.js +46 -0
  12. package/dist/cli/chat/fileMentionSuggestions.d.ts +29 -0
  13. package/dist/cli/chat/fileMentionSuggestions.js +92 -0
  14. package/dist/cli/chat/inputSuggestions.d.ts +5 -0
  15. package/dist/cli/chat/inputSuggestions.js +17 -3
  16. package/dist/cli/chat/liveRegion.d.ts +25 -0
  17. package/dist/cli/chat/liveRegion.js +48 -0
  18. package/dist/cli/chat/messages.d.ts +33 -2
  19. package/dist/cli/chat/messages.js +216 -33
  20. package/dist/cli/chat/sessionLifecycle.d.ts +67 -0
  21. package/dist/cli/chat/sessionLifecycle.js +205 -0
  22. package/dist/cli/chat/sessionRecorder.js +80 -14
  23. package/dist/cli/chat/startupInfo.js +11 -4
  24. package/dist/cli/chat/tips.d.ts +21 -0
  25. package/dist/cli/chat/tips.js +43 -0
  26. package/dist/cli/chat/wizardDispatch.d.ts +64 -0
  27. package/dist/cli/chat/wizardDispatch.js +744 -0
  28. package/dist/cli/commands/chat.d.ts +6 -0
  29. package/dist/cli/commands/chat.js +373 -790
  30. package/dist/cli/commands/chatModes.d.ts +1 -1
  31. package/dist/cli/commands/chatModes.js +7 -2
  32. package/dist/cli/commands/commandHelp.js +5 -3
  33. package/dist/cli/commands/commands.d.ts +5 -2
  34. package/dist/cli/commands/commands.js +22 -18
  35. package/dist/cli/commands/doctor.d.ts +19 -0
  36. package/dist/cli/commands/doctor.js +76 -0
  37. package/dist/cli/commands/fleetCommand.d.ts +14 -0
  38. package/dist/cli/commands/fleetCommand.js +46 -0
  39. package/dist/cli/commands/formatters.d.ts +5 -0
  40. package/dist/cli/commands/formatters.js +35 -6
  41. package/dist/cli/commands/logsCommand.js +1 -7
  42. package/dist/cli/commands/modelCommand.js +1 -1
  43. package/dist/cli/commands/ndjsonSink.d.ts +23 -0
  44. package/dist/cli/commands/ndjsonSink.js +38 -0
  45. package/dist/cli/commands/providerWizard.d.ts +10 -2
  46. package/dist/cli/commands/providerWizard.js +50 -4
  47. package/dist/cli/commands/runCommand.d.ts +4 -0
  48. package/dist/cli/commands/runCommand.js +142 -16
  49. package/dist/cli/commands/sessionPicker.d.ts +9 -0
  50. package/dist/cli/commands/sessionPicker.js +29 -0
  51. package/dist/cli/commands/settingsSummary.js +6 -4
  52. package/dist/cli/commands/skillConfirmRemove.js +4 -3
  53. package/dist/cli/commands/skillWizard.d.ts +2 -0
  54. package/dist/cli/commands/skillWizard.js +16 -6
  55. package/dist/cli/commands/streaming/abortCause.d.ts +24 -0
  56. package/dist/cli/commands/streaming/abortCause.js +16 -0
  57. package/dist/cli/commands/streaming/assistantText.js +9 -2
  58. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +65 -0
  59. package/dist/cli/commands/streaming/goalCheckpoint.js +23 -0
  60. package/dist/cli/commands/streaming/goalSupervisor.d.ts +64 -0
  61. package/dist/cli/commands/streaming/goalSupervisor.js +127 -0
  62. package/dist/cli/commands/streaming/idleTimer.d.ts +26 -0
  63. package/dist/cli/commands/streaming/idleTimer.js +24 -0
  64. package/dist/cli/commands/streaming/toolCallRecovery.d.ts +2 -0
  65. package/dist/cli/commands/streaming/toolCallRecovery.js +24 -0
  66. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +31 -0
  67. package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -2
  68. package/dist/cli/commands/streaming/toolResultState.d.ts +6 -1
  69. package/dist/cli/commands/streaming/toolResultState.js +29 -7
  70. package/dist/cli/commands/streaming/turnOutcome.d.ts +17 -0
  71. package/dist/cli/commands/streaming/turnOutcome.js +27 -11
  72. package/dist/cli/commands/streaming/turnRuntime.js +6 -4
  73. package/dist/cli/commands/streaming.d.ts +82 -3
  74. package/dist/cli/commands/streaming.js +528 -91
  75. package/dist/cli/commands/wizardActions.d.ts +7 -0
  76. package/dist/cli/commands/wizardActions.js +7 -0
  77. package/dist/cli/commands/wizardPrompts.js +7 -1
  78. package/dist/cli/commands/wizardSuggestions.d.ts +8 -0
  79. package/dist/cli/commands/wizardSuggestions.js +64 -14
  80. package/dist/cli/commands/wizardTransition.d.ts +4 -0
  81. package/dist/cli/commands/wizardTransition.js +1 -2
  82. package/dist/cli/index.js +82 -22
  83. package/dist/cli/terminalTitle.d.ts +6 -0
  84. package/dist/cli/terminalTitle.js +36 -0
  85. package/dist/config/inputHistory.d.ts +3 -3
  86. package/dist/config/inputHistory.js +12 -18
  87. package/dist/config/modelDiscovery.d.ts +71 -0
  88. package/dist/config/modelDiscovery.js +214 -0
  89. package/dist/config/privateStorage.js +28 -2
  90. package/dist/config/providerAuth.d.ts +14 -0
  91. package/dist/config/providerAuth.js +49 -0
  92. package/dist/config/providerPresets.d.ts +49 -5
  93. package/dist/config/providerPresets.js +573 -73
  94. package/dist/config/providers.d.ts +2 -0
  95. package/dist/config/providers.js +9 -0
  96. package/dist/config/settings.d.ts +58 -0
  97. package/dist/config/settings.js +38 -1
  98. package/dist/config/skillSettings.d.ts +6 -13
  99. package/dist/config/skillSettings.js +20 -19
  100. package/dist/core/agent/budgets.d.ts +36 -0
  101. package/dist/core/agent/budgets.js +44 -0
  102. package/dist/core/agent/compaction.d.ts +38 -0
  103. package/dist/core/agent/compaction.js +108 -19
  104. package/dist/core/agent/completionController.d.ts +230 -0
  105. package/dist/core/agent/completionController.js +287 -0
  106. package/dist/core/agent/contextBudget.d.ts +46 -0
  107. package/dist/core/agent/contextBudget.js +89 -7
  108. package/dist/core/agent/errors.js +6 -2
  109. package/dist/core/agent/events.d.ts +86 -0
  110. package/dist/core/agent/reasoningPolicy.d.ts +31 -0
  111. package/dist/core/agent/reasoningPolicy.js +27 -0
  112. package/dist/core/agent/toolCapabilities.d.ts +27 -0
  113. package/dist/core/agent/toolCapabilities.js +58 -0
  114. package/dist/core/agent/toolExecutionBudget.d.ts +35 -0
  115. package/dist/core/agent/toolExecutionBudget.js +49 -0
  116. package/dist/core/agent/toolOutputStore.d.ts +13 -0
  117. package/dist/core/agent/toolOutputStore.js +27 -10
  118. package/dist/core/agent/toolResults.d.ts +12 -0
  119. package/dist/core/agent/toolResults.js +38 -0
  120. package/dist/core/agent/turnBudget.d.ts +35 -0
  121. package/dist/core/agent/turnBudget.js +27 -0
  122. package/dist/core/agent/turnPolicy.d.ts +11 -0
  123. package/dist/core/agent/turnPolicy.js +19 -0
  124. package/dist/core/agent/workState.d.ts +76 -1
  125. package/dist/core/agent/workState.js +120 -13
  126. package/dist/core/attachments/imageAttachments.d.ts +90 -0
  127. package/dist/core/attachments/imageAttachments.js +245 -0
  128. package/dist/core/attachments/readBlessings.d.ts +37 -0
  129. package/dist/core/attachments/readBlessings.js +79 -0
  130. package/dist/core/deadline.d.ts +33 -0
  131. package/dist/core/deadline.js +74 -0
  132. package/dist/core/goal/completionPolicy.d.ts +27 -0
  133. package/dist/core/goal/completionPolicy.js +37 -1
  134. package/dist/core/goal/requestClassifier.d.ts +0 -3
  135. package/dist/core/goal/requestClassifier.js +0 -13
  136. package/dist/core/io/boundedRead.js +76 -29
  137. package/dist/core/limits/byteBudgets.d.ts +7 -0
  138. package/dist/core/limits/byteBudgets.js +7 -0
  139. package/dist/core/limits/textBudgets.d.ts +25 -0
  140. package/dist/core/limits/textBudgets.js +25 -0
  141. package/dist/core/log/llmLog.js +7 -0
  142. package/dist/core/persistence/orderedFileWriter.d.ts +10 -0
  143. package/dist/core/persistence/orderedFileWriter.js +16 -2
  144. package/dist/core/process/backgroundRegistry.d.ts +35 -0
  145. package/dist/core/process/backgroundRegistry.js +195 -0
  146. package/dist/core/process/runBoundedProcess.d.ts +9 -0
  147. package/dist/core/process/runBoundedProcess.js +74 -29
  148. package/dist/core/safety/missingExecutable.d.ts +42 -0
  149. package/dist/core/safety/missingExecutable.js +77 -0
  150. package/dist/core/safety/urlGuard.d.ts +2 -1
  151. package/dist/core/safety/urlGuard.js +3 -2
  152. package/dist/core/session/sessionSlimming.js +47 -4
  153. package/dist/core/session/sessionStore.d.ts +74 -0
  154. package/dist/core/session/sessionStore.js +268 -18
  155. package/dist/core/subagent/contracts.d.ts +120 -0
  156. package/dist/core/subagent/contracts.js +55 -0
  157. package/dist/core/subagent/executionProfiles.d.ts +28 -0
  158. package/dist/core/subagent/executionProfiles.js +45 -0
  159. package/dist/core/subagent/subagentCoordinator.d.ts +78 -0
  160. package/dist/core/subagent/subagentCoordinator.js +164 -0
  161. package/dist/core/subagent/subagentRunner.d.ts +211 -145
  162. package/dist/core/subagent/subagentRunner.js +208 -98
  163. package/dist/core/subagent/workspaceMutationPolicy.d.ts +11 -0
  164. package/dist/core/subagent/workspaceMutationPolicy.js +52 -0
  165. package/dist/core/tasks/taskStorage.js +12 -1
  166. package/dist/llm/client.d.ts +36 -29
  167. package/dist/llm/client.js +102 -33
  168. package/dist/llm/hazeTools.d.ts +2559 -150
  169. package/dist/llm/hazeTools.js +119 -31
  170. package/dist/llm/lsp.d.ts +26 -4
  171. package/dist/llm/lsp.js +90 -14
  172. package/dist/llm/lspTools.d.ts +2366 -0
  173. package/dist/llm/lspTools.js +87 -79
  174. package/dist/llm/openaiCodex.d.ts +3 -0
  175. package/dist/llm/openaiCodex.js +47 -0
  176. package/dist/llm/openaiCodexOAuth.d.ts +54 -0
  177. package/dist/llm/openaiCodexOAuth.js +214 -0
  178. package/dist/llm/requestContext.d.ts +25 -1
  179. package/dist/llm/requestContext.js +51 -8
  180. package/dist/llm/systemPrompt.d.ts +15 -1
  181. package/dist/llm/systemPrompt.js +24 -8
  182. package/dist/llm/toolResultTypes.d.ts +8 -1
  183. package/dist/llm/tools/bashTool.d.ts +906 -32
  184. package/dist/llm/tools/bashTool.js +30 -4
  185. package/dist/llm/tools/editMatch.d.ts +14 -0
  186. package/dist/llm/tools/editMatch.js +72 -0
  187. package/dist/llm/tools/failures.d.ts +2 -0
  188. package/dist/llm/tools/failures.js +1 -0
  189. package/dist/llm/tools/fetchTool.d.ts +42 -26
  190. package/dist/llm/tools/fetchTool.js +1 -1
  191. package/dist/llm/tools/fileToolShared.d.ts +6 -4
  192. package/dist/llm/tools/fileToolShared.js +18 -23
  193. package/dist/llm/tools/gitIgnore.d.ts +49 -0
  194. package/dist/llm/tools/gitIgnore.js +129 -0
  195. package/dist/llm/tools/grepRunner.d.ts +5 -0
  196. package/dist/llm/tools/grepRunner.js +52 -71
  197. package/dist/llm/tools/outputCap.d.ts +2 -6
  198. package/dist/llm/tools/outputCap.js +2 -6
  199. package/dist/llm/tools/processTool.d.ts +1077 -0
  200. package/dist/llm/tools/processTool.js +41 -0
  201. package/dist/llm/tools/readRecovery.d.ts +10 -0
  202. package/dist/llm/tools/readRecovery.js +135 -0
  203. package/dist/llm/tools/toolContext.d.ts +9 -1
  204. package/dist/llm/tools/toolContext.js +83 -43
  205. package/dist/llm/tools/workspaceFile.d.ts +9 -1
  206. package/dist/llm/tools/workspaceFile.js +33 -4
  207. package/dist/llm/webFetch.d.ts +17 -0
  208. package/dist/llm/webFetch.js +66 -86
  209. package/dist/llm/workerContext.d.ts +18 -0
  210. package/dist/llm/workerContext.js +55 -0
  211. package/dist/skills/SkillLoader.d.ts +2 -2
  212. package/dist/skills/SkillRegistry.d.ts +3 -2
  213. package/dist/skills/SkillRegistry.js +43 -13
  214. package/dist/skills/builder/SkillBuilder.d.ts +3 -0
  215. package/dist/skills/builder/SkillBuilder.js +23 -5
  216. package/dist/skills/skillTools.js +11 -4
  217. package/dist/skills/types.d.ts +6 -1
  218. package/dist/ui/codeHighlight.d.ts +4 -0
  219. package/dist/ui/codeHighlight.js +31 -0
  220. package/dist/ui/components/Header.d.ts +1 -1
  221. package/dist/ui/components/MarkdownText.d.ts +16 -2
  222. package/dist/ui/components/MarkdownText.js +244 -34
  223. package/dist/ui/components/TextInput.d.ts +12 -2
  224. package/dist/ui/components/TextInput.js +80 -8
  225. package/dist/ui/theme.d.ts +4 -3
  226. package/dist/ui/theme.js +5 -4
  227. package/dist/utils/buildInfo.d.ts +104 -0
  228. package/dist/utils/buildInfo.js +253 -0
  229. package/dist/utils/format.d.ts +2 -0
  230. package/dist/utils/format.js +8 -0
  231. package/dist/utils/fs.d.ts +9 -1
  232. package/dist/utils/fs.js +87 -29
  233. package/dist/utils/openPath.d.ts +2 -0
  234. package/dist/utils/openPath.js +22 -0
  235. package/dist/utils/path.d.ts +2 -0
  236. package/dist/utils/path.js +5 -1
  237. package/dist/utils/utf8.d.ts +22 -0
  238. package/dist/utils/utf8.js +54 -0
  239. package/dist/utils/version.d.ts +9 -3
  240. package/dist/utils/version.js +28 -2
  241. package/package.json +24 -19
@@ -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
+ }
@@ -0,0 +1,2 @@
1
+ /** Human-readable byte sizes for display text (CLI rows, session placeholders). */
2
+ export declare function formatBytes(bytes: number): string;
@@ -0,0 +1,8 @@
1
+ /** Human-readable byte sizes for display text (CLI rows, session placeholders). */
2
+ export function formatBytes(bytes) {
3
+ if (bytes < 1024)
4
+ return `${bytes} B`;
5
+ if (bytes < 1024 * 1024)
6
+ return `${(bytes / 1024).toFixed(1)} KB`;
7
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
8
+ }
@@ -9,7 +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[]>;
15
- export declare function listFilesRecursive(root: string): Promise<string[]>;
package/dist/utils/fs.js CHANGED
@@ -2,39 +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
  }
37
- export async function listFilesRecursive(root) {
38
- const entries = await walkDir(root, { recursive: true });
39
- return entries.filter(e => e.isFile).map(e => e.path).sort();
40
- }
@@ -0,0 +1,2 @@
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>;
@@ -0,0 +1,22 @@
1
+ import { spawn } from 'node:child_process';
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.
7
+ const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
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
+ });
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}`);
@@ -0,0 +1,22 @@
1
+ export interface Utf8BufferTruncation {
2
+ buffer: Buffer;
3
+ bytes: number;
4
+ truncated: boolean;
5
+ }
6
+ /** Retain at most `maxBytes` from the start without splitting a UTF-8 character. */
7
+ export declare function truncateUtf8BufferAtBytes(input: Buffer, maxBytes: number): Utf8BufferTruncation;
8
+ /**
9
+ * Retain at most `maxBytes` from the end without starting inside a UTF-8 character.
10
+ *
11
+ * Best-effort for malformed UTF-8 input: if the buffer contains stray bytes that
12
+ * are not part of a valid sequence, the result may begin with a replacement
13
+ * character when decoded. Callers that need strict UTF-8 validation should
14
+ * validate before truncating.
15
+ */
16
+ export declare function truncateUtf8TailBufferAtBytes(input: Buffer, maxBytes: number): Utf8BufferTruncation;
17
+ /** Retain a string or Buffer prefix under a byte budget and return valid UTF-8 text. */
18
+ export declare function truncateUtf8AtBytes(input: string | Buffer, maxBytes: number): {
19
+ text: string;
20
+ bytes: number;
21
+ truncated: boolean;
22
+ };
@@ -0,0 +1,54 @@
1
+ function isContinuationByte(byte) {
2
+ return byte !== undefined && (byte & 0xc0) === 0x80;
3
+ }
4
+ function expectedSequenceBytes(lead) {
5
+ if (lead <= 0x7f)
6
+ return 1;
7
+ if (lead >= 0xc2 && lead <= 0xdf)
8
+ return 2;
9
+ if (lead >= 0xe0 && lead <= 0xef)
10
+ return 3;
11
+ if (lead >= 0xf0 && lead <= 0xf4)
12
+ return 4;
13
+ return 1;
14
+ }
15
+ function completePrefixEnd(input, proposedEnd) {
16
+ if (proposedEnd === 0)
17
+ return 0;
18
+ let sequenceStart = proposedEnd - 1;
19
+ while (sequenceStart > 0 && isContinuationByte(input[sequenceStart]))
20
+ sequenceStart--;
21
+ const expected = expectedSequenceBytes(input[sequenceStart]);
22
+ return proposedEnd - sequenceStart < expected ? sequenceStart : proposedEnd;
23
+ }
24
+ /** Retain at most `maxBytes` from the start without splitting a UTF-8 character. */
25
+ export function truncateUtf8BufferAtBytes(input, maxBytes) {
26
+ const limit = Math.max(0, Math.floor(maxBytes));
27
+ const end = completePrefixEnd(input, Math.min(input.byteLength, limit));
28
+ const buffer = end === input.byteLength ? input : input.subarray(0, end);
29
+ return { buffer, bytes: buffer.byteLength, truncated: buffer.byteLength < input.byteLength };
30
+ }
31
+ /**
32
+ * Retain at most `maxBytes` from the end without starting inside a UTF-8 character.
33
+ *
34
+ * Best-effort for malformed UTF-8 input: if the buffer contains stray bytes that
35
+ * are not part of a valid sequence, the result may begin with a replacement
36
+ * character when decoded. Callers that need strict UTF-8 validation should
37
+ * validate before truncating.
38
+ */
39
+ export function truncateUtf8TailBufferAtBytes(input, maxBytes) {
40
+ const limit = Math.max(0, Math.floor(maxBytes));
41
+ if (input.byteLength <= limit)
42
+ return { buffer: input, bytes: input.byteLength, truncated: false };
43
+ let start = input.byteLength - limit;
44
+ while (start < input.byteLength && isContinuationByte(input[start]))
45
+ start++;
46
+ const buffer = input.subarray(start);
47
+ return { buffer, bytes: buffer.byteLength, truncated: true };
48
+ }
49
+ /** Retain a string or Buffer prefix under a byte budget and return valid UTF-8 text. */
50
+ export function truncateUtf8AtBytes(input, maxBytes) {
51
+ const source = typeof input === 'string' ? Buffer.from(input, 'utf8') : input;
52
+ const result = truncateUtf8BufferAtBytes(source, maxBytes);
53
+ return { text: result.buffer.toString('utf8'), bytes: result.bytes, truncated: result.truncated };
54
+ }