@denizokcu/haze 1.1.1 → 1.2.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 +25 -0
- package/README.md +15 -12
- package/SECURITY.md +1 -1
- package/dist/buildInfo.json +3 -3
- package/dist/cli/chat/sessionLifecycle.js +2 -0
- package/dist/cli/chat/sessionRecorder.d.ts +7 -0
- package/dist/cli/chat/sessionRecorder.js +6 -0
- package/dist/cli/commands/chat.js +24 -2
- package/dist/cli/commands/runCommand.js +6 -0
- package/dist/cli/commands/streaming/agentAttempt.d.ts +11 -1
- package/dist/cli/commands/streaming/agentAttempt.js +9 -5
- package/dist/cli/commands/streaming/attemptOutcome.d.ts +23 -3
- package/dist/cli/commands/streaming/attemptOutcome.js +52 -9
- package/dist/cli/commands/streaming/attemptSetup.d.ts +10 -3
- package/dist/cli/commands/streaming/attemptSetup.js +30 -13
- package/dist/cli/commands/streaming/goalSupervisor.d.ts +1 -1
- package/dist/cli/commands/streaming/goalSupervisor.js +9 -0
- package/dist/cli/commands/streaming/prepareStep.d.ts +6 -1
- package/dist/cli/commands/streaming/prepareStep.js +35 -19
- package/dist/cli/commands/streaming/stallRecovery.js +2 -2
- package/dist/cli/commands/streaming/streamLoop.d.ts +31 -4
- package/dist/cli/commands/streaming/streamLoop.js +280 -44
- package/dist/cli/commands/streaming/toolPartHandlers.js +13 -0
- package/dist/cli/commands/streaming/turnRuntime.d.ts +1 -1
- package/dist/cli/commands/streaming/turnRuntime.js +3 -2
- package/dist/cli/commands/streaming.d.ts +8 -0
- package/dist/cli/commands/streaming.js +14 -4
- package/dist/cli/index.js +3 -2
- package/dist/config/modelCatalog.d.ts +32 -0
- package/dist/config/modelCatalog.js +84 -0
- package/dist/config/settings.d.ts +10 -2
- package/dist/config/settings.js +3 -0
- package/dist/core/agent/budgets.d.ts +10 -0
- package/dist/core/agent/budgets.js +10 -0
- package/dist/core/agent/compaction.d.ts +42 -3
- package/dist/core/agent/compaction.js +53 -5
- package/dist/core/agent/completionController.d.ts +3 -1
- package/dist/core/agent/completionController.js +1 -0
- package/dist/core/agent/contextBudget.d.ts +56 -0
- package/dist/core/agent/contextBudget.js +53 -0
- package/dist/core/agent/errors.js +2 -2
- package/dist/core/agent/events.d.ts +24 -1
- package/dist/core/agent/overflow.d.ts +45 -0
- package/dist/core/agent/overflow.js +91 -0
- package/dist/core/agent/requestAssembly.d.ts +7 -0
- package/dist/core/agent/requestAssembly.js +15 -7
- package/dist/core/agent/workState.js +13 -1
- package/dist/core/safety/shellClassifier.d.ts +16 -0
- package/dist/core/safety/shellClassifier.js +31 -0
- package/dist/core/session/sessionStore.d.ts +10 -0
- package/dist/core/session/sessionStore.js +6 -0
- package/dist/core/validation/outputParser.d.ts +1 -1
- package/dist/core/validation/outputParser.js +6 -1
- package/dist/llm/client.d.ts +2 -2
- package/dist/llm/client.js +14 -6
- package/dist/llm/tools/shellTool.js +27 -8
- package/dist/ui/components/TextInput.d.ts +18 -1
- package/dist/ui/components/TextInput.js +44 -6
- package/package.json +16 -15
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Provider context-overflow classification (Pillar 1.2 of the Pi learning
|
|
3
|
+
* roadmap). Three overflow modes exist and each routes to different recovery:
|
|
4
|
+
*
|
|
5
|
+
* 1. **Error overflow**: the provider rejects an oversized request with a
|
|
6
|
+
* provider-specific error message (`errorIndicatesContextOverflow`).
|
|
7
|
+
* 2. **Silent overflow**: some gateways (z.ai-style) accept the oversized
|
|
8
|
+
* request and answer normally; only the reported usage exceeds the window
|
|
9
|
+
* (`isSilentContextOverflow`).
|
|
10
|
+
* 3. **Length-stop overflow**: some local servers truncate the input to fill
|
|
11
|
+
* the window, leaving no room for output — a `length` finish with ~zero
|
|
12
|
+
* output and input filling the window (`isLengthStopOverflow`).
|
|
13
|
+
*
|
|
14
|
+
* Pattern families are battle-tested against the providers listed per regex;
|
|
15
|
+
* keep this file a pure data table so tests can pin it (like the theme
|
|
16
|
+
* registry). Additive changes only.
|
|
17
|
+
*/
|
|
18
|
+
import { inputLikeTokens } from './contextBudget.js';
|
|
19
|
+
/** Provider error shapes that indicate the request exceeded the context window. */
|
|
20
|
+
const OVERFLOW_PATTERNS = [
|
|
21
|
+
/prompt is too long/i, // Anthropic: "prompt is too long: 213462 tokens > 200000 maximum"
|
|
22
|
+
/request_too_large/i, // Anthropic HTTP 413 request_too_large
|
|
23
|
+
/input is too long for requested model/i, // Amazon Bedrock
|
|
24
|
+
/exceeds the context window/i, // OpenAI (Completions & Responses)
|
|
25
|
+
/exceeds (?:the )?(?:model'?s )?maximum context length/i, // OpenAI/LiteLLM
|
|
26
|
+
/input token count.*exceeds the maximum/i, // Google Gemini
|
|
27
|
+
/maximum prompt length is \d+/i, // xAI Grok
|
|
28
|
+
/reduce the length of the messages/i, // Groq
|
|
29
|
+
/maximum context length is \d+ tokens/i, // OpenRouter (most backends)
|
|
30
|
+
/exceeds (?:the )?maximum allowed input length/i, // OpenRouter/Poolside
|
|
31
|
+
/input \(\d+ tokens\) is longer than the model'?s context length/i, // Together AI
|
|
32
|
+
/exceeds the limit of \d+/i, // GitHub Copilot
|
|
33
|
+
/exceeds the available context size/i, // llama.cpp server
|
|
34
|
+
/greater than the context length/i, // LM Studio
|
|
35
|
+
/context window exceeds limit/i, // MiniMax
|
|
36
|
+
/exceeded model token limit/i, // Kimi
|
|
37
|
+
/too large for model with \d+ maximum context length/i, // Mistral
|
|
38
|
+
/prompt has [\d,]+ tokens?, but the configured context size is/i, // DS4
|
|
39
|
+
/model_context_window_exceeded/i, // z.ai finish_reason surfaced as error text
|
|
40
|
+
/prompt too long; exceeded (?:max )?context length/i, // Ollama explicit overflow
|
|
41
|
+
/range of input length should be/i, // DashScope / Qwen
|
|
42
|
+
/context[_ ]length[_ ]exceeded/i, // Generic fallback
|
|
43
|
+
/too many tokens/i, // Generic fallback
|
|
44
|
+
/token limit exceeded/i, // Generic fallback
|
|
45
|
+
/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i, // Cerebras: 400/413 with no body
|
|
46
|
+
];
|
|
47
|
+
/**
|
|
48
|
+
* Error shapes that look like overflow but are not (rate limiting and other
|
|
49
|
+
* transient throttles). Checked before the overflow patterns so a throttling
|
|
50
|
+
* message containing "too many tokens" cannot trigger compaction.
|
|
51
|
+
*/
|
|
52
|
+
const NON_OVERFLOW_PATTERNS = [
|
|
53
|
+
/^(?:throttling|service unavailable)/i, // AWS Bedrock throttling/unavailable prefixes (raw ThrottlingException and formatted variants)
|
|
54
|
+
/rate limit/i,
|
|
55
|
+
/too many requests/i,
|
|
56
|
+
];
|
|
57
|
+
/** Does an error text indicate a provider context-window overflow? */
|
|
58
|
+
export function errorIndicatesContextOverflow(text) {
|
|
59
|
+
if (NON_OVERFLOW_PATTERNS.some(pattern => pattern.test(text)))
|
|
60
|
+
return false;
|
|
61
|
+
return OVERFLOW_PATTERNS.some(pattern => pattern.test(text));
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Silent overflow: the request succeeded but the reported input already
|
|
65
|
+
* exceeded the model's context window (some gateways accept and stream an
|
|
66
|
+
* answer anyway; the next request will fail or be truncated). The input-like
|
|
67
|
+
* term is convention-robust (see `inputLikeTokens`): subset-style cached
|
|
68
|
+
* tokens inside `inputTokens` are never double counted, so a cache-heavy
|
|
69
|
+
* successful finish cannot false-positive.
|
|
70
|
+
*/
|
|
71
|
+
export function isSilentContextOverflow(input) {
|
|
72
|
+
if (input.contextWindowTokens <= 0)
|
|
73
|
+
return false;
|
|
74
|
+
return inputLikeTokens(input) > input.contextWindowTokens;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Length-stop overflow: the server truncated the oversized input to fit the
|
|
78
|
+
* window, leaving no room to generate — a `length` finish with zero output and
|
|
79
|
+
* input filling (≥99% of) the window.
|
|
80
|
+
*/
|
|
81
|
+
export function isLengthStopOverflow(input) {
|
|
82
|
+
if (input.finishReason !== 'length' || (input.outputTokens ?? 0) > 0)
|
|
83
|
+
return false;
|
|
84
|
+
if (input.contextWindowTokens <= 0)
|
|
85
|
+
return false;
|
|
86
|
+
return inputLikeTokens(input) >= input.contextWindowTokens * 0.99;
|
|
87
|
+
}
|
|
88
|
+
/** Overflow patterns exposed for pinning tests. */
|
|
89
|
+
export function getOverflowPatterns() {
|
|
90
|
+
return OVERFLOW_PATTERNS;
|
|
91
|
+
}
|
|
@@ -2,6 +2,13 @@ import type { ModelMessage } from 'ai';
|
|
|
2
2
|
export declare function stripSyntheticControls(messages: ModelMessage[]): ModelMessage[];
|
|
3
3
|
export declare function withoutSystemMessages(messages: ModelMessage[]): ModelMessage[];
|
|
4
4
|
export declare function withSyntheticControl(messages: ModelMessage[], control: string): ModelMessage[];
|
|
5
|
+
/**
|
|
6
|
+
* Append a per-step control without rewriting an already-sent provider prefix.
|
|
7
|
+
* Active/session conversation state still removes every tagged control through
|
|
8
|
+
* `stripSyntheticControls`; this variant exists only for an in-flight logical
|
|
9
|
+
* turn whose next provider request should remain cache-prefix compatible.
|
|
10
|
+
*/
|
|
11
|
+
export declare function appendSyntheticControl(messages: ModelMessage[], control: string): ModelMessage[];
|
|
5
12
|
/** Drop only a trailing text-only assistant final that completion policy rejected. */
|
|
6
13
|
export declare function withoutRejectedAssistantFinal(messages: ModelMessage[]): ModelMessage[];
|
|
7
14
|
export declare function compactToolHistory(messages: ModelMessage[], options?: {
|
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import { estimateValueTokens } from './contextBudget.js';
|
|
1
|
+
import { estimateValueTokens, SYNTHETIC_CONTROL_MARKER } from './contextBudget.js';
|
|
2
2
|
import { isFailedToolOutput } from './toolResults.js';
|
|
3
|
-
const SYNTHETIC_CONTROL_OPEN = '<haze_control>';
|
|
4
3
|
function isSyntheticControlMessage(message) {
|
|
5
4
|
return message.role === 'user'
|
|
6
5
|
&& typeof message.content === 'string'
|
|
7
|
-
&& message.content.startsWith(
|
|
6
|
+
&& message.content.startsWith(SYNTHETIC_CONTROL_MARKER);
|
|
8
7
|
}
|
|
9
8
|
export function stripSyntheticControls(messages) {
|
|
10
9
|
return messages.filter(message => !isSyntheticControlMessage(message));
|
|
@@ -22,11 +21,20 @@ function modelMessageTextForContext(message) {
|
|
|
22
21
|
return JSON.stringify(content);
|
|
23
22
|
return content.map(part => typeof part === 'object' && part != null && 'text' in part && typeof part.text === 'string' ? part.text : JSON.stringify(part)).join('\n');
|
|
24
23
|
}
|
|
24
|
+
function syntheticControlMessage(control) {
|
|
25
|
+
return { role: 'user', content: `${SYNTHETIC_CONTROL_MARKER}\n${control}\n</haze_control>` };
|
|
26
|
+
}
|
|
25
27
|
export function withSyntheticControl(messages, control) {
|
|
26
|
-
return [
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
28
|
+
return [...stripSyntheticControls(messages), syntheticControlMessage(control)];
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Append a per-step control without rewriting an already-sent provider prefix.
|
|
32
|
+
* Active/session conversation state still removes every tagged control through
|
|
33
|
+
* `stripSyntheticControls`; this variant exists only for an in-flight logical
|
|
34
|
+
* turn whose next provider request should remain cache-prefix compatible.
|
|
35
|
+
*/
|
|
36
|
+
export function appendSyntheticControl(messages, control) {
|
|
37
|
+
return [...messages, syntheticControlMessage(control)];
|
|
30
38
|
}
|
|
31
39
|
/** Drop only a trailing text-only assistant final that completion policy rejected. */
|
|
32
40
|
export function withoutRejectedAssistantFinal(messages) {
|
|
@@ -291,7 +291,19 @@ export function deriveValidationOutcome(state) {
|
|
|
291
291
|
if (stale)
|
|
292
292
|
return 'stale';
|
|
293
293
|
const latest = state.validations.at(-1) ?? state.carriedValidation;
|
|
294
|
-
|
|
294
|
+
if (latest?.status !== 'passed')
|
|
295
|
+
return 'failed';
|
|
296
|
+
// A self-declared custom check (generic kind, `purpose=validation`) cannot
|
|
297
|
+
// clear a failed classifier-confirmed validation: known test/build commands
|
|
298
|
+
// are the authoritative completion evidence, custom checks supplement them
|
|
299
|
+
// (found by the honest-impossibility eval — a model ran `npm test` red, then
|
|
300
|
+
// passed an unrelated self-written script and claimed completion). A failed
|
|
301
|
+
// validation carried from a goal checkpoint counts as confirmed too.
|
|
302
|
+
const confirmedFailed = state.validations.some(entry => entry.kind !== 'generic' && entry.status === 'failed')
|
|
303
|
+
|| (state.carriedValidation?.status === 'failed' && state.carriedValidation.kind !== 'generic');
|
|
304
|
+
if (latest.kind === 'generic' && confirmedFailed)
|
|
305
|
+
return 'failed';
|
|
306
|
+
return 'passed';
|
|
295
307
|
}
|
|
296
308
|
export function workStatePrompt(state) {
|
|
297
309
|
return `<work_state>\n${JSON.stringify(state)}\n</work_state>`;
|
|
@@ -8,4 +8,20 @@ export type ShellClassification = {
|
|
|
8
8
|
};
|
|
9
9
|
export declare function classifyShellCommand(command: string): ShellClassification;
|
|
10
10
|
export declare function isValidationClassification(classification: ShellClassification): boolean;
|
|
11
|
+
/**
|
|
12
|
+
* Approximate quoted-span removal ('…', "…", `…`). Used to keep command-shape
|
|
13
|
+
* heuristics (validation kind, exit masking) from firing on text the model
|
|
14
|
+
* authored inside quoted payloads. False positives only make decisions more
|
|
15
|
+
* conservative, never the reverse.
|
|
16
|
+
*/
|
|
17
|
+
export declare function stripQuotedSpans(command: string): string;
|
|
18
|
+
/**
|
|
19
|
+
* Whether a command's final exit status can mask an earlier failing stage.
|
|
20
|
+
* POSIX list operators `;`, `||`, and single `&` end a list with the *last*
|
|
21
|
+
* command's status, so `npm test > out.txt; cat out.txt` exits 0 even when
|
|
22
|
+
* the suite failed (found by the honest-impossibility eval). Redirections
|
|
23
|
+
* (`2>&1`, `&>`, `<&`) are not list operators and are excluded. Pipelines are
|
|
24
|
+
* covered separately by `pipefail`; `&&` propagates failures.
|
|
25
|
+
*/
|
|
26
|
+
export declare function commandMasksValidationExit(command: string): boolean;
|
|
11
27
|
export {};
|
|
@@ -81,3 +81,34 @@ export function classifyShellCommand(command) {
|
|
|
81
81
|
export function isValidationClassification(classification) {
|
|
82
82
|
return classification.traits.includes('runs_tests') || classification.traits.includes('runs_build');
|
|
83
83
|
}
|
|
84
|
+
/**
|
|
85
|
+
* Approximate quoted-span removal ('…', "…", `…`). Used to keep command-shape
|
|
86
|
+
* heuristics (validation kind, exit masking) from firing on text the model
|
|
87
|
+
* authored inside quoted payloads. False positives only make decisions more
|
|
88
|
+
* conservative, never the reverse.
|
|
89
|
+
*/
|
|
90
|
+
export function stripQuotedSpans(command) {
|
|
91
|
+
return command
|
|
92
|
+
.replace(/'[^']*'/g, ' ')
|
|
93
|
+
.replace(/"[^"]*"/g, ' ')
|
|
94
|
+
.replace(/`[^`]*`/g, ' ');
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Whether a command's final exit status can mask an earlier failing stage.
|
|
98
|
+
* POSIX list operators `;`, `||`, and single `&` end a list with the *last*
|
|
99
|
+
* command's status, so `npm test > out.txt; cat out.txt` exits 0 even when
|
|
100
|
+
* the suite failed (found by the honest-impossibility eval). Redirections
|
|
101
|
+
* (`2>&1`, `&>`, `<&`) are not list operators and are excluded. Pipelines are
|
|
102
|
+
* covered separately by `pipefail`; `&&` propagates failures.
|
|
103
|
+
*/
|
|
104
|
+
export function commandMasksValidationExit(command) {
|
|
105
|
+
const unquoted = stripQuotedSpans(command);
|
|
106
|
+
if (unquoted.includes(';'))
|
|
107
|
+
return true;
|
|
108
|
+
if (/(?<!\|)\|\|(?!\|)/.test(unquoted))
|
|
109
|
+
return true;
|
|
110
|
+
// Single `&` that is not part of `&&` and not a redirection (`>&`, `<&`, `&>`).
|
|
111
|
+
if (/(?<![<>&])&(?![&>])/.test(unquoted))
|
|
112
|
+
return true;
|
|
113
|
+
return false;
|
|
114
|
+
}
|
|
@@ -29,6 +29,16 @@ export type SessionEntry = {
|
|
|
29
29
|
at: string;
|
|
30
30
|
name: string;
|
|
31
31
|
text?: string;
|
|
32
|
+
}
|
|
33
|
+
/** First-class compaction audit entry (Pillar 1.7): conversation snapshots remain the restore source of truth; this records what was compacted, when, and how. */
|
|
34
|
+
| {
|
|
35
|
+
type: 'compact';
|
|
36
|
+
at: string;
|
|
37
|
+
method: 'heuristic' | 'llm';
|
|
38
|
+
olderCount: number;
|
|
39
|
+
keptCount: number;
|
|
40
|
+
instructions?: string;
|
|
41
|
+
summary: string;
|
|
32
42
|
} | {
|
|
33
43
|
type: 'goal';
|
|
34
44
|
at: string;
|
|
@@ -250,6 +250,12 @@ function parseSessionEntry(value) {
|
|
|
250
250
|
if (typeof value.at !== 'string' || typeof value.name !== 'string' || !optionalString(value.text))
|
|
251
251
|
return invalid('invalid event');
|
|
252
252
|
return value;
|
|
253
|
+
case 'compact':
|
|
254
|
+
if (typeof value.at !== 'string' || (value.method !== 'heuristic' && value.method !== 'llm')
|
|
255
|
+
|| typeof value.olderCount !== 'number' || typeof value.keptCount !== 'number'
|
|
256
|
+
|| typeof value.summary !== 'string' || !optionalString(value.instructions))
|
|
257
|
+
return invalid('invalid compact');
|
|
258
|
+
return value;
|
|
253
259
|
case 'goal':
|
|
254
260
|
if (typeof value.at !== 'string' || typeof value.goalId !== 'string'
|
|
255
261
|
|| (value.phase !== 'goal_start' && value.phase !== 'goal_continue' && value.phase !== 'goal_end')
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type ShellClassification } from '../safety/shellClassifier.js';
|
|
2
2
|
import type { ValidationSummary } from '../../llm/toolResultTypes.js';
|
|
3
3
|
export declare function parseValidationOutput(input: {
|
|
4
4
|
command: string;
|
|
@@ -1,9 +1,14 @@
|
|
|
1
|
+
import { stripQuotedSpans } from '../safety/shellClassifier.js';
|
|
1
2
|
import { capOutputForProcessing } from '../toolOutput/reduction.js';
|
|
2
3
|
function uniq(values) {
|
|
3
4
|
return [...new Set(values.filter(Boolean))];
|
|
4
5
|
}
|
|
5
6
|
function inferKind(command, classification) {
|
|
6
|
-
|
|
7
|
+
// Shape-only inference on the unquoted command: kind authority must come
|
|
8
|
+
// from running a recognized tool, never from words the model authored
|
|
9
|
+
// inside a quoted payload (found by the honest-impossibility eval — a
|
|
10
|
+
// self-written `node -e` script mentioning "test" claimed kind 'test').
|
|
11
|
+
const lower = stripQuotedSpans(command).toLowerCase();
|
|
7
12
|
if (/typecheck|\btsc\b/.test(lower))
|
|
8
13
|
return 'typecheck';
|
|
9
14
|
if (/\beslint\b|\blint\b/.test(lower))
|
package/dist/llm/client.d.ts
CHANGED
|
@@ -22,8 +22,8 @@ export interface ModelRuntimeConfig {
|
|
|
22
22
|
* (128K hosted / 32K local) so `contextWindowSource` can flag the guess.
|
|
23
23
|
*/
|
|
24
24
|
contextWindowTokens: number;
|
|
25
|
-
/** Where contextWindowTokens came from: per-model settings, a user-set fallback, or the built-in default. */
|
|
26
|
-
contextWindowSource: 'settings' | 'user-fallback' | 'default-fallback';
|
|
25
|
+
/** Where contextWindowTokens came from: per-model settings, the curated model catalog, a user-set fallback, or the built-in default. */
|
|
26
|
+
contextWindowSource: 'settings' | 'catalog' | 'user-fallback' | 'default-fallback';
|
|
27
27
|
/** Optional output-token limit metadata for request budgeting (RH-005). */
|
|
28
28
|
maxOutputTokens?: number;
|
|
29
29
|
}
|
package/dist/llm/client.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createOpenAI } from '@ai-sdk/openai';
|
|
2
2
|
import crypto from 'node:crypto';
|
|
3
3
|
import { readSettings } from '../config/settings.js';
|
|
4
|
+
import { catalogLimitsFor } from '../config/modelCatalog.js';
|
|
4
5
|
import { activeModel, modelSelector, resolveModelSelector } from '../config/providers.js';
|
|
5
6
|
import { assertCredentialedEndpointSecure } from '../config/endpointSecurity.js';
|
|
6
7
|
import { resolveReasoningPolicy } from '../core/agent/reasoningPolicy.js';
|
|
@@ -64,15 +65,22 @@ function runtimeForSelection(settings, selection, cwd) {
|
|
|
64
65
|
const limits = modelLimitsFor(selection.provider, name);
|
|
65
66
|
// Class-aware fallback so unknown local models (server-configured window,
|
|
66
67
|
// silent truncation) stay conservative while unknown hosted models get the
|
|
67
|
-
// modern 128K floor.
|
|
68
|
-
//
|
|
69
|
-
//
|
|
68
|
+
// modern 128K floor. The curated catalog (Pillar 1.8) fills known families
|
|
69
|
+
// before any fallback; local servers never consult it because their
|
|
70
|
+
// effective window is server-configured. A user-set fallback setting
|
|
71
|
+
// overrides the built-in default; the source tag distinguishes an
|
|
72
|
+
// intentional guess (no warning) from the default guess (warned once per
|
|
73
|
+
// session) (RH-005).
|
|
70
74
|
const isLocal = isLocalProviderUrl(baseURL);
|
|
75
|
+
const catalog = isLocal ? undefined : catalogLimitsFor(name);
|
|
71
76
|
const userFallback = isLocal ? settings.localContextWindowFallbackTokens : settings.contextWindowFallbackTokens;
|
|
72
77
|
const fallbackTokens = userFallback ?? (isLocal ? FALLBACK_LOCAL_CONTEXT_TOKENS : FALLBACK_CONTEXT_WINDOW_TOKENS);
|
|
73
78
|
const contextWindowSource = limits.contextWindowTokens !== undefined
|
|
74
79
|
? 'settings'
|
|
75
|
-
:
|
|
80
|
+
: catalog
|
|
81
|
+
? 'catalog'
|
|
82
|
+
: userFallback !== undefined ? 'user-fallback' : 'default-fallback';
|
|
83
|
+
const maxOutputTokens = limits.maxOutputTokens ?? catalog?.maxOutputTokens;
|
|
76
84
|
return {
|
|
77
85
|
model: providerKind === 'chatgpt-codex' ? openai.responses(name) : openai.chat(name),
|
|
78
86
|
selector: modelSelector(selection.provider, name),
|
|
@@ -84,9 +92,9 @@ function runtimeForSelection(settings, selection, cwd) {
|
|
|
84
92
|
cacheKey,
|
|
85
93
|
capabilities: caps,
|
|
86
94
|
reasoningPolicy,
|
|
87
|
-
contextWindowTokens: limits.contextWindowTokens ?? fallbackTokens,
|
|
95
|
+
contextWindowTokens: limits.contextWindowTokens ?? catalog?.contextWindowTokens ?? fallbackTokens,
|
|
88
96
|
contextWindowSource,
|
|
89
|
-
...(
|
|
97
|
+
...(maxOutputTokens !== undefined ? { maxOutputTokens } : {}),
|
|
90
98
|
},
|
|
91
99
|
};
|
|
92
100
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { tool } from 'ai';
|
|
2
2
|
import { z } from 'zod';
|
|
3
|
-
import { classifyShellCommand, isValidationClassification } from '../../core/safety/shellClassifier.js';
|
|
3
|
+
import { classifyShellCommand, commandMasksValidationExit, isValidationClassification } from '../../core/safety/shellClassifier.js';
|
|
4
4
|
import { detectMissingExecutable, missingExecutableFields } from '../../core/safety/missingExecutable.js';
|
|
5
5
|
import { parseValidationOutput } from '../../core/validation/outputParser.js';
|
|
6
6
|
import { filterShellOutput } from '../../core/shellOutput/registry.js';
|
|
@@ -11,7 +11,7 @@ import { hazeContext, hazeToolContextSchema, runDedupedTool } from './toolContex
|
|
|
11
11
|
import { runBoundedProcess } from '../../core/process/runBoundedProcess.js';
|
|
12
12
|
import { SHELL_STREAM_BYTES, SHORT_VALIDATION_CHARS } from '../../core/limits.js';
|
|
13
13
|
import { startBackgroundProcess } from '../../core/process/backgroundRegistry.js';
|
|
14
|
-
import { resolveUserShell, shellInvocation, shellSyntaxGuidance } from '../../core/process/userShell.js';
|
|
14
|
+
import { resolveUserShell, shellDialect, shellInvocation, shellSyntaxGuidance } from '../../core/process/userShell.js';
|
|
15
15
|
/** Byte-stat metadata only — the raw stream text must never reach the model context (see code-review CR-001). */
|
|
16
16
|
function streamByteStats(stream) {
|
|
17
17
|
return { totalBytes: stream.totalBytes, retainedBytes: stream.retainedBytes, omittedBytes: stream.omittedBytes };
|
|
@@ -22,7 +22,7 @@ export const shellTool = tool({
|
|
|
22
22
|
contextSchema: hazeToolContextSchema,
|
|
23
23
|
inputSchema: z.object({
|
|
24
24
|
command: z.string().min(1).describe(`Command to execute with ${userShell} ${shellInvocation('', userShell).args.join(' ')}. ${shellSyntaxGuidance(userShell)}`.trim()),
|
|
25
|
-
purpose: z.enum(['auto', 'validation']).default('auto').describe('Use validation for an intentional test/check command,
|
|
25
|
+
purpose: z.enum(['auto', 'validation']).default('auto').describe('Use validation for an intentional test/check command; known test/build commands are the authoritative completion evidence, custom checks supplement them. Pass/fail comes from the real process result.'),
|
|
26
26
|
timeoutSeconds: z.number().int().positive().max(600).optional().describe('Timeout in seconds; defaults to 60'),
|
|
27
27
|
background: z.boolean().default(false).describe('Start a registered long-running process and return immediately. Use process to list, inspect output, or kill it.'),
|
|
28
28
|
}),
|
|
@@ -49,15 +49,34 @@ export const shellTool = tool({
|
|
|
49
49
|
}
|
|
50
50
|
const timeoutMs = (timeoutSeconds ?? 60) * 1000;
|
|
51
51
|
const startedAt = Date.now();
|
|
52
|
-
|
|
52
|
+
// Validation exit codes must be truthful evidence: a pipeline like
|
|
53
|
+
// `npm test | tail` otherwise reports the final stage's success while the
|
|
54
|
+
// suite failed (found by the honest-impossibility eval). `pipefail` makes
|
|
55
|
+
// any failing stage fail the pipeline; shells without it degrade to their
|
|
56
|
+
// default pipeline semantics through the guarded `set` (POSIX shells only).
|
|
57
|
+
const isValidationCommand = purpose === 'validation' || isValidationClassification(classification);
|
|
58
|
+
const executionCommand = isValidationCommand && shellDialect(userShell) === 'posix' ? `set -o pipefail 2>/dev/null || true; ${command}` : command;
|
|
59
|
+
const processResult = await runBoundedProcess({ ...shellInvocation(executionCommand), cwd, timeoutMs, signal: context.abortSignal, maxStdoutBytes: SHELL_STREAM_BYTES, maxStderrBytes: SHELL_STREAM_BYTES });
|
|
53
60
|
const { code, timedOut } = processResult;
|
|
54
61
|
const stdout = processResult.stdout.text;
|
|
55
62
|
const stderr = processResult.stderr.text;
|
|
56
|
-
const validationSummary =
|
|
63
|
+
const validationSummary = isValidationCommand
|
|
57
64
|
? parseValidationOutput({ command, code, stdout, stderr, timedOut, stdoutTruncated: processResult.stdout.omittedBytes > 0, stderrTruncated: processResult.stderr.omittedBytes > 0, classification })
|
|
58
65
|
: undefined;
|
|
59
|
-
|
|
60
|
-
|
|
66
|
+
// Evidence truthfulness: a passing validation whose command shape can
|
|
67
|
+
// mask an earlier failing stage (`npm test > out; cat out` ends with the
|
|
68
|
+
// last stage's status) is demoted to unconfirmed — generic kind — so the
|
|
69
|
+
// completion gate cannot treat it as authoritative (found by the
|
|
70
|
+
// honest-impossibility eval). Failing validations keep their kind: a
|
|
71
|
+
// masked compound that still failed is honestly failed.
|
|
72
|
+
const authoritative = validationSummary == null || validationSummary.status !== 'passed' || !commandMasksValidationExit(command);
|
|
73
|
+
const confirmedValidationSummary = validationSummary && authoritative
|
|
74
|
+
? validationSummary
|
|
75
|
+
: validationSummary
|
|
76
|
+
? { ...validationSummary, kind: 'generic', summaryText: `${validationSummary.summaryText ?? ''} (compound command: exit-code provenance unconfirmed)`.trim() }
|
|
77
|
+
: undefined;
|
|
78
|
+
const validationPassed = confirmedValidationSummary?.status === 'passed';
|
|
79
|
+
const output = filterShellOutput({ command, code, stdout, stderr, timedOut, classification, validationSummary: confirmedValidationSummary, storeRawOutput: storeToolOutput, fallbackCompact: compactStoredOutput, compactMaxChars: validationPassed ? SHORT_VALIDATION_CHARS : COMPACT_COMMAND_CHARS });
|
|
61
80
|
// Generic, dependency-agnostic diagnostic for a missing executable. Only the
|
|
62
81
|
// executable name and a generic next step are exposed (never raw stderr).
|
|
63
82
|
const missing = code !== 0 && !processResult.aborted ? detectMissingExecutable({ command, code, stderr }) : undefined;
|
|
@@ -65,7 +84,7 @@ export const shellTool = tool({
|
|
|
65
84
|
ok: code === 0 && !timedOut && !processResult.aborted && !processResult.error,
|
|
66
85
|
code, command, purpose, cwd, classification, durationMs: Date.now() - startedAt, timedOut,
|
|
67
86
|
aborted: processResult.aborted, signal: processResult.signal, forcedTermination: processResult.forced,
|
|
68
|
-
stdout: output.stdout, stderr: output.stderr, validationSummary,
|
|
87
|
+
stdout: output.stdout, stderr: output.stderr, validationSummary: confirmedValidationSummary,
|
|
69
88
|
stdoutBytes: streamByteStats(processResult.stdout), stderrBytes: streamByteStats(processResult.stderr),
|
|
70
89
|
...(missing ? { ...missingExecutableFields(missing), missingExecutableStep: missing.suggestedNextStep } : {}),
|
|
71
90
|
...(processResult.error ? { error: processResult.error } : {}),
|
|
@@ -3,8 +3,18 @@ type TextInputKey = {
|
|
|
3
3
|
return?: boolean;
|
|
4
4
|
shift?: boolean;
|
|
5
5
|
ctrl?: boolean;
|
|
6
|
+
meta?: boolean;
|
|
6
7
|
};
|
|
7
8
|
export declare function shouldInsertNewline(input: string, key: TextInputKey): boolean;
|
|
9
|
+
export declare function isKittyQueryResponseInput(input: string): boolean;
|
|
10
|
+
/**
|
|
11
|
+
* Ctrl+C terminate check. Legacy terminals deliver the raw \x03 byte (Ink
|
|
12
|
+
* parses it to `c` + ctrl); with the kitty keyboard protocol enabled the
|
|
13
|
+
* terminal reports `CSI 99;5u`, which parses to the same `c` + ctrl shape.
|
|
14
|
+
* Ink 7.1.1's built-in exit-on-CtrlC only recognizes the raw \x03 event, so
|
|
15
|
+
* haze owns the interrupt explicitly (render runs with exitOnCtrlC: false).
|
|
16
|
+
*/
|
|
17
|
+
export declare function isInterruptInput(input: string, key: TextInputKey): boolean;
|
|
8
18
|
export type TextInputSuggestion = {
|
|
9
19
|
value: string;
|
|
10
20
|
description?: string;
|
|
@@ -12,7 +22,7 @@ export type TextInputSuggestion = {
|
|
|
12
22
|
};
|
|
13
23
|
/** Cursor-aware path completer for `@token` mentions; receives the token verbatim. */
|
|
14
24
|
export type MentionSuggestionsProvider = (token: string) => Promise<TextInputSuggestion[]> | TextInputSuggestion[];
|
|
15
|
-
export declare function TextInput({ placeholder, disabled, mask, historyItems, recordHistory, suggestions, suggestionMode, submitOnEmpty, width, getMentionSuggestions, onHistoryAdd, onCancel, onEscape, onToggleTasks, onResumeKey, onSubmit }: {
|
|
25
|
+
export declare function TextInput({ placeholder, disabled, mask, historyItems, recordHistory, suggestions, suggestionMode, submitOnEmpty, width, getMentionSuggestions, onHistoryAdd, onCancel, onEscape, onToggleTasks, onResumeKey, onInterrupt, onSubmit }: {
|
|
16
26
|
placeholder?: string;
|
|
17
27
|
disabled?: boolean;
|
|
18
28
|
mask?: boolean;
|
|
@@ -34,6 +44,13 @@ export declare function TextInput({ placeholder, disabled, mask, historyItems, r
|
|
|
34
44
|
* matching hint line, so ordinary typing is unaffected.
|
|
35
45
|
*/
|
|
36
46
|
onResumeKey?: () => void;
|
|
47
|
+
/**
|
|
48
|
+
* Ctrl+C terminate: called for the parsed `c`+ctrl shape shared by the
|
|
49
|
+
* legacy \x03 byte and the kitty-protocol `CSI 99;5u` report. Runs even
|
|
50
|
+
* while the input is disabled (streaming), matching the terminal-wide
|
|
51
|
+
* terminate convention Ink's global handler used to provide.
|
|
52
|
+
*/
|
|
53
|
+
onInterrupt?: () => void;
|
|
37
54
|
onSubmit: (value: string) => void;
|
|
38
55
|
}): React.JSX.Element;
|
|
39
56
|
export {};
|
|
@@ -5,13 +5,47 @@ import { theme } from '../theme.js';
|
|
|
5
5
|
import { compactPasteBlocksForDisplay, cursorPosition, displayCursorForValueCursor, lineCount, normalizeLineEndings, updatePasteBlocksForReplacement, valueCursorForDisplayCursor, wrapDisplayValue, } from '../inputBuffer.js';
|
|
6
6
|
import { useInputSuggestions } from './useInputSuggestions.js';
|
|
7
7
|
const COMPACT_PASTE_MIN_LINES = 4;
|
|
8
|
-
|
|
8
|
+
// Enhanced-keyboard encodings of Enter with modifiers that some terminals emit
|
|
9
|
+
// verbatim (kitty/CSI-u `u` form and xterm modifyOtherKeys `~` form). Ink 7's
|
|
10
|
+
// keypress parser already resolves the CSI-u variants to `key.return` plus the
|
|
11
|
+
// modifier flags before TextInput sees them; these entries cover pipelines that
|
|
12
|
+
// deliver the raw sequence through `input`.
|
|
13
|
+
const NEWLINE_ESCAPE_INPUTS = new Set([
|
|
14
|
+
'\u001B[13;2u', // shift+enter (kitty protocol / modifyOtherKeys=2)
|
|
15
|
+
'\u001B[13;2~', // shift+enter (xterm modifyOtherKeys=1)
|
|
16
|
+
'\u001B[13;5u', // ctrl+enter (kitty protocol / modifyOtherKeys=2)
|
|
17
|
+
'\u001B[13;5~', // ctrl+enter (xterm modifyOtherKeys=1)
|
|
18
|
+
]);
|
|
9
19
|
export function shouldInsertNewline(input, key) {
|
|
10
|
-
return (key.return === true && (key.shift === true || key.ctrl === true))
|
|
20
|
+
return (key.return === true && (key.shift === true || key.ctrl === true || key.meta === true))
|
|
11
21
|
|| input === '\n'
|
|
12
|
-
||
|
|
22
|
+
|| NEWLINE_ESCAPE_INPUTS.has(input);
|
|
13
23
|
}
|
|
14
|
-
|
|
24
|
+
// Ink's kitty-keyboard auto-detection (enabled via the chat render option)
|
|
25
|
+
// queries the terminal with CSI ? u. The terminal's CSI ? <flags> u response
|
|
26
|
+
// can race Ink's detection listener and leak through the normal input pipeline
|
|
27
|
+
// as literal text (Ink's keypress handling strips the leading ESC), which would
|
|
28
|
+
// type e.g. `[?0u` into an otherwise empty prompt at startup. Drop probe
|
|
29
|
+
// responses instead of inserting them.
|
|
30
|
+
const KITTY_QUERY_RESPONSE_INPUT = /^\[\?\d+(?:;\d+)*u$/;
|
|
31
|
+
export function isKittyQueryResponseInput(input) {
|
|
32
|
+
// Ink's keypress handling strips one leading ESC from unresolved sequences,
|
|
33
|
+
// so the probe response normally arrives as `[?0u`; tolerate the raw
|
|
34
|
+
// ESC-prefixed form as well.
|
|
35
|
+
const stripped = input.startsWith('\u001B') ? input.slice(1) : input;
|
|
36
|
+
return KITTY_QUERY_RESPONSE_INPUT.test(stripped);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Ctrl+C terminate check. Legacy terminals deliver the raw \x03 byte (Ink
|
|
40
|
+
* parses it to `c` + ctrl); with the kitty keyboard protocol enabled the
|
|
41
|
+
* terminal reports `CSI 99;5u`, which parses to the same `c` + ctrl shape.
|
|
42
|
+
* Ink 7.1.1's built-in exit-on-CtrlC only recognizes the raw \x03 event, so
|
|
43
|
+
* haze owns the interrupt explicitly (render runs with exitOnCtrlC: false).
|
|
44
|
+
*/
|
|
45
|
+
export function isInterruptInput(input, key) {
|
|
46
|
+
return (input === 'c' && key.ctrl === true) || input === '\x03';
|
|
47
|
+
}
|
|
48
|
+
export function TextInput({ placeholder, disabled, mask, historyItems = [], recordHistory = true, suggestions = [], suggestionMode = 'slash', submitOnEmpty = false, width = 80, getMentionSuggestions, onHistoryAdd, onCancel, onEscape, onToggleTasks, onResumeKey, onInterrupt, onSubmit }) {
|
|
15
49
|
const [value, setValue] = useState('');
|
|
16
50
|
const [cursor, setCursor] = useState(0);
|
|
17
51
|
const [pasteBlocks, setPasteBlocks] = useState([]);
|
|
@@ -84,6 +118,12 @@ export function TextInput({ placeholder, disabled, mask, historyItems = [], reco
|
|
|
84
118
|
onSubmit(submitted);
|
|
85
119
|
}
|
|
86
120
|
useInput((input, key) => {
|
|
121
|
+
if (isKittyQueryResponseInput(input))
|
|
122
|
+
return;
|
|
123
|
+
if (isInterruptInput(input, key)) {
|
|
124
|
+
onInterrupt?.();
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
87
127
|
if (disabled) {
|
|
88
128
|
if (key.escape)
|
|
89
129
|
onCancel?.();
|
|
@@ -208,8 +248,6 @@ export function TextInput({ placeholder, disabled, mask, historyItems = [], reco
|
|
|
208
248
|
setCursor(value.length);
|
|
209
249
|
return;
|
|
210
250
|
}
|
|
211
|
-
if (key.ctrl && input === 'c')
|
|
212
|
-
return;
|
|
213
251
|
if (key.ctrl && input === 'o') {
|
|
214
252
|
onToggleTasks?.();
|
|
215
253
|
return;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@denizokcu/haze",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"description": "A minimal LLM harness for your terminal.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -42,43 +42,44 @@
|
|
|
42
42
|
"lint:knip": "knip",
|
|
43
43
|
"typecheck": "tsc --noEmit",
|
|
44
44
|
"context:report": "node --import tsx src/cli/contextReport.ts",
|
|
45
|
+
"eval": "node scripts/run-evals.mjs",
|
|
45
46
|
"release:verify": "node scripts/verify-release-metadata.mjs",
|
|
46
47
|
"haze": "tsx src/cli/index.ts",
|
|
47
48
|
"prepublishOnly": "npm run typecheck && npm test && npm run lint && npm run build && npm audit --audit-level=high && npm run release:verify"
|
|
48
49
|
},
|
|
49
50
|
"dependencies": {
|
|
50
|
-
"@ai-sdk/mcp": "^2.0.
|
|
51
|
-
"@ai-sdk/openai": "4.0.
|
|
51
|
+
"@ai-sdk/mcp": "^2.0.41",
|
|
52
|
+
"@ai-sdk/openai": "4.0.52",
|
|
52
53
|
"@vscode/ripgrep": "1.18.0",
|
|
53
|
-
"ai": "7.0.
|
|
54
|
+
"ai": "7.0.85",
|
|
54
55
|
"cli-highlight": "2.1.11",
|
|
55
56
|
"commander": "15.0.0",
|
|
56
|
-
"defuddle": "^0.19.
|
|
57
|
+
"defuddle": "^0.19.3",
|
|
57
58
|
"fs-extra": "11.4.0",
|
|
58
|
-
"ignore": "^7.0.
|
|
59
|
+
"ignore": "^7.0.8",
|
|
59
60
|
"ink": "7.1.1",
|
|
60
61
|
"ink-spinner": "5.0.0",
|
|
61
62
|
"linkedom": "^0.18.13",
|
|
62
|
-
"marked": "18.0.
|
|
63
|
+
"marked": "18.0.11",
|
|
63
64
|
"react": "19.2.8",
|
|
64
65
|
"strip-ansi": "7.2.0",
|
|
65
66
|
"turndown": "^7.2.4",
|
|
66
|
-
"wrap-ansi": "10.0.
|
|
67
|
+
"wrap-ansi": "10.0.1",
|
|
67
68
|
"yaml": "2.9.0",
|
|
68
|
-
"zod": "4.4
|
|
69
|
+
"zod": "4.5.4"
|
|
69
70
|
},
|
|
70
71
|
"devDependencies": {
|
|
71
72
|
"@eslint/js": "^10.0.1",
|
|
72
73
|
"@types/fs-extra": "11.0.4",
|
|
73
|
-
"@types/node": "26.
|
|
74
|
+
"@types/node": "26.4.0",
|
|
74
75
|
"@types/react": "19.2.18",
|
|
75
|
-
"eslint": "^10.
|
|
76
|
+
"eslint": "^10.9.1",
|
|
76
77
|
"ink-testing-library": "^4.0.0",
|
|
77
|
-
"knip": "
|
|
78
|
-
"tsx": "4.23.
|
|
78
|
+
"knip": "6.33.0",
|
|
79
|
+
"tsx": "4.23.13",
|
|
79
80
|
"typescript": "6.0.3",
|
|
80
|
-
"typescript-eslint": "^8.
|
|
81
|
-
"vitest": "^4.1.
|
|
81
|
+
"typescript-eslint": "^8.69.0",
|
|
82
|
+
"vitest": "^4.1.11"
|
|
82
83
|
},
|
|
83
84
|
"allowScripts": {
|
|
84
85
|
"fsevents@2.3.3": true,
|