@denizokcu/haze 1.1.1 → 1.4.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 +78 -0
- package/README.md +26 -15
- package/SECURITY.md +1 -1
- package/bin/haze.js +27 -7
- package/dist/buildInfo.json +3 -3
- package/dist/cli/chat/inputSuggestions.js +3 -0
- package/dist/cli/chat/liveMessages.d.ts +36 -0
- package/dist/cli/chat/liveMessages.js +64 -0
- package/dist/cli/chat/sessionLifecycle.d.ts +2 -1
- package/dist/cli/chat/sessionLifecycle.js +25 -2
- package/dist/cli/chat/sessionRecorder.d.ts +7 -0
- package/dist/cli/chat/sessionRecorder.js +6 -0
- package/dist/cli/chat/wizard/sessionThemeHandlers.d.ts +1 -1
- package/dist/cli/chat/wizard/sessionThemeHandlers.js +16 -1
- package/dist/cli/commands/chat.js +63 -36
- package/dist/cli/commands/commandHelp.js +2 -0
- package/dist/cli/commands/commands.js +2 -0
- package/dist/cli/commands/formatters.js +5 -1
- package/dist/cli/commands/ndjsonSink.d.ts +12 -0
- package/dist/cli/commands/ndjsonSink.js +29 -0
- package/dist/cli/commands/reasoningCommand.d.ts +35 -0
- package/dist/cli/commands/reasoningCommand.js +46 -0
- package/dist/cli/commands/runCommand.d.ts +14 -0
- package/dist/cli/commands/runCommand.js +43 -11
- package/dist/cli/commands/settingsSummary.js +2 -0
- package/dist/cli/commands/streaming/agentAttempt.d.ts +14 -1
- package/dist/cli/commands/streaming/agentAttempt.js +9 -5
- package/dist/cli/commands/streaming/assistantSegments.d.ts +0 -7
- package/dist/cli/commands/streaming/assistantSegments.js +1 -1
- package/dist/cli/commands/streaming/attemptLifecycle.js +13 -9
- package/dist/cli/commands/streaming/attemptOutcome.d.ts +23 -3
- package/dist/cli/commands/streaming/attemptOutcome.js +64 -11
- package/dist/cli/commands/streaming/attemptSetup.d.ts +13 -3
- package/dist/cli/commands/streaming/attemptSetup.js +40 -15
- package/dist/cli/commands/streaming/goalCheckpoint.d.ts +6 -0
- package/dist/cli/commands/streaming/goalCheckpoint.js +1 -0
- package/dist/cli/commands/streaming/goalSupervisor.d.ts +6 -1
- package/dist/cli/commands/streaming/goalSupervisor.js +18 -4
- package/dist/cli/commands/streaming/prepareStep.d.ts +6 -4
- package/dist/cli/commands/streaming/prepareStep.js +43 -22
- 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 +15 -2
- package/dist/cli/commands/streaming.js +37 -8
- package/dist/cli/commands/wizardFlow.d.ts +7 -0
- package/dist/cli/commands/wizardFlow.js +22 -0
- package/dist/cli/index.js +8 -3
- package/dist/config/modelCatalog.d.ts +32 -0
- package/dist/config/modelCatalog.js +84 -0
- package/dist/config/modelDiscovery.js +68 -5
- package/dist/config/settings.d.ts +18 -6
- package/dist/config/settings.js +11 -1
- package/dist/core/agent/budgets.d.ts +10 -2
- package/dist/core/agent/budgets.js +10 -2
- package/dist/core/agent/compaction.d.ts +42 -3
- package/dist/core/agent/compaction.js +53 -5
- package/dist/core/agent/completionController.d.ts +11 -1
- package/dist/core/agent/completionController.js +33 -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 +26 -2
- package/dist/core/agent/goalPolicy.d.ts +7 -0
- package/dist/core/agent/goalPolicy.js +9 -0
- package/dist/core/agent/overflow.d.ts +45 -0
- package/dist/core/agent/overflow.js +91 -0
- package/dist/core/agent/reasoningPolicy.d.ts +45 -9
- package/dist/core/agent/reasoningPolicy.js +49 -9
- package/dist/core/agent/requestAssembly.d.ts +7 -0
- package/dist/core/agent/requestAssembly.js +15 -7
- package/dist/core/agent/toolCapabilities.d.ts +3 -3
- package/dist/core/agent/toolCapabilities.js +31 -7
- package/dist/core/agent/workState.d.ts +6 -4
- package/dist/core/agent/workState.js +53 -29
- package/dist/core/deadline.js +22 -24
- package/dist/core/safety/secretPaths.js +10 -7
- package/dist/core/safety/shellClassifier.d.ts +18 -0
- package/dist/core/safety/shellClassifier.js +39 -0
- package/dist/core/session/sessionSlimming.d.ts +2 -0
- package/dist/core/session/sessionSlimming.js +50 -1
- package/dist/core/session/sessionStore.d.ts +14 -8
- package/dist/core/session/sessionStore.js +59 -32
- package/dist/core/shellOutput/reducers/git.js +7 -2
- package/dist/core/shellOutput/reducers/validation.d.ts +1 -1
- package/dist/core/shellOutput/reducers/validation.js +14 -1
- package/dist/core/shellOutput/registry.js +3 -2
- package/dist/core/subagent/contracts.d.ts +8 -1
- package/dist/core/subagent/subagentRunner.d.ts +4 -0
- package/dist/core/subagent/subagentRunner.js +33 -25
- package/dist/core/tasks/taskStorage.js +8 -1
- package/dist/core/validation/outputParser.d.ts +1 -1
- package/dist/core/validation/outputParser.js +30 -1
- package/dist/llm/client.d.ts +4 -3
- package/dist/llm/client.js +34 -16
- package/dist/llm/hazeTools.d.ts +2039 -16
- package/dist/llm/hazeTools.js +43 -2
- package/dist/llm/lsp/client.d.ts +7 -1
- package/dist/llm/lsp/client.js +58 -9
- package/dist/llm/lsp/pool.d.ts +11 -0
- package/dist/llm/lsp/pool.js +61 -4
- package/dist/llm/lsp/protocol.d.ts +6 -23
- package/dist/llm/lsp/requests.d.ts +54 -60
- package/dist/llm/lsp/requests.js +152 -28
- package/dist/llm/lsp/symbols.d.ts +16 -0
- package/dist/llm/lsp/symbols.js +70 -0
- package/dist/llm/lsp/workspaceEdit.d.ts +43 -0
- package/dist/llm/lsp/workspaceEdit.js +117 -0
- package/dist/llm/lspTools.d.ts +7518 -2859
- package/dist/llm/lspTools.js +195 -110
- package/dist/llm/requestContext.d.ts +3 -2
- package/dist/llm/requestContext.js +8 -4
- package/dist/llm/systemPrompt.js +2 -2
- package/dist/llm/tools/fetchTool.d.ts +4 -0
- package/dist/llm/tools/processTool.d.ts +4 -0
- package/dist/llm/tools/replaceInFiles.d.ts +105 -0
- package/dist/llm/tools/replaceInFiles.js +131 -0
- package/dist/llm/tools/shellTool.d.ts +4 -0
- package/dist/llm/tools/shellTool.js +27 -8
- package/dist/llm/tools/storedOutputTool.d.ts +4 -0
- package/dist/llm/tools/taskTool.d.ts +4 -0
- package/dist/llm/tools/toolContext.d.ts +3 -0
- package/dist/llm/tools/toolContext.js +26 -4
- package/dist/skills/SkillLoader.js +27 -1
- package/dist/ui/components/TextInput.d.ts +18 -1
- package/dist/ui/components/TextInput.js +44 -6
- package/dist/ui/components/useInputSuggestions.js +18 -6
- package/dist/utils/buildInfo.js +29 -8
- package/dist/utils/fs.js +5 -1
- package/package.json +20 -19
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { walkDir } from '../../utils/fs.js';
|
|
5
|
+
import { workspaceRoot } from '../../utils/path.js';
|
|
6
|
+
import { prepareWorkspaceMutation, prepareWorkspaceRead } from './workspaceFile.js';
|
|
7
|
+
import { createIgnoreClassifier } from './gitIgnore.js';
|
|
8
|
+
import { boundedDiff, fileDiff } from './editMatch.js';
|
|
9
|
+
import { readUtf8Prefix } from '../../core/io/boundedRead.js';
|
|
10
|
+
import { EXACT_MUTATION_BYTES } from '../../core/limits.js';
|
|
11
|
+
import { storeToolOutput } from '../../core/agent/toolOutputStore.js';
|
|
12
|
+
function globRegex(glob) {
|
|
13
|
+
const escaped = glob.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*\*/g, '__HAZE_DOUBLE_STAR__').replace(/\*/g, '[^/]*').replace(/\?/g, '[^/]').replace(/__HAZE_DOUBLE_STAR__/g, '.*');
|
|
14
|
+
return new RegExp(`^${escaped}$`);
|
|
15
|
+
}
|
|
16
|
+
function matcher(input) {
|
|
17
|
+
if (input.mode === 'literal')
|
|
18
|
+
return new RegExp(input.needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g');
|
|
19
|
+
return new RegExp(input.needle, 'gm');
|
|
20
|
+
}
|
|
21
|
+
function occurrencesIn(filePath, content, input) {
|
|
22
|
+
const regex = matcher(input);
|
|
23
|
+
const result = [];
|
|
24
|
+
for (const match of content.matchAll(regex)) {
|
|
25
|
+
const start = match.index;
|
|
26
|
+
if (start == null)
|
|
27
|
+
continue;
|
|
28
|
+
const matched = match[0];
|
|
29
|
+
if (matched.length === 0)
|
|
30
|
+
throw new Error('needle must not match an empty string');
|
|
31
|
+
let replacement = input.replacement;
|
|
32
|
+
if (input.mode === 'regex') {
|
|
33
|
+
// A sticky match retains lookaround, captures, and native $`/$' input context.
|
|
34
|
+
const single = new RegExp(input.needle, 'my');
|
|
35
|
+
single.lastIndex = start;
|
|
36
|
+
const replaced = content.replace(single, input.replacement);
|
|
37
|
+
replacement = replaced.slice(start, replaced.length - (content.length - start - matched.length));
|
|
38
|
+
}
|
|
39
|
+
const digest = crypto.createHash('sha256').update(`${filePath}\0${start}\0${matched}`).digest('hex').slice(0, 12);
|
|
40
|
+
result.push({ id: `${filePath}:${result.length}@${digest}`, path: filePath, start, end: start + matched.length, line: content.slice(0, start).split('\n').length, matched, replacement });
|
|
41
|
+
}
|
|
42
|
+
return result;
|
|
43
|
+
}
|
|
44
|
+
function applyOccurrences(content, occurrences) {
|
|
45
|
+
let updated = content;
|
|
46
|
+
for (const occurrence of [...occurrences].sort((a, b) => b.start - a.start))
|
|
47
|
+
updated = `${updated.slice(0, occurrence.start)}${occurrence.replacement}${updated.slice(occurrence.end)}`;
|
|
48
|
+
return updated;
|
|
49
|
+
}
|
|
50
|
+
export async function replaceInFiles(input, context) {
|
|
51
|
+
if (!input.needle)
|
|
52
|
+
throw new Error('needle must not be empty');
|
|
53
|
+
const base = await prepareWorkspaceRead(input.path, false, context);
|
|
54
|
+
const stat = await fs.stat(base);
|
|
55
|
+
const ignore = createIgnoreClassifier(workspaceRoot());
|
|
56
|
+
const entries = stat.isFile() ? [{ path: path.relative(workspaceRoot(), base), absolutePath: base, isFile: true, isDirectory: false, name: path.basename(base) }] : await walkDir(base, {
|
|
57
|
+
recursive: true,
|
|
58
|
+
maxEntries: 20_000,
|
|
59
|
+
ignoreBatch: async (values) => await ignore.classify(values.map(value => ({ path: path.relative(workspaceRoot(), value.absolutePath), isDirectory: value.isDirectory }))),
|
|
60
|
+
});
|
|
61
|
+
const include = input.includeGlob ? globRegex(input.includeGlob) : undefined;
|
|
62
|
+
const exclude = input.excludeGlob ? globRegex(input.excludeGlob) : undefined;
|
|
63
|
+
const files = [];
|
|
64
|
+
let skippedFiles = 0;
|
|
65
|
+
for (const entry of entries) {
|
|
66
|
+
if (!entry.isFile)
|
|
67
|
+
continue;
|
|
68
|
+
const relative = path.relative(workspaceRoot(), entry.absolutePath).replace(/\\/g, '/');
|
|
69
|
+
if ((include && !include.test(relative)) || exclude?.test(relative))
|
|
70
|
+
continue;
|
|
71
|
+
let content;
|
|
72
|
+
try {
|
|
73
|
+
const safePath = await prepareWorkspaceRead(entry.absolutePath, false, context);
|
|
74
|
+
const read = await readUtf8Prefix(safePath, EXACT_MUTATION_BYTES);
|
|
75
|
+
if (read.truncated)
|
|
76
|
+
continue;
|
|
77
|
+
content = read.content;
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
skippedFiles++;
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (content.includes('\0'))
|
|
84
|
+
continue;
|
|
85
|
+
const occurrences = occurrencesIn(relative, content, input);
|
|
86
|
+
if (occurrences.length > 0)
|
|
87
|
+
files.push({ path: relative, absolutePath: entry.absolutePath, content, occurrences });
|
|
88
|
+
}
|
|
89
|
+
const all = files.flatMap(file => file.occurrences);
|
|
90
|
+
const fullPreview = all.map(occurrence => ({ id: occurrence.id, path: occurrence.path, line: occurrence.line, before: occurrence.matched, after: occurrence.replacement }));
|
|
91
|
+
const preview = fullPreview.slice(0, 100).map(occurrence => ({ ...occurrence, before: occurrence.before.slice(0, 200), after: occurrence.after.slice(0, 200) }));
|
|
92
|
+
const occurrenceHandle = fullPreview.length > preview.length || fullPreview.some(occurrence => occurrence.before.length > 200 || occurrence.after.length > 200)
|
|
93
|
+
? storeToolOutput(JSON.stringify(fullPreview, null, 2))
|
|
94
|
+
: undefined;
|
|
95
|
+
const previewFields = { skippedFiles, occurrences: preview, occurrencesTruncated: occurrenceHandle != null, ...(occurrenceHandle ? { occurrenceHandle } : {}) };
|
|
96
|
+
if (input.dryRun)
|
|
97
|
+
return { ok: true, dryRun: true, occurrenceCount: all.length, fileCount: files.length, ...previewFields };
|
|
98
|
+
if (input.expectedCount != null && input.expectedCount !== all.length)
|
|
99
|
+
return { ok: false, error: `expectedCount=${input.expectedCount}, but found ${all.length}; no changes applied.`, ...previewFields, recoverable: true };
|
|
100
|
+
const requested = input.occurrenceIds ? new Set(input.occurrenceIds) : undefined;
|
|
101
|
+
if (requested) {
|
|
102
|
+
const currentIds = new Set(all.map(occurrence => occurrence.id));
|
|
103
|
+
const stale = [...requested].filter(id => !currentIds.has(id));
|
|
104
|
+
if (stale.length > 0)
|
|
105
|
+
return { ok: false, error: `${stale.length} occurrence id(s) are stale or unknown; no changes applied.`, staleOccurrenceIds: stale, recoverable: true, suggestedNextStep: 'Run replaceInFiles with dryRun=true again and use the current occurrence IDs.' };
|
|
106
|
+
}
|
|
107
|
+
const selectedFiles = files.map(file => ({ ...file, selected: requested ? file.occurrences.filter(occurrence => requested.has(occurrence.id)) : file.occurrences })).filter(file => file.selected.length > 0);
|
|
108
|
+
if (selectedFiles.length === 0)
|
|
109
|
+
return { ok: false, error: 'No occurrences selected; no changes applied.', recoverable: true };
|
|
110
|
+
for (const file of selectedFiles) {
|
|
111
|
+
const prepared = await prepareWorkspaceMutation('replaceInFiles', file.path, false, context);
|
|
112
|
+
if (prepared.scopedStop)
|
|
113
|
+
return prepared.scopedStop;
|
|
114
|
+
}
|
|
115
|
+
const changed = selectedFiles.map(file => ({ ...file, updated: applyOccurrences(file.content, file.selected) })).filter(file => file.updated !== file.content);
|
|
116
|
+
const changedPaths = [];
|
|
117
|
+
for (const file of changed) {
|
|
118
|
+
try {
|
|
119
|
+
await fs.writeFile(file.absolutePath, file.updated, 'utf8');
|
|
120
|
+
changedPaths.push(file.path);
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
return { ok: false, changedPaths, uncertainPaths: [file.path], error: `Write failed for ${file.path}; earlier writes were not rolled back.`, recoverable: true, suggestedNextStep: 'Read the changed and uncertain paths before retrying; validate all completed changes.' };
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
const fullFiles = changed.map(file => ({ path: file.path, ...fileDiff(file.content, file.updated) }));
|
|
127
|
+
const changedFiles = fullFiles.map(file => ({ ...file, diff: boundedDiff(file.diff, 12).diff }));
|
|
128
|
+
const diffLineCount = fullFiles.reduce((sum, file) => sum + file.diff.length, 0);
|
|
129
|
+
const diffHandle = diffLineCount > changedFiles.reduce((sum, file) => sum + file.diff.length, 0) ? storeToolOutput(JSON.stringify(fullFiles, null, 2)) : undefined;
|
|
130
|
+
return { ok: true, dryRun: false, changedPaths, noChange: changed.length === 0, occurrenceCount: changed.reduce((sum, file) => sum + file.selected.length, 0), fileCount: changed.length, diffLineCount, files: changedFiles, ...(diffHandle ? { diffHandle } : {}) };
|
|
131
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export declare const shellTool: ({
|
|
2
|
+
deferLoading?: boolean;
|
|
2
3
|
title?: string;
|
|
3
4
|
providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
|
|
4
5
|
metadata?: import("@ai-sdk/provider").JSONObject;
|
|
@@ -377,6 +378,7 @@ export declare const shellTool: ({
|
|
|
377
378
|
background?: undefined;
|
|
378
379
|
}, NoInfer<import("./toolContext.js").HazeToolContext>>;
|
|
379
380
|
}) | ({
|
|
381
|
+
deferLoading?: boolean;
|
|
380
382
|
title?: string;
|
|
381
383
|
providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
|
|
382
384
|
metadata?: import("@ai-sdk/provider").JSONObject;
|
|
@@ -755,6 +757,7 @@ export declare const shellTool: ({
|
|
|
755
757
|
background?: undefined;
|
|
756
758
|
}, NoInfer<import("./toolContext.js").HazeToolContext>>;
|
|
757
759
|
}) | ({
|
|
760
|
+
deferLoading?: boolean;
|
|
758
761
|
title?: string;
|
|
759
762
|
providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
|
|
760
763
|
metadata?: import("@ai-sdk/provider").JSONObject;
|
|
@@ -1123,6 +1126,7 @@ export declare const shellTool: ({
|
|
|
1123
1126
|
background?: undefined;
|
|
1124
1127
|
}, NoInfer<import("./toolContext.js").HazeToolContext>>;
|
|
1125
1128
|
}) | ({
|
|
1129
|
+
deferLoading?: boolean;
|
|
1126
1130
|
title?: string;
|
|
1127
1131
|
providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
|
|
1128
1132
|
metadata?: import("@ai-sdk/provider").JSONObject;
|
|
@@ -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 } : {}),
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export declare const readToolOutputTool: ({
|
|
2
|
+
deferLoading?: boolean;
|
|
2
3
|
title?: string;
|
|
3
4
|
providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
|
|
4
5
|
metadata?: import("@ai-sdk/provider").JSONObject;
|
|
@@ -92,6 +93,7 @@ export declare const readToolOutputTool: ({
|
|
|
92
93
|
error: string;
|
|
93
94
|
}, NoInfer<import("@ai-sdk/provider-utils").Context>>;
|
|
94
95
|
}) | ({
|
|
96
|
+
deferLoading?: boolean;
|
|
95
97
|
title?: string;
|
|
96
98
|
providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
|
|
97
99
|
metadata?: import("@ai-sdk/provider").JSONObject;
|
|
@@ -185,6 +187,7 @@ export declare const readToolOutputTool: ({
|
|
|
185
187
|
error: string;
|
|
186
188
|
}, NoInfer<import("@ai-sdk/provider-utils").Context>>;
|
|
187
189
|
}) | ({
|
|
190
|
+
deferLoading?: boolean;
|
|
188
191
|
title?: string;
|
|
189
192
|
providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
|
|
190
193
|
metadata?: import("@ai-sdk/provider").JSONObject;
|
|
@@ -267,6 +270,7 @@ export declare const readToolOutputTool: ({
|
|
|
267
270
|
error: string;
|
|
268
271
|
}, NoInfer<import("@ai-sdk/provider-utils").Context>>;
|
|
269
272
|
}) | ({
|
|
273
|
+
deferLoading?: boolean;
|
|
270
274
|
title?: string;
|
|
271
275
|
providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
|
|
272
276
|
metadata?: import("@ai-sdk/provider").JSONObject;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export declare const writeTasksTool: ({
|
|
2
|
+
deferLoading?: boolean;
|
|
2
3
|
title?: string;
|
|
3
4
|
providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
|
|
4
5
|
metadata?: import("@ai-sdk/provider").JSONObject;
|
|
@@ -125,6 +126,7 @@ export declare const writeTasksTool: ({
|
|
|
125
126
|
error?: undefined;
|
|
126
127
|
}, NoInfer<import("@ai-sdk/provider-utils").Context>>;
|
|
127
128
|
}) | ({
|
|
129
|
+
deferLoading?: boolean;
|
|
128
130
|
title?: string;
|
|
129
131
|
providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
|
|
130
132
|
metadata?: import("@ai-sdk/provider").JSONObject;
|
|
@@ -251,6 +253,7 @@ export declare const writeTasksTool: ({
|
|
|
251
253
|
error?: undefined;
|
|
252
254
|
}, NoInfer<import("@ai-sdk/provider-utils").Context>>;
|
|
253
255
|
}) | ({
|
|
256
|
+
deferLoading?: boolean;
|
|
254
257
|
title?: string;
|
|
255
258
|
providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
|
|
256
259
|
metadata?: import("@ai-sdk/provider").JSONObject;
|
|
@@ -367,6 +370,7 @@ export declare const writeTasksTool: ({
|
|
|
367
370
|
error?: undefined;
|
|
368
371
|
}, NoInfer<import("@ai-sdk/provider-utils").Context>>;
|
|
369
372
|
}) | ({
|
|
373
|
+
deferLoading?: boolean;
|
|
370
374
|
title?: string;
|
|
371
375
|
providerOptions?: import("@ai-sdk/provider-utils").ProviderOptions;
|
|
372
376
|
metadata?: import("@ai-sdk/provider").JSONObject;
|
|
@@ -18,6 +18,7 @@ export type ToolExecutionContext = {
|
|
|
18
18
|
context?: unknown;
|
|
19
19
|
experimental_context?: unknown;
|
|
20
20
|
};
|
|
21
|
+
export type PostMutationDiagnostics = (paths: readonly string[]) => Promise<unknown | undefined>;
|
|
21
22
|
export type HazeToolContext = {
|
|
22
23
|
inFlightToolCalls?: Map<string, Promise<unknown>>;
|
|
23
24
|
completedToolCalls?: Map<string, number>;
|
|
@@ -37,6 +38,8 @@ export type HazeToolContext = {
|
|
|
37
38
|
isSubagent?: boolean;
|
|
38
39
|
/** Real paths the user mentioned this turn; read tools may escape workspace for them. */
|
|
39
40
|
blessedPaths?: readonly BlessedPath[];
|
|
41
|
+
/** Runs LSP diagnostics after successful file mutations and embeds them in that tool result. */
|
|
42
|
+
postMutationDiagnostics?: PostMutationDiagnostics;
|
|
40
43
|
};
|
|
41
44
|
export declare const hazeToolContextSchema: z.ZodCustom<HazeToolContext, HazeToolContext>;
|
|
42
45
|
export declare function hazeContext(context: ToolExecutionContext): HazeToolContext | undefined;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
+
import { changedPathsFromTool, isMutatingCapability } from '../../core/agent/toolCapabilities.js';
|
|
2
3
|
import { readScopedContextFilesForPath } from '../../config/contextFiles.js';
|
|
3
4
|
import { workspacePathKey, workspaceRoot } from '../../utils/path.js';
|
|
4
5
|
import { isFailedToolOutput, requiresReadFileRecovery, toolInputField } from '../../core/agent/toolResults.js';
|
|
@@ -45,7 +46,8 @@ function isHazeToolContext(value) {
|
|
|
45
46
|
&& validOptional('mutationPolicy', isMutationPolicy)
|
|
46
47
|
&& validOptional('mutationOwner', field => typeof field === 'symbol')
|
|
47
48
|
&& validOptional('isSubagent', field => typeof field === 'boolean')
|
|
48
|
-
&& validOptional('blessedPaths', field => Array.isArray(field) && field.every(item => isRecord(item) && typeof item.realPath === 'string' && typeof item.isDirectory === 'boolean'))
|
|
49
|
+
&& validOptional('blessedPaths', field => Array.isArray(field) && field.every(item => isRecord(item) && typeof item.realPath === 'string' && typeof item.isDirectory === 'boolean'))
|
|
50
|
+
&& validOptional('postMutationDiagnostics', field => typeof field === 'function');
|
|
49
51
|
}
|
|
50
52
|
export const hazeToolContextSchema = z.custom(isHazeToolContext, 'Invalid haze tool context');
|
|
51
53
|
export function hazeContext(context) {
|
|
@@ -55,7 +57,7 @@ export function hazeContext(context) {
|
|
|
55
57
|
return isHazeToolContext(value) ? value : undefined;
|
|
56
58
|
}
|
|
57
59
|
export function toolsContextFor(tools, context) {
|
|
58
|
-
const hazeToolNames = new Set(['listFiles', 'readFile', 'grep', 'replaceLines', 'writeFile', 'editFile', 'shell', 'process', 'fetch']);
|
|
60
|
+
const hazeToolNames = new Set(['listFiles', 'readFile', 'grep', 'replaceInFiles', 'replaceLines', 'writeFile', 'editFile', 'shell', 'process', 'fetch', 'lspRenameSymbol', 'lspSafeDeleteSymbol']);
|
|
59
61
|
return Object.fromEntries(Object.keys(tools).filter(name => hazeToolNames.has(name)).map(name => [name, context]));
|
|
60
62
|
}
|
|
61
63
|
/**
|
|
@@ -113,10 +115,30 @@ export function scopedContextMutationStop(toolName, filePath, files) {
|
|
|
113
115
|
applicableProjectInstructions: files,
|
|
114
116
|
};
|
|
115
117
|
}
|
|
118
|
+
// Shared effects policy keeps diagnostics and completion evidence in agreement.
|
|
116
119
|
function isMutatingTool(toolName) {
|
|
117
120
|
// Shell execution is conservatively workspace-mutation-capable. Classification remains
|
|
118
121
|
// informational and is not a sandbox boundary.
|
|
119
|
-
return
|
|
122
|
+
return isMutatingCapability(toolName) || toolName === 'shell';
|
|
123
|
+
}
|
|
124
|
+
/** Paths actually changed by a successful dedicated file-mutation result. */
|
|
125
|
+
function changedPathsForDiagnostics(toolName, input, result) {
|
|
126
|
+
return changedPathsFromTool(toolName, input, result);
|
|
127
|
+
}
|
|
128
|
+
async function attachPostMutationDiagnostics(toolName, input, result, diagnostics) {
|
|
129
|
+
if (!diagnostics)
|
|
130
|
+
return result;
|
|
131
|
+
const paths = changedPathsForDiagnostics(toolName, input, result);
|
|
132
|
+
if (paths.length === 0 || !isRecord(result))
|
|
133
|
+
return result;
|
|
134
|
+
try {
|
|
135
|
+
const lspDiagnostics = await diagnostics(paths);
|
|
136
|
+
return lspDiagnostics === undefined ? result : { ...result, lspDiagnostics };
|
|
137
|
+
}
|
|
138
|
+
catch (error) {
|
|
139
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
140
|
+
return { ...result, lspDiagnostics: { ok: false, error: `Automatic LSP diagnostics failed: ${message.split('\n')[0]}` } };
|
|
141
|
+
}
|
|
120
142
|
}
|
|
121
143
|
function isReadOnlyFileTool(toolName) {
|
|
122
144
|
return ['listFiles', 'readFile', 'grep'].includes(toolName);
|
|
@@ -217,7 +239,7 @@ export async function runDedupedTool(toolName, input, context, execute) {
|
|
|
217
239
|
}
|
|
218
240
|
}
|
|
219
241
|
ctx.completedToolCalls.set(key, ctx.mutationEpoch);
|
|
220
|
-
return result;
|
|
242
|
+
return await attachPostMutationDiagnostics(toolName, input, result, ctx.postMutationDiagnostics);
|
|
221
243
|
}
|
|
222
244
|
catch (error) {
|
|
223
245
|
if (isMutatingTool(toolName) && mutationPathKey && requiresReadFileRecovery(error)) {
|
|
@@ -4,7 +4,11 @@ import YAML from 'yaml';
|
|
|
4
4
|
import { assertRealPathInsideRoot } from '../utils/path.js';
|
|
5
5
|
import { SKILL_MARKDOWN_BYTES } from '../core/limits.js';
|
|
6
6
|
import { readUtf8Prefix } from '../core/io/boundedRead.js';
|
|
7
|
+
import { isProtectedSecretPath } from '../core/safety/secretPaths.js';
|
|
7
8
|
const MAX_REFERENCE_BYTES = 50_000;
|
|
9
|
+
/** CI-04: aggregate bounds so a dense skill cannot allocate unbounded memory. */
|
|
10
|
+
const MAX_REFERENCES = 20;
|
|
11
|
+
const MAX_TOTAL_REFERENCE_BYTES = 200_000;
|
|
8
12
|
const FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;
|
|
9
13
|
const MARKDOWN_LINK_RE = /\[[^\]]*\]\(([^)]+)\)/g;
|
|
10
14
|
const PLAIN_REFERENCE_RE = /(?:^|\n)\s*(?:[-*]\s+)?((?:[A-Za-z0-9_.-]+\/)+[A-Za-z0-9_.-]+\.[A-Za-z0-9]+)\s*(?=\n|$)/g;
|
|
@@ -52,7 +56,14 @@ async function loadReference(dir, referencePath) {
|
|
|
52
56
|
const relative = path.relative(dir, absolutePath);
|
|
53
57
|
if (relative.startsWith('..') || path.isAbsolute(relative))
|
|
54
58
|
throw new Error(`Skill reference escapes skill directory: ${referencePath}`);
|
|
59
|
+
// CI-03: the shared secret policy applies to skill bodies and references —
|
|
60
|
+
// confinement alone does not; a protected name inside the skill directory is
|
|
61
|
+
// refused before any filesystem access. Errors carry path metadata only.
|
|
62
|
+
if (isProtectedSecretPath(absolutePath))
|
|
63
|
+
throw new Error(`Skill reference is a protected secret file: ${referencePath}`);
|
|
55
64
|
const realPath = await assertRealPathInsideRoot(dir, absolutePath, referencePath, 'skill directory');
|
|
65
|
+
if (isProtectedSecretPath(realPath))
|
|
66
|
+
throw new Error(`Skill reference is a protected secret file: ${referencePath}`);
|
|
56
67
|
const stat = await fs.stat(realPath);
|
|
57
68
|
if (!stat.isFile())
|
|
58
69
|
throw new Error(`Skill reference is not a file: ${referencePath}`);
|
|
@@ -66,6 +77,8 @@ export async function loadSkill(dir, source = 'global') {
|
|
|
66
77
|
if (!(await fs.pathExists(skillPath)))
|
|
67
78
|
return null;
|
|
68
79
|
const realSkillPath = await assertRealPathInsideRoot(dir, skillPath, 'SKILL.md', 'skill directory');
|
|
80
|
+
if (isProtectedSecretPath(realSkillPath))
|
|
81
|
+
throw new Error('SKILL.md is a protected secret file');
|
|
69
82
|
const stat = await fs.stat(realSkillPath);
|
|
70
83
|
if (!stat.isFile())
|
|
71
84
|
throw new Error('SKILL.md is not a file');
|
|
@@ -74,6 +87,19 @@ export async function loadSkill(dir, source = 'global') {
|
|
|
74
87
|
throw new Error(`SKILL.md exceeds ${SKILL_MARKDOWN_BYTES} byte limit`);
|
|
75
88
|
const content = prefix.content;
|
|
76
89
|
const { frontmatter, body } = parseSkillMarkdown(content);
|
|
77
|
-
const
|
|
90
|
+
const referencePaths = referencedPaths(body);
|
|
91
|
+
if (referencePaths.length > MAX_REFERENCES)
|
|
92
|
+
throw new Error(`Skill declares ${referencePaths.length} references; the maximum is ${MAX_REFERENCES}.`);
|
|
93
|
+
// Sequential bounded loading (CI-04): no unbounded Promise.all fan-out, and
|
|
94
|
+
// the aggregate byte budget fails loudly instead of growing silently.
|
|
95
|
+
const references = [];
|
|
96
|
+
let totalReferenceBytes = 0;
|
|
97
|
+
for (const ref of referencePaths) {
|
|
98
|
+
const loaded = await loadReference(dir, ref);
|
|
99
|
+
totalReferenceBytes += Buffer.byteLength(loaded.content);
|
|
100
|
+
if (totalReferenceBytes > MAX_TOTAL_REFERENCE_BYTES)
|
|
101
|
+
throw new Error(`Skill references exceed the aggregate ${MAX_TOTAL_REFERENCE_BYTES} byte limit`);
|
|
102
|
+
references.push(loaded);
|
|
103
|
+
}
|
|
78
104
|
return { dir, path: realSkillPath, name: frontmatter.name, description: frontmatter.description, body, references, source };
|
|
79
105
|
}
|
|
@@ -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;
|
|
@@ -27,27 +27,39 @@ export function useInputSuggestions({ value, cursor, suggestions, suggestionMode
|
|
|
27
27
|
const detectedMention = !mask && suggestionMode === 'slash' && !value.startsWith('/') && getMentionSuggestions
|
|
28
28
|
? detectMentionAtCursor(value, cursor)
|
|
29
29
|
: undefined;
|
|
30
|
+
// Token identity binds results to the mention that produced them (SU-06): a
|
|
31
|
+
// previous token's list is only visible while the current token matches, so a
|
|
32
|
+
// fast Tab during a refetch can never complete with another token's entry.
|
|
33
|
+
const mentionTokenKey = detectedMention ? `${detectedMention.start}:${detectedMention.end}:${detectedMention.token}` : undefined;
|
|
34
|
+
const [mentionResultsFor, setMentionResultsFor] = useState();
|
|
30
35
|
useEffect(() => {
|
|
31
36
|
setMentionContext(detectedMention);
|
|
37
|
+
if (!detectedMention) {
|
|
38
|
+
setMentionSuggestions([]);
|
|
39
|
+
setMentionResultsFor(undefined);
|
|
40
|
+
}
|
|
32
41
|
}, [detectedMention?.token, detectedMention?.start, detectedMention?.end]);
|
|
33
42
|
useEffect(() => {
|
|
34
43
|
if (!mentionContext || !getMentionSuggestions) {
|
|
35
|
-
|
|
36
|
-
setMentionSuggestions([]);
|
|
44
|
+
setMentionSuggestions(current => (current.length > 0 ? [] : current));
|
|
37
45
|
return;
|
|
38
46
|
}
|
|
47
|
+
const key = `${mentionContext.start}:${mentionContext.end}:${mentionContext.token}`;
|
|
39
48
|
let cancelled = false;
|
|
40
49
|
Promise.resolve(getMentionSuggestions(mentionContext.token))
|
|
41
50
|
.then(results => { if (!cancelled) {
|
|
42
51
|
setMentionSuggestions(results);
|
|
43
52
|
setMentionSelectedIndex(0);
|
|
53
|
+
setMentionResultsFor(key);
|
|
44
54
|
} })
|
|
45
|
-
.catch(() => { if (!cancelled)
|
|
46
|
-
setMentionSuggestions([]);
|
|
55
|
+
.catch(() => { if (!cancelled) {
|
|
56
|
+
setMentionSuggestions([]);
|
|
57
|
+
setMentionResultsFor(undefined);
|
|
58
|
+
} });
|
|
47
59
|
return () => { cancelled = true; };
|
|
48
|
-
}, [mentionContext?.token, mentionContext?.start, mentionContext?.end]);
|
|
60
|
+
}, [mentionContext?.token, mentionContext?.start, mentionContext?.end, getMentionSuggestions]);
|
|
49
61
|
const inMentionMode = !!detectedMention;
|
|
50
|
-
const mentionList = inMentionMode ? mentionSuggestions : [];
|
|
62
|
+
const mentionList = inMentionMode && mentionResultsFor === mentionTokenKey ? mentionSuggestions : [];
|
|
51
63
|
const activeMentionIndex = Math.min(mentionSelectedIndex, Math.max(0, mentionList.length - 1));
|
|
52
64
|
const activeSuggestionIndex = Math.min(selectedSuggestionIndex, Math.max(0, filteredSuggestions.length - 1));
|
|
53
65
|
const activeSuggestion = inMentionMode ? mentionList[activeMentionIndex] : filteredSuggestions[activeSuggestionIndex];
|