@ywldan/kiro 0.2.12 → 0.3.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/README.md CHANGED
@@ -120,6 +120,16 @@ kiro update # npm install -g @ywldan/kiro@latest
120
120
 
121
121
  `check` exits `0` when current, `1` when an update exists, and `2` when the registry cannot be reached. `update` prints npm's output and needs the permissions of a global install.
122
122
 
123
+ ### Diagnostics
124
+
125
+ ```bash
126
+ kiro doctor # config, key storage, and endpoint checks
127
+ kiro doctor --offline # skip the network checks
128
+ kiro doctor --test # also send a small chat completion
129
+ ```
130
+
131
+ `doctor` checks the Node version, the config file, `.env` permissions, the active profile's key, and `GET /models`. Each line is marked `ok`, `warn`, `fail`, or `skip`, with a suggested fix when something is wrong. It never prints a key. Exit code is `0` when no check fails and `1` otherwise. `--profile <name>` inspects another profile. A missing `GET /models` is only a warning, because some servers do not implement it.
132
+
123
133
  ### Where keys live
124
134
 
125
135
  `config.json` stores only `apiKeyEnv`, the name of a variable. Values live in the environment or in `~/.kiro/.env`:
@@ -235,6 +245,7 @@ kiro [options]
235
245
 
236
246
  kiro check Compare the installed version with the latest on npm
237
247
  kiro update Install the latest version from npm globally
248
+ kiro doctor Check Node, config, key storage, and the active endpoint
238
249
  ```
239
250
 
240
251
  `--flag=value` works too. CLI overrides last for the current process only.
@@ -262,6 +273,7 @@ Exit codes: `0` success, `1` model/tool/session error, `2` usage error, `130` ca
262
273
  | Key | Action |
263
274
  | --- | --- |
264
275
  | `Enter` | Send the prompt, or run the highlighted `/` command |
276
+ | `Ctrl+J`, `Alt+Enter`, or `\` + Enter | Start a new line without sending |
265
277
  | `Ctrl+C` | Press twice to exit; while a turn runs, the first press cancels it |
266
278
  | `PgUp` / `PgDn` | Scroll the history (the wheel works too, unless you pass `--no-mouse`) |
267
279
  | `Ctrl+O` | Expand or collapse the full output of the most recent tool call |
@@ -274,6 +286,10 @@ Exit codes: `0` success, `1` model/tool/session error, `2` usage error, `130` ca
274
286
  | `Ctrl+W` | Delete the previous word |
275
287
  | Left / Right / Home / End | Move the cursor |
276
288
 
289
+ The input grows to six rows and scrolls with the cursor. Text pasted from another window keeps its line breaks and is not sent until you press Enter.
290
+
291
+ Type `@` to pick a file from the project. The list respects `.gitignore` and skips `node_modules`, `.git`, `dist`, and `build`. Use `↑`/`↓` to move, `Tab` or `Enter` to insert the path, and `Esc` to close the list without clearing the prompt. Names with spaces are inserted quoted.
292
+
277
293
  The status bar shows the profile, model, working directory, context meter (`ctx 42k/128k`), queued message count, and state (`ready`, `thinking…`, `replying…`, `running <tool>…`, `approval needed`, `cancelling…`, `Ctrl+C again to quit`). Long profile names are shortened in the middle. On wide terminals the context meter moves into the Usage card.
278
294
 
279
295
  You can type while the agent works. The prompt is queued, shown in the transcript, and runs when the current turn ends; the status bar shows `N queued`. Ctrl+C clears the queue with the running turn, and slash commands queue the same way.
@@ -484,6 +500,7 @@ test/
484
500
 
485
501
  - Only the `openai` provider type. Anthropic-style APIs are not supported.
486
502
  - Model discovery assumes an OpenAI-compatible `GET /models`. Endpoints without it work, but the model id must be typed manually.
503
+ - `@` lists files only and stops at 50,000 paths; directories and ignored files are not offered.
487
504
  - Removing a profile leaves its key in `~/.kiro/.env`; there is no command that deletes stored secrets.
488
505
  - No sub-agents, MCP, plugins, web search, image input, themes, or git integration.
489
506
  - Sessions are single-process and stored as plaintext JSON. There is no delete or rename command and no cross-directory session browser; `/export` writes a Markdown transcript you can keep.
@@ -43,6 +43,7 @@ export async function buildSystemPrompt(cwd) {
43
43
  '- Use apply_patch for coordinated changes across multiple files, or when you already have a unified diff. Patches are validated before anything is written.',
44
44
  '- Use write_file only for new files or complete rewrites.',
45
45
  '- All file paths are resolved relative to the working directory. Paths escaping it require user approval.',
46
+ '- A path written as @path in a user message points at a file in the working directory. Read it with read_file before relying on its contents.',
46
47
  '- Prefer run_command for builds, tests, and quick checks so you can verify your work. Commands run in the working directory.',
47
48
  '- Tool output may be truncated. Use read_file offsets, narrower grep patterns/globs, or smaller result limits if you need more detail.',
48
49
  '- If a tool returns an error, read it carefully and adjust; edit_file/multi_edit errors include a hint about the closest line or whitespace mismatch.',
package/dist/doctor.js ADDED
@@ -0,0 +1,251 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { stat } from 'node:fs/promises';
3
+ import { configPath, ConfigError, loadConfig, } from './config.js';
4
+ import { envPath, keyStatus, loadEnvFile } from './env.js';
5
+ import { discoverModels, testConnection } from './model/discovery.js';
6
+ import { redactSecrets, registerSecretEnv } from './secrets.js';
7
+ import { formatDuration } from './ui/text.js';
8
+ import { VERSION } from './version.js';
9
+ const DOCTOR_HELP = `Kiro doctor
10
+
11
+ Usage:
12
+ kiro doctor [options]
13
+
14
+ Checks the Node version, config file, where the key is stored, and the active
15
+ endpoint. Prints one line per check and exits 1 when a check fails.
16
+
17
+ Options:
18
+ --profile <name> inspect a profile other than the active one
19
+ --offline skip the network checks
20
+ --test send a small chat completion to verify the key and model
21
+ -h, --help show this help
22
+ `;
23
+ class DoctorUsageError extends Error {
24
+ }
25
+ function parseOptions(argv) {
26
+ const options = { offline: false, test: false, help: false };
27
+ for (let index = 0; index < argv.length; index++) {
28
+ const arg = argv[index];
29
+ if (arg === '-h' || arg === '--help') {
30
+ options.help = true;
31
+ continue;
32
+ }
33
+ if (arg === '--offline') {
34
+ options.offline = true;
35
+ continue;
36
+ }
37
+ if (arg === '--test') {
38
+ options.test = true;
39
+ continue;
40
+ }
41
+ if (arg === '--profile' || arg.startsWith('--profile=')) {
42
+ const value = arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : argv[++index];
43
+ if (!value)
44
+ throw new DoctorUsageError('Option --profile requires a value.');
45
+ options.profile = value;
46
+ continue;
47
+ }
48
+ throw new DoctorUsageError(`Unknown option: ${arg}`);
49
+ }
50
+ return options;
51
+ }
52
+ function nodeCheck() {
53
+ const major = Number(process.versions.node.split('.')[0]);
54
+ const text = `Node v${process.versions.node} (requires >= 20)`;
55
+ return major >= 20
56
+ ? { level: 'ok', text }
57
+ : {
58
+ level: 'fail',
59
+ text,
60
+ hint: 'Upgrade Node to 20 or newer, then run kiro again.',
61
+ };
62
+ }
63
+ async function configChecks(profileName) {
64
+ const file = configPath();
65
+ if (!existsSync(file)) {
66
+ return {
67
+ checks: [
68
+ {
69
+ level: 'fail',
70
+ text: `Config ${file} does not exist`,
71
+ hint: 'Run "kiro model" to create a profile.',
72
+ },
73
+ ],
74
+ };
75
+ }
76
+ let config;
77
+ try {
78
+ ({ config } = await loadConfig());
79
+ }
80
+ catch (error) {
81
+ return {
82
+ checks: [
83
+ {
84
+ level: 'fail',
85
+ text: `Config ${file} is invalid`,
86
+ hint: error instanceof ConfigError ? error.message : String(error),
87
+ },
88
+ ],
89
+ };
90
+ }
91
+ const checks = [{ level: 'ok', text: `Config ${file}` }];
92
+ const name = profileName ?? config.activeProfile;
93
+ const profile = config.profiles[name];
94
+ if (!profile) {
95
+ checks.push({
96
+ level: 'fail',
97
+ text: `Profile "${name}" is not configured`,
98
+ hint: `Available profiles: ${Object.keys(config.profiles).join(', ')}.`,
99
+ });
100
+ return { checks };
101
+ }
102
+ checks.push({
103
+ level: 'ok',
104
+ text: `Profile ${name}: ${profile.model} @ ${profile.baseUrl}`,
105
+ });
106
+ const status = keyStatus(profile);
107
+ if (profile.apiKeyEnv && !process.env[profile.apiKeyEnv]) {
108
+ checks.push({
109
+ level: 'fail',
110
+ text: `Key ${status}`,
111
+ hint: `Store it with "kiro model" (Edit a model) or export ${profile.apiKeyEnv}=...`,
112
+ });
113
+ }
114
+ else {
115
+ checks.push({ level: 'ok', text: `Key ${status}` });
116
+ }
117
+ const apiKey = profile.apiKeyEnv ? process.env[profile.apiKeyEnv] : undefined;
118
+ if (profile.apiKeyEnv)
119
+ registerSecretEnv(profile.apiKeyEnv, apiKey, true);
120
+ return { checks, profile, apiKey };
121
+ }
122
+ async function envCheck() {
123
+ const file = envPath();
124
+ let missing = false;
125
+ try {
126
+ const result = await loadEnvFile();
127
+ missing = result.missing;
128
+ }
129
+ catch (error) {
130
+ return {
131
+ level: 'fail',
132
+ text: `Key file ${file} could not be read`,
133
+ hint: error.message,
134
+ };
135
+ }
136
+ if (missing) {
137
+ return {
138
+ level: 'warn',
139
+ text: `Key file ${file} does not exist`,
140
+ hint: 'Keys can still come from the environment. Run "kiro model" to store one.',
141
+ };
142
+ }
143
+ if (process.platform !== 'win32') {
144
+ try {
145
+ const mode = (await stat(file)).mode & 0o777;
146
+ if ((mode & 0o077) !== 0) {
147
+ return {
148
+ level: 'warn',
149
+ text: `Key file ${file} is readable by other users (mode ${mode.toString(8)})`,
150
+ hint: `Run: chmod 600 ${file}`,
151
+ };
152
+ }
153
+ }
154
+ catch (error) {
155
+ return {
156
+ level: 'fail',
157
+ text: `Key file ${file} could not be inspected`,
158
+ hint: error.message,
159
+ };
160
+ }
161
+ }
162
+ return { level: 'ok', text: `Key file ${file}` };
163
+ }
164
+ async function networkChecks(profile, apiKey, test) {
165
+ const checks = [];
166
+ const started = performance.now();
167
+ const result = await discoverModels({
168
+ baseUrl: profile.baseUrl,
169
+ apiKey,
170
+ timeoutMs: 5000,
171
+ });
172
+ const latency = formatDuration(Math.max(0, Math.round(performance.now() - started)));
173
+ if (!result.ok) {
174
+ const transient = result.status === 404 || result.status === 429;
175
+ checks.push({
176
+ level: transient ? 'warn' : 'fail',
177
+ text: redactSecrets(result.message),
178
+ hint: result.status === 404
179
+ ? 'Some servers do not implement GET /models. The profile can still work.'
180
+ : undefined,
181
+ });
182
+ return checks;
183
+ }
184
+ checks.push({
185
+ level: 'ok',
186
+ text: `GET ${result.url} returned ${result.models.length} model${result.models.length === 1 ? '' : 's'} in ${latency}`,
187
+ });
188
+ if (!result.models.includes(profile.model)) {
189
+ checks.push({
190
+ level: 'warn',
191
+ text: `Model "${profile.model}" is not in the endpoint's list`,
192
+ hint: 'Check the model id; some servers hide models from /models.',
193
+ });
194
+ }
195
+ if (test) {
196
+ const tested = await testConnection(profile, apiKey);
197
+ checks.push({
198
+ level: tested.ok ? 'ok' : 'fail',
199
+ text: redactSecrets(tested.message),
200
+ });
201
+ }
202
+ return checks;
203
+ }
204
+ function printChecks(checks) {
205
+ for (const check of checks) {
206
+ process.stdout.write(`${check.level.padEnd(4)} ${redactSecrets(check.text)}\n`);
207
+ if (check.hint) {
208
+ process.stdout.write(` ${redactSecrets(check.hint)}\n`);
209
+ }
210
+ }
211
+ }
212
+ export async function runDoctor(argv) {
213
+ let options;
214
+ try {
215
+ options = parseOptions(argv);
216
+ }
217
+ catch (error) {
218
+ if (error instanceof DoctorUsageError) {
219
+ console.error(`Kiro doctor: ${error.message}`);
220
+ console.error('Run "kiro doctor --help" for usage.');
221
+ return 2;
222
+ }
223
+ throw error;
224
+ }
225
+ if (options.help) {
226
+ process.stdout.write(DOCTOR_HELP);
227
+ return 0;
228
+ }
229
+ if (options.offline && options.test) {
230
+ console.error('Kiro doctor: --test needs the network; drop --offline or --test.');
231
+ return 2;
232
+ }
233
+ const checks = [nodeCheck()];
234
+ const keyFile = await envCheck();
235
+ const configResult = await configChecks(options.profile);
236
+ checks.push(...configResult.checks);
237
+ if (configResult.profile)
238
+ checks.push(keyFile);
239
+ if (configResult.profile) {
240
+ if (options.offline) {
241
+ checks.push({ level: 'skip', text: 'Network checks skipped (--offline)' });
242
+ }
243
+ else {
244
+ checks.push(...(await networkChecks(configResult.profile, configResult.apiKey, options.test)));
245
+ }
246
+ }
247
+ process.stdout.write(`Kiro ${VERSION} doctor\n\n`);
248
+ printChecks(checks);
249
+ return checks.some((check) => check.level === 'fail') ? 1 : 0;
250
+ }
251
+ //# sourceMappingURL=doctor.js.map
package/dist/index.js CHANGED
@@ -12,11 +12,13 @@ import { latestSession, loadSession } from './sessions.js';
12
12
  import { MOUSE_OFF } from './ui/mouse.js';
13
13
  import { App } from './ui/App.js';
14
14
  import { runCheck, runUpdate } from './update.js';
15
+ import { runDoctor } from './doctor.js';
15
16
  import { VERSION } from './version.js';
16
17
  const HELP = `Kiro: a small terminal coding agent
17
18
 
18
19
  Usage: kiro [options]
19
20
  kiro model [command]
21
+ kiro doctor [options]
20
22
 
21
23
  Options:
22
24
  --profile <name> Use a profile from ~/.kiro/config.json
@@ -50,6 +52,9 @@ Update commands:
50
52
  kiro check Compare the installed version with the latest on npm
51
53
  kiro update Install the latest version from npm globally
52
54
 
55
+ Diagnostics:
56
+ kiro doctor Check Node, config, key storage, and the active endpoint
57
+
53
58
  Config: ~/.kiro/config.json (created with a template on first run)
54
59
  Keys: ~/.kiro/.env (mode 0600), or the environment variable named by "apiKeyEnv".
55
60
  Sessions: ~/.kiro/sessions (one directory per working directory)
@@ -201,6 +206,10 @@ async function main() {
201
206
  process.exitCode = await runUpdate();
202
207
  return;
203
208
  }
209
+ if (rawArgs[0] === 'doctor') {
210
+ process.exitCode = await runDoctor(rawArgs.slice(1));
211
+ return;
212
+ }
204
213
  let options;
205
214
  try {
206
215
  options = parseArgs(rawArgs);
@@ -1,72 +1,14 @@
1
1
  import { spawn } from 'node:child_process';
2
- import { readFile, readdir, stat } from 'node:fs/promises';
2
+ import { readFile, stat } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { denied, ok, toolError } from './types.js';
5
5
  import { matchGlob } from './glob.js';
6
- import { isIgnored, parseIgnoreFile } from './ignore.js';
7
6
  import { booleanArg, displayPath, integerArg, resolvePath, stringArg } from './paths.js';
7
+ import { ALWAYS_SKIP, walkTree } from './walk.js';
8
8
  const GLOB_LIMIT = 200;
9
- const MAX_WALK_ENTRIES = 200_000;
10
9
  const MAX_GREP_FILE_BYTES = 2 * 1024 * 1024;
11
10
  const MAX_GREP_LINE_CHARS = 500;
12
11
  const MAX_CAPTURE_CHARS = 4_000_000;
13
- const ALWAYS_SKIP = new Set(['node_modules', '.git', 'dist', 'build']);
14
- async function readIgnoreRules(dirAbs, baseRel) {
15
- try {
16
- return parseIgnoreFile(await readFile(path.join(dirAbs, '.gitignore'), 'utf8'), baseRel);
17
- }
18
- catch {
19
- return [];
20
- }
21
- }
22
- /** Depth-first walk that honours .gitignore and always skips heavy directories. */
23
- async function walkTree(options) {
24
- const { cwd, rootAbs, signal, visit } = options;
25
- const rootRel = path.relative(cwd, rootAbs).split(path.sep).join('/');
26
- let visited = 0;
27
- let stopped = false;
28
- const visitDir = async (dirAbs, relDir, inherited) => {
29
- if (stopped || signal.aborted)
30
- return;
31
- const rules = [...inherited, ...(await readIgnoreRules(dirAbs, relDir))];
32
- let entries;
33
- try {
34
- entries = await readdir(dirAbs, { withFileTypes: true });
35
- }
36
- catch {
37
- return;
38
- }
39
- entries.sort((left, right) => left.name.localeCompare(right.name));
40
- for (const entry of entries) {
41
- if (stopped || signal.aborted)
42
- return;
43
- if (entry.isSymbolicLink())
44
- continue;
45
- const rel = relDir ? `${relDir}/${entry.name}` : entry.name;
46
- const isDir = entry.isDirectory();
47
- if (isDir && ALWAYS_SKIP.has(entry.name))
48
- continue;
49
- if (isIgnored(rules, rel, isDir))
50
- continue;
51
- visited++;
52
- if (visited > MAX_WALK_ENTRIES) {
53
- stopped = true;
54
- return;
55
- }
56
- const abs = path.join(dirAbs, entry.name);
57
- if ((await visit({ abs, rel, isDir })) === false) {
58
- stopped = true;
59
- return;
60
- }
61
- if (isDir) {
62
- await visitDir(abs, rel, rules);
63
- if (stopped)
64
- return;
65
- }
66
- }
67
- };
68
- await visitDir(rootAbs, rootRel, []);
69
- }
70
12
  const globTool = {
71
13
  readOnly: true,
72
14
  definition: {
@@ -0,0 +1,62 @@
1
+ import { readFile, readdir } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { isIgnored, parseIgnoreFile } from './ignore.js';
4
+ export const MAX_WALK_ENTRIES = 200_000;
5
+ export const ALWAYS_SKIP = new Set(['node_modules', '.git', 'dist', 'build']);
6
+ async function readIgnoreRules(dirAbs, baseRel) {
7
+ try {
8
+ return parseIgnoreFile(await readFile(path.join(dirAbs, '.gitignore'), 'utf8'), baseRel);
9
+ }
10
+ catch {
11
+ return [];
12
+ }
13
+ }
14
+ /** Depth-first walk that honours .gitignore and always skips heavy directories. */
15
+ export async function walkTree(options) {
16
+ const { cwd, rootAbs, signal, visit } = options;
17
+ const rootRel = path.relative(cwd, rootAbs).split(path.sep).join('/');
18
+ let visited = 0;
19
+ let stopped = false;
20
+ const visitDir = async (dirAbs, relDir, inherited) => {
21
+ if (stopped || signal.aborted)
22
+ return;
23
+ const rules = [...inherited, ...(await readIgnoreRules(dirAbs, relDir))];
24
+ let entries;
25
+ try {
26
+ entries = await readdir(dirAbs, { withFileTypes: true });
27
+ }
28
+ catch {
29
+ return;
30
+ }
31
+ entries.sort((left, right) => left.name.localeCompare(right.name));
32
+ for (const entry of entries) {
33
+ if (stopped || signal.aborted)
34
+ return;
35
+ if (entry.isSymbolicLink())
36
+ continue;
37
+ const rel = relDir ? `${relDir}/${entry.name}` : entry.name;
38
+ const isDir = entry.isDirectory();
39
+ if (isDir && ALWAYS_SKIP.has(entry.name))
40
+ continue;
41
+ if (isIgnored(rules, rel, isDir))
42
+ continue;
43
+ visited++;
44
+ if (visited > MAX_WALK_ENTRIES) {
45
+ stopped = true;
46
+ return;
47
+ }
48
+ const abs = path.join(dirAbs, entry.name);
49
+ if ((await visit({ abs, rel, isDir })) === false) {
50
+ stopped = true;
51
+ return;
52
+ }
53
+ if (isDir) {
54
+ await visitDir(abs, rel, rules);
55
+ if (stopped)
56
+ return;
57
+ }
58
+ }
59
+ };
60
+ await visitDir(rootAbs, rootRel, []);
61
+ }
62
+ //# sourceMappingURL=walk.js.map
package/dist/ui/App.js CHANGED
@@ -17,6 +17,7 @@ import { ApprovalPrompt } from './ApprovalPrompt.js';
17
17
  import { ApprovalPolicy } from './approval-policy.js';
18
18
  import { builtinCommandNames, buildSkillCommands, SLASH_COMMANDS, slashHelpLines, } from './commands.js';
19
19
  import { defaultExportPath, renderTranscriptMarkdown } from './export.js';
20
+ import { listProjectFiles } from './file-index.js';
20
21
  import { buildResumedView } from './history.js';
21
22
  import { Input } from './Input.js';
22
23
  import { MessageList } from './MessageList.js';
@@ -88,6 +89,17 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
88
89
  const [usageCardEnabled, setUsageCardEnabled] = useState(true);
89
90
  const [mouseOn, setMouseOn] = useState(mouseEnabled);
90
91
  const [expandedToolId, setExpandedToolId] = useState(null);
92
+ const [inputRows, setInputRows] = useState(1);
93
+ const fileIndexRef = useRef(null);
94
+ const loadFileIndex = useCallback(async () => {
95
+ const cached = fileIndexRef.current;
96
+ if (cached && cached.cwd === cwd && Date.now() - cached.builtAt < 5000) {
97
+ return cached.files;
98
+ }
99
+ const files = await listProjectFiles(cwd);
100
+ fileIndexRef.current = { cwd, files, builtAt: Date.now() };
101
+ return files;
102
+ }, [cwd]);
91
103
  const messagesRef = useRef((initialSession?.messages ?? []).filter((message) => message.role !== 'system'));
92
104
  const usageRef = useRef(null);
93
105
  const roundStartedAtRef = useRef(0);
@@ -1254,6 +1266,7 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
1254
1266
  const trimmed = value.trim();
1255
1267
  if (!trimmed)
1256
1268
  return;
1269
+ const isCommand = trimmed.startsWith('/') && !trimmed.includes('\n');
1257
1270
  if (wizardActiveRef.current || transitioningRef.current) {
1258
1271
  // The wizard owns the keyboard; ignore stray input.
1259
1272
  return;
@@ -1262,7 +1275,7 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
1262
1275
  // Type-ahead: the message runs as soon as the current turn finishes.
1263
1276
  queuedRef.current.push(trimmed);
1264
1277
  setQueuedCount(queuedRef.current.length);
1265
- if (!trimmed.startsWith('/')) {
1278
+ if (!isCommand) {
1266
1279
  setItems((current) => [
1267
1280
  ...current,
1268
1281
  { kind: 'user', id: nextItemIdRef.current++, text: trimmed },
@@ -1271,7 +1284,7 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
1271
1284
  addNotice('muted', 'Queued. It runs after the current turn; PgUp/PgDn still scrolls the transcript meanwhile.');
1272
1285
  return;
1273
1286
  }
1274
- if (trimmed.startsWith('/')) {
1287
+ if (isCommand) {
1275
1288
  void handleCommand(trimmed).finally(() => drainQueueRef.current?.());
1276
1289
  return;
1277
1290
  }
@@ -1370,10 +1383,15 @@ export function App({ config, baseConfig, overrides, configPath, configCreated,
1370
1383
  const contextWindow = contextWindowFor(activeProfile);
1371
1384
  const pickerPopup = pickerOpen && !pendingApproval ? pickerPopupRect(columns, rows) : null;
1372
1385
  const pickerInline = pickerOpen && !pendingApproval && pickerPopup === null;
1373
- const viewportHeight = Math.max(3, rows - 5 - (pendingApproval ? 12 : 0) - (pickerInline ? PICKER_INLINE_ROWS : 0));
1386
+ const extraInputRows = pendingApproval || pickerInline ? 0 : Math.max(0, inputRows - 1);
1387
+ const viewportHeight = Math.max(3, rows -
1388
+ 5 -
1389
+ extraInputRows -
1390
+ (pendingApproval ? 12 : 0) -
1391
+ (pickerInline ? PICKER_INLINE_ROWS : 0));
1374
1392
  const showUsageCard = usageCardEnabled && shouldShowUsageCard(columns, viewportHeight);
1375
1393
  const chatWidth = showUsageCard ? Math.max(40, width - USAGE_CARD_WIDTH - USAGE_CARD_GAP) : width;
1376
- return (_jsxs(Box, { flexDirection: "column", width: columns, paddingX: 1, children: [_jsxs(Box, { flexDirection: "row", alignItems: "flex-end", width: width, children: [_jsx(MessageList, { items: items, width: chatWidth, height: viewportHeight, resetSignal: resetSignal, expandedToolId: expandedToolId, palette: palette, interactive: !pendingApproval && !pickerOpen && !wizardActive && wizardPrompt === null }), showUsageCard ? (_jsx(Box, { marginLeft: USAGE_CARD_GAP, flexShrink: 0, children: _jsx(UsageCard, { usage: sessionUsage, contextTokens: contextTokens, contextWindow: contextWindow, contextEstimated: usageRef.current === null, lastReply: lastReply, busy: busy }) })) : null] }), pendingApproval ? (_jsx(ApprovalPrompt, { request: pendingApproval, width: width, onDecision: resolveApproval })) : pickerInline ? (_jsx(ModelPicker, { config: runtimeConfig, activeProfile: profileName, width: width, onSelect: (name, model) => void selectModel(name, model), onRefresh: refreshProfileModels, onCancel: () => setPickerOpen(false) })) : (_jsx(Input, { disabled: pickerOpen, width: width, mask: wizardPrompt?.mask, allowEmpty: wizardPrompt?.allowEmpty, history: wizardPrompt || wizardActive ? undefined : promptHistory, slashCommands: [...SLASH_COMMANDS, ...skillCommands], onPaletteChange: setPalette, placeholder: pickerOpen
1394
+ return (_jsxs(Box, { flexDirection: "column", width: columns, paddingX: 1, children: [_jsxs(Box, { flexDirection: "row", alignItems: "flex-end", width: width, children: [_jsx(MessageList, { items: items, width: chatWidth, height: viewportHeight, resetSignal: resetSignal, expandedToolId: expandedToolId, palette: palette, interactive: !pendingApproval && !pickerOpen && !wizardActive && wizardPrompt === null }), showUsageCard ? (_jsx(Box, { marginLeft: USAGE_CARD_GAP, flexShrink: 0, children: _jsx(UsageCard, { usage: sessionUsage, contextTokens: contextTokens, contextWindow: contextWindow, contextEstimated: usageRef.current === null, lastReply: lastReply, busy: busy }) })) : null] }), pendingApproval ? (_jsx(ApprovalPrompt, { request: pendingApproval, width: width, onDecision: resolveApproval })) : pickerInline ? (_jsx(ModelPicker, { config: runtimeConfig, activeProfile: profileName, width: width, onSelect: (name, model) => void selectModel(name, model), onRefresh: refreshProfileModels, onCancel: () => setPickerOpen(false) })) : (_jsx(Input, { disabled: pickerOpen, width: width, mask: wizardPrompt?.mask, allowEmpty: wizardPrompt?.allowEmpty, fileMenu: !wizardActive && !wizardPrompt, loadFiles: loadFileIndex, maxRows: Math.max(1, Math.min(6, rows - 9)), history: wizardPrompt || wizardActive ? undefined : promptHistory, slashCommands: [...SLASH_COMMANDS, ...skillCommands], onPaletteChange: setPalette, onHeightChange: setInputRows, placeholder: pickerOpen
1377
1395
  ? 'Model picker open · Esc to close'
1378
1396
  : wizardPrompt
1379
1397
  ? wizardPrompt.defaultValue && !wizardPrompt.mask
package/dist/ui/Input.js CHANGED
@@ -1,19 +1,27 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useEffect, useRef, useState } from 'react';
3
3
  import { Box, Text, useInput, useStdin } from 'ink';
4
- import stringWidth from 'string-width';
5
4
  import { filterSlashCommands } from './commands.js';
5
+ import { filterFiles } from './file-index.js';
6
+ import { mentionAt, mentionNearby, mentionText } from './mention.js';
6
7
  import { isMouseSequence } from './mouse.js';
7
- import { applyInputOps, parseEditSequence, parseInputChunk, } from './text.js';
8
+ import { applyInputOps, cursorLineIndex, feedPaste, layoutInput, parseEditSequence, parseInputChunk, } from './text.js';
8
9
  const MAX_INPUT_CHARS = 20_000;
9
10
  const MAX_MENU_ROWS = 6;
10
- export function Input({ disabled, placeholder, width, mask = false, allowEmpty = false, slashMenu = true, slashCommands, history, onSubmit, onCancel, onPaletteChange, }) {
11
+ const MAX_VISIBLE_LINES = 6;
12
+ const PASTE_ON = '\x1b[?2004h';
13
+ const PASTE_OFF = '\x1b[?2004l';
14
+ export function Input({ disabled, placeholder, width, mask = false, allowEmpty = false, slashMenu = true, fileMenu = true, loadFiles, maxRows = MAX_VISIBLE_LINES, slashCommands, history, onSubmit, onCancel, onHeightChange, onPaletteChange, }) {
11
15
  const { stdin } = useStdin();
12
16
  const [state, setState] = useState({ chars: [], cursor: 0 });
13
17
  const [selected, setSelected] = useState(0);
14
18
  const [historyIndex, setHistoryIndex] = useState(null);
19
+ const [mentionStart, setMentionStart] = useState(null);
20
+ const [files, setFiles] = useState(null);
21
+ const [filesLoading, setFilesLoading] = useState(false);
15
22
  const stateRef = useRef(state);
16
23
  stateRef.current = state;
24
+ const pasteRef = useRef({ open: false, buffer: '', pending: '' });
17
25
  const text = state.chars.join('');
18
26
  const recalled = historyIndex !== null ? (history?.[historyIndex] ?? null) : null;
19
27
  useEffect(() => {
@@ -22,21 +30,89 @@ export function Input({ disabled, placeholder, width, mask = false, allowEmpty =
22
30
  setHistoryIndex(null);
23
31
  }
24
32
  }, [historyIndex, recalled, text]);
25
- const matches = slashMenu && !mask && !disabled ? filterSlashCommands(text, slashCommands) : [];
33
+ const matches = slashMenu && !mask && !disabled && !text.includes('\n')
34
+ ? filterSlashCommands(text, slashCommands)
35
+ : [];
26
36
  const menuOpen = matches.length > 0;
27
37
  const activeIndex = Math.min(selected, Math.max(0, matches.length - 1));
28
38
  const menuStart = Math.max(0, Math.min(activeIndex - Math.floor(MAX_MENU_ROWS / 2), matches.length - MAX_MENU_ROWS));
29
39
  const visibleCommands = matches.slice(menuStart, menuStart + MAX_MENU_ROWS);
40
+ const mention = fileMenu && !mask && !disabled && mentionStart !== null && !text.startsWith('/')
41
+ ? mentionAt(state.chars, state.cursor, mentionStart)
42
+ : null;
43
+ const mentionOpen = mention !== null;
44
+ const mentionQuery = mention?.query ?? '';
45
+ const fileMatches = mention && files ? filterFiles(files, mentionQuery) : [];
46
+ const fileActive = Math.min(selected, Math.max(0, fileMatches.length - 1));
47
+ const fileStart = Math.max(0, Math.min(fileActive - Math.floor(MAX_MENU_ROWS / 2), fileMatches.length - MAX_MENU_ROWS));
48
+ const visibleFiles = fileMatches.slice(fileStart, fileStart + MAX_MENU_ROWS);
49
+ const filesHeader = filesLoading && files === null
50
+ ? 'files · indexing…'
51
+ : fileMatches.length === 0
52
+ ? `files · no matches for "${mentionQuery}" · Esc to close`
53
+ : `files ${fileStart + 1}-${fileStart + visibleFiles.length} of ${fileMatches.length} · ↑/↓ move · Tab/Enter insert · Esc close`;
54
+ const fileSignature = `${mentionOpen}|${mentionQuery}|${filesLoading}|${fileStart}|${fileActive}|${visibleFiles.join('\u0000')}`;
30
55
  useEffect(() => {
31
56
  setSelected(0);
32
57
  }, [text]);
33
58
  useEffect(() => {
34
- onPaletteChange?.(menuOpen
35
- ? { commands: visibleCommands, activeIndex: Math.max(0, activeIndex - menuStart) }
36
- : null);
37
- // visibleCommands is derived from text, activeIndex and menuStart.
59
+ if (!mentionOpen || !loadFiles)
60
+ return;
61
+ let cancelled = false;
62
+ setFilesLoading(true);
63
+ loadFiles()
64
+ .then((list) => {
65
+ if (!cancelled)
66
+ setFiles(list);
67
+ })
68
+ .catch(() => {
69
+ if (!cancelled)
70
+ setFiles([]);
71
+ })
72
+ .finally(() => {
73
+ if (!cancelled)
74
+ setFilesLoading(false);
75
+ });
76
+ return () => {
77
+ cancelled = true;
78
+ };
79
+ }, [mentionOpen, loadFiles]);
80
+ useEffect(() => {
81
+ if (mentionStart !== null && !mentionAt(state.chars, state.cursor, mentionStart)) {
82
+ setMentionStart(null);
83
+ }
84
+ }, [state, mentionStart]);
85
+ useEffect(() => {
86
+ if (menuOpen) {
87
+ onPaletteChange?.({
88
+ kind: 'commands',
89
+ commands: visibleCommands,
90
+ activeIndex: Math.max(0, activeIndex - menuStart),
91
+ });
92
+ return;
93
+ }
94
+ if (mentionOpen) {
95
+ onPaletteChange?.({
96
+ kind: 'files',
97
+ files: visibleFiles,
98
+ activeIndex: Math.max(0, fileActive - fileStart),
99
+ header: filesHeader,
100
+ });
101
+ return;
102
+ }
103
+ onPaletteChange?.(null);
104
+ // visible rows are derived from text, fileSignature, and the window offsets.
38
105
  // eslint-disable-next-line react-hooks/exhaustive-deps
39
- }, [menuOpen, text, activeIndex, menuStart, onPaletteChange]);
106
+ }, [
107
+ menuOpen,
108
+ text,
109
+ activeIndex,
110
+ menuStart,
111
+ mentionOpen,
112
+ fileSignature,
113
+ filesHeader,
114
+ onPaletteChange,
115
+ ]);
40
116
  useEffect(() => () => onPaletteChange?.(null), [onPaletteChange]);
41
117
  const update = (chars, cursor) => {
42
118
  const next = { chars, cursor: Math.max(0, Math.min(cursor, chars.length)) };
@@ -89,12 +165,58 @@ export function Input({ disabled, placeholder, width, mask = false, allowEmpty =
89
165
  // deleteBackward/deleteForward only use stable setters and refs.
90
166
  // eslint-disable-next-line react-hooks/exhaustive-deps
91
167
  }, [disabled, stdin]);
168
+ useEffect(() => {
169
+ if (disabled || !process.stdout.isTTY)
170
+ return;
171
+ process.stdout.write(PASTE_ON);
172
+ return () => {
173
+ process.stdout.write(PASTE_OFF);
174
+ };
175
+ }, [disabled]);
92
176
  useInput((input, key) => {
93
177
  const { chars, cursor } = stateRef.current;
94
178
  if (key.backspace || key.delete)
95
179
  return; // handled from raw stdin above
96
180
  if (isMouseSequence(input))
97
181
  return;
182
+ const pasted = feedPaste(pasteRef.current, input);
183
+ pasteRef.current = pasted.state;
184
+ if (pasted.consumed) {
185
+ if (pasted.text !== null) {
186
+ const inserted = mask ? pasted.text.replace(/\n/g, ' ') : pasted.text;
187
+ const applied = applyInputOps({ chars, cursor }, [{ type: 'insert', text: inserted }], MAX_INPUT_CHARS);
188
+ setMentionStart(null);
189
+ update(applied.state.chars, applied.state.cursor);
190
+ }
191
+ return;
192
+ }
193
+ if (mention) {
194
+ if (key.upArrow) {
195
+ if (fileMatches.length > 0) {
196
+ setSelected((fileActive - 1 + fileMatches.length) % fileMatches.length);
197
+ }
198
+ return;
199
+ }
200
+ if (key.downArrow) {
201
+ if (fileMatches.length > 0) {
202
+ setSelected((fileActive + 1) % fileMatches.length);
203
+ }
204
+ return;
205
+ }
206
+ if ((key.tab || key.return) && fileMatches.length > 0) {
207
+ const file = fileMatches[fileActive];
208
+ const inserted = Array.from(`${mentionText(file)} `);
209
+ const next = [
210
+ ...chars.slice(0, mention.start),
211
+ ...inserted,
212
+ ...chars.slice(mention.end),
213
+ ];
214
+ update(next, mention.start + inserted.length);
215
+ setMentionStart(null);
216
+ setSelected(0);
217
+ return;
218
+ }
219
+ }
98
220
  if (menuOpen) {
99
221
  if (key.upArrow) {
100
222
  setSelected((activeIndex - 1 + matches.length) % matches.length);
@@ -147,29 +269,46 @@ export function Input({ disabled, placeholder, width, mask = false, allowEmpty =
147
269
  if (key.return) {
148
270
  if (menuOpen) {
149
271
  const command = matches[activeIndex].name;
272
+ setMentionStart(null);
150
273
  update([], 0);
151
274
  setSelected(0);
152
275
  onSubmit(command);
153
276
  return;
154
277
  }
278
+ if (!mask && key.meta) {
279
+ update([...chars.slice(0, cursor), '\n', ...chars.slice(cursor)], cursor + 1);
280
+ return;
281
+ }
282
+ if (!mask && cursor > 0 && chars[cursor - 1] === '\\') {
283
+ update([...chars.slice(0, cursor - 1), '\n', ...chars.slice(cursor)], cursor);
284
+ return;
285
+ }
155
286
  const value = chars.join('');
156
287
  if (value.trim() || allowEmpty) {
288
+ setMentionStart(null);
157
289
  update([], 0);
158
290
  onSubmit(value);
159
291
  }
160
292
  return;
161
293
  }
162
294
  if (key.escape) {
295
+ if (mentionOpen) {
296
+ setMentionStart(null);
297
+ setSelected(0);
298
+ return;
299
+ }
163
300
  update([], 0);
164
301
  if (onCancel)
165
302
  onCancel();
166
303
  return;
167
304
  }
168
305
  if (key.ctrl && input === 'a') {
306
+ setMentionStart(null);
169
307
  update(chars, 0);
170
308
  return;
171
309
  }
172
310
  if (key.ctrl && input === 'e') {
311
+ setMentionStart(null);
173
312
  update(chars, chars.length);
174
313
  return;
175
314
  }
@@ -191,18 +330,22 @@ export function Input({ disabled, placeholder, width, mask = false, allowEmpty =
191
330
  return;
192
331
  }
193
332
  if (key.leftArrow) {
333
+ setMentionStart(null);
194
334
  update(chars, cursor - 1);
195
335
  return;
196
336
  }
197
337
  if (key.rightArrow) {
338
+ setMentionStart(null);
198
339
  update(chars, cursor + 1);
199
340
  return;
200
341
  }
201
342
  if (key.home) {
343
+ setMentionStart(null);
202
344
  update(chars, 0);
203
345
  return;
204
346
  }
205
347
  if (key.end) {
348
+ setMentionStart(null);
206
349
  update(chars, chars.length);
207
350
  return;
208
351
  }
@@ -210,42 +353,67 @@ export function Input({ disabled, placeholder, width, mask = false, allowEmpty =
210
353
  return;
211
354
  // Chunks that mix text with control bytes (\r, \x7f, ctrl keys) are not
212
355
  // decoded by Ink, so replay their control bytes as edits in chunk order.
213
- const ops = parseInputChunk(input);
356
+ const ops = parseInputChunk(mask ? input.replace(/\n/g, ' ') : input);
214
357
  if (ops.length === 0)
215
358
  return;
216
359
  const applied = applyInputOps({ chars, cursor }, ops, MAX_INPUT_CHARS);
217
360
  const value = applied.state.chars.join('');
218
361
  if (applied.submitted && (value.trim() || allowEmpty)) {
362
+ setMentionStart(null);
219
363
  update([], 0);
220
364
  onSubmit(value);
221
365
  return;
222
366
  }
367
+ if (!mask && fileMenu && !value.startsWith('/')) {
368
+ const opened = mentionNearby(applied.state.chars, applied.state.cursor);
369
+ if (opened !== null)
370
+ setMentionStart(opened);
371
+ }
223
372
  update(applied.state.chars, applied.state.cursor);
224
373
  }, { isActive: !disabled });
225
374
  const maxWidth = Math.max(4, width - 2);
226
375
  const { chars, cursor } = state;
227
- const displayChars = mask ? chars.map(() => '•') : chars;
228
- const charWidths = displayChars.map((char) => Math.max(1, stringWidth(char)));
229
- let start = 0;
230
- let widthToCursor = charWidths.slice(0, cursor).reduce((total, value) => total + value, 0);
231
- const cursorWidth = cursor < displayChars.length ? (charWidths[cursor] ?? 1) : 1;
232
- while (start < cursor && widthToCursor + cursorWidth > maxWidth) {
233
- widthToCursor -= charWidths[start] ?? 1;
234
- start++;
376
+ const lines = layoutInput(chars, maxWidth, mask);
377
+ const cursorIndex = cursorLineIndex(lines, cursor);
378
+ const windowSize = Math.max(1, Math.min(maxRows, MAX_VISIBLE_LINES, lines.length));
379
+ const windowStart = Math.max(0, Math.min(cursorIndex - windowSize + 1, lines.length - windowSize));
380
+ const visible = lines.slice(windowStart, windowStart + windowSize);
381
+ const hiddenAbove = windowStart > 0;
382
+ const hiddenBelow = windowStart + visible.length < lines.length;
383
+ const rows = disabled || chars.length === 0 ? 1 : visible.length;
384
+ useEffect(() => {
385
+ onHeightChange?.(rows);
386
+ }, [rows, onHeightChange]);
387
+ if (disabled) {
388
+ return (_jsxs(Box, { flexShrink: 0, children: [_jsx(Text, { color: "gray", bold: true, children: '› ' }), _jsx(Text, { dimColor: true, wrap: "truncate-end", children: placeholder })] }));
235
389
  }
236
- let end = start;
237
- let used = 0;
238
- while (end < displayChars.length) {
239
- const charWidth = charWidths[end] ?? 1;
240
- if (used + charWidth > maxWidth)
241
- break;
242
- used += charWidth;
243
- end++;
390
+ if (chars.length === 0) {
391
+ return (_jsxs(Box, { flexShrink: 0, children: [_jsx(Text, { color: "cyan", bold: true, children: '› ' }), _jsxs(Text, { wrap: "truncate-end", children: [_jsx(Text, { inverse: true, children: " " }), _jsxs(Text, { dimColor: true, children: [" ", placeholder] })] })] }));
244
392
  }
245
- const before = displayChars.slice(start, cursor).join('');
246
- const at = displayChars[cursor] ?? ' ';
247
- const after = displayChars.slice(cursor + 1, end).join('');
248
- const showPlaceholder = chars.length === 0;
249
- return (_jsxs(Box, { flexShrink: 0, children: [_jsx(Text, { color: disabled ? 'gray' : 'cyan', bold: true, children: '› ' }), disabled ? (_jsx(Text, { dimColor: true, wrap: "truncate-end", children: placeholder })) : showPlaceholder ? (_jsxs(Text, { wrap: "truncate-end", children: [_jsx(Text, { inverse: true, children: " " }), _jsxs(Text, { dimColor: true, children: [" ", placeholder] })] })) : (_jsxs(Text, { wrap: "truncate-end", children: [before, _jsx(Text, { inverse: true, children: at }), after] }))] }));
393
+ const shown = (values) => (mask ? '•'.repeat(values.length) : values.join(''));
394
+ return (_jsx(Box, { flexDirection: "column", flexShrink: 0, children: visible.map((line, offset) => {
395
+ const absolute = windowStart + offset;
396
+ const isCursor = absolute === cursorIndex;
397
+ const isFirst = absolute === 0;
398
+ const isLast = offset === visible.length - 1;
399
+ const prefix = isLast && hiddenBelow
400
+ ? '↓ '
401
+ : offset === 0 && hiddenAbove
402
+ ? '↑ '
403
+ : isFirst
404
+ ? '› '
405
+ : ' ';
406
+ const prefixColor = isFirst && !hiddenAbove ? 'cyan' : 'gray';
407
+ const before = shown(chars.slice(line.start, Math.min(cursor, line.end)));
408
+ const at = isCursor
409
+ ? cursor < line.end
410
+ ? shown([chars[cursor]])
411
+ : ' '
412
+ : '';
413
+ const after = isCursor
414
+ ? shown(chars.slice(Math.min(cursor + 1, line.end), line.end))
415
+ : '';
416
+ return (_jsxs(Box, { flexDirection: "row", children: [_jsx(Text, { color: prefixColor, dimColor: prefixColor === 'gray', bold: prefixColor === 'cyan', children: prefix }), isCursor ? (_jsxs(Text, { wrap: "truncate-end", children: [before, _jsx(Text, { inverse: true, children: at }), after] })) : (_jsx(Text, { wrap: "truncate-end", children: line.text }))] }, absolute));
417
+ }) }));
250
418
  }
251
419
  //# sourceMappingURL=Input.js.map
@@ -186,6 +186,32 @@ export function buildLines(items, width, expandedToolId = null) {
186
186
  const PALETTE_ROWS = 6;
187
187
  /** Header plus the visible command rows; padded so filtering never changes its height. */
188
188
  export function buildPaletteLines(palette, width) {
189
+ if (palette.kind === 'files') {
190
+ const header = {
191
+ prefix: ' ',
192
+ text: truncateToWidth(palette.header, width),
193
+ dim: true,
194
+ };
195
+ const rows = palette.files.slice(0, PALETTE_ROWS).map((file, index) => {
196
+ const active = index === palette.activeIndex;
197
+ const slash = file.lastIndexOf('/');
198
+ const directory = slash === -1 ? '' : file.slice(0, slash + 1);
199
+ const name = file.slice(slash + 1);
200
+ return {
201
+ prefix: active ? '› ' : ' ',
202
+ prefixColor: active ? 'cyan' : undefined,
203
+ text: '',
204
+ segments: [
205
+ { text: directory, dim: true },
206
+ { text: name, bold: active },
207
+ ],
208
+ inverse: active,
209
+ };
210
+ });
211
+ while (rows.length < PALETTE_ROWS)
212
+ rows.push({ prefix: '', text: '' });
213
+ return [header, ...rows];
214
+ }
189
215
  const header = {
190
216
  prefix: ' ',
191
217
  text: truncateToWidth('commands · ↑/↓ move · Tab complete · Enter run', width),
@@ -0,0 +1,111 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import { walkTree } from '../tools/walk.js';
4
+ const execFileAsync = promisify(execFile);
5
+ export const MAX_INDEX_FILES = 50_000;
6
+ const MAX_GIT_OUTPUT_BYTES = 20 * 1024 * 1024;
7
+ function normalize(paths) {
8
+ const unique = new Set();
9
+ for (const raw of paths) {
10
+ const path = raw.split('\\').join('/').replace(/^\.\//, '');
11
+ if (!path || path.includes('\n'))
12
+ continue;
13
+ unique.add(path);
14
+ }
15
+ return [...unique].sort((left, right) => left.localeCompare(right)).slice(0, MAX_INDEX_FILES);
16
+ }
17
+ /** Tracked and untracked files, honouring .gitignore. Null when git is unavailable or fails. */
18
+ async function gitFiles(cwd, signal) {
19
+ try {
20
+ const { stdout } = await execFileAsync('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard'], {
21
+ cwd,
22
+ timeout: 3000,
23
+ maxBuffer: MAX_GIT_OUTPUT_BYTES,
24
+ signal,
25
+ });
26
+ return normalize(stdout.split('\0'));
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ }
32
+ async function walkFiles(cwd, signal) {
33
+ const controller = new AbortController();
34
+ const onAbort = () => controller.abort();
35
+ if (signal?.aborted)
36
+ return [];
37
+ signal?.addEventListener('abort', onAbort, { once: true });
38
+ const files = [];
39
+ try {
40
+ await walkTree({
41
+ cwd,
42
+ rootAbs: cwd,
43
+ signal: controller.signal,
44
+ visit(entry) {
45
+ if (entry.isDir)
46
+ return true;
47
+ files.push(entry.rel);
48
+ return files.length < MAX_INDEX_FILES;
49
+ },
50
+ });
51
+ }
52
+ finally {
53
+ signal?.removeEventListener('abort', onAbort);
54
+ }
55
+ return normalize(files);
56
+ }
57
+ /** File list for the @ menu: git first, then a .gitignore-aware walk. */
58
+ export async function listProjectFiles(cwd, signal) {
59
+ if (signal?.aborted)
60
+ return [];
61
+ const fromGit = await gitFiles(cwd, signal);
62
+ if (fromGit !== null)
63
+ return fromGit;
64
+ return walkFiles(cwd, signal);
65
+ }
66
+ function subsequence(text, needle) {
67
+ let index = 0;
68
+ for (const char of text) {
69
+ if (char === needle[index])
70
+ index++;
71
+ if (index === needle.length)
72
+ return true;
73
+ }
74
+ return false;
75
+ }
76
+ /** Ranks paths for a mention query: basename matches first, then path matches. */
77
+ export function filterFiles(files, query, limit = 200) {
78
+ const needle = query.trim().toLowerCase();
79
+ if (!needle)
80
+ return files.slice(0, limit);
81
+ const scored = [];
82
+ for (const file of files) {
83
+ const lower = file.toLowerCase();
84
+ const base = lower.slice(lower.lastIndexOf('/') + 1);
85
+ let score = 0;
86
+ if (lower === needle)
87
+ score = 1000;
88
+ else if (base.startsWith(needle))
89
+ score = 900;
90
+ else if (base.includes(needle))
91
+ score = 800;
92
+ else if (lower.startsWith(needle))
93
+ score = 750;
94
+ else if (lower.split('/').some((segment) => segment.startsWith(needle)))
95
+ score = 700;
96
+ else if (lower.includes(needle))
97
+ score = 600;
98
+ else if (subsequence(base, needle))
99
+ score = 500;
100
+ else if (subsequence(lower, needle))
101
+ score = 400;
102
+ else
103
+ continue;
104
+ scored.push({ path: file, score });
105
+ }
106
+ scored.sort((left, right) => right.score - left.score ||
107
+ left.path.length - right.path.length ||
108
+ left.path.localeCompare(right.path));
109
+ return scored.slice(0, limit).map((entry) => entry.path);
110
+ }
111
+ //# sourceMappingURL=file-index.js.map
@@ -0,0 +1,63 @@
1
+ const BOUNDARY = /[\s([{'"]/;
2
+ /** Index of a freshly typed @ that can start a mention, or null. */
3
+ export function mentionOpeningAt(chars, cursor) {
4
+ if (cursor < 1 || chars[cursor - 1] !== '@')
5
+ return null;
6
+ if (cursor === 1)
7
+ return 0;
8
+ return BOUNDARY.test(chars[cursor - 2] ?? '') ? cursor - 1 : null;
9
+ }
10
+ /** Nearest valid mention ending at the caret, used after a typed chunk. */
11
+ export function mentionNearby(chars, cursor) {
12
+ for (let start = cursor - 1; start >= 0 && cursor - start <= 200; start--) {
13
+ const char = chars[start];
14
+ if (char === '\n')
15
+ return null;
16
+ if (char !== '@')
17
+ continue;
18
+ if (start > 0 && !BOUNDARY.test(chars[start - 1] ?? ''))
19
+ continue;
20
+ if (mentionAt(chars, cursor, start))
21
+ return start;
22
+ }
23
+ return null;
24
+ }
25
+ /** Reads the mention that starts at `start`, or null when the caret left it or it has whitespace. */
26
+ export function mentionAt(chars, cursor, start) {
27
+ if (start < 0 || start >= chars.length || chars[start] !== '@')
28
+ return null;
29
+ if (start > 0 && !BOUNDARY.test(chars[start - 1] ?? ''))
30
+ return null;
31
+ if (cursor <= start)
32
+ return null;
33
+ const quote = chars[start + 1];
34
+ if (quote === '"') {
35
+ let close = -1;
36
+ for (let index = start + 2; index < chars.length; index++) {
37
+ if (chars[index] === '"') {
38
+ close = index;
39
+ break;
40
+ }
41
+ if (chars[index] === '\n')
42
+ return null;
43
+ }
44
+ if (close !== -1 && close < cursor)
45
+ return null;
46
+ const end = close === -1 ? cursor : close + 1;
47
+ return {
48
+ start,
49
+ end,
50
+ query: chars.slice(start + 2, Math.min(cursor, end)).join(''),
51
+ quoted: true,
52
+ };
53
+ }
54
+ const query = chars.slice(start + 1, cursor).join('');
55
+ if (/[\s\n]/.test(query))
56
+ return null;
57
+ return { start, end: cursor, query, quoted: false };
58
+ }
59
+ /** Text to insert for a file path, quoting names that contain spaces. */
60
+ export function mentionText(file) {
61
+ return /[\s"]/.test(file) ? `@"${file.replace(/"/g, '\\"')}"` : `@${file}`;
62
+ }
63
+ //# sourceMappingURL=mention.js.map
package/dist/ui/text.js CHANGED
@@ -114,7 +114,7 @@ export function parseEditSequence(text) {
114
114
  }
115
115
  const clamp = (value, max) => Math.max(0, Math.min(value, max));
116
116
  const ANSI_TOKEN = new RegExp(`(${ANSI_CSI.source}|${ANSI_OSC.source})`, 'g');
117
- /** Above this chunk size a trailing newline is treated as pasted text, not Enter. */
117
+ /** Above this chunk size a trailing carriage return is treated as pasted text, not Enter. */
118
118
  const MAX_SUBMIT_CHUNK = 200;
119
119
  /**
120
120
  * Ink hands a whole stdin chunk to a single `useInput` call and only decodes
@@ -128,7 +128,7 @@ export function parseInputChunk(text) {
128
128
  if (text === '' || parseEditSequence(text) !== null)
129
129
  return [];
130
130
  const lineBreaks = (text.match(/[\r\n]/g) ?? []).length;
131
- const trailingEnter = lineBreaks === 1 && text.length <= MAX_SUBMIT_CHUNK && /[\r\n]$/.test(text);
131
+ const trailingEnter = lineBreaks === 1 && text.length <= MAX_SUBMIT_CHUNK && text.endsWith('\r');
132
132
  const ops = [];
133
133
  let buffer = '';
134
134
  const flush = () => {
@@ -148,21 +148,32 @@ export function parseInputChunk(text) {
148
148
  }
149
149
  continue;
150
150
  }
151
- for (const char of token) {
151
+ for (let index = 0; index < token.length; index++) {
152
+ const char = token[index];
152
153
  const code = char.codePointAt(0) ?? 0;
153
154
  if (char === '\x7f' || char === '\x08') {
154
155
  flush();
155
156
  ops.push({ type: 'backspace', count: 1 });
156
157
  }
157
- else if (char === '\r' || char === '\n') {
158
+ else if (char === '\r') {
158
159
  if (trailingEnter) {
159
- flush();
160
- ops.push({ type: 'submit' });
160
+ if (buffer.endsWith('\\')) {
161
+ buffer = `${buffer.slice(0, -1)}\n`;
162
+ }
163
+ else {
164
+ flush();
165
+ ops.push({ type: 'submit' });
166
+ }
161
167
  }
162
168
  else {
163
- buffer += ' ';
169
+ buffer += '\n';
170
+ if (token[index + 1] === '\n')
171
+ index++;
164
172
  }
165
173
  }
174
+ else if (char === '\n') {
175
+ buffer += '\n';
176
+ }
166
177
  else if (char === '\t') {
167
178
  buffer += ' ';
168
179
  }
@@ -257,6 +268,147 @@ export function applyInputOps(state, ops, maxChars = Number.POSITIVE_INFINITY) {
257
268
  }
258
269
  return { state: current, submitted: false };
259
270
  }
271
+ export const PASTE_START = '\x1b[200~';
272
+ export const PASTE_END = '\x1b[201~';
273
+ const PASTE_START_BARE = '[200~';
274
+ const PASTE_END_BARE = '[201~';
275
+ export function normalizePastedText(text) {
276
+ return text
277
+ .replace(/\r\n?/g, '\n')
278
+ .replace(/\t/g, ' ')
279
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, '');
280
+ }
281
+ function findPasteStart(text) {
282
+ const escaped = text.indexOf(PASTE_START);
283
+ if (escaped !== -1)
284
+ return { index: escaped, length: PASTE_START.length };
285
+ if (text.startsWith(PASTE_START_BARE))
286
+ return { index: 0, length: PASTE_START_BARE.length };
287
+ return null;
288
+ }
289
+ function findPasteEnd(text) {
290
+ const escaped = text.indexOf(PASTE_END);
291
+ const bare = text.indexOf(PASTE_END_BARE);
292
+ if (escaped === -1 && bare === -1)
293
+ return null;
294
+ if (escaped === -1)
295
+ return { index: bare, length: PASTE_END_BARE.length };
296
+ if (bare === -1 || escaped <= bare)
297
+ return { index: escaped, length: PASTE_END.length };
298
+ return { index: bare, length: PASTE_END_BARE.length };
299
+ }
300
+ /** Longest suffix that could still become a start marker. */
301
+ function pendingStart(text) {
302
+ const limit = Math.min(PASTE_START.length - 1, text.length);
303
+ for (let length = limit; length >= 3; length--) {
304
+ const suffix = text.slice(-length);
305
+ if (PASTE_START.startsWith(suffix) || PASTE_START_BARE.startsWith(suffix))
306
+ return suffix;
307
+ }
308
+ return '';
309
+ }
310
+ /**
311
+ * Consumes bracketed paste markers from a raw input chunk. Ink strips one
312
+ * leading escape byte per chunk and a terminal may split a marker across
313
+ * reads, so both cases are buffered.
314
+ */
315
+ export function feedPaste(state, input) {
316
+ if (state.open) {
317
+ const combined = state.buffer + input;
318
+ const end = findPasteEnd(combined);
319
+ if (!end) {
320
+ return {
321
+ state: { open: true, buffer: combined, pending: '' },
322
+ text: null,
323
+ consumed: true,
324
+ };
325
+ }
326
+ const text = normalizePastedText(combined.slice(0, end.index)) +
327
+ normalizePastedText(combined.slice(end.index + end.length));
328
+ return { state: { open: false, buffer: '', pending: '' }, text, consumed: true };
329
+ }
330
+ const hadPending = state.pending !== '';
331
+ const combined = state.pending + input;
332
+ const start = findPasteStart(combined);
333
+ if (!start) {
334
+ const pending = pendingStart(combined);
335
+ if (pending.length >= 3 && pending.length === combined.length) {
336
+ return { state: { open: false, buffer: '', pending }, text: null, consumed: true };
337
+ }
338
+ if (!hadPending) {
339
+ return { state: { open: false, buffer: '', pending: '' }, text: null, consumed: false };
340
+ }
341
+ const flushed = combined.slice(0, combined.length - pending.length);
342
+ return {
343
+ state: { open: false, buffer: '', pending },
344
+ text: flushed ? normalizePastedText(flushed) : null,
345
+ consumed: true,
346
+ };
347
+ }
348
+ const prefix = combined.slice(0, start.index);
349
+ const after = combined.slice(start.index + start.length);
350
+ const end = findPasteEnd(after);
351
+ if (!end) {
352
+ return {
353
+ state: { open: true, buffer: after, pending: '' },
354
+ text: prefix ? normalizePastedText(prefix) : null,
355
+ consumed: true,
356
+ };
357
+ }
358
+ const pasted = after.slice(0, end.index);
359
+ const rest = after.slice(end.index + end.length);
360
+ return {
361
+ state: { open: false, buffer: '', pending: '' },
362
+ text: normalizePastedText(prefix + pasted) + normalizePastedText(rest),
363
+ consumed: true,
364
+ };
365
+ }
366
+ /** Splits input into visual lines, honouring explicit newlines and hard wrapping. */
367
+ export function layoutInput(chars, width, masked = false) {
368
+ const maxWidth = Math.max(1, width);
369
+ const lines = [];
370
+ let start = 0;
371
+ let text = '';
372
+ let used = 0;
373
+ const flush = (end, wrapped) => {
374
+ lines.push({ start, end, text, wrapped });
375
+ start = end;
376
+ text = '';
377
+ used = 0;
378
+ };
379
+ for (let index = 0; index < chars.length; index++) {
380
+ const char = masked ? '•' : chars[index];
381
+ if (char === '\n') {
382
+ flush(index, false);
383
+ start = index + 1;
384
+ continue;
385
+ }
386
+ const charWidth = Math.max(1, stringWidth(char));
387
+ if (used > 0 && used + charWidth > maxWidth)
388
+ flush(index, true);
389
+ text += char;
390
+ used += charWidth;
391
+ }
392
+ flush(chars.length, false);
393
+ return lines;
394
+ }
395
+ /** Finds the visual line holding the caret; wraps forward, newlines stay put. */
396
+ export function cursorLineIndex(lines, cursor) {
397
+ for (let index = 0; index < lines.length; index++) {
398
+ const line = lines[index];
399
+ if (cursor < line.start)
400
+ return Math.max(0, index - 1);
401
+ if (cursor < line.end)
402
+ return index;
403
+ if (cursor === line.end) {
404
+ const next = lines[index + 1];
405
+ if (line.wrapped && next && next.start === cursor)
406
+ return index + 1;
407
+ return index;
408
+ }
409
+ }
410
+ return lines.length - 1;
411
+ }
260
412
  export function formatDuration(ms) {
261
413
  if (ms < 1000)
262
414
  return `${ms}ms`;
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
- export const VERSION = '0.2.12';
1
+ export const VERSION = '0.3.0';
2
2
  //# sourceMappingURL=version.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ywldan/kiro",
3
- "version": "0.2.12",
3
+ "version": "0.3.0",
4
4
  "description": "A small terminal coding agent with your own OpenAI-compatible endpoint",
5
5
  "keywords": [
6
6
  "ai",