@denizokcu/haze 0.10.0 → 1.0.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 (294) hide show
  1. package/CHANGELOG.md +100 -1
  2. package/README.md +77 -27
  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 +2 -2
  9. package/dist/cli/chat/chatMetrics.js +1 -1
  10. package/dist/cli/chat/contextReport.js +2 -0
  11. package/dist/cli/chat/fileMentionSuggestions.js +3 -2
  12. package/dist/cli/chat/inputSuggestions.d.ts +8 -16
  13. package/dist/cli/chat/inputSuggestions.js +9 -41
  14. package/dist/cli/chat/liveRegion.d.ts +25 -0
  15. package/dist/cli/chat/liveRegion.js +48 -0
  16. package/dist/cli/chat/messages.d.ts +33 -4
  17. package/dist/cli/chat/messages.js +218 -35
  18. package/dist/cli/chat/sessionLifecycle.d.ts +11 -1
  19. package/dist/cli/chat/sessionLifecycle.js +64 -14
  20. package/dist/cli/chat/sessionRecorder.js +75 -7
  21. package/dist/cli/chat/startupInfo.d.ts +0 -1
  22. package/dist/cli/chat/startupInfo.js +11 -15
  23. package/dist/cli/chat/turnState.d.ts +1 -1
  24. package/dist/cli/chat/wizardDispatch.d.ts +90 -28
  25. package/dist/cli/chat/wizardDispatch.js +349 -133
  26. package/dist/cli/commands/chat.d.ts +5 -0
  27. package/dist/cli/commands/chat.js +216 -172
  28. package/dist/cli/commands/chatModes.d.ts +8 -1
  29. package/dist/cli/commands/chatModes.js +9 -44
  30. package/dist/cli/commands/commands.d.ts +2 -0
  31. package/dist/cli/commands/commands.js +10 -5
  32. package/dist/cli/commands/doctor.d.ts +19 -0
  33. package/dist/cli/commands/doctor.js +76 -0
  34. package/dist/cli/commands/formatters.d.ts +3 -3
  35. package/dist/cli/commands/formatters.js +8 -25
  36. package/dist/cli/commands/ndjsonSink.d.ts +23 -0
  37. package/dist/cli/commands/ndjsonSink.js +38 -0
  38. package/dist/cli/commands/providerWizard.d.ts +9 -2
  39. package/dist/cli/commands/providerWizard.js +39 -7
  40. package/dist/cli/commands/runCommand.d.ts +3 -0
  41. package/dist/cli/commands/runCommand.js +117 -11
  42. package/dist/cli/commands/serverWizard.d.ts +34 -0
  43. package/dist/cli/commands/{mcpWizard.js → serverWizard.js} +44 -2
  44. package/dist/cli/commands/skillsWizard.d.ts +41 -0
  45. package/dist/cli/commands/{skillWizard.js → skillsWizard.js} +33 -11
  46. package/dist/cli/commands/streaming/abortCause.d.ts +25 -0
  47. package/dist/cli/commands/streaming/abortCause.js +16 -0
  48. package/dist/cli/commands/streaming/agentAttempt.d.ts +43 -0
  49. package/dist/cli/commands/streaming/agentAttempt.js +79 -0
  50. package/dist/cli/commands/streaming/assistantText.js +9 -2
  51. package/dist/cli/commands/streaming/attemptLifecycle.d.ts +56 -0
  52. package/dist/cli/commands/streaming/attemptLifecycle.js +110 -0
  53. package/dist/cli/commands/streaming/attemptOutcome.d.ts +96 -0
  54. package/dist/cli/commands/streaming/attemptOutcome.js +206 -0
  55. package/dist/cli/commands/streaming/attemptSetup.d.ts +78 -0
  56. package/dist/cli/commands/streaming/attemptSetup.js +167 -0
  57. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +65 -0
  58. package/dist/cli/commands/streaming/goalCheckpoint.js +23 -0
  59. package/dist/cli/commands/streaming/goalSupervisor.d.ts +64 -0
  60. package/dist/cli/commands/streaming/goalSupervisor.js +130 -0
  61. package/dist/cli/commands/streaming/stallRecovery.d.ts +94 -0
  62. package/dist/cli/commands/streaming/stallRecovery.js +105 -0
  63. package/dist/cli/commands/streaming/streamLoop.d.ts +72 -0
  64. package/dist/cli/commands/streaming/streamLoop.js +448 -0
  65. package/dist/cli/commands/streaming/toolCallRecovery.d.ts +16 -0
  66. package/dist/cli/commands/streaming/toolCallRecovery.js +80 -0
  67. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +31 -1
  68. package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -4
  69. package/dist/cli/commands/streaming/toolResultState.d.ts +6 -1
  70. package/dist/cli/commands/streaming/toolResultState.js +29 -7
  71. package/dist/cli/commands/streaming/turnRuntime.d.ts +4 -0
  72. package/dist/cli/commands/streaming/turnRuntime.js +6 -0
  73. package/dist/cli/commands/streaming.d.ts +65 -9
  74. package/dist/cli/commands/streaming.js +133 -430
  75. package/dist/cli/commands/wizardFlow.d.ts +334 -0
  76. package/dist/cli/commands/wizardFlow.js +377 -0
  77. package/dist/cli/contextReport.js +3 -0
  78. package/dist/cli/index.js +68 -22
  79. package/dist/cli/terminalTitle.js +1 -1
  80. package/dist/config/contextFiles.js +9 -3
  81. package/dist/config/inputHistory.d.ts +0 -1
  82. package/dist/config/inputHistory.js +1 -1
  83. package/dist/config/modelDiscovery.d.ts +36 -0
  84. package/dist/config/modelDiscovery.js +164 -1
  85. package/dist/config/privateStorage.js +28 -2
  86. package/dist/config/providerAuth.d.ts +14 -0
  87. package/dist/config/providerAuth.js +49 -0
  88. package/dist/config/providerPresets.d.ts +39 -7
  89. package/dist/config/providerPresets.js +371 -100
  90. package/dist/config/providers.js +2 -0
  91. package/dist/config/settings.d.ts +43 -0
  92. package/dist/config/settings.js +12 -0
  93. package/dist/config/skillSettings.js +4 -4
  94. package/dist/config/updateCheck.d.ts +0 -1
  95. package/dist/config/updateCheck.js +1 -1
  96. package/dist/core/agent/budgets.d.ts +73 -1
  97. package/dist/core/agent/budgets.js +94 -1
  98. package/dist/core/agent/compaction.d.ts +38 -0
  99. package/dist/core/agent/compaction.js +92 -17
  100. package/dist/core/agent/completionController.d.ts +224 -0
  101. package/dist/core/agent/completionController.js +296 -0
  102. package/dist/core/agent/contextBudget.d.ts +36 -2
  103. package/dist/core/agent/contextBudget.js +62 -9
  104. package/dist/core/agent/errors.d.ts +0 -1
  105. package/dist/core/agent/errors.js +1 -1
  106. package/dist/core/agent/events.d.ts +78 -0
  107. package/dist/core/agent/goalPolicy.d.ts +47 -0
  108. package/dist/core/agent/goalPolicy.js +106 -0
  109. package/dist/core/agent/reasoningPolicy.d.ts +31 -0
  110. package/dist/core/agent/reasoningPolicy.js +27 -0
  111. package/dist/core/agent/requestAssembly.d.ts +2 -2
  112. package/dist/core/agent/requestAssembly.js +16 -4
  113. package/dist/core/agent/toolCapabilities.d.ts +27 -0
  114. package/dist/core/agent/toolCapabilities.js +58 -0
  115. package/dist/core/agent/toolOutputStore.d.ts +8 -0
  116. package/dist/core/agent/toolOutputStore.js +11 -11
  117. package/dist/core/agent/toolResults.d.ts +12 -0
  118. package/dist/core/agent/toolResults.js +38 -0
  119. package/dist/core/agent/turnPolicy.d.ts +11 -0
  120. package/dist/core/agent/turnPolicy.js +19 -0
  121. package/dist/core/agent/workState.d.ts +81 -3
  122. package/dist/core/agent/workState.js +176 -10
  123. package/dist/core/attachments/imageAttachments.js +90 -42
  124. package/dist/core/deadline.d.ts +27 -0
  125. package/dist/core/deadline.js +74 -0
  126. package/dist/core/io/boundedRead.js +1 -1
  127. package/dist/core/limits.d.ts +51 -0
  128. package/dist/core/limits.js +51 -0
  129. package/dist/core/log/llmLog.js +8 -1
  130. package/dist/core/persistence/orderedFileWriter.d.ts +10 -0
  131. package/dist/core/persistence/orderedFileWriter.js +16 -2
  132. package/dist/core/process/backgroundRegistry.d.ts +2 -3
  133. package/dist/core/process/backgroundRegistry.js +15 -10
  134. package/dist/core/process/runBoundedProcess.d.ts +8 -2
  135. package/dist/core/process/runBoundedProcess.js +15 -6
  136. package/dist/core/process/userShell.d.ts +16 -0
  137. package/dist/core/process/userShell.js +59 -0
  138. package/dist/core/safety/missingExecutable.d.ts +42 -0
  139. package/dist/core/safety/missingExecutable.js +77 -0
  140. package/dist/core/safety/shellClassifier.d.ts +11 -0
  141. package/dist/core/safety/{bashClassifier.js → shellClassifier.js} +5 -3
  142. package/dist/core/safety/urlGuard.d.ts +1 -1
  143. package/dist/core/session/sessionSlimming.d.ts +0 -3
  144. package/dist/core/session/sessionSlimming.js +2 -3
  145. package/dist/core/session/sessionStore.d.ts +38 -0
  146. package/dist/core/session/sessionStore.js +242 -59
  147. package/dist/core/{bashOutput → shellOutput}/lineFilter.js +8 -2
  148. package/dist/core/{bashOutput → shellOutput}/reducers/search.d.ts +0 -1
  149. package/dist/core/{bashOutput → shellOutput}/reducers/search.js +1 -1
  150. package/dist/core/shellOutput/registry.d.ts +2 -0
  151. package/dist/core/{bashOutput → shellOutput}/registry.js +3 -3
  152. package/dist/core/{bashOutput → shellOutput}/types.d.ts +6 -5
  153. package/dist/core/subagent/contracts.d.ts +6 -14
  154. package/dist/core/subagent/contracts.js +4 -3
  155. package/dist/core/subagent/executionProfiles.js +2 -2
  156. package/dist/core/subagent/subagentCoordinator.d.ts +4 -0
  157. package/dist/core/subagent/subagentCoordinator.js +32 -2
  158. package/dist/core/subagent/subagentRunner.js +19 -40
  159. package/dist/core/toolOutput/reduction.d.ts +0 -12
  160. package/dist/core/toolOutput/reduction.js +1 -1
  161. package/dist/core/validation/outputParser.d.ts +2 -2
  162. package/dist/llm/client.d.ts +17 -1
  163. package/dist/llm/client.js +86 -14
  164. package/dist/llm/hazeTools.d.ts +693 -204
  165. package/dist/llm/hazeTools.js +110 -28
  166. package/dist/llm/initPrompt.js +1 -1
  167. package/dist/llm/lsp/client.d.ts +45 -0
  168. package/dist/llm/lsp/client.js +195 -0
  169. package/dist/llm/lsp/pool.d.ts +23 -0
  170. package/dist/llm/lsp/pool.js +86 -0
  171. package/dist/llm/lsp/protocol.d.ts +64 -0
  172. package/dist/llm/lsp/protocol.js +128 -0
  173. package/dist/llm/lsp/requests.d.ts +94 -0
  174. package/dist/llm/lsp/requests.js +119 -0
  175. package/dist/llm/lspTools.d.ts +5653 -33
  176. package/dist/llm/lspTools.js +152 -80
  177. package/dist/llm/openaiCodex.d.ts +1 -0
  178. package/dist/llm/openaiCodex.js +43 -0
  179. package/dist/llm/openaiCodexOAuth.d.ts +51 -0
  180. package/dist/llm/openaiCodexOAuth.js +217 -0
  181. package/dist/llm/requestContext.d.ts +7 -0
  182. package/dist/llm/requestContext.js +30 -4
  183. package/dist/llm/systemPrompt.d.ts +12 -0
  184. package/dist/llm/systemPrompt.js +24 -11
  185. package/dist/llm/toolResultTypes.d.ts +7 -14
  186. package/dist/llm/toolResultTypes.js +1 -4
  187. package/dist/llm/tools/editMatch.d.ts +14 -9
  188. package/dist/llm/tools/editMatch.js +73 -1
  189. package/dist/llm/tools/failures.d.ts +2 -0
  190. package/dist/llm/tools/failures.js +1 -0
  191. package/dist/llm/tools/fetchTool.d.ts +16 -0
  192. package/dist/llm/tools/fetchTool.js +1 -1
  193. package/dist/llm/tools/fileToolShared.d.ts +8 -5
  194. package/dist/llm/tools/fileToolShared.js +22 -23
  195. package/dist/llm/tools/gitIgnore.d.ts +42 -0
  196. package/dist/llm/tools/gitIgnore.js +247 -0
  197. package/dist/llm/tools/grepParse.d.ts +2 -1
  198. package/dist/llm/tools/grepRunner.d.ts +1 -1
  199. package/dist/llm/tools/grepRunner.js +2 -2
  200. package/dist/llm/tools/outputCap.d.ts +2 -7
  201. package/dist/llm/tools/outputCap.js +3 -3
  202. package/dist/llm/tools/processTool.d.ts +16 -16
  203. package/dist/llm/tools/processTool.js +1 -1
  204. package/dist/llm/tools/readRecovery.d.ts +8 -0
  205. package/dist/llm/tools/readRecovery.js +135 -0
  206. package/dist/llm/tools/{bashTool.d.ts → shellTool.d.ts} +171 -123
  207. package/dist/llm/tools/{bashTool.js → shellTool.js} +20 -14
  208. package/dist/llm/tools/toolContext.d.ts +1 -1
  209. package/dist/llm/tools/toolContext.js +66 -37
  210. package/dist/llm/tools/workspaceFile.d.ts +0 -1
  211. package/dist/llm/tools/workspaceFile.js +1 -6
  212. package/dist/llm/webFetch.d.ts +18 -1
  213. package/dist/llm/webFetch.js +64 -97
  214. package/dist/skills/SkillLoader.d.ts +1 -11
  215. package/dist/skills/SkillLoader.js +1 -2
  216. package/dist/skills/types.d.ts +2 -1
  217. package/dist/ui/codeHighlight.d.ts +4 -0
  218. package/dist/ui/codeHighlight.js +31 -0
  219. package/dist/ui/components/Header.d.ts +1 -1
  220. package/dist/ui/components/MarkdownText.d.ts +16 -2
  221. package/dist/ui/components/MarkdownText.js +244 -34
  222. package/dist/ui/components/TextInput.d.ts +8 -1
  223. package/dist/ui/components/TextInput.js +6 -2
  224. package/dist/ui/theme.d.ts +4 -3
  225. package/dist/ui/theme.js +5 -4
  226. package/dist/utils/buildInfo.d.ts +97 -0
  227. package/dist/utils/buildInfo.js +244 -0
  228. package/dist/utils/fs.d.ts +11 -0
  229. package/dist/utils/fs.js +91 -26
  230. package/dist/utils/openPath.d.ts +2 -2
  231. package/dist/utils/openPath.js +19 -6
  232. package/dist/utils/path.d.ts +2 -1
  233. package/dist/utils/path.js +6 -2
  234. package/dist/utils/utf8.d.ts +22 -0
  235. package/dist/utils/utf8.js +54 -0
  236. package/dist/utils/version.d.ts +9 -3
  237. package/dist/utils/version.js +28 -2
  238. package/package.json +28 -21
  239. package/dist/cli/commands/lspWizard.d.ts +0 -14
  240. package/dist/cli/commands/lspWizard.js +0 -44
  241. package/dist/cli/commands/mcpWizard.d.ts +0 -15
  242. package/dist/cli/commands/skillConfirmRemove.d.ts +0 -11
  243. package/dist/cli/commands/skillConfirmRemove.js +0 -20
  244. package/dist/cli/commands/skillCreation.d.ts +0 -12
  245. package/dist/cli/commands/skillCreation.js +0 -14
  246. package/dist/cli/commands/skillWizard.d.ts +0 -17
  247. package/dist/cli/commands/streaming/idleTimer.d.ts +0 -26
  248. package/dist/cli/commands/streaming/idleTimer.js +0 -24
  249. package/dist/cli/commands/streaming/turnOutcome.d.ts +0 -10
  250. package/dist/cli/commands/streaming/turnOutcome.js +0 -13
  251. package/dist/cli/commands/wizardActions.d.ts +0 -46
  252. package/dist/cli/commands/wizardActions.js +0 -46
  253. package/dist/cli/commands/wizardInput.d.ts +0 -4
  254. package/dist/cli/commands/wizardInput.js +0 -19
  255. package/dist/cli/commands/wizardPrompts.d.ts +0 -22
  256. package/dist/cli/commands/wizardPrompts.js +0 -52
  257. package/dist/cli/commands/wizardSuggestions.d.ts +0 -31
  258. package/dist/cli/commands/wizardSuggestions.js +0 -188
  259. package/dist/cli/commands/wizardTransition.d.ts +0 -37
  260. package/dist/cli/commands/wizardTransition.js +0 -43
  261. package/dist/core/bashOutput/ansi.d.ts +0 -1
  262. package/dist/core/bashOutput/ansi.js +0 -7
  263. package/dist/core/bashOutput/registry.d.ts +0 -4
  264. package/dist/core/goal/completionPolicy.d.ts +0 -2
  265. package/dist/core/goal/completionPolicy.js +0 -7
  266. package/dist/core/goal/requestClassifier.d.ts +0 -3
  267. package/dist/core/goal/requestClassifier.js +0 -18
  268. package/dist/core/goal/sessionGoal.d.ts +0 -8
  269. package/dist/core/goal/sessionGoal.js +0 -30
  270. package/dist/core/limits/byteBudgets.d.ts +0 -18
  271. package/dist/core/limits/byteBudgets.js +0 -18
  272. package/dist/core/limits/textBudgets.d.ts +0 -23
  273. package/dist/core/limits/textBudgets.js +0 -23
  274. package/dist/core/safety/bashClassifier.d.ts +0 -10
  275. package/dist/llm/lsp.d.ts +0 -129
  276. package/dist/llm/lsp.js +0 -307
  277. package/dist/ui/components/ErrorView.d.ts +0 -4
  278. package/dist/ui/components/ErrorView.js +0 -7
  279. package/dist/utils/yaml.d.ts +0 -2
  280. package/dist/utils/yaml.js +0 -8
  281. package/examples/skills/files/SKILL.md +0 -16
  282. package/examples/skills/files/examples/file-editing.md +0 -3
  283. /package/dist/core/{bashOutput → shellOutput}/command.d.ts +0 -0
  284. /package/dist/core/{bashOutput → shellOutput}/command.js +0 -0
  285. /package/dist/core/{bashOutput → shellOutput}/lineFilter.d.ts +0 -0
  286. /package/dist/core/{bashOutput → shellOutput}/reducers/content.d.ts +0 -0
  287. /package/dist/core/{bashOutput → shellOutput}/reducers/content.js +0 -0
  288. /package/dist/core/{bashOutput → shellOutput}/reducers/gh.d.ts +0 -0
  289. /package/dist/core/{bashOutput → shellOutput}/reducers/gh.js +0 -0
  290. /package/dist/core/{bashOutput → shellOutput}/reducers/git.d.ts +0 -0
  291. /package/dist/core/{bashOutput → shellOutput}/reducers/git.js +0 -0
  292. /package/dist/core/{bashOutput → shellOutput}/reducers/validation.d.ts +0 -0
  293. /package/dist/core/{bashOutput → shellOutput}/reducers/validation.js +0 -0
  294. /package/dist/core/{bashOutput → shellOutput}/types.js +0 -0
@@ -0,0 +1,244 @@
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
+ 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
+ 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
+ return { goalSupervisorAvailable: goalSupervisorArtifactPresent(root) };
147
+ }
148
+ /** One-line capability summary for logs and doctor output. */
149
+ export function formatCapabilities(capabilities) {
150
+ return `goal-supervisor=${capabilities.goalSupervisorAvailable ? 'enabled' : 'disabled'}`;
151
+ }
152
+ /** Resolved entry executable (process.argv[1]); undefined in non-CLI contexts. */
153
+ export function resolveExecutable() {
154
+ if (!process.argv[1])
155
+ return undefined;
156
+ try {
157
+ return realpathSync(process.argv[1]);
158
+ }
159
+ catch {
160
+ return process.argv[1];
161
+ }
162
+ }
163
+ function describeRuntime(input = {}) {
164
+ const runtimeRoot = input.runtimeRoot ?? resolvePackageRoot();
165
+ const build = readBuildInfo(input.runtimeRoot ? [join(input.runtimeRoot, 'dist', 'buildInfo.json')] : undefined);
166
+ const version = build?.version ?? readPackageVersionAt(runtimeRoot ?? '') ?? '0.0.0';
167
+ return { version, build, runtimeRoot, executable: resolveExecutable(), capabilities: runtimeCapabilities(runtimeRoot ?? process.cwd()) };
168
+ }
169
+ /** `haze --version --verbose` block: version, commit, runtime/executable paths, supervisor state. */
170
+ export function formatVersionVerbose(provenance = describeRuntime()) {
171
+ const lines = [
172
+ `Haze ${provenance.version}`,
173
+ `commit: ${provenance.build?.commit ?? 'unknown'}`,
174
+ ...(provenance.build?.builtAt ? [`builtAt: ${provenance.build.builtAt}`] : []),
175
+ ];
176
+ if (provenance.runtimeRoot)
177
+ lines.push(`runtime: ${join(provenance.runtimeRoot, 'dist')}`);
178
+ if (provenance.executable)
179
+ lines.push(`executable: ${provenance.executable}`);
180
+ lines.push(`goal supervisor: ${provenance.capabilities.goalSupervisorAvailable ? 'enabled' : 'disabled'}`);
181
+ return lines.join('\n');
182
+ }
183
+ function sameRealPath(a, b) {
184
+ try {
185
+ return realpathSync(a) === realpathSync(b);
186
+ }
187
+ catch {
188
+ return resolve(a) === resolve(b);
189
+ }
190
+ }
191
+ /**
192
+ * Detect a haze source checkout at/above `cwd` that differs from the executing
193
+ * runtime — the classic failure where a globally installed haze (e.g. 0.10.0)
194
+ * silently serves requests while the checkout beside the workspace already
195
+ * contains the fix. Returns undefined when there is nothing to warn about.
196
+ */
197
+ export function detectCheckoutMismatch(input = {}) {
198
+ const executingRoot = input.executingRoot ?? resolvePackageRoot();
199
+ if (!executingRoot)
200
+ return undefined;
201
+ let dir = resolve(input.cwd ?? process.cwd());
202
+ let checkoutRoot;
203
+ while (true) {
204
+ if (readPackageNameAt(dir) === HAZE_PACKAGE_NAME) {
205
+ checkoutRoot = dir;
206
+ break;
207
+ }
208
+ const parent = dirname(dir);
209
+ if (parent === dir)
210
+ break;
211
+ dir = parent;
212
+ }
213
+ if (!checkoutRoot || sameRealPath(checkoutRoot, executingRoot))
214
+ return undefined;
215
+ const executingVersion = readPackageVersionAt(executingRoot) ?? readBuildInfo([join(executingRoot, 'dist', 'buildInfo.json')])?.version ?? 'unknown';
216
+ const checkoutVersion = readPackageVersionAt(checkoutRoot) ?? 'unknown';
217
+ const executingCommit = readBuildInfo([join(executingRoot, 'dist', 'buildInfo.json')])?.commit ?? gitHeadCommit(executingRoot);
218
+ const checkoutCommit = readBuildInfo([join(checkoutRoot, 'dist', 'buildInfo.json')])?.commit ?? gitHeadCommit(checkoutRoot);
219
+ const versionDiffers = executingVersion !== checkoutVersion;
220
+ const commitDiffers = executingCommit != null && checkoutCommit != null && executingCommit !== checkoutCommit;
221
+ if (!versionDiffers && !commitDiffers)
222
+ return undefined;
223
+ return {
224
+ executingRoot,
225
+ executingVersion,
226
+ ...(executingCommit ? { executingCommit } : {}),
227
+ checkoutRoot,
228
+ checkoutVersion,
229
+ ...(checkoutCommit ? { checkoutCommit } : {}),
230
+ versionDiffers,
231
+ checkoutNewer: compareVersions(checkoutVersion, executingVersion) > 0,
232
+ };
233
+ }
234
+ /** Startup warning for a stale runtime executing next to a newer checkout. */
235
+ export function formatMismatchWarning(mismatch) {
236
+ const head = mismatch.versionDiffers
237
+ ? `Running Haze ${mismatch.executingVersion} from ${mismatch.executingRoot}, but checkout ${mismatch.checkoutRoot} is ${mismatch.checkoutVersion}.`
238
+ : `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) ?? '?'}.`;
239
+ return [
240
+ head,
241
+ 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.',
242
+ 'Run `npm run dev:link` inside the checkout (rebuild + relink), or start it directly with `npm run haze -- <args>`.',
243
+ ].join('\n');
244
+ }
@@ -9,6 +9,17 @@ 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 (with real directory-ness, so dir-only patterns
17
+ * evaluate exactly like Git), return the subset that is ignored. Ignored
18
+ * entries are dropped and ignored directories are not descended into.
19
+ * Evaluation is in-process, so a listing costs O(visited directories) rule
20
+ * file reads rather than one per entry (RH-001). Fails open: an empty set
21
+ * means "keep all".
22
+ */
23
+ ignoreBatch?: (entries: WalkEntry[]) => Promise<Set<string>>;
13
24
  }
14
25
  export declare function walkDir(root: string, options?: WalkOptions): Promise<WalkEntry[]>;
package/dist/utils/fs.js CHANGED
@@ -1,36 +1,101 @@
1
1
  import fs from 'fs-extra';
2
2
  import path from 'node:path';
3
- const SKIP_ENTRIES = new Set(['node_modules', '.git']);
3
+ // Repository metadata and dependency trees are never useful discovery targets.
4
+ // Skip both even when a project has no `.gitignore`: this keeps traversal bounded
5
+ // and prevents dependency contents from crowding out workspace source files.
6
+ const SKIP_ENTRIES = new Set(['.git', 'node_modules']);
4
7
  export async function walkDir(root, options = {}) {
5
- const { recursive = false, maxEntries = Infinity, cursor, filter } = options;
8
+ const { recursive = false, maxEntries = Infinity, cursor, filter, ignoreBatch } = options;
6
9
  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) {
10
+ // Cursor semantics: the cursor is the last entry a previous page returned.
11
+ // This walk resumes strictly *after* that entry in depth-first traversal
12
+ // order, without re-checking or even descending into earlier subtrees.
13
+ const cursorSegments = cursor ? cursor.split(/[\\/]/).filter(Boolean) : [];
14
+ let collecting = cursor == null;
15
+ if (!(await fs.pathExists(root)))
16
+ return result;
17
+ async function readSortedChildren(dir) {
18
+ const entries = await fs.readdir(dir, { withFileTypes: true });
19
+ return entries.filter(entry => !SKIP_ENTRIES.has(entry.name)).sort((a, b) => a.name.localeCompare(b.name));
20
+ }
21
+ function toWalkEntry(dir, dirent) {
22
+ const absolutePath = path.join(dir, dirent.name);
23
+ return {
24
+ path: path.relative(root, absolutePath),
25
+ absolutePath,
26
+ name: dirent.name,
27
+ isDirectory: dirent.isDirectory(),
28
+ isFile: dirent.isFile(),
29
+ };
30
+ }
31
+ async function keepNonIgnored(entries) {
32
+ if (!ignoreBatch)
33
+ return entries;
34
+ if (entries.length === 0)
35
+ return entries;
36
+ const ignored = await ignoreBatch(entries);
37
+ if (ignored.size === 0)
38
+ return entries;
39
+ return entries.filter(entry => !ignored.has(entry.path));
40
+ }
41
+ async function walk(dir, depth) {
42
+ if (result.length >= maxEntries)
43
+ return;
44
+ const dirents = await readSortedChildren(dir);
45
+ const entries = dirents.map(dirent => toWalkEntry(dir, dirent));
46
+ if (collecting) {
47
+ const kept = await keepNonIgnored(entries);
48
+ for (const entry of kept) {
49
+ if (result.length >= maxEntries)
50
+ return;
51
+ const passesFilter = !filter || (await filter(entry));
52
+ if (passesFilter)
53
+ result.push(entry);
54
+ if (passesFilter && recursive && entry.isDirectory)
55
+ await walk(entry.absolutePath, depth + 1);
56
+ }
57
+ return;
58
+ }
59
+ // Pre-cursor region. The cursor's branch child at this depth splits the
60
+ // sorted children into three DFS-ordered groups: entries strictly before
61
+ // the branch (pre-cursor: skipped without classifying or descending), the
62
+ // branch child itself (descended into to resolve the cursor, never emitted),
63
+ // and entries after the branch (post-cursor: emitted normally). This keeps
64
+ // a later page from re-checking or re-walking earlier subtrees (RH-001).
65
+ const branchName = depth < cursorSegments.length ? cursorSegments[depth] : undefined;
66
+ const branchIndex = branchName ? entries.findIndex(entry => entry.name === branchName) : -1;
67
+ if (branchIndex === -1)
68
+ return; // stale cursor: emit nothing rather than duplicate earlier pages
69
+ const branch = entries[branchIndex];
70
+ const atCursorLevel = depth >= cursorSegments.length - 1;
71
+ if (atCursorLevel) {
72
+ // The branch child is the cursor entry itself; do not re-emit it. If it is
73
+ // a directory its children follow it in DFS order, so descend now that we
74
+ // are collecting.
75
+ if (branch.path === cursor) {
76
+ collecting = true;
77
+ if (recursive && branch.isDirectory)
78
+ await walk(branch.absolutePath, depth + 1);
79
+ }
80
+ }
81
+ else if (branch.isDirectory && recursive) {
82
+ // Ancestor directory: descend to resolve the cursor deeper in the tree.
83
+ await walk(branch.absolutePath, depth + 1);
84
+ }
85
+ if (!collecting)
86
+ return; // cursor was not found inside the branch (stale)
87
+ // Post-cursor siblings at this level are emitted and descended normally.
88
+ const keptPost = await keepNonIgnored(entries.slice(branchIndex + 1));
89
+ for (const entry of keptPost) {
11
90
  if (result.length >= maxEntries)
12
91
  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);
92
+ const passesFilter = !filter || (await filter(entry));
93
+ if (passesFilter)
94
+ result.push(entry);
95
+ if (passesFilter && recursive && entry.isDirectory)
96
+ await walk(entry.absolutePath, depth + 1);
31
97
  }
32
98
  }
33
- if (await fs.pathExists(root))
34
- await walk(root);
99
+ await walk(root, 0);
35
100
  return result;
36
101
  }
@@ -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,7 +1,8 @@
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
- export declare function assertPathInsideRoot(root: string, candidate: string, inputPath: string, label?: string): void;
5
6
  export declare function assertRealPathInsideRoot(root: string, candidate: string, inputPath?: string, label?: string): Promise<string>;
6
7
  export declare function assertRealPathInsideWorkspace(absolutePath: string, inputPath?: string): Promise<void>;
7
8
  export declare function assertWritablePathInsideWorkspace(absolutePath: string, inputPath?: string): Promise<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}`);
@@ -15,7 +19,7 @@ export function resolveWorkspacePath(inputPath) {
15
19
  export function workspaceRelativePath(absolutePath) {
16
20
  return path.relative(workspaceRoot(), absolutePath) || '.';
17
21
  }
18
- export function assertPathInsideRoot(root, candidate, inputPath, label = 'workspace') {
22
+ function assertPathInsideRoot(root, candidate, inputPath, label = 'workspace') {
19
23
  const relative = path.relative(root, candidate);
20
24
  if (relative.startsWith('..') || path.isAbsolute(relative)) {
21
25
  throw new Error(`Path is outside the ${label}: ${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
+ }
@@ -1,11 +1,17 @@
1
+ /** Read the installed package version once, returning undefined if metadata is unavailable. */
2
+ export declare function readPackageVersion(): string | undefined;
1
3
  /**
2
4
  * Minimal, dependency-free version comparison for the update check.
3
5
  *
4
6
  * Handles npm package versions like `0.6.0`, `1.2.3`, with optional leading
5
7
  * `v` and optional pre-release suffix (`1.0.0-beta.1`). Numeric release
6
- * segments are compared numerically; pre-release sorts *below* its release
7
- * (so `1.0.0-beta.1` is older than `1.0.0`). Malformed input is treated as
8
- * `0.0.0` so the check degrades to "no update" rather than throwing.
8
+ * segments are compared numerically; non-numeric trailing chars in a release
9
+ * segment are silently stripped (`1.2.0a` → `1.2.0`), since semver does not
10
+ * define them. Pre-release sorts *below* its release (so `1.0.0-beta.1` is
11
+ * older than `1.0.0`), and within a pre-release, numeric identifiers always
12
+ * have lower precedence than alphanumeric ones (semver rule). Malformed input
13
+ * is treated as `0.0.0` so the check degrades to "no update" rather than
14
+ * throwing.
9
15
  *
10
16
  * Kept small on purpose: no `semver` dependency for a single comparison.
11
17
  */
@@ -1,3 +1,23 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { dirname, join } from 'node:path';
4
+ const PACKAGE_JSON_PATH = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'package.json');
5
+ let packageVersionLoaded = false;
6
+ let cachedPackageVersion;
7
+ /** Read the installed package version once, returning undefined if metadata is unavailable. */
8
+ export function readPackageVersion() {
9
+ if (packageVersionLoaded)
10
+ return cachedPackageVersion;
11
+ packageVersionLoaded = true;
12
+ try {
13
+ const parsed = JSON.parse(readFileSync(PACKAGE_JSON_PATH, 'utf8'));
14
+ cachedPackageVersion = typeof parsed.version === 'string' ? parsed.version : undefined;
15
+ }
16
+ catch {
17
+ cachedPackageVersion = undefined;
18
+ }
19
+ return cachedPackageVersion;
20
+ }
1
21
  export function parseVersion(input) {
2
22
  const cleaned = input.trim().replace(/^v/i, '');
3
23
  // Drop build metadata: everything from the first '+' onward is ignored.
@@ -11,6 +31,7 @@ export function parseVersion(input) {
11
31
  const segments = releasePart.split('.');
12
32
  const nums = [0, 0, 0];
13
33
  for (let index = 0; index < 3; index++) {
34
+ // Non-numeric trailing chars (e.g., `1.2.0a`) are dropped, not rejected.
14
35
  const parsed = Number.parseInt((segments[index] ?? '').replace(/[^0-9]/g, ''), 10);
15
36
  nums[index] = Number.isFinite(parsed) ? parsed : 0;
16
37
  }
@@ -30,13 +51,18 @@ function comparePrerelease(a, b) {
30
51
  const bb = b[index];
31
52
  const anum = Number(aa);
32
53
  const bnum = Number(bb);
33
- const bothNumeric = Number.isFinite(anum) && Number.isFinite(bnum);
34
- if (bothNumeric) {
54
+ const aNumeric = Number.isFinite(anum);
55
+ const bNumeric = Number.isFinite(bnum);
56
+ // Semver: numeric identifiers always have lower precedence than alphanumeric.
57
+ if (aNumeric && bNumeric) {
35
58
  if (anum < bnum)
36
59
  return -1;
37
60
  if (anum > bnum)
38
61
  return 1;
39
62
  }
63
+ else if (aNumeric !== bNumeric) {
64
+ return aNumeric ? -1 : 1;
65
+ }
40
66
  else {
41
67
  if (aa < bb)
42
68
  return -1;