@steerable/agent-protocol 0.14.2 → 0.14.4

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.
@@ -0,0 +1,616 @@
1
+ /**
2
+ * Lightweight, fail-safe read-only shell command classifier shared by Web and TUI.
3
+ *
4
+ * Mirrors Codex `codex-shell-command::parse_command`: single-purpose read-only
5
+ * exploration commands (`ls`, `cat`, `sed -n`, `rg`, `find`) are mapped to
6
+ * human-readable intents (`list`, `read`, `skill`, `search`). Any redirection,
7
+ * command substitution, control-flow keyword, multi-statement chain (other than
8
+ * a leading `cd <dir> &&`), or mutating flag immediately falls back to `'run'`.
9
+ */
10
+ const SHELL_NAMES = new Set(['zsh', 'bash', 'sh', 'dash', 'ksh']);
11
+ const CONTROL_KEYWORDS = new Set([
12
+ 'for',
13
+ 'while',
14
+ 'until',
15
+ 'if',
16
+ 'case',
17
+ 'select',
18
+ 'function',
19
+ '{',
20
+ '(',
21
+ 'do',
22
+ 'then',
23
+ 'time',
24
+ 'coproc',
25
+ ]);
26
+ const SAFE_PIPE_FILTERS = new Set([
27
+ 'head',
28
+ 'tail',
29
+ 'wc',
30
+ 'cat',
31
+ 'nl',
32
+ 'sort',
33
+ 'uniq',
34
+ 'cut',
35
+ ]);
36
+ const HARMLESS_ENV_RE = /^(?:LC_[A-Z_]+|LANG|PAGER|GIT_PAGER|NO_COLOR|TERM)=/;
37
+ /** Extract skill directory identifier when a path points to `.../ <skillName> / SKILL.md`. */
38
+ export function extractSkillNameFromPath(rawPath) {
39
+ const cleaned = rawPath.trim().replace(/:L\d+(?:-\d+)?$/, '');
40
+ const match = /(?:^|[\\/])([^\\/]+)[\\/]SKILL\.md$/i.exec(cleaned);
41
+ return match && match[1] ? match[1] : null;
42
+ }
43
+ function collapseOneLine(text) {
44
+ return text.replace(/\s+/g, ' ').trim();
45
+ }
46
+ function isAsciiWhitespace(ch) {
47
+ return ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r' || ch === '\f' || ch === '\v';
48
+ }
49
+ function skipWhitespace(text, index) {
50
+ let i = index;
51
+ while (i < text.length && isAsciiWhitespace(text[i]))
52
+ i += 1;
53
+ return i;
54
+ }
55
+ function isAsciiLetter(ch) {
56
+ const code = ch.charCodeAt(0);
57
+ return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
58
+ }
59
+ /**
60
+ * Strip a leading `/usr/bin/env`, `/bin/`, or `/usr/bin/` prefix.
61
+ * Returns the remainder, or null when the prefix is absent.
62
+ */
63
+ function stripShellPrefix(text, prefix) {
64
+ if (!text.startsWith(prefix))
65
+ return null;
66
+ return text.slice(prefix.length);
67
+ }
68
+ /**
69
+ * Read `sh -c <script>` without a backtracking regular expression.
70
+ * The script is caller-controlled and can be long.
71
+ */
72
+ function splitShellInvocation(text) {
73
+ let rest = text;
74
+ const afterEnv = stripShellPrefix(rest, '/usr/bin/env');
75
+ if (afterEnv !== null) {
76
+ const next = skipWhitespace(afterEnv, 0);
77
+ if (next === 0)
78
+ return null;
79
+ rest = afterEnv.slice(next);
80
+ }
81
+ const afterUsrBin = stripShellPrefix(rest, '/usr/bin/');
82
+ if (afterUsrBin !== null)
83
+ rest = afterUsrBin;
84
+ else {
85
+ const afterBin = stripShellPrefix(rest, '/bin/');
86
+ if (afterBin !== null)
87
+ rest = afterBin;
88
+ }
89
+ let nameEnd = 0;
90
+ while (nameEnd < rest.length && !isAsciiWhitespace(rest[nameEnd]))
91
+ nameEnd += 1;
92
+ if (nameEnd === 0 || nameEnd === rest.length)
93
+ return null;
94
+ if (!SHELL_NAMES.has(rest.slice(0, nameEnd)))
95
+ return null;
96
+ let i = skipWhitespace(rest, nameEnd);
97
+ if (rest[i] !== '-')
98
+ return null;
99
+ let flagEnd = i + 1;
100
+ while (flagEnd < rest.length && isAsciiLetter(rest[flagEnd]))
101
+ flagEnd += 1;
102
+ if (flagEnd === i + 1 || rest[flagEnd - 1] !== 'c')
103
+ return null;
104
+ if (flagEnd < rest.length && !isAsciiWhitespace(rest[flagEnd]))
105
+ return null;
106
+ i = skipWhitespace(rest, flagEnd);
107
+ if (i >= rest.length)
108
+ return null;
109
+ return rest.slice(i);
110
+ }
111
+ /** Strip outer `/bin/zsh -lc '...'` or `bash -c "..."` wrapper if present. */
112
+ export function unwrapShellWrapper(rawCommand) {
113
+ const trimmed = rawCommand.trim();
114
+ const script = splitShellInvocation(trimmed);
115
+ if (!script)
116
+ return trimmed;
117
+ const arg = script.trim();
118
+ if (arg.length >= 2 && arg.startsWith("'") && arg.endsWith("'")) {
119
+ return arg.slice(1, -1).replace(/'\\''/g, "'");
120
+ }
121
+ if (arg.length >= 2 && arg.startsWith('"') && arg.endsWith('"')) {
122
+ let inner = '';
123
+ const body = arg.slice(1, -1);
124
+ for (let i = 0; i < body.length; i += 1) {
125
+ if (body[i] === '\\' && i + 1 < body.length) {
126
+ const next = body[i + 1];
127
+ if (next === '"' || next === '\\' || next === '$' || next === '`') {
128
+ inner += next;
129
+ i += 1;
130
+ continue;
131
+ }
132
+ }
133
+ inner += body[i];
134
+ }
135
+ return inner;
136
+ }
137
+ return arg;
138
+ }
139
+ /**
140
+ * Scan unquoted characters for redirection, substitution, semicolons, newlines,
141
+ * `||`, background `&`, and split top-level `&&` segments.
142
+ */
143
+ function scanTopLevelAndSegments(script) {
144
+ let quote = null;
145
+ const segments = [];
146
+ let start = 0;
147
+ for (let i = 0; i < script.length; i += 1) {
148
+ const ch = script[i];
149
+ if (quote === "'") {
150
+ if (ch === "'")
151
+ quote = null;
152
+ continue;
153
+ }
154
+ if (quote === '"') {
155
+ if (ch === '\\') {
156
+ i += 1;
157
+ continue;
158
+ }
159
+ if (ch === '`')
160
+ return { safe: false, andSegments: [] };
161
+ if (ch === '$' && script[i + 1] === '(')
162
+ return { safe: false, andSegments: [] };
163
+ if (ch === '"')
164
+ quote = null;
165
+ continue;
166
+ }
167
+ if (ch === '\\') {
168
+ i += 1;
169
+ continue;
170
+ }
171
+ if (ch === "'" || ch === '"') {
172
+ quote = ch;
173
+ continue;
174
+ }
175
+ if (ch === '\n' || ch === '\r' || ch === ';' || ch === '`') {
176
+ return { safe: false, andSegments: [] };
177
+ }
178
+ if (ch === '$' && script[i + 1] === '(') {
179
+ return { safe: false, andSegments: [] };
180
+ }
181
+ if (ch === '<') {
182
+ return { safe: false, andSegments: [] };
183
+ }
184
+ if (ch === '>') {
185
+ // Allow only `2>&1` or `2>/dev/null` / `2> /dev/null`
186
+ const prev = i > 0 ? script[i - 1] : '';
187
+ const prev2 = i > 1 ? script[i - 2] : '';
188
+ const isFd2 = prev === '2' && (i === 1 || /\s/.test(prev2));
189
+ if (!isFd2)
190
+ return { safe: false, andSegments: [] };
191
+ const rest = script.slice(i + 1);
192
+ const redirMatch = /^(?:&1(?=\s|$|\|)|[ \t]*\/dev\/null(?=\s|$|\|))/.exec(rest);
193
+ if (!redirMatch)
194
+ return { safe: false, andSegments: [] };
195
+ i += redirMatch[0].length;
196
+ continue;
197
+ }
198
+ if (ch === '|' && script[i + 1] === '|') {
199
+ return { safe: false, andSegments: [] };
200
+ }
201
+ if (ch === '&') {
202
+ if (script[i + 1] === '&') {
203
+ segments.push(script.slice(start, i).trim());
204
+ i += 1;
205
+ start = i + 1;
206
+ continue;
207
+ }
208
+ return { safe: false, andSegments: [] };
209
+ }
210
+ }
211
+ if (quote !== null)
212
+ return { safe: false, andSegments: [] };
213
+ segments.push(script.slice(start).trim());
214
+ return { safe: segments.every((s) => s.length > 0), andSegments: segments };
215
+ }
216
+ function splitUnquotedPipes(segment) {
217
+ let quote = null;
218
+ const parts = [];
219
+ let start = 0;
220
+ for (let i = 0; i < segment.length; i += 1) {
221
+ const ch = segment[i];
222
+ if (quote === "'") {
223
+ if (ch === "'")
224
+ quote = null;
225
+ continue;
226
+ }
227
+ if (quote === '"') {
228
+ if (ch === '\\') {
229
+ i += 1;
230
+ continue;
231
+ }
232
+ if (ch === '"')
233
+ quote = null;
234
+ continue;
235
+ }
236
+ if (ch === '\\') {
237
+ i += 1;
238
+ continue;
239
+ }
240
+ if (ch === "'" || ch === '"') {
241
+ quote = ch;
242
+ continue;
243
+ }
244
+ if (ch === '|') {
245
+ parts.push(segment.slice(start, i).trim());
246
+ start = i + 1;
247
+ }
248
+ }
249
+ parts.push(segment.slice(start).trim());
250
+ return parts;
251
+ }
252
+ function stripBenignStderrRedirs(segment) {
253
+ return segment
254
+ .replace(/(?:^|\s)2>&1(?=\s|$)/g, ' ')
255
+ .replace(/(?:^|\s)2>\s*\/dev\/null(?=\s|$)/g, ' ')
256
+ .trim();
257
+ }
258
+ function tokenizeWords(segment) {
259
+ const cleaned = stripBenignStderrRedirs(segment);
260
+ if (!cleaned)
261
+ return null;
262
+ const tokens = [];
263
+ let current = '';
264
+ let hasToken = false;
265
+ let quote = null;
266
+ for (let i = 0; i < cleaned.length; i += 1) {
267
+ const ch = cleaned[i];
268
+ if (quote === "'") {
269
+ if (ch === "'")
270
+ quote = null;
271
+ else
272
+ current += ch;
273
+ continue;
274
+ }
275
+ if (quote === '"') {
276
+ if (ch === '\\' && i + 1 < cleaned.length) {
277
+ current += cleaned[i + 1];
278
+ i += 1;
279
+ continue;
280
+ }
281
+ if (ch === '"')
282
+ quote = null;
283
+ else
284
+ current += ch;
285
+ continue;
286
+ }
287
+ if (ch === "'" || ch === '"') {
288
+ quote = ch;
289
+ hasToken = true;
290
+ continue;
291
+ }
292
+ if (ch === '\\' && i + 1 < cleaned.length) {
293
+ current += cleaned[i + 1];
294
+ hasToken = true;
295
+ i += 1;
296
+ continue;
297
+ }
298
+ if (/\s/.test(ch)) {
299
+ if (hasToken) {
300
+ tokens.push(current);
301
+ current = '';
302
+ hasToken = false;
303
+ }
304
+ continue;
305
+ }
306
+ current += ch;
307
+ hasToken = true;
308
+ }
309
+ if (quote !== null)
310
+ return null;
311
+ if (hasToken)
312
+ tokens.push(current);
313
+ return tokens;
314
+ }
315
+ function isSafePipeFilter(pipeSegment) {
316
+ const words = tokenizeWords(pipeSegment);
317
+ if (!words || words.length === 0)
318
+ return false;
319
+ const cmd = baseCommandName(words[0]);
320
+ if (cmd === 'sed') {
321
+ const hasQuiet = words.slice(1).some((w) => w === '-n' || w === '--quiet' || w === '--silent');
322
+ const hasInPlace = words.slice(1).some((w) => w.startsWith('-i') || w === '--in-place' || w === '-f');
323
+ return hasQuiet && !hasInPlace;
324
+ }
325
+ if (!SAFE_PIPE_FILTERS.has(cmd))
326
+ return false;
327
+ // `sort -o file` writes to a file
328
+ if (cmd === 'sort' && words.slice(1).some((w) => w === '-o' || w.startsWith('--output'))) {
329
+ return false;
330
+ }
331
+ return true;
332
+ }
333
+ function baseCommandName(word) {
334
+ const idx = word.lastIndexOf('/');
335
+ return idx >= 0 ? word.slice(idx + 1) : word;
336
+ }
337
+ function joinCdPrefix(cdDir, target) {
338
+ if (!cdDir || target.startsWith('/') || target.startsWith('~'))
339
+ return target;
340
+ if (target === '.')
341
+ return cdDir;
342
+ const cleanDir = cdDir.replace(/\/+$/, '');
343
+ const cleanTarget = target.replace(/^\.\//, '');
344
+ return `${cleanDir}/${cleanTarget}`;
345
+ }
346
+ function classifyReadFiles(files, cdDir, rawCommand) {
347
+ if (files.length === 0)
348
+ return null;
349
+ const resolved = files.map((file) => joinCdPrefix(cdDir, file));
350
+ if (resolved.length === 1) {
351
+ const skillName = extractSkillNameFromPath(resolved[0]);
352
+ if (skillName) {
353
+ return { kind: 'skill', skillName, path: resolved[0], rawCommand };
354
+ }
355
+ }
356
+ return { kind: 'read', files: resolved, rawCommand };
357
+ }
358
+ const SEARCH_VALUE_FLAGS = new Set([
359
+ '-e',
360
+ '--regexp',
361
+ '-f',
362
+ '--file',
363
+ '-g',
364
+ '--glob',
365
+ '--iglob',
366
+ '-t',
367
+ '--type',
368
+ '-T',
369
+ '--type-not',
370
+ '-A',
371
+ '--after-context',
372
+ '-B',
373
+ '--before-context',
374
+ '-C',
375
+ '--context',
376
+ '-m',
377
+ '--max-count',
378
+ '--max-depth',
379
+ '--max-filesize',
380
+ '--threads',
381
+ '-j',
382
+ '--color',
383
+ '--Include',
384
+ '--include',
385
+ '--exclude',
386
+ '--exclude-dir',
387
+ ]);
388
+ function parseGrepArgs(args, cdDir, rawCommand) {
389
+ if (args.includes('--files')) {
390
+ const pos = args.filter((a) => !a.startsWith('-'));
391
+ const target = pos[0] ? joinCdPrefix(cdDir, pos[0]) : cdDir ?? '.';
392
+ return { kind: 'list', paths: [target], rawCommand };
393
+ }
394
+ let explicitQuery = null;
395
+ const positional = [];
396
+ for (let i = 0; i < args.length; i += 1) {
397
+ const arg = args[i];
398
+ if (arg === '--') {
399
+ positional.push(...args.slice(i + 1));
400
+ break;
401
+ }
402
+ if (arg === '-e' || arg === '--regexp') {
403
+ const val = args[i + 1];
404
+ if (val !== undefined) {
405
+ explicitQuery ??= val;
406
+ i += 1;
407
+ }
408
+ continue;
409
+ }
410
+ if (arg.startsWith('-e') && arg.length > 2) {
411
+ explicitQuery ??= arg.slice(2);
412
+ continue;
413
+ }
414
+ if (SEARCH_VALUE_FLAGS.has(arg)) {
415
+ i += 1;
416
+ continue;
417
+ }
418
+ if (arg.startsWith('-'))
419
+ continue;
420
+ positional.push(arg);
421
+ }
422
+ const query = explicitQuery ?? positional[0] ?? null;
423
+ const rawPath = explicitQuery ? positional[0] ?? null : positional[1] ?? null;
424
+ const path = rawPath ? joinCdPrefix(cdDir, rawPath) : cdDir;
425
+ return { kind: 'search', query, path, rawCommand };
426
+ }
427
+ function parseFindArgs(cmd, args, cdDir, rawCommand, fallbackCommand) {
428
+ if (cmd === 'find') {
429
+ const unsafe = args.some((a) => a === '-exec' ||
430
+ a === '-execdir' ||
431
+ a === '-ok' ||
432
+ a === '-okdir' ||
433
+ a === '-delete' ||
434
+ a === '-fls' ||
435
+ a === '-fprint' ||
436
+ a === '-fprint0' ||
437
+ a === '-fprintf');
438
+ if (unsafe)
439
+ return { kind: 'run', command: fallbackCommand, rawCommand };
440
+ let root = null;
441
+ let query = null;
442
+ for (let i = 0; i < args.length; i += 1) {
443
+ const arg = args[i];
444
+ if (arg === '-name' || arg === '-iname' || arg === '-path' || arg === '-ipath' || arg === '-regex') {
445
+ if (args[i + 1])
446
+ query ??= args[i + 1];
447
+ i += 1;
448
+ continue;
449
+ }
450
+ if (!arg.startsWith('-') && arg !== '!' && arg !== '(' && arg !== ')' && root === null) {
451
+ root = arg;
452
+ }
453
+ }
454
+ return {
455
+ kind: 'search',
456
+ query,
457
+ path: root ? joinCdPrefix(cdDir, root) : cdDir ?? '.',
458
+ rawCommand,
459
+ };
460
+ }
461
+ // `fd` / `fdfind`
462
+ const unsafeFd = args.some((a) => a === '-x' || a === '--exec' || a === '-X' || a === '--exec-batch');
463
+ if (unsafeFd)
464
+ return { kind: 'run', command: fallbackCommand, rawCommand };
465
+ const positional = args.filter((a) => !a.startsWith('-'));
466
+ const query = positional[0] ?? null;
467
+ const rawPath = positional[1] ?? null;
468
+ return {
469
+ kind: 'search',
470
+ query,
471
+ path: rawPath ? joinCdPrefix(cdDir, rawPath) : cdDir,
472
+ rawCommand,
473
+ };
474
+ }
475
+ /**
476
+ * Classify a shell command into a read-only exploration action (`list`, `read`,
477
+ * `skill`, `search`) or a general execution (`run`).
478
+ */
479
+ export function classifyShellCommand(rawCommand) {
480
+ const unwrapped = unwrapShellWrapper(rawCommand);
481
+ const fallbackCommand = collapseOneLine(unwrapped);
482
+ const fallback = {
483
+ kind: 'run',
484
+ command: fallbackCommand,
485
+ rawCommand,
486
+ };
487
+ if (!fallbackCommand)
488
+ return fallback;
489
+ const scanned = scanTopLevelAndSegments(unwrapped);
490
+ if (!scanned.safe || scanned.andSegments.length === 0)
491
+ return fallback;
492
+ let cdDir = null;
493
+ let mainSegment = scanned.andSegments[0];
494
+ if (scanned.andSegments.length > 1) {
495
+ // Allow only leading `cd <dir> && ...` before one final read-only segment.
496
+ for (let i = 0; i < scanned.andSegments.length - 1; i += 1) {
497
+ const cdWords = tokenizeWords(scanned.andSegments[i]);
498
+ if (!cdWords || cdWords[0] !== 'cd' || cdWords.length !== 2 || cdWords[1].startsWith('-')) {
499
+ return fallback;
500
+ }
501
+ cdDir = joinCdPrefix(cdDir, cdWords[1]);
502
+ }
503
+ mainSegment = scanned.andSegments[scanned.andSegments.length - 1];
504
+ }
505
+ const pipeParts = splitUnquotedPipes(mainSegment);
506
+ if (pipeParts.some((p) => p.length === 0))
507
+ return fallback;
508
+ for (let i = 1; i < pipeParts.length; i += 1) {
509
+ if (!isSafePipeFilter(pipeParts[i]))
510
+ return fallback;
511
+ }
512
+ const rawWords = tokenizeWords(pipeParts[0]);
513
+ if (!rawWords || rawWords.length === 0)
514
+ return fallback;
515
+ let wordIdx = 0;
516
+ while (wordIdx < rawWords.length && HARMLESS_ENV_RE.test(rawWords[wordIdx])) {
517
+ wordIdx += 1;
518
+ }
519
+ const words = rawWords.slice(wordIdx);
520
+ if (words.length === 0)
521
+ return fallback;
522
+ if (words[0].includes('=') && !words[0].startsWith('-'))
523
+ return fallback;
524
+ const first = words[0];
525
+ if (CONTROL_KEYWORDS.has(first))
526
+ return fallback;
527
+ const cmd = baseCommandName(first);
528
+ const args = words.slice(1);
529
+ if (cmd === 'pwd' && args.every((a) => a.startsWith('-'))) {
530
+ return { kind: 'list', paths: [cdDir ?? '.'], rawCommand };
531
+ }
532
+ if (cmd === 'ls' || cmd === 'lsd' || cmd === 'exa' || cmd === 'eza' || cmd === 'tree') {
533
+ const paths = [];
534
+ for (let i = 0; i < args.length; i += 1) {
535
+ const arg = args[i];
536
+ if (arg === '--') {
537
+ paths.push(...args.slice(i + 1));
538
+ break;
539
+ }
540
+ if ((cmd === 'tree' || cmd === 'lsd' || cmd === 'exa' || cmd === 'eza') && (arg === '-L' || arg === '--depth' || arg === '-I')) {
541
+ i += 1;
542
+ continue;
543
+ }
544
+ if (arg.startsWith('-'))
545
+ continue;
546
+ paths.push(arg);
547
+ }
548
+ const resolved = paths.length > 0 ? paths.map((p) => joinCdPrefix(cdDir, p)) : [cdDir ?? '.'];
549
+ return { kind: 'list', paths: resolved, rawCommand };
550
+ }
551
+ if (cmd === 'cat' ||
552
+ cmd === 'head' ||
553
+ cmd === 'tail' ||
554
+ cmd === 'nl' ||
555
+ cmd === 'bat' ||
556
+ cmd === 'Get-Content' ||
557
+ cmd === 'gc') {
558
+ const files = [];
559
+ for (let i = 0; i < args.length; i += 1) {
560
+ const arg = args[i];
561
+ if (arg === '--') {
562
+ files.push(...args.slice(i + 1));
563
+ break;
564
+ }
565
+ if (arg === '-n' || arg === '-c' || arg === '--lines' || arg === '--bytes' || arg === '-TotalCount' || arg === '-Tail') {
566
+ i += 1;
567
+ continue;
568
+ }
569
+ if (arg.startsWith('-'))
570
+ continue;
571
+ files.push(arg);
572
+ }
573
+ return classifyReadFiles(files, cdDir, rawCommand) ?? fallback;
574
+ }
575
+ if (cmd === 'sed') {
576
+ let quiet = false;
577
+ const positional = [];
578
+ for (let i = 0; i < args.length; i += 1) {
579
+ const arg = args[i];
580
+ if (arg === '-n' || arg === '--quiet' || arg === '--silent') {
581
+ quiet = true;
582
+ continue;
583
+ }
584
+ if (arg.startsWith('-i') || arg === '--in-place' || arg === '-f' || arg === '--file') {
585
+ return fallback;
586
+ }
587
+ if (arg === '-e' || arg === '--expression') {
588
+ const expr = args[i + 1] ?? '';
589
+ if (!/^[0-9,$+;p\s]+$/.test(expr))
590
+ return fallback;
591
+ i += 1;
592
+ positional.unshift(expr);
593
+ continue;
594
+ }
595
+ if (arg.startsWith('-'))
596
+ continue;
597
+ positional.push(arg);
598
+ }
599
+ if (!quiet || positional.length < 2)
600
+ return fallback;
601
+ const scriptExpr = positional[0];
602
+ if (!/^[0-9,$+;p\s]+$/.test(scriptExpr))
603
+ return fallback;
604
+ return classifyReadFiles(positional.slice(1), cdDir, rawCommand) ?? fallback;
605
+ }
606
+ if (cmd === 'rg' || cmd === 'ripgrep' || cmd === 'grep' || cmd === 'egrep' || cmd === 'fgrep') {
607
+ return parseGrepArgs(args, cdDir, rawCommand);
608
+ }
609
+ if (cmd === 'git' && args[0] === 'grep') {
610
+ return parseGrepArgs(args.slice(1), cdDir, rawCommand);
611
+ }
612
+ if (cmd === 'find' || cmd === 'fd' || cmd === 'fdfind') {
613
+ return parseFindArgs(cmd, args, cdDir, rawCommand, fallbackCommand);
614
+ }
615
+ return fallback;
616
+ }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Zero-dependency transcript parsing helpers shared by `@steerable/agent-shell-web`
3
+ * and `@steerable/agent-cli` (TUI).
4
+ *
5
+ * Lives in Tier-1 `@steerable/agent-protocol` (alongside `turn-failure-kind.ts`)
6
+ * so browser bundles and Node TUI share one implementation for:
7
+ * 1. Unwrapping serialized / 300-char-truncated `ToolResult` JSON envelopes;
8
+ * 2. Extracting clean terminal `command`, `stdout`, `stderr`, `exitCode`;
9
+ * 3. Extracting or synthesizing Unified Diff + `+added / -removed` stats;
10
+ * 4. Detecting skill invocations (`skill` tool or reading `.../SKILL.md`);
11
+ * 5. Codex-style head + tail middle output truncation (`truncateOutputMiddle`).
12
+ */
13
+ import { type ClassifiedShellAction } from './shell-command-classifier.js';
14
+ export interface ToolEnvelope {
15
+ success: boolean | null;
16
+ error: string | null;
17
+ message: string | null;
18
+ fields: Record<string, unknown>;
19
+ }
20
+ export interface TerminalExecutionView {
21
+ settled: boolean;
22
+ command: string | null;
23
+ language: string | null;
24
+ cwd: string | null;
25
+ packages?: string[];
26
+ stdout: string;
27
+ stderr: string;
28
+ error: string | null;
29
+ exitCode: number | null;
30
+ timedOut: boolean;
31
+ }
32
+ export interface FileChangePreview {
33
+ path: string;
34
+ isWrite: boolean;
35
+ addedLines: number;
36
+ removedLines: number;
37
+ totalLines: number | null;
38
+ diff: string | null;
39
+ contentPreview: string | null;
40
+ error?: string | null;
41
+ }
42
+ export interface TruncatedOutput {
43
+ truncated: boolean;
44
+ totalLines: number;
45
+ head: string;
46
+ tail: string;
47
+ omittedLines: number;
48
+ }
49
+ /** Parse a JSON object/array string when well-formed; return original value otherwise. */
50
+ export declare function parseJsonValue(value: unknown): unknown;
51
+ export declare function extractPartialJsonStringFieldWithState(raw: string, field: string): {
52
+ value: string;
53
+ complete: boolean;
54
+ } | null;
55
+ export declare function extractPartialJsonStringField(raw: string, field: string): string | null;
56
+ export declare function extractPartialJsonExitCode(raw: string): number | null;
57
+ /** Unwrap a sidecar `ToolResult` (object or JSON/truncated-JSON string) into normalized envelope fields. */
58
+ export declare function parseToolEnvelope(result: unknown): ToolEnvelope;
59
+ /** Unwrap a terminal/snippet tool call into clean command + stdout/stderr without internal `_sandbox` keys. */
60
+ export declare function parseTerminalExecution(action: {
61
+ arguments?: unknown;
62
+ result?: unknown;
63
+ }): TerminalExecutionView;
64
+ /** True when a classified search command (`rg`/`grep`) exited with code 1 and empty stderr (standard "no matches"). */
65
+ export declare function isBenignSearchNoMatch(classified: ClassifiedShellAction | null, terminal: TerminalExecutionView): boolean;
66
+ /** Detect `skill` tool calls or `SKILL.md` file/shell reads. */
67
+ export declare function extractSkillInvocation(action: {
68
+ tool: string;
69
+ arguments?: unknown;
70
+ }): {
71
+ skillName: string;
72
+ path: string | null;
73
+ } | null;
74
+ /**
75
+ * Extract unified diff + `+added / -removed` counts for file mutation tools.
76
+ * Recovers full unified diffs from `arguments.edits` when persisted `result`
77
+ * strings were truncated to 300 characters.
78
+ */
79
+ export declare function extractFileChangePreview(action: {
80
+ tool: string;
81
+ arguments?: unknown;
82
+ result?: unknown;
83
+ }): FileChangePreview | null;
84
+ /**
85
+ * Keep head + tail lines of multi-line command output so both the command header
86
+ * and trailing error/summary stay visible on screen without scrolling.
87
+ */
88
+ export declare function truncateOutputMiddle(text: string, options?: {
89
+ headLines?: number;
90
+ tailLines?: number;
91
+ minTotalLines?: number;
92
+ }): TruncatedOutput;