@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.
- package/CHANGELOG.md +133 -17
- package/README.md +164 -68
- package/SECURITY.md +22 -0
- package/bin/haze.js +102 -1
- package/dist/buildInfo.json +7 -0
- package/dist/cli/chat/TaskBar.d.ts +2 -1
- package/dist/cli/chat/TaskBar.js +7 -4
- package/dist/cli/chat/chatMetrics.d.ts +17 -1
- package/dist/cli/chat/chatMetrics.js +22 -5
- package/dist/cli/chat/contextReport.d.ts +11 -0
- package/dist/cli/chat/contextReport.js +46 -0
- package/dist/cli/chat/fileMentionSuggestions.d.ts +29 -0
- package/dist/cli/chat/fileMentionSuggestions.js +92 -0
- package/dist/cli/chat/inputSuggestions.d.ts +5 -0
- package/dist/cli/chat/inputSuggestions.js +17 -3
- package/dist/cli/chat/liveRegion.d.ts +25 -0
- package/dist/cli/chat/liveRegion.js +48 -0
- package/dist/cli/chat/messages.d.ts +33 -2
- package/dist/cli/chat/messages.js +216 -33
- package/dist/cli/chat/sessionLifecycle.d.ts +67 -0
- package/dist/cli/chat/sessionLifecycle.js +205 -0
- package/dist/cli/chat/sessionRecorder.js +80 -14
- package/dist/cli/chat/startupInfo.js +11 -4
- package/dist/cli/chat/tips.d.ts +21 -0
- package/dist/cli/chat/tips.js +43 -0
- package/dist/cli/chat/wizardDispatch.d.ts +64 -0
- package/dist/cli/chat/wizardDispatch.js +744 -0
- package/dist/cli/commands/chat.d.ts +6 -0
- package/dist/cli/commands/chat.js +373 -790
- package/dist/cli/commands/chatModes.d.ts +1 -1
- package/dist/cli/commands/chatModes.js +7 -2
- package/dist/cli/commands/commandHelp.js +5 -3
- package/dist/cli/commands/commands.d.ts +5 -2
- package/dist/cli/commands/commands.js +22 -18
- package/dist/cli/commands/doctor.d.ts +19 -0
- package/dist/cli/commands/doctor.js +76 -0
- package/dist/cli/commands/fleetCommand.d.ts +14 -0
- package/dist/cli/commands/fleetCommand.js +46 -0
- package/dist/cli/commands/formatters.d.ts +5 -0
- package/dist/cli/commands/formatters.js +35 -6
- package/dist/cli/commands/logsCommand.js +1 -7
- package/dist/cli/commands/modelCommand.js +1 -1
- package/dist/cli/commands/ndjsonSink.d.ts +23 -0
- package/dist/cli/commands/ndjsonSink.js +38 -0
- package/dist/cli/commands/providerWizard.d.ts +10 -2
- package/dist/cli/commands/providerWizard.js +50 -4
- package/dist/cli/commands/runCommand.d.ts +4 -0
- package/dist/cli/commands/runCommand.js +142 -16
- package/dist/cli/commands/sessionPicker.d.ts +9 -0
- package/dist/cli/commands/sessionPicker.js +29 -0
- package/dist/cli/commands/settingsSummary.js +6 -4
- package/dist/cli/commands/skillConfirmRemove.js +4 -3
- package/dist/cli/commands/skillWizard.d.ts +2 -0
- package/dist/cli/commands/skillWizard.js +16 -6
- package/dist/cli/commands/streaming/abortCause.d.ts +24 -0
- package/dist/cli/commands/streaming/abortCause.js +16 -0
- package/dist/cli/commands/streaming/assistantText.js +9 -2
- package/dist/cli/commands/streaming/goalCheckpoint.d.ts +65 -0
- package/dist/cli/commands/streaming/goalCheckpoint.js +23 -0
- package/dist/cli/commands/streaming/goalSupervisor.d.ts +64 -0
- package/dist/cli/commands/streaming/goalSupervisor.js +127 -0
- package/dist/cli/commands/streaming/idleTimer.d.ts +26 -0
- package/dist/cli/commands/streaming/idleTimer.js +24 -0
- package/dist/cli/commands/streaming/toolCallRecovery.d.ts +2 -0
- package/dist/cli/commands/streaming/toolCallRecovery.js +24 -0
- package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +31 -0
- package/dist/cli/commands/streaming/toolGroupRenderer.js +50 -2
- package/dist/cli/commands/streaming/toolResultState.d.ts +6 -1
- package/dist/cli/commands/streaming/toolResultState.js +29 -7
- package/dist/cli/commands/streaming/turnOutcome.d.ts +17 -0
- package/dist/cli/commands/streaming/turnOutcome.js +27 -11
- package/dist/cli/commands/streaming/turnRuntime.js +6 -4
- package/dist/cli/commands/streaming.d.ts +82 -3
- package/dist/cli/commands/streaming.js +528 -91
- package/dist/cli/commands/wizardActions.d.ts +7 -0
- package/dist/cli/commands/wizardActions.js +7 -0
- package/dist/cli/commands/wizardPrompts.js +7 -1
- package/dist/cli/commands/wizardSuggestions.d.ts +8 -0
- package/dist/cli/commands/wizardSuggestions.js +64 -14
- package/dist/cli/commands/wizardTransition.d.ts +4 -0
- package/dist/cli/commands/wizardTransition.js +1 -2
- package/dist/cli/index.js +82 -22
- package/dist/cli/terminalTitle.d.ts +6 -0
- package/dist/cli/terminalTitle.js +36 -0
- package/dist/config/inputHistory.d.ts +3 -3
- package/dist/config/inputHistory.js +12 -18
- package/dist/config/modelDiscovery.d.ts +71 -0
- package/dist/config/modelDiscovery.js +214 -0
- package/dist/config/privateStorage.js +28 -2
- package/dist/config/providerAuth.d.ts +14 -0
- package/dist/config/providerAuth.js +49 -0
- package/dist/config/providerPresets.d.ts +49 -5
- package/dist/config/providerPresets.js +573 -73
- package/dist/config/providers.d.ts +2 -0
- package/dist/config/providers.js +9 -0
- package/dist/config/settings.d.ts +58 -0
- package/dist/config/settings.js +38 -1
- package/dist/config/skillSettings.d.ts +6 -13
- package/dist/config/skillSettings.js +20 -19
- package/dist/core/agent/budgets.d.ts +36 -0
- package/dist/core/agent/budgets.js +44 -0
- package/dist/core/agent/compaction.d.ts +38 -0
- package/dist/core/agent/compaction.js +108 -19
- package/dist/core/agent/completionController.d.ts +230 -0
- package/dist/core/agent/completionController.js +287 -0
- package/dist/core/agent/contextBudget.d.ts +46 -0
- package/dist/core/agent/contextBudget.js +89 -7
- package/dist/core/agent/errors.js +6 -2
- package/dist/core/agent/events.d.ts +86 -0
- package/dist/core/agent/reasoningPolicy.d.ts +31 -0
- package/dist/core/agent/reasoningPolicy.js +27 -0
- package/dist/core/agent/toolCapabilities.d.ts +27 -0
- package/dist/core/agent/toolCapabilities.js +58 -0
- package/dist/core/agent/toolExecutionBudget.d.ts +35 -0
- package/dist/core/agent/toolExecutionBudget.js +49 -0
- package/dist/core/agent/toolOutputStore.d.ts +13 -0
- package/dist/core/agent/toolOutputStore.js +27 -10
- package/dist/core/agent/toolResults.d.ts +12 -0
- package/dist/core/agent/toolResults.js +38 -0
- package/dist/core/agent/turnBudget.d.ts +35 -0
- package/dist/core/agent/turnBudget.js +27 -0
- package/dist/core/agent/turnPolicy.d.ts +11 -0
- package/dist/core/agent/turnPolicy.js +19 -0
- package/dist/core/agent/workState.d.ts +76 -1
- package/dist/core/agent/workState.js +120 -13
- package/dist/core/attachments/imageAttachments.d.ts +90 -0
- package/dist/core/attachments/imageAttachments.js +245 -0
- package/dist/core/attachments/readBlessings.d.ts +37 -0
- package/dist/core/attachments/readBlessings.js +79 -0
- package/dist/core/deadline.d.ts +33 -0
- package/dist/core/deadline.js +74 -0
- package/dist/core/goal/completionPolicy.d.ts +27 -0
- package/dist/core/goal/completionPolicy.js +37 -1
- package/dist/core/goal/requestClassifier.d.ts +0 -3
- package/dist/core/goal/requestClassifier.js +0 -13
- package/dist/core/io/boundedRead.js +76 -29
- package/dist/core/limits/byteBudgets.d.ts +7 -0
- package/dist/core/limits/byteBudgets.js +7 -0
- package/dist/core/limits/textBudgets.d.ts +25 -0
- package/dist/core/limits/textBudgets.js +25 -0
- package/dist/core/log/llmLog.js +7 -0
- package/dist/core/persistence/orderedFileWriter.d.ts +10 -0
- package/dist/core/persistence/orderedFileWriter.js +16 -2
- package/dist/core/process/backgroundRegistry.d.ts +35 -0
- package/dist/core/process/backgroundRegistry.js +195 -0
- package/dist/core/process/runBoundedProcess.d.ts +9 -0
- package/dist/core/process/runBoundedProcess.js +74 -29
- package/dist/core/safety/missingExecutable.d.ts +42 -0
- package/dist/core/safety/missingExecutable.js +77 -0
- package/dist/core/safety/urlGuard.d.ts +2 -1
- package/dist/core/safety/urlGuard.js +3 -2
- package/dist/core/session/sessionSlimming.js +47 -4
- package/dist/core/session/sessionStore.d.ts +74 -0
- package/dist/core/session/sessionStore.js +268 -18
- package/dist/core/subagent/contracts.d.ts +120 -0
- package/dist/core/subagent/contracts.js +55 -0
- package/dist/core/subagent/executionProfiles.d.ts +28 -0
- package/dist/core/subagent/executionProfiles.js +45 -0
- package/dist/core/subagent/subagentCoordinator.d.ts +78 -0
- package/dist/core/subagent/subagentCoordinator.js +164 -0
- package/dist/core/subagent/subagentRunner.d.ts +211 -145
- package/dist/core/subagent/subagentRunner.js +208 -98
- package/dist/core/subagent/workspaceMutationPolicy.d.ts +11 -0
- package/dist/core/subagent/workspaceMutationPolicy.js +52 -0
- package/dist/core/tasks/taskStorage.js +12 -1
- package/dist/llm/client.d.ts +36 -29
- package/dist/llm/client.js +102 -33
- package/dist/llm/hazeTools.d.ts +2559 -150
- package/dist/llm/hazeTools.js +119 -31
- package/dist/llm/lsp.d.ts +26 -4
- package/dist/llm/lsp.js +90 -14
- package/dist/llm/lspTools.d.ts +2366 -0
- package/dist/llm/lspTools.js +87 -79
- package/dist/llm/openaiCodex.d.ts +3 -0
- package/dist/llm/openaiCodex.js +47 -0
- package/dist/llm/openaiCodexOAuth.d.ts +54 -0
- package/dist/llm/openaiCodexOAuth.js +214 -0
- package/dist/llm/requestContext.d.ts +25 -1
- package/dist/llm/requestContext.js +51 -8
- package/dist/llm/systemPrompt.d.ts +15 -1
- package/dist/llm/systemPrompt.js +24 -8
- package/dist/llm/toolResultTypes.d.ts +8 -1
- package/dist/llm/tools/bashTool.d.ts +906 -32
- package/dist/llm/tools/bashTool.js +30 -4
- package/dist/llm/tools/editMatch.d.ts +14 -0
- package/dist/llm/tools/editMatch.js +72 -0
- package/dist/llm/tools/failures.d.ts +2 -0
- package/dist/llm/tools/failures.js +1 -0
- package/dist/llm/tools/fetchTool.d.ts +42 -26
- package/dist/llm/tools/fetchTool.js +1 -1
- package/dist/llm/tools/fileToolShared.d.ts +6 -4
- package/dist/llm/tools/fileToolShared.js +18 -23
- package/dist/llm/tools/gitIgnore.d.ts +49 -0
- package/dist/llm/tools/gitIgnore.js +129 -0
- package/dist/llm/tools/grepRunner.d.ts +5 -0
- package/dist/llm/tools/grepRunner.js +52 -71
- package/dist/llm/tools/outputCap.d.ts +2 -6
- package/dist/llm/tools/outputCap.js +2 -6
- package/dist/llm/tools/processTool.d.ts +1077 -0
- package/dist/llm/tools/processTool.js +41 -0
- package/dist/llm/tools/readRecovery.d.ts +10 -0
- package/dist/llm/tools/readRecovery.js +135 -0
- package/dist/llm/tools/toolContext.d.ts +9 -1
- package/dist/llm/tools/toolContext.js +83 -43
- package/dist/llm/tools/workspaceFile.d.ts +9 -1
- package/dist/llm/tools/workspaceFile.js +33 -4
- package/dist/llm/webFetch.d.ts +17 -0
- package/dist/llm/webFetch.js +66 -86
- package/dist/llm/workerContext.d.ts +18 -0
- package/dist/llm/workerContext.js +55 -0
- package/dist/skills/SkillLoader.d.ts +2 -2
- package/dist/skills/SkillRegistry.d.ts +3 -2
- package/dist/skills/SkillRegistry.js +43 -13
- package/dist/skills/builder/SkillBuilder.d.ts +3 -0
- package/dist/skills/builder/SkillBuilder.js +23 -5
- package/dist/skills/skillTools.js +11 -4
- package/dist/skills/types.d.ts +6 -1
- package/dist/ui/codeHighlight.d.ts +4 -0
- package/dist/ui/codeHighlight.js +31 -0
- package/dist/ui/components/Header.d.ts +1 -1
- package/dist/ui/components/MarkdownText.d.ts +16 -2
- package/dist/ui/components/MarkdownText.js +244 -34
- package/dist/ui/components/TextInput.d.ts +12 -2
- package/dist/ui/components/TextInput.js +80 -8
- package/dist/ui/theme.d.ts +4 -3
- package/dist/ui/theme.js +5 -4
- package/dist/utils/buildInfo.d.ts +104 -0
- package/dist/utils/buildInfo.js +253 -0
- package/dist/utils/format.d.ts +2 -0
- package/dist/utils/format.js +8 -0
- package/dist/utils/fs.d.ts +9 -1
- package/dist/utils/fs.js +87 -29
- package/dist/utils/openPath.d.ts +2 -0
- package/dist/utils/openPath.js +22 -0
- package/dist/utils/path.d.ts +2 -0
- package/dist/utils/path.js +5 -1
- package/dist/utils/utf8.d.ts +22 -0
- package/dist/utils/utf8.js +54 -0
- package/dist/utils/version.d.ts +9 -3
- package/dist/utils/version.js +28 -2
- package/package.json +24 -19
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
const DEFAULT_TIMEOUT_MS = 5000;
|
|
2
|
+
/** Discovery feeds a type-filtered picker; cap the stored list, not the UX. */
|
|
3
|
+
const MAX_DISCOVERED_MODELS = 500;
|
|
4
|
+
export function modelsEndpointUrl(baseUrl) {
|
|
5
|
+
return `${baseUrl.trim().replace(/\/+$/, '')}/models`;
|
|
6
|
+
}
|
|
7
|
+
export function parseModelsBody(body) {
|
|
8
|
+
const data = body?.data;
|
|
9
|
+
if (!Array.isArray(data))
|
|
10
|
+
return [];
|
|
11
|
+
const ids = data
|
|
12
|
+
.map(item => item?.id)
|
|
13
|
+
.filter((id) => typeof id === 'string' && id.trim().length > 0)
|
|
14
|
+
.map(id => id.trim());
|
|
15
|
+
return [...new Set(ids)].sort((a, b) => a.localeCompare(b)).slice(0, MAX_DISCOVERED_MODELS);
|
|
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
|
+
}
|
|
179
|
+
function describeFetchError(error) {
|
|
180
|
+
if (error instanceof Error) {
|
|
181
|
+
if (error.name === 'TimeoutError' || error.name === 'AbortError')
|
|
182
|
+
return 'timed out';
|
|
183
|
+
return error.message;
|
|
184
|
+
}
|
|
185
|
+
return String(error);
|
|
186
|
+
}
|
|
187
|
+
export async function discoverProviderModels(provider, options = {}) {
|
|
188
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
189
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
190
|
+
let response;
|
|
191
|
+
try {
|
|
192
|
+
response = await fetchImpl(modelsEndpointUrl(provider.url), {
|
|
193
|
+
headers: { accept: 'application/json', ...(provider.key ? { authorization: `Bearer ${provider.key}` } : {}) },
|
|
194
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
catch (error) {
|
|
198
|
+
return { status: 'failed', error: describeFetchError(error) };
|
|
199
|
+
}
|
|
200
|
+
if (!response.ok)
|
|
201
|
+
return { status: 'failed', error: `endpoint returned HTTP ${response.status}` };
|
|
202
|
+
let body;
|
|
203
|
+
try {
|
|
204
|
+
body = await response.json();
|
|
205
|
+
}
|
|
206
|
+
catch {
|
|
207
|
+
return { status: 'failed', error: 'endpoint returned no JSON' };
|
|
208
|
+
}
|
|
209
|
+
const models = parseModelsBody(body);
|
|
210
|
+
if (models.length === 0)
|
|
211
|
+
return { status: 'failed', error: 'endpoint returned no models' };
|
|
212
|
+
const modelLimits = harvestModelLimits(body);
|
|
213
|
+
return { status: 'ok', models, ...(Object.keys(modelLimits).length > 0 ? { modelLimits } : {}) };
|
|
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
|
-
|
|
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
|
|
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
|
+
}
|
|
@@ -1,8 +1,24 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Known provider presets derived from
|
|
3
|
-
*
|
|
4
|
-
*
|
|
2
|
+
* Known OpenAI-compatible provider presets derived from provider documentation and
|
|
3
|
+
* community conventions. Do not copy native-provider entries from multi-adapter clients:
|
|
4
|
+
* every standard preset here must accept OpenAI Chat Completions requests at its base URL.
|
|
5
|
+
* The OpenAI Subscription preset is the explicit exception and uses its own Codex adapter.
|
|
6
|
+
* Hosted presets carry a pre-configured base URL so users only need to supply an API key
|
|
7
|
+
* and model names. Local/keyless providers have sensible localhost defaults.
|
|
8
|
+
*
|
|
9
|
+
* `modelLimits` values are curated from models.dev (the same catalog pi and nanocoder
|
|
10
|
+
* consume; refreshed 2026-08-15). They are keyed by the exact suggested model id for
|
|
11
|
+
* THIS preset: aggregators may cap context below the origin model's capability (e.g.
|
|
12
|
+
* Together serves DeepSeek-V4-Pro at 512K vs DeepSeek's own 1M), so limits never
|
|
13
|
+
* transfer between providers. When the wizard adds a suggested model, these values are
|
|
14
|
+
* written into the provider's settings `modelLimits`, where they remain user-editable.
|
|
15
|
+
* Local providers (Ollama/llama.cpp/MLX/LM Studio) intentionally carry no limits: their
|
|
16
|
+
* effective context depends on the local server configuration, not the model.
|
|
5
17
|
*/
|
|
18
|
+
export interface PresetModelLimits {
|
|
19
|
+
contextWindowTokens: number;
|
|
20
|
+
maxOutputTokens: number;
|
|
21
|
+
}
|
|
6
22
|
export interface ProviderPreset {
|
|
7
23
|
/** Unique identifier used as the selection value. */
|
|
8
24
|
id: string;
|
|
@@ -10,14 +26,42 @@ export interface ProviderPreset {
|
|
|
10
26
|
name: string;
|
|
11
27
|
/** Pre-configured OpenAI-compatible base URL. */
|
|
12
28
|
baseUrl: string;
|
|
13
|
-
/** Whether an API key is typically required. Local providers
|
|
29
|
+
/** Whether an API key is typically required. Local and OAuth providers use false. */
|
|
14
30
|
needsApiKey: boolean;
|
|
31
|
+
/** Provider-specific sign-in flow, when setup is not an API-key prompt. */
|
|
32
|
+
auth?: 'chatgpt-oauth';
|
|
15
33
|
/** Hint shown when prompting for the API key. */
|
|
16
34
|
apiKeyHint?: string;
|
|
17
|
-
/**
|
|
35
|
+
/**
|
|
36
|
+
* Conventional environment variable holding this provider's API key (from Pi's
|
|
37
|
+
* auth registry). Informational only — haze never reads provider env vars itself.
|
|
38
|
+
*/
|
|
39
|
+
apiKeyEnvVar?: string;
|
|
40
|
+
/**
|
|
41
|
+
* Curated model ids. Pinned atop the live /models discovery picker when the
|
|
42
|
+
* endpoint actually serves them (stale entries simply don't pin), and shown
|
|
43
|
+
* as type-in examples when discovery fails.
|
|
44
|
+
*/
|
|
18
45
|
suggestedModels?: string[];
|
|
46
|
+
/**
|
|
47
|
+
* Context-window and output-token limits keyed by exact suggested model id
|
|
48
|
+
* (provider-specific; see the module comment). Feeds request budgeting when a
|
|
49
|
+
* user adds the model without configuring limits themselves.
|
|
50
|
+
*/
|
|
51
|
+
modelLimits?: Record<string, PresetModelLimits>;
|
|
19
52
|
/** Category for grouping in the picker. */
|
|
20
53
|
category: 'cloud' | 'local';
|
|
21
54
|
}
|
|
22
55
|
export declare const PROVIDER_PRESETS: ProviderPreset[];
|
|
23
56
|
export declare function findPreset(id: string): ProviderPreset | undefined;
|
|
57
|
+
/**
|
|
58
|
+
* Limits for models a wizard flow is adding to a provider, matched by the
|
|
59
|
+
* provider's base URL or its name (a provider created from a preset keeps the
|
|
60
|
+
* preset's name unless the user renamed it). Returns only entries the caller
|
|
61
|
+
* should merge into the provider's settings `modelLimits`; user-configured
|
|
62
|
+
* limits always win because callers merge without overwriting existing keys.
|
|
63
|
+
*/
|
|
64
|
+
export declare function presetModelLimitsForModels(provider: {
|
|
65
|
+
name?: string;
|
|
66
|
+
url?: string;
|
|
67
|
+
}, models: readonly string[]): Record<string, PresetModelLimits>;
|