@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
@@ -6,6 +6,7 @@ export declare const PROVIDER_ACTIONS: {
6
6
  readonly useProvider: "use provider";
7
7
  readonly addModels: "add models";
8
8
  readonly setApiKey: "set API key";
9
+ readonly signInChatGpt: "sign in with ChatGPT";
9
10
  readonly markImageCapable: "mark image-capable";
10
11
  readonly clearImageCapable: "clear image-capable";
11
12
  readonly removeModels: "remove models";
@@ -6,6 +6,7 @@ export const PROVIDER_ACTIONS = {
6
6
  useProvider: 'use provider',
7
7
  addModels: 'add models',
8
8
  setApiKey: 'set API key',
9
+ signInChatGpt: 'sign in with ChatGPT',
9
10
  markImageCapable: 'mark image-capable',
10
11
  clearImageCapable: 'clear image-capable',
11
12
  removeModels: 'remove models',
@@ -1,5 +1,6 @@
1
1
  import { configuredLspServers } from '../../config/lspSettings.js';
2
2
  import { findMcpServer } from '../../config/mcpSettings.js';
3
+ import { CHATGPT_CODEX_BASE_URL } from '../../llm/openaiCodexOAuth.js';
3
4
  import { MCP_TRANSPORTS } from './wizardActions.js';
4
5
  import { commandParts, isValidUrl } from './wizardInput.js';
5
6
  export function captureProviderName(settings, value) {
@@ -29,7 +30,12 @@ export function captureMcpName(settings, value) {
29
30
  export function captureProviderUrl(value) {
30
31
  if (!isValidUrl(value))
31
32
  return { message: 'Enter a valid URL, for example http://localhost:1234/v1.' };
32
- return { draft: { url: value.trim() }, nextMode: 'providerAddKey', systemMessage: 'API key? Leave blank for local/keyless providers.' };
33
+ // The Codex endpoint only accepts ChatGPT sign-in, never API keys; point
34
+ // users at the preset instead of a custom provider that cannot work (F-14).
35
+ const codexHint = value.trim() === CHATGPT_CODEX_BASE_URL
36
+ ? `\nNote: ${CHATGPT_CODEX_BASE_URL} serves ChatGPT sign-in only. To use it, add the OpenAI Subscription preset via /provider instead of a custom API-key provider.`
37
+ : '';
38
+ return { draft: { url: value.trim() }, nextMode: 'providerAddKey', systemMessage: `API key? Leave blank for local/keyless providers.${codexHint}` };
33
39
  }
34
40
  export function captureMcpUrl(value) {
35
41
  if (!isValidUrl(value))
@@ -26,8 +26,10 @@ export function providerActionSuggestions(settings, selectedProviderName) {
26
26
  const provider = selectedProviderName ? findProvider(settings, selectedProviderName) : undefined;
27
27
  return [
28
28
  { value: PROVIDER_ACTIONS.useProvider, description: 'Set this provider and choose a model', kind: 'provider' },
29
- { value: PROVIDER_ACTIONS.addModels, description: 'Fetch the provider model list and add models', kind: 'provider' },
30
- { value: PROVIDER_ACTIONS.setApiKey, description: provider?.key ? 'Update the saved API key' : 'Add an API key', kind: 'provider' },
29
+ { value: PROVIDER_ACTIONS.addModels, description: provider?.kind === 'chatgpt-codex' ? 'Add a supported Codex model name' : 'Fetch the provider model list and add models', kind: 'provider' },
30
+ ...(provider?.kind === 'chatgpt-codex'
31
+ ? [{ value: PROVIDER_ACTIONS.signInChatGpt, description: 'Sign in again or switch ChatGPT account', kind: 'provider' }]
32
+ : [{ value: PROVIDER_ACTIONS.setApiKey, description: provider?.key ? 'Update the saved API key' : 'Add an API key', kind: 'provider' }]),
31
33
  provider
32
34
  ? (providerImageCapable(provider)
33
35
  ? { value: PROVIDER_ACTIONS.clearImageCapable, description: 'Stop sending attached images to this provider', kind: 'provider' }
@@ -43,7 +45,7 @@ export function presetSuggestions() {
43
45
  return [
44
46
  ...cloudPresets.map(preset => ({
45
47
  value: preset.id,
46
- description: `${preset.baseUrl}${preset.suggestedModels?.length ? ' · e.g. ' + preset.suggestedModels.slice(0, 2).join(', ') : ''}`,
48
+ description: `${preset.baseUrl}${preset.auth === 'chatgpt-oauth' ? ' · browser sign-in' : ''}${preset.suggestedModels?.length ? ' · e.g. ' + preset.suggestedModels.slice(0, 2).join(', ') : ''}`,
47
49
  kind: 'provider',
48
50
  })),
49
51
  ...localPresets.map(preset => ({
package/dist/cli/index.js CHANGED
@@ -1,28 +1,30 @@
1
1
  #!/usr/bin/env node
2
- import { readFileSync } from 'node:fs';
3
- import { fileURLToPath } from 'node:url';
4
- import { dirname, join } from 'node:path';
5
2
  import { Command, Option } from 'commander';
6
3
  import { chatCommand } from './commands/chat.js';
7
4
  import { runHeadless } from './commands/runCommand.js';
8
5
  import { installTerminalTitle, terminalTitleLabel } from './terminalTitle.js';
9
6
  import { findSession } from '../core/session/sessionStore.js';
10
7
  import { installBackgroundProcessSignalHandlers, teardownBackgroundProcesses } from '../core/process/backgroundRegistry.js';
11
- const __dirname = dirname(fileURLToPath(import.meta.url));
8
+ import { STDIN_PROMPT_BYTES } from '../core/limits/byteBudgets.js';
9
+ import { readPackageVersion } from '../utils/version.js';
10
+ import { formatVersionVerbose, readBuildInfo } from '../utils/buildInfo.js';
11
+ import { runDoctor } from './commands/doctor.js';
12
12
  installBackgroundProcessSignalHandlers();
13
- const pkg = JSON.parse(readFileSync(join(__dirname, '..', '..', 'package.json'), 'utf8'));
13
+ const version = readPackageVersion() ?? '0.0.0';
14
14
  const program = new Command();
15
15
  program
16
16
  .name('haze')
17
17
  .description('A pragmatic, intentionally limited agentic CLI.')
18
- .version(pkg.version)
18
+ .option('-V, --version', 'print the haze version (add --verbose for build provenance: commit, runtime paths, capabilities)')
19
+ .option('--verbose', 'with --version: also print commit, runtime/executable paths, and the capability registry')
19
20
  .option('--debug', 'show model/tool debug logs and write a detailed JSONL log to ~/.haze/logs/')
20
21
  .option('-c, --continue', 'resume the latest saved session for this workspace')
21
22
  .addOption(new Option('--resume <id>', 'resume an exact saved session id for this workspace').conflicts(['continue', 'session']))
22
23
  .option('--no-session', 'run without saving or resuming a durable session')
23
24
  .option('-p, --prompt <text>', 'print mode: run a single non-interactive turn and print the result (falls back to piped stdin)')
24
25
  .option('-m, --model <selector>', 'override the model for this run only — a registered model name or provider:name')
25
- .addOption(new Option('--output <format>', 'print-mode output: plain text, a single JSON result envelope, or a stream-json NDJSON event stream').choices(['text', 'json', 'stream-json']).default('text'));
26
+ .addOption(new Option('--output <format>', 'print-mode output: plain text, a single JSON result envelope, or a stream-json NDJSON event stream').choices(['text', 'json', 'stream-json']).default('text'))
27
+ .option('--timeout <duration>', 'print-mode absolute turn deadline (e.g. 30s, 10m, 2h); bounds total elapsed time so a busy tool cannot run indefinitely');
26
28
  program.addHelpText('after', `
27
29
  Examples:
28
30
  $ haze start the interactive chat
@@ -37,33 +39,69 @@ Examples:
37
39
  Print mode (-p):
38
40
  Runs a single agentic turn with the full toolset and guardrails, prints the final assistant
39
41
  text, then exits (0 = complete; non-zero = aborted/failed, so CI can gate on the exit code).
40
- The prompt comes from -p, otherwise from piped stdin. With --output json the reply is wrapped
41
- in a single-line { type, status, result, usage } envelope. With --output stream-json haze streams
42
- one NDJSON agent event per line (turn_start, message_*, tool_*, retry, turn_end) as the run
43
- progresses, then prints that same { type:'result', ... } envelope as the final line — giving
44
- harnesses live progress and stagnation detection. --model overrides the model for this
42
+ The prompt comes from -p, otherwise from piped stdin. Piped prompts over 256 KiB are rejected;
43
+ pass a file path and ask haze to read it instead. With --output json the reply is wrapped in a
44
+ single-line { type, status, result, usage } envelope. With --output stream-json haze streams
45
+ one NDJSON agent event per line (turn_start, step_*, message_*, tool_*, retry, turn_end) as the
46
+ run progresses, then prints that same { type:'result', ... } envelope as the final line — giving
47
+ harnesses live progress, per-step usage, bounded tool-failure diagnostics, and stagnation
48
+ detection without raw tool inputs or outputs. --model overrides the model for this
45
49
  run only (no settings change) and must already be registered under a provider (add it once via
46
50
  the /provider picker). Print-mode runs are non-durable: --continue is ignored and no session is
47
- saved. --resume <id> loads saved context for the turn without changing that session. There is no
48
- automatic context-overflow recovery.
51
+ saved. --resume <id> loads saved context for the turn without changing that session. On a
52
+ provider context overflow, haze compacts the conversation and retries the request once; when
53
+ compaction is unavailable, the error says so explicitly.
49
54
  `);
50
55
  async function readStdinPrompt() {
51
56
  // Only read stdin when it is piped (non-TTY); never hang waiting on an interactive terminal.
52
- if (process.stdin.isTTY === false) {
53
- return new Promise((resolve) => {
57
+ if (!process.stdin.isTTY) {
58
+ return new Promise((resolve, reject) => {
54
59
  let data = '';
55
- process.stdin.setEncoding('utf8');
56
- process.stdin.on('data', (chunk) => {
60
+ let bytes = 0;
61
+ const cleanup = () => {
62
+ process.stdin.removeListener('data', onData);
63
+ process.stdin.removeListener('end', onEnd);
64
+ process.stdin.removeListener('error', onError);
65
+ };
66
+ const onData = (chunk) => {
67
+ bytes += Buffer.byteLength(chunk, 'utf8');
68
+ if (bytes > STDIN_PROMPT_BYTES) {
69
+ cleanup();
70
+ process.stdin.pause();
71
+ reject(new Error(`stdin prompt exceeds ${STDIN_PROMPT_BYTES} bytes; pass a file path and ask haze to read it instead.`));
72
+ return;
73
+ }
57
74
  data += chunk;
58
- });
59
- process.stdin.on('end', () => resolve(data.trim() ? data : undefined));
60
- process.stdin.on('error', () => resolve(undefined));
75
+ };
76
+ const onEnd = () => {
77
+ cleanup();
78
+ resolve(data.trim() ? data : undefined);
79
+ };
80
+ const onError = () => {
81
+ cleanup();
82
+ resolve(undefined);
83
+ };
84
+ process.stdin.setEncoding('utf8');
85
+ process.stdin.on('data', onData);
86
+ process.stdin.on('end', onEnd);
87
+ process.stdin.on('error', onError);
61
88
  });
62
89
  }
63
90
  return undefined;
64
91
  }
92
+ program.command('doctor')
93
+ .description('print runtime provenance (version, commit, executable/runtime paths), verify build integrity, and show the capability registry')
94
+ .action(async () => {
95
+ process.exitCode = await runDoctor();
96
+ });
65
97
  program.action(async () => {
66
98
  const opts = program.opts();
99
+ if (opts.version) {
100
+ // Handled here (not via commander's built-in .version()) so --verbose can
101
+ // enrich it and the bin launcher can answer without loading dist.
102
+ process.stdout.write(opts.verbose ? `${formatVersionVerbose()}\n` : `${version}\n`);
103
+ return;
104
+ }
67
105
  // Name the terminal tab for the run; no-op unless stdout is a real TTY.
68
106
  installTerminalTitle(terminalTitleLabel(process.cwd()));
69
107
  // -p takes precedence; otherwise fall back to piped stdin. An empty stdin yields no prompt.
@@ -81,14 +119,22 @@ program.action(async () => {
81
119
  // 'text' | 'json' | 'stream-json'; default to text for piped/stdin runs without the flag.
82
120
  output: opts.output === 'json' || opts.output === 'stream-json' ? opts.output : 'text',
83
121
  debug: Boolean(opts.debug),
122
+ timeout: opts.timeout,
84
123
  });
85
124
  // Set the exit code and return instead of process.exit(code): the latter does not wait
86
125
  // for stdout to drain and can truncate piped/redirected output (e.g. `haze -p ... | jq`).
87
126
  process.exitCode = code;
88
127
  return;
89
128
  }
90
- await chatCommand({ debug: Boolean(opts.debug), continueSession: Boolean(opts.continue), resumeSessionId: opts.resume, noSession: opts.session === false, version: pkg.version });
129
+ await chatCommand({ debug: Boolean(opts.debug), continueSession: Boolean(opts.continue), resumeSessionId: opts.resume, noSession: opts.session === false, version, build: sessionBuildProvenance() });
91
130
  });
131
+ /** Safe build provenance recorded into session headers (commit + build time only). */
132
+ function sessionBuildProvenance() {
133
+ const info = readBuildInfo();
134
+ if (!info?.commit && !info?.builtAt)
135
+ return undefined;
136
+ return { ...(info?.commit ? { commit: info.commit } : {}), ...(info?.builtAt ? { builtAt: info.builtAt } : {}) };
137
+ }
92
138
  program.parseAsync().catch(async (error) => {
93
139
  console.error(error instanceof Error ? error.message : error);
94
140
  await teardownBackgroundProcesses().catch(() => undefined);
@@ -11,7 +11,7 @@ function titleEscape(label) {
11
11
  }
12
12
  export function terminalTitleLabel(cwd) {
13
13
  // eslint-disable-next-line no-control-regex -- stripping control characters is the point here.
14
- const dir = basename(cwd).replace(/[\u0000-\u001F\u007F]/g, '').trim();
14
+ const dir = basename(cwd).replace(/[\u0000-\u001F\u007F-\u009F]/g, '').trim();
15
15
  return `haze${dir ? ` - ${dir}` : ''}`;
16
16
  }
17
17
  /**
@@ -1,4 +1,9 @@
1
1
  import type { HazeProviderSettings } from './settings.js';
2
+ /** Per-model limits harvested from a provider's /models listing. */
3
+ export type HarvestedModelLimits = Record<string, {
4
+ contextWindowTokens?: number;
5
+ maxOutputTokens?: number;
6
+ }>;
2
7
  /**
3
8
  * Model discovery against the OpenAI-compatible `/models` endpoint every
4
9
  * provider in haze exposes. Used to turn "add models" from a memorize-and-type
@@ -8,13 +13,59 @@ import type { HazeProviderSettings } from './settings.js';
8
13
  export type ModelDiscoveryResult = {
9
14
  status: 'ok';
10
15
  models: string[];
16
+ modelLimits?: HarvestedModelLimits;
11
17
  } | {
12
18
  status: 'failed';
13
19
  error: string;
14
20
  };
15
21
  export declare function modelsEndpointUrl(baseUrl: string): string;
16
22
  export declare function parseModelsBody(body: unknown): string[];
23
+ /**
24
+ * Ollama native enrichment. Ollama's OpenAI-compatible /v1/models returns no
25
+ * context fields (verified against ollama 0.32), but its native API does, with
26
+ * different fidelity levels — resolved best-first per model:
27
+ * 1. GET /api/ps — the ACTUAL runtime context of a currently-loaded model
28
+ * (reflects OLLAMA_CONTEXT_LENGTH and Ollama's vram-based auto-sizing);
29
+ * only available while the model stays loaded (keep_alive window).
30
+ * 2. POST /api/show parameters `num_ctx N` — the user's explicit per-model
31
+ * setting (Modelfile), capped by the model's trained maximum.
32
+ * 3. POST /api/show model_info `<arch>.context_length` — the model's
33
+ * theoretical maximum. The effective runtime window may be smaller
34
+ * (auto-sized to VRAM), so it is capped at the conservative local
35
+ * fallback rather than trusted outright (silent truncation guard).
36
+ */
37
+ export declare const OLLAMA_PROBE_TIMEOUT_MS = 4000;
38
+ interface OllamaShowFacts {
39
+ max?: number;
40
+ numCtx?: number;
41
+ }
42
+ /** Extract context facts from an /api/show response body. */
43
+ export declare function ollamaContextFromShow(show: unknown): OllamaShowFacts;
44
+ /**
45
+ * Probe a local Ollama server for the effective context of the given models.
46
+ * Best-effort: any failing request simply omits that model. Only call for
47
+ * loopback base URLs (the /api/* surface is Ollama-specific).
48
+ */
49
+ export declare function ollamaModelLimits(input: {
50
+ baseUrl: string;
51
+ models: readonly string[];
52
+ conservativeCap: number;
53
+ fetchImpl?: typeof fetch;
54
+ timeoutMs?: number;
55
+ }): Promise<HarvestedModelLimits>;
56
+ /**
57
+ * Harvest non-standard context/output fields from an OpenAI-compatible
58
+ * `/models` response. The official schema carries only `id`/`created`/`object`,
59
+ * but several providers add extensions (OpenRouter `context_length`, Groq
60
+ * `context_window`, LM Studio `max_context_length`, plus the usual
61
+ * `max_output_tokens`/`max_completion_tokens`/`max_tokens` output caps).
62
+ * Values are sanity-clamped so a quirky proxy cannot poison request budgeting;
63
+ * models with no recognizable fields are simply omitted. This is the only
64
+ * source that can know a local server's actually-configured window.
65
+ */
66
+ export declare function harvestModelLimits(body: unknown): HarvestedModelLimits;
17
67
  export declare function discoverProviderModels(provider: Pick<HazeProviderSettings, 'url' | 'key'>, options?: {
18
68
  timeoutMs?: number;
19
69
  fetchImpl?: typeof fetch;
20
70
  }): Promise<ModelDiscoveryResult>;
71
+ export {};
@@ -14,6 +14,168 @@ export function parseModelsBody(body) {
14
14
  .map(id => id.trim());
15
15
  return [...new Set(ids)].sort((a, b) => a.localeCompare(b)).slice(0, MAX_DISCOVERED_MODELS);
16
16
  }
17
+ /** Lowest and highest plausible token values; anything outside is treated as garbage. */
18
+ const HARVEST_MIN_TOKENS = 1_000;
19
+ const HARVEST_MAX_TOKENS = 10_000_000;
20
+ function harvestedTokens(value) {
21
+ if (typeof value !== 'number' || !Number.isSafeInteger(value))
22
+ return undefined;
23
+ return value >= HARVEST_MIN_TOKENS && value <= HARVEST_MAX_TOKENS ? value : undefined;
24
+ }
25
+ function firstHarvested(...values) {
26
+ for (const value of values) {
27
+ const tokens = harvestedTokens(value);
28
+ if (tokens !== undefined)
29
+ return tokens;
30
+ }
31
+ return undefined;
32
+ }
33
+ /**
34
+ * Ollama native enrichment. Ollama's OpenAI-compatible /v1/models returns no
35
+ * context fields (verified against ollama 0.32), but its native API does, with
36
+ * different fidelity levels — resolved best-first per model:
37
+ * 1. GET /api/ps — the ACTUAL runtime context of a currently-loaded model
38
+ * (reflects OLLAMA_CONTEXT_LENGTH and Ollama's vram-based auto-sizing);
39
+ * only available while the model stays loaded (keep_alive window).
40
+ * 2. POST /api/show parameters `num_ctx N` — the user's explicit per-model
41
+ * setting (Modelfile), capped by the model's trained maximum.
42
+ * 3. POST /api/show model_info `<arch>.context_length` — the model's
43
+ * theoretical maximum. The effective runtime window may be smaller
44
+ * (auto-sized to VRAM), so it is capped at the conservative local
45
+ * fallback rather than trusted outright (silent truncation guard).
46
+ */
47
+ export const OLLAMA_PROBE_TIMEOUT_MS = 4_000;
48
+ /** Bound the per-save /api/show probe loop so bulk pastes stay cheap. */
49
+ const OLLAMA_PROBE_MAX_MODELS = 8;
50
+ function loopbackRoot(baseUrl) {
51
+ try {
52
+ const url = new URL(baseUrl);
53
+ return `${url.protocol}//${url.host}`;
54
+ }
55
+ catch {
56
+ return undefined;
57
+ }
58
+ }
59
+ /** Extract context facts from an /api/show response body. */
60
+ export function ollamaContextFromShow(show) {
61
+ if (typeof show !== 'object' || show == null)
62
+ return {};
63
+ const record = show;
64
+ const facts = {};
65
+ const modelInfo = record.model_info;
66
+ if (typeof modelInfo === 'object' && modelInfo != null) {
67
+ let max;
68
+ for (const [key, value] of Object.entries(modelInfo)) {
69
+ // Skip derived keys like `<arch>.rope.scaling.original_context_length`,
70
+ // which describe the pre-scaling trained length, not the usable window.
71
+ if (!key.endsWith('.context_length') || /rope|original/.test(key))
72
+ continue;
73
+ if (typeof value === 'number' && Number.isSafeInteger(value) && value > 0) {
74
+ max = max === undefined ? value : Math.max(max, value);
75
+ }
76
+ }
77
+ if (max !== undefined)
78
+ facts.max = max;
79
+ }
80
+ if (typeof record.parameters === 'string') {
81
+ const match = /(?<![\w.])num_ctx\s+(\d+)/.exec(record.parameters);
82
+ const parsed = match ? Number(match[1]) : undefined;
83
+ if (parsed !== undefined && Number.isSafeInteger(parsed) && parsed > 0)
84
+ facts.numCtx = parsed;
85
+ }
86
+ return facts;
87
+ }
88
+ /** Effective context for one model given the probe results; undefined = nothing trustworthy. */
89
+ function resolveOllamaContext(psContext, facts, conservativeCap) {
90
+ if (psContext !== undefined && psContext > 0)
91
+ return psContext;
92
+ if (facts.numCtx !== undefined)
93
+ return Math.min(facts.numCtx, facts.max ?? Number.MAX_SAFE_INTEGER);
94
+ if (facts.max !== undefined)
95
+ return Math.min(facts.max, conservativeCap);
96
+ return undefined;
97
+ }
98
+ /**
99
+ * Probe a local Ollama server for the effective context of the given models.
100
+ * Best-effort: any failing request simply omits that model. Only call for
101
+ * loopback base URLs (the /api/* surface is Ollama-specific).
102
+ */
103
+ export async function ollamaModelLimits(input) {
104
+ const root = loopbackRoot(input.baseUrl);
105
+ if (!root || input.models.length === 0)
106
+ return {};
107
+ const fetchImpl = input.fetchImpl ?? fetch;
108
+ const timeoutMs = input.timeoutMs ?? OLLAMA_PROBE_TIMEOUT_MS;
109
+ const get = async (url, init) => {
110
+ const response = await fetchImpl(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
111
+ if (!response.ok)
112
+ throw new Error(`HTTP ${response.status}`);
113
+ return await response.json();
114
+ };
115
+ const out = {};
116
+ // Runtime ground truth for loaded models (one request, may be stale/empty).
117
+ const psLoaded = new Map();
118
+ try {
119
+ const ps = await get(`${root}/api/ps`);
120
+ for (const entry of ps?.models ?? []) {
121
+ for (const key of [entry.name, entry.model]) {
122
+ if (typeof key === 'string' && typeof entry.context_length === 'number' && entry.context_length > 0) {
123
+ psLoaded.set(key, entry.context_length);
124
+ }
125
+ }
126
+ }
127
+ }
128
+ catch {
129
+ // Not an Ollama server, or /api/ps unavailable: fall through to /api/show.
130
+ }
131
+ for (const model of input.models.slice(0, OLLAMA_PROBE_MAX_MODELS)) {
132
+ const psContext = psLoaded.get(model);
133
+ if (psContext !== undefined) {
134
+ out[model] = { contextWindowTokens: psContext };
135
+ continue;
136
+ }
137
+ try {
138
+ const facts = ollamaContextFromShow(await get(`${root}/api/show`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ model }) }));
139
+ const contextWindowTokens = resolveOllamaContext(undefined, facts, input.conservativeCap);
140
+ if (contextWindowTokens !== undefined)
141
+ out[model] = { contextWindowTokens };
142
+ }
143
+ catch {
144
+ // Unknown model, cloud model, or not an Ollama server: leave unset.
145
+ }
146
+ }
147
+ return out;
148
+ }
149
+ /**
150
+ * Harvest non-standard context/output fields from an OpenAI-compatible
151
+ * `/models` response. The official schema carries only `id`/`created`/`object`,
152
+ * but several providers add extensions (OpenRouter `context_length`, Groq
153
+ * `context_window`, LM Studio `max_context_length`, plus the usual
154
+ * `max_output_tokens`/`max_completion_tokens`/`max_tokens` output caps).
155
+ * Values are sanity-clamped so a quirky proxy cannot poison request budgeting;
156
+ * models with no recognizable fields are simply omitted. This is the only
157
+ * source that can know a local server's actually-configured window.
158
+ */
159
+ export function harvestModelLimits(body) {
160
+ const data = body?.data;
161
+ if (!Array.isArray(data))
162
+ return {};
163
+ const out = {};
164
+ for (const item of data) {
165
+ if (typeof item !== 'object' || item == null)
166
+ continue;
167
+ const entry = item;
168
+ const id = typeof entry.id === 'string' && entry.id.trim() ? entry.id.trim() : undefined;
169
+ if (!id)
170
+ continue;
171
+ const contextWindowTokens = firstHarvested(entry.context_window, entry.context_length, entry.max_context_length, entry.max_context_tokens);
172
+ const maxOutputTokens = firstHarvested(entry.max_output_tokens, entry.max_completion_tokens, entry.max_tokens);
173
+ if (contextWindowTokens !== undefined || maxOutputTokens !== undefined) {
174
+ out[id] = { ...(contextWindowTokens !== undefined ? { contextWindowTokens } : {}), ...(maxOutputTokens !== undefined ? { maxOutputTokens } : {}) };
175
+ }
176
+ }
177
+ return out;
178
+ }
17
179
  function describeFetchError(error) {
18
180
  if (error instanceof Error) {
19
181
  if (error.name === 'TimeoutError' || error.name === 'AbortError')
@@ -47,5 +209,6 @@ export async function discoverProviderModels(provider, options = {}) {
47
209
  const models = parseModelsBody(body);
48
210
  if (models.length === 0)
49
211
  return { status: 'failed', error: 'endpoint returned no models' };
50
- return { status: 'ok', models };
212
+ const modelLimits = harvestModelLimits(body);
213
+ return { status: 'ok', models, ...(Object.keys(modelLimits).length > 0 ? { modelLimits } : {}) };
51
214
  }
@@ -1,3 +1,4 @@
1
+ import crypto from 'node:crypto';
1
2
  import fs from 'node:fs/promises';
2
3
  import path from 'node:path';
3
4
  import { HAZE_DIR } from './paths.js';
@@ -8,6 +9,11 @@ export async function ensurePrivateDir(dir) {
8
9
  await fs.mkdir(absolute, { recursive: true, mode: DIRECTORY_MODE });
9
10
  if (process.platform === 'win32')
10
11
  return;
12
+ // Walk every ancestor under ~/.haze and chmod each one. Per-ancestor calls
13
+ // are necessary because mkdir's mode only applies to leaves created by this
14
+ // call — pre-existing ancestors may have permissive umask-derived modes.
15
+ // Cost: O(depth) syscalls per ensure. Session append paths are amortized by
16
+ // the caller batching writes; do not add a per-call cache without one.
11
17
  const hazeRoot = path.resolve(HAZE_DIR);
12
18
  const relative = path.relative(hazeRoot, absolute);
13
19
  if (!relative.startsWith('..') && !path.isAbsolute(relative)) {
@@ -39,7 +45,10 @@ export async function appendPrivateFile(file, content) {
39
45
  }
40
46
  export async function writePrivateFileAtomic(file, content) {
41
47
  await ensurePrivateDir(path.dirname(file));
42
- const temp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);
48
+ // Crypto-random suffix (not Math.random) so a same-user attacker cannot win a
49
+ // temp-file race on platforms where the private dir is not strictly 0700
50
+ // (Windows relies on inherited ACLs from the user profile).
51
+ const temp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${Date.now()}.${crypto.randomBytes(8).toString('hex')}.tmp`);
43
52
  let handle;
44
53
  try {
45
54
  handle = await fs.open(temp, 'wx', FILE_MODE);
@@ -47,7 +56,7 @@ export async function writePrivateFileAtomic(file, content) {
47
56
  await handle.sync();
48
57
  await handle.close();
49
58
  handle = undefined;
50
- await fs.rename(temp, file);
59
+ await renameAtomic(temp, file);
51
60
  if (process.platform !== 'win32')
52
61
  await fs.chmod(file, FILE_MODE);
53
62
  }
@@ -56,6 +65,23 @@ export async function writePrivateFileAtomic(file, content) {
56
65
  await fs.rm(temp, { force: true }).catch(() => undefined);
57
66
  }
58
67
  }
68
+ async function renameAtomic(temp, target) {
69
+ // POSIX rename is atomic. On Windows, rename over an existing file fails
70
+ // with EPERM when the target is held open by another process (e.g., a second
71
+ // haze instance reading auth.json). Retry by unlinking the target first.
72
+ try {
73
+ await fs.rename(temp, target);
74
+ }
75
+ catch (error) {
76
+ if (process.platform === 'win32' && error.code === 'EPERM') {
77
+ await fs.unlink(target).catch(() => undefined);
78
+ await fs.rename(temp, target);
79
+ }
80
+ else {
81
+ throw error;
82
+ }
83
+ }
84
+ }
59
85
  export async function writePrivateJsonAtomic(file, value) {
60
86
  await writePrivateFileAtomic(file, `${JSON.stringify(value, null, 2)}\n`);
61
87
  }
@@ -0,0 +1,14 @@
1
+ export interface OAuthProviderAuth {
2
+ type: 'oauth';
3
+ access: string;
4
+ refresh: string;
5
+ expires: number;
6
+ accountId?: string;
7
+ }
8
+ export type ProviderAuth = OAuthProviderAuth;
9
+ export type ProviderAuthStore = Record<string, ProviderAuth>;
10
+ export declare const PROVIDER_AUTH_FILE: string;
11
+ export declare function readProviderAuthStore(): Promise<ProviderAuthStore>;
12
+ export declare function getProviderAuth(providerName: string): Promise<ProviderAuth | undefined>;
13
+ export declare function setProviderAuth(providerName: string, auth: ProviderAuth): Promise<void>;
14
+ export declare function removeProviderAuth(providerName: string): Promise<void>;
@@ -0,0 +1,49 @@
1
+ import fs from 'fs-extra';
2
+ import path from 'node:path';
3
+ import { z } from 'zod';
4
+ import { HAZE_DIR } from './paths.js';
5
+ import { tightenPrivateFile, writePrivateJsonAtomic } from './privateStorage.js';
6
+ export const PROVIDER_AUTH_FILE = path.join(HAZE_DIR, 'auth.json');
7
+ const oauthProviderAuthSchema = z.object({
8
+ type: z.literal('oauth'),
9
+ access: z.string().min(1),
10
+ refresh: z.string().min(1),
11
+ expires: z.number().int().nonnegative(),
12
+ accountId: z.string().min(1).optional(),
13
+ });
14
+ const providerAuthStoreSchema = z.record(z.string().min(1), oauthProviderAuthSchema);
15
+ function authReadError(error) {
16
+ const message = error instanceof Error ? error.message : String(error);
17
+ return new Error(`Failed to read Haze provider authentication at ${PROVIDER_AUTH_FILE}: ${message}. Sign in again or repair the authentication file, then retry.`);
18
+ }
19
+ export async function readProviderAuthStore() {
20
+ try {
21
+ if (await fs.pathExists(PROVIDER_AUTH_FILE))
22
+ await tightenPrivateFile(PROVIDER_AUTH_FILE);
23
+ const raw = await fs.readJson(PROVIDER_AUTH_FILE);
24
+ return providerAuthStoreSchema.parse(raw);
25
+ }
26
+ catch (error) {
27
+ const code = typeof error === 'object' && error != null && 'code' in error ? error.code : undefined;
28
+ if (code === 'ENOENT')
29
+ return {};
30
+ throw authReadError(error);
31
+ }
32
+ }
33
+ export async function getProviderAuth(providerName) {
34
+ return (await readProviderAuthStore())[providerName];
35
+ }
36
+ export async function setProviderAuth(providerName, auth) {
37
+ const name = providerName.trim();
38
+ if (!name)
39
+ throw new Error('Provider name is required to save authentication.');
40
+ const next = { ...await readProviderAuthStore(), [name]: oauthProviderAuthSchema.parse(auth) };
41
+ await writePrivateJsonAtomic(PROVIDER_AUTH_FILE, next);
42
+ }
43
+ export async function removeProviderAuth(providerName) {
44
+ const current = await readProviderAuthStore();
45
+ if (!(providerName in current))
46
+ return;
47
+ delete current[providerName];
48
+ await writePrivateJsonAtomic(PROVIDER_AUTH_FILE, current);
49
+ }