shellpuppet 0.0.1 → 0.1.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.
Files changed (112) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +31 -0
  3. package/README.md +340 -8
  4. package/dist/cli/index.d.ts +13 -0
  5. package/dist/cli/index.js +693 -0
  6. package/dist/cli/index.js.map +1 -0
  7. package/dist/client/http.d.ts +82 -0
  8. package/dist/client/http.js +225 -0
  9. package/dist/client/http.js.map +1 -0
  10. package/dist/core/dialogs.d.ts +88 -0
  11. package/dist/core/dialogs.js +214 -0
  12. package/dist/core/dialogs.js.map +1 -0
  13. package/dist/core/echo.d.ts +71 -0
  14. package/dist/core/echo.js +249 -0
  15. package/dist/core/echo.js.map +1 -0
  16. package/dist/core/find.d.ts +34 -0
  17. package/dist/core/find.js +41 -0
  18. package/dist/core/find.js.map +1 -0
  19. package/dist/core/keys.d.ts +22 -0
  20. package/dist/core/keys.js +80 -0
  21. package/dist/core/keys.js.map +1 -0
  22. package/dist/core/manager.d.ts +66 -0
  23. package/dist/core/manager.js +158 -0
  24. package/dist/core/manager.js.map +1 -0
  25. package/dist/core/nativePty.d.ts +69 -0
  26. package/dist/core/nativePty.js +156 -0
  27. package/dist/core/nativePty.js.map +1 -0
  28. package/dist/core/policy.d.ts +61 -0
  29. package/dist/core/policy.js +143 -0
  30. package/dist/core/policy.js.map +1 -0
  31. package/dist/core/promptDetector.d.ts +75 -0
  32. package/dist/core/promptDetector.js +606 -0
  33. package/dist/core/promptDetector.js.map +1 -0
  34. package/dist/core/reasoning.d.ts +252 -0
  35. package/dist/core/reasoning.js +740 -0
  36. package/dist/core/reasoning.js.map +1 -0
  37. package/dist/core/regexBudget.d.ts +44 -0
  38. package/dist/core/regexBudget.js +79 -0
  39. package/dist/core/regexBudget.js.map +1 -0
  40. package/dist/core/renderer.d.ts +112 -0
  41. package/dist/core/renderer.js +225 -0
  42. package/dist/core/renderer.js.map +1 -0
  43. package/dist/core/session.d.ts +311 -0
  44. package/dist/core/session.js +966 -0
  45. package/dist/core/session.js.map +1 -0
  46. package/dist/core/types.d.ts +281 -0
  47. package/dist/core/types.js +47 -0
  48. package/dist/core/types.js.map +1 -0
  49. package/dist/core/waiter.d.ts +86 -0
  50. package/dist/core/waiter.js +317 -0
  51. package/dist/core/waiter.js.map +1 -0
  52. package/dist/core/windowsPtyStart.d.ts +90 -0
  53. package/dist/core/windowsPtyStart.js +129 -0
  54. package/dist/core/windowsPtyStart.js.map +1 -0
  55. package/dist/daemon/audit.d.ts +23 -0
  56. package/dist/daemon/audit.js +51 -0
  57. package/dist/daemon/audit.js.map +1 -0
  58. package/dist/daemon/auth.d.ts +127 -0
  59. package/dist/daemon/auth.js +241 -0
  60. package/dist/daemon/auth.js.map +1 -0
  61. package/dist/daemon/config.d.ts +76 -0
  62. package/dist/daemon/config.js +301 -0
  63. package/dist/daemon/config.js.map +1 -0
  64. package/dist/daemon/index.d.ts +7 -0
  65. package/dist/daemon/index.js +87 -0
  66. package/dist/daemon/index.js.map +1 -0
  67. package/dist/daemon/liveness.d.ts +36 -0
  68. package/dist/daemon/liveness.js +71 -0
  69. package/dist/daemon/liveness.js.map +1 -0
  70. package/dist/daemon/logger.d.ts +7 -0
  71. package/dist/daemon/logger.js +29 -0
  72. package/dist/daemon/logger.js.map +1 -0
  73. package/dist/daemon/meta.d.ts +9 -0
  74. package/dist/daemon/meta.js +24 -0
  75. package/dist/daemon/meta.js.map +1 -0
  76. package/dist/daemon/paths.d.ts +83 -0
  77. package/dist/daemon/paths.js +154 -0
  78. package/dist/daemon/paths.js.map +1 -0
  79. package/dist/daemon/screenshot.d.ts +87 -0
  80. package/dist/daemon/screenshot.js +256 -0
  81. package/dist/daemon/screenshot.js.map +1 -0
  82. package/dist/daemon/server.d.ts +244 -0
  83. package/dist/daemon/server.js +2187 -0
  84. package/dist/daemon/server.js.map +1 -0
  85. package/dist/daemon/terminalReports.d.ts +38 -0
  86. package/dist/daemon/terminalReports.js +84 -0
  87. package/dist/daemon/terminalReports.js.map +1 -0
  88. package/dist/daemon/viewerLauncher.d.ts +135 -0
  89. package/dist/daemon/viewerLauncher.js +280 -0
  90. package/dist/daemon/viewerLauncher.js.map +1 -0
  91. package/dist/daemon/viewerSync.d.ts +38 -0
  92. package/dist/daemon/viewerSync.js +83 -0
  93. package/dist/daemon/viewerSync.js.map +1 -0
  94. package/dist/mcp/config.d.ts +57 -0
  95. package/dist/mcp/config.js +106 -0
  96. package/dist/mcp/config.js.map +1 -0
  97. package/dist/mcp/index.d.ts +10 -0
  98. package/dist/mcp/index.js +69 -0
  99. package/dist/mcp/index.js.map +1 -0
  100. package/dist/mcp/tools.d.ts +59 -0
  101. package/dist/mcp/tools.js +537 -0
  102. package/dist/mcp/tools.js.map +1 -0
  103. package/dist/viewer/icon-16.png +0 -0
  104. package/dist/viewer/icon-180.png +0 -0
  105. package/dist/viewer/icon-32.png +0 -0
  106. package/dist/viewer/icon-512.png +0 -0
  107. package/dist/viewer/icon.svg +66 -0
  108. package/dist/viewer/index.html +56 -0
  109. package/dist/viewer/viewer.css +84 -0
  110. package/dist/viewer/viewer.js +661 -0
  111. package/package.json +66 -7
  112. package/index.js +0 -4
@@ -0,0 +1,740 @@
1
+ /**
2
+ * Reading an agent CLI's screen without its reasoning.
3
+ *
4
+ * Several agent CLIs draw the model's reasoning on screen as they work, and a
5
+ * supervisor reading the screen with `terminal_snapshot` takes all of it into
6
+ * its own context: text it did not need, and another model's reasoning it
7
+ * has no business collecting. This module tells the parts of a screen apart:
8
+ * the reasoning blocks, the answer that ends a turn, the composer and the
9
+ * status lines under it. `terminal_snapshot` and `terminal_find` can then
10
+ * leave the reasoning out (`hideReasoning`), and `terminal_result` returns
11
+ * the answer alone.
12
+ *
13
+ * Each program is described as data, a signature, because each draws its
14
+ * screen its own way. A signature says how to recognise a line by its text
15
+ * and by how it is drawn (bold, dim, italic, colour): reasoning is usually
16
+ * drawn dim or italic, an answer often starts with a bullet in the text
17
+ * colour while tool calls get a grey or coloured one. Every built-in
18
+ * signature is pinned by fixtures captured from the real program's screen
19
+ * (`test/fixtures/reasoning/`), and config `agents.signatures` adds or
20
+ * replaces one without a release.
21
+ *
22
+ * Both readers fail closed. A session whose program has no signature is
23
+ * refused rather than shown unfiltered, and `terminal_result` refuses when it
24
+ * cannot find an answer it recognises, rather than returning something else.
25
+ * What the filter cannot promise: a program that draws its reasoning in a
26
+ * shape its signature does not describe, a new version that changes the
27
+ * shape, or a screen that imitates one, defeats it. Screen content is
28
+ * untrusted input either way (design §4.4).
29
+ *
30
+ * Every pattern runs under the regular-expression time budget
31
+ * (`regexBudget.ts`), as patterns from config are text a person wrote.
32
+ */
33
+ import { RegexBudgetError, withRegexBudget } from './regexBudget.js';
34
+ // ---------------------------------------------------------------- built in
35
+ const RULE = '^[─━]{10,}$';
36
+ const RULE_INDENTED = '^\\s*[─━]{10,}';
37
+ /**
38
+ * Built-in signatures. Each comment names the screens its fixtures come from.
39
+ */
40
+ export const BUILT_IN_SIGNATURES = [
41
+ {
42
+ // Claude Code 2.1.312, default view and the ctrl+o transcript: no
43
+ // reasoning text is drawn in either, only a spinner line while the model
44
+ // thinks ("✻ Pondering… (2s · thinking with xhigh effort)"). The answer
45
+ // is a `●` in the text colour; tool calls get a grey or coloured `●`.
46
+ name: 'claude',
47
+ programs: ['claude'],
48
+ measured: 'Claude Code 2.1.312',
49
+ // The composer's prompt glyph is followed by a non-breaking space once
50
+ // something is typed; the echo of a sent prompt by an ordinary one.
51
+ composer: { text: '^❯( |\\xa0|$)' },
52
+ typed: { text: '^❯[ \\xa0]\\S', word: { dim: false } },
53
+ chrome: [{ text: RULE }, { text: '/effort\\s*$' }],
54
+ frame: { text: RULE },
55
+ busy: [{ text: '^[✻✽✶✢✳·*] \\S+…' }],
56
+ turn: { text: '^❯ \\S' },
57
+ answer: {
58
+ start: { text: '^● ', lead: { fg: ['default', '#ffffff', '#000000'] } },
59
+ continues: { text: '^ {2}' },
60
+ },
61
+ trailer: { text: '^✻ \\S' },
62
+ requireTrailer: true,
63
+ },
64
+ {
65
+ // Codex CLI 0.165.0 (GPT-6-Sol, high effort), default view. The answer is
66
+ // a dim "•" with plain text after it; a tool group is a dim "•" with a
67
+ // bold heading ("Explored"), a command a bold green "•" ("Ran"). While a
68
+ // turn runs, "Working (Ns • esc to interrupt)" sits above the composer.
69
+ name: 'codex',
70
+ programs: ['codex'],
71
+ measured: 'Codex CLI 0.165.0',
72
+ composer: { text: '^› ' },
73
+ // The placeholder ("Ask Codex to do anything") is dim; typed text is not.
74
+ typed: { text: '^› \\S', word: { dim: false } },
75
+ chrome: [{ text: 'esc to interrupt' }],
76
+ busy: [{ text: 'esc to interrupt' }],
77
+ turn: { text: '^› \\S' },
78
+ answer: {
79
+ start: { text: '^• ', lead: { dim: true }, word: { bold: false, italic: false } },
80
+ continues: { text: '^ {2}(?!Worked for )[^\\s└]' },
81
+ },
82
+ trailer: { text: '^ {2}Worked for ' },
83
+ requireTrailer: true,
84
+ },
85
+ {
86
+ // Antigravity CLI 1.4.10 (Gemini 3.8 Flash, high effort). A summary of
87
+ // the model's reasoning stays on screen as one line, "○ Thought for 4.2s
88
+ // (Create the file, then…)"; while it works, the spinner's label is the
89
+ // subject of what it is thinking about. "▸ Thought for 5s, 228 tokens"
90
+ // carries no text. Tool calls are a green "●"; the answer is plain text
91
+ // indented two spaces. While a turn runs, "esc to cancel" is under the
92
+ // composer.
93
+ name: 'agy',
94
+ programs: ['agy', 'antigravity'],
95
+ measured: 'Antigravity CLI 1.4.10',
96
+ composer: { text: '^>' },
97
+ chrome: [{ text: RULE_INDENTED }, { text: '^[⠀-⣿] {2}' }, { text: '^└ ' }],
98
+ frame: { text: RULE_INDENTED },
99
+ busy: [{ text: '^[⠀-⣿] {2}\\S' }, { text: '^esc to cancel' }],
100
+ turn: { text: '^> \\S' },
101
+ reasoning: [
102
+ { start: { text: '^○ Thought for ' } },
103
+ { start: { text: '^[⠀-⣿] {2}\\S' } },
104
+ ],
105
+ answer: {
106
+ start: { text: '^ {2}\\S', lead: { fg: ['default', '#ffffff', '#000000', 'p7', 'p15'] } },
107
+ continues: { text: '^ {2}\\S', lead: { fg: ['default', '#ffffff', '#000000', 'p7', 'p15'] } },
108
+ upward: true,
109
+ },
110
+ },
111
+ {
112
+ // Grok Build 1.0.70 (grok-4.7, xhigh effort). While the model thinks, its
113
+ // reasoning streams into a block behind a fading "│" bar, headed
114
+ // "♦ Thinking…"; once it is done the block collapses to "♦ Thought for
115
+ // Ns" with nothing under it. Messages and the answer are plain text
116
+ // indented five spaces; tool work is a "♦" line ("♦ Edited primes.py, ran
117
+ // 1 command"); "Worked for Ns" closes the turn. While a turn runs, a
118
+ // spinner line ("| Thinking… 3.1s") sits above the composer's box.
119
+ name: 'grok',
120
+ programs: ['grok'],
121
+ measured: 'Grok Build 1.0.70',
122
+ composer: { text: '^ {2}│ >' },
123
+ chrome: [{ text: '^ {2}╭' }, { text: '^ {3}[|/\\\\-] \\S' }, { text: '^ {3}\\S.*shift\\+tab', }],
124
+ frame: { text: '^ {2}[╭╰]' },
125
+ busy: [{ text: '^ {3}[|/\\\\-] .* \\d+(?:\\.\\d+)?s\\s*$' }, { text: '♦ Thinking…' }],
126
+ turn: { text: '^ {5}> \\S' },
127
+ reasoning: [
128
+ {
129
+ start: { text: '^ {2}│ {2}♦ Thinking' },
130
+ continues: { text: '^ {2}│' },
131
+ },
132
+ // The spinner's label can be the model's own words about what it is
133
+ // doing; it goes too, and the busy state still shows in the result.
134
+ { start: { text: '^ {3}[|/\\\\-] \\S' } },
135
+ // The bar on its own: the heading may have scrolled away.
136
+ {
137
+ start: { text: '^ {2}│ {2}\\S' },
138
+ continues: { text: '^ {2}│' },
139
+ },
140
+ ],
141
+ answer: {
142
+ start: { text: '^ {5}(?!Worked for )[^\\s♦>]', lead: { fg: ['default', '#c8c8c8', '#ffffff', '#000000'] } },
143
+ continues: { text: '^ {5}(?!Worked for )[^\\s♦>]', lead: { fg: ['default', '#c8c8c8', '#ffffff', '#000000'] } },
144
+ upward: true,
145
+ },
146
+ trailer: { text: '^ {5}Worked for ' },
147
+ requireTrailer: true,
148
+ // A right-aligned time on each message row.
149
+ tidy: ' {2,}\\d{1,2}:\\d{2}(?: ?[A-Za-z]{2})?\\s*$',
150
+ },
151
+ {
152
+ // OpenCode 2.0.26 (GLM-5.3): no reasoning text is drawn. While the model
153
+ // thinks it shows "⠇ Thinking"; afterwards a collapsed "+ Thought · Ns"
154
+ // with nothing under it. The answer is plain paragraphs, in the same
155
+ // colour and indent as any other text, closed by a footer naming the
156
+ // agent, the model and the time ("Build · GLM-5.3 · 7.0s"). A sidebar
157
+ // can share the rows on the right.
158
+ name: 'opencode',
159
+ programs: ['opencode'],
160
+ measured: 'OpenCode 2.0.26',
161
+ composer: { text: '^ {2}[┃╹]' },
162
+ chrome: [{ text: '^ {2}┃' }, { text: '^\\s{60,}\\S' }],
163
+ busy: [
164
+ { text: '\\besc interrupt\\b' },
165
+ { text: '^ {3,}[⠀-⣿] ' },
166
+ { text: '^ {3,}\\+ Thought\\s*$' },
167
+ ],
168
+ turn: { text: '^ {2}┃ {2}\\S' },
169
+ answer: {
170
+ start: { text: '^ {5}[^\\s→+⠀-⣿]', lead: { fg: ['default', '#eeeeee', '#ffffff', '#000000'] } },
171
+ continues: { text: '^ {5}[^\\s→+⠀-⣿]', lead: { fg: ['default', '#eeeeee', '#ffffff', '#000000'] } },
172
+ upward: true,
173
+ },
174
+ trailer: { text: '^ {5}\\S+ · [^·]+ · \\d[\\d.]*m?s\\b' },
175
+ requireTrailer: true,
176
+ // The sidebar, on the same rows to the right.
177
+ tidy: ' {20,}\\S.*$',
178
+ },
179
+ {
180
+ // MiMoCode 0.1.16 (MiMo-V2.6-Pro), built from OpenCode: no reasoning text
181
+ // is drawn. A collapsed "+ Thought: Ns" sits before each tool group and
182
+ // before the answer; tool calls are boxes behind a bar drawn in the
183
+ // background colour, the person's prompt and the composer behind one in
184
+ // the agent's colour. The answer is plain paragraphs closed by "▣ Build ·
185
+ // MiMo-V2.6-Pro · Ns", which carries no time while the turn runs. A side
186
+ // panel on the right shares the rows (the session's title, context and
187
+ // cost). The composer can hold a suggestion of its own after a turn.
188
+ name: 'mimo',
189
+ programs: ['mimo', 'mimocode', 'mimo-code'],
190
+ measured: 'MiMoCode 0.1.16',
191
+ composer: { text: '^ {2}[┃╹]' },
192
+ chrome: [{ text: '^ {2}┃' }, { text: '^\\s{60,}\\S' }],
193
+ busy: [
194
+ { text: '\\besc (?:to )?interrupt\\b' },
195
+ { text: '^ {5}▣ {2}\\S+ · [^·]+?\\s*(?:[⎘█].*)?$' },
196
+ { text: '^ {3,}[⠀-⣿] ' },
197
+ ],
198
+ turn: { text: '^ {2}┃ {2}\\S', lead: { notFg: ['#0a0a0a'] } },
199
+ answer: {
200
+ start: { text: '^ {5}[^\\s→+⠀-⣿▣]' },
201
+ continues: { text: '^ {5}[^\\s→+⠀-⣿▣]' },
202
+ upward: true,
203
+ },
204
+ trailer: { text: '^ {5}▣ {2}\\S+ · [^·]+ · \\d' },
205
+ requireTrailer: true,
206
+ // The scrollbar, the side panel and the copy button, on the same rows.
207
+ tidy: '\\s+[⎘█].*$',
208
+ },
209
+ {
210
+ // Qoder CLI 1.1.80 (GLM-5.3), default thinking: a "Thinking" heading in
211
+ // italics, then the reasoning behind a grey "│" bar in grey italics, as
212
+ // the model works and after it has answered. Messages start with a "▪"
213
+ // in the text colour, tool calls with a green one. While a turn runs, a
214
+ // braille spinner line says "(esc to cancel, Ns)".
215
+ name: 'qoder',
216
+ programs: ['qodercli', 'qoder'],
217
+ measured: 'Qoder CLI 1.1.80',
218
+ composer: { text: '^ > ' },
219
+ // The placeholder ("Type your message or @path/to/file") is grey; typed text is not.
220
+ typed: { text: '^ > ', word: { notFg: ['#95958f'] } },
221
+ chrome: [
222
+ { text: RULE_INDENTED },
223
+ { text: 'Shift\\+Tab' },
224
+ { text: '\\? for shortcuts\\s*$' },
225
+ { text: '\\(esc to cancel' },
226
+ ],
227
+ frame: { text: RULE_INDENTED },
228
+ busy: [{ text: '\\(esc to cancel' }],
229
+ turn: { text: '^ > \\S' },
230
+ reasoning: [
231
+ // The bar by its text alone: a code span or a table inside the
232
+ // reasoning is drawn upright, and an upright line is still reasoning.
233
+ {
234
+ start: { text: '^ Thinking\\s*$', lead: { italic: true } },
235
+ continues: { text: '^ │( |$)' },
236
+ },
237
+ // The same bar on its own: the heading may have scrolled away.
238
+ {
239
+ start: { text: '^ │ ' },
240
+ continues: { text: '^ │( |$)' },
241
+ },
242
+ ],
243
+ answer: {
244
+ start: { text: '^ ▪ ', lead: { fg: ['default', '#eeeeeb', '#ffffff', '#000000'] } },
245
+ continues: { text: '^ {3}[^\\s└│]' },
246
+ },
247
+ },
248
+ ];
249
+ /** How long a signature that ran past its time budget is set aside. */
250
+ export const SET_ASIDE_MS = 60_000;
251
+ /** Whether a signature is set aside for running past its time budget just now. */
252
+ export function setAside(signature, now = Date.now()) {
253
+ return signature.overBudgetAt !== null && now - signature.overBudgetAt < SET_ASIDE_MS;
254
+ }
255
+ function isRecord(value) {
256
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
257
+ }
258
+ /** A regular expression from a signature, or an error that says which one would not compile. */
259
+ function pattern(source, at) {
260
+ try {
261
+ return new RegExp(source, 'u');
262
+ }
263
+ catch (error) {
264
+ throw new Error(`${at} does not compile (${error instanceof Error ? error.message : String(error)})`, {
265
+ cause: error,
266
+ });
267
+ }
268
+ }
269
+ function compileStyle(value, at) {
270
+ if (!isRecord(value))
271
+ throw new Error(`${at} must be an object`);
272
+ const style = {};
273
+ for (const key of Object.keys(value)) {
274
+ const v = value[key];
275
+ if (key === 'bold' || key === 'dim' || key === 'italic') {
276
+ if (typeof v !== 'boolean')
277
+ throw new Error(`${at}.${key} must be true or false`);
278
+ style[key] = v;
279
+ }
280
+ else if (key === 'fg' || key === 'notFg') {
281
+ if (!Array.isArray(v) || v.length === 0 || !v.every((c) => typeof c === 'string' && /^(default|p\d{1,3}|#[0-9a-f]{6})$/.test(c))) {
282
+ throw new Error(`${at}.${key} must list colours as "default", "p<n>" or "#rrggbb"`);
283
+ }
284
+ style[key] = new Set(v);
285
+ }
286
+ else {
287
+ throw new Error(`${at} has an unknown key ${key}`);
288
+ }
289
+ }
290
+ return style;
291
+ }
292
+ function compileLine(value, at) {
293
+ if (!isRecord(value))
294
+ throw new Error(`${at} must be an object`);
295
+ const line = {};
296
+ for (const key of Object.keys(value)) {
297
+ const v = value[key];
298
+ if (key === 'text') {
299
+ if (typeof v !== 'string' || v === '')
300
+ throw new Error(`${at}.text must be a non-empty regular expression`);
301
+ line.text = pattern(v, `${at}.text`);
302
+ }
303
+ else if (key === 'lead' || key === 'body' || key === 'word') {
304
+ line[key] = compileStyle(v, `${at}.${key}`);
305
+ }
306
+ else {
307
+ throw new Error(`${at} has an unknown key ${key}`);
308
+ }
309
+ }
310
+ if (line.text === undefined && line.lead === undefined && line.body === undefined && line.word === undefined) {
311
+ throw new Error(`${at} needs text, lead, word or body`);
312
+ }
313
+ return line;
314
+ }
315
+ function compileBlock(value, at) {
316
+ if (!isRecord(value))
317
+ throw new Error(`${at} must be an object with start`);
318
+ for (const key of Object.keys(value)) {
319
+ if (key !== 'start' && key !== 'continues' && key !== 'upward')
320
+ throw new Error(`${at} has an unknown key ${key}`);
321
+ }
322
+ const upward = value['upward'] ?? false;
323
+ if (typeof upward !== 'boolean')
324
+ throw new Error(`${at}.upward must be true or false`);
325
+ return {
326
+ start: compileLine(value['start'], `${at}.start`),
327
+ ...(value['continues'] !== undefined ? { continues: compileLine(value['continues'], `${at}.continues`) } : {}),
328
+ upward,
329
+ };
330
+ }
331
+ const SIGNATURE_KEYS = new Set([
332
+ 'name', 'programs', 'measured', 'composer', 'chrome', 'frame', 'busy', 'turn', 'reasoning', 'answer', 'trailer',
333
+ 'requireTrailer', 'typed', 'tidy',
334
+ ]);
335
+ /**
336
+ * Compile signatures, setting aside any that cannot be used and saying why,
337
+ * in words a person can act on.
338
+ */
339
+ export function compileSignatures(list, where = 'agents.signatures') {
340
+ const signatures = [];
341
+ const problems = [];
342
+ const usable = [];
343
+ list.forEach((entry, index) => {
344
+ const at = `${where}[${String(index)}]`;
345
+ try {
346
+ if (!isRecord(entry))
347
+ throw new Error(`${at} must be an object`);
348
+ const name = entry['name'];
349
+ if (typeof name !== 'string' || !/^[a-z][a-z0-9-]{0,31}$/.test(name)) {
350
+ throw new Error(`${at}.name must be a short lower-case name such as "codex"`);
351
+ }
352
+ const named = `${at} (${name})`;
353
+ for (const key of Object.keys(entry)) {
354
+ if (!SIGNATURE_KEYS.has(key))
355
+ throw new Error(`${named} has an unknown key ${key}`);
356
+ }
357
+ const programs = entry['programs'] ?? [];
358
+ if (!Array.isArray(programs) || !programs.every((p) => typeof p === 'string' && p !== '')) {
359
+ throw new Error(`${named}.programs must be a list of command names`);
360
+ }
361
+ const composer = entry['composer'];
362
+ const chrome = entry['chrome'] ?? [];
363
+ const busy = entry['busy'] ?? [];
364
+ const reasoning = entry['reasoning'] ?? [];
365
+ if (!Array.isArray(chrome))
366
+ throw new Error(`${named}.chrome must be a list of line tests`);
367
+ if (!Array.isArray(busy))
368
+ throw new Error(`${named}.busy must be a list of line tests`);
369
+ if (!Array.isArray(reasoning))
370
+ throw new Error(`${named}.reasoning must be a list of blocks`);
371
+ if (entry['answer'] === undefined)
372
+ throw new Error(`${named} needs an answer block`);
373
+ const measured = entry['measured'];
374
+ const tidy = entry['tidy'];
375
+ if (tidy !== undefined && (typeof tidy !== 'string' || tidy === '')) {
376
+ throw new Error(`${named}.tidy must be a non-empty regular expression`);
377
+ }
378
+ const requireTrailer = entry['requireTrailer'] ?? false;
379
+ if (typeof requireTrailer !== 'boolean')
380
+ throw new Error(`${named}.requireTrailer must be true or false`);
381
+ if (requireTrailer && entry['trailer'] === undefined) {
382
+ throw new Error(`${named}.requireTrailer needs a trailer to require`);
383
+ }
384
+ signatures.push({
385
+ name,
386
+ programs: programs.map((p) => p.toLowerCase()),
387
+ ...(typeof measured === 'string' ? { measured } : {}),
388
+ source: JSON.stringify(entry),
389
+ composer: compileLine(composer, `${named}.composer`),
390
+ chrome: chrome.map((c, i) => compileLine(c, `${named}.chrome[${String(i)}]`)),
391
+ ...(entry['frame'] !== undefined ? { frame: compileLine(entry['frame'], `${named}.frame`) } : {}),
392
+ busy: busy.map((b, i) => compileLine(b, `${named}.busy[${String(i)}]`)),
393
+ ...(entry['turn'] !== undefined ? { turn: compileLine(entry['turn'], `${named}.turn`) } : {}),
394
+ reasoning: reasoning.map((r, i) => compileBlock(r, `${named}.reasoning[${String(i)}]`)),
395
+ answer: compileBlock(entry['answer'], `${named}.answer`),
396
+ ...(entry['trailer'] !== undefined ? { trailer: compileLine(entry['trailer'], `${named}.trailer`) } : {}),
397
+ requireTrailer,
398
+ ...(entry['typed'] !== undefined ? { typed: compileLine(entry['typed'], `${named}.typed`) } : {}),
399
+ ...(typeof tidy === 'string' ? { tidy: pattern(tidy, `${named}.tidy`) } : {}),
400
+ overBudgetAt: null,
401
+ });
402
+ usable.push(index);
403
+ }
404
+ catch (error) {
405
+ problems.push(`${error instanceof Error ? error.message : String(error)}: ignored`);
406
+ }
407
+ });
408
+ return { signatures, problems, usable };
409
+ }
410
+ let active = compileSignatures(BUILT_IN_SIGNATURES, 'built-in').signatures;
411
+ let reportOverBudget = () => undefined;
412
+ /**
413
+ * Use the built-in signatures plus `extra`, the entries from config; an entry
414
+ * named like a built-in one replaces it. Returns what was wrong with `extra`.
415
+ */
416
+ export function useAgentSignatures(extra, onOverBudget = () => undefined) {
417
+ const { signatures, problems } = compileSignatures(extra);
418
+ const replaced = new Set(signatures.map((s) => s.name));
419
+ active = [
420
+ ...compileSignatures(BUILT_IN_SIGNATURES, 'built-in').signatures.filter((s) => !replaced.has(s.name)),
421
+ ...signatures,
422
+ ];
423
+ reportOverBudget = onOverBudget;
424
+ return problems;
425
+ }
426
+ /** The names `terminal_start`'s `agent` accepts. */
427
+ export function agentNames() {
428
+ return active.map((s) => s.name).sort();
429
+ }
430
+ /** A program's name from its start command: `C:\x\Claude.EXE` is `claude`. */
431
+ export function programName(command) {
432
+ const base = command.split(/[\\/]/).pop() ?? command;
433
+ return base.replace(/\.(exe|cmd|bat|ps1|com)$/i, '').toLowerCase();
434
+ }
435
+ /**
436
+ * The agent a session runs as, by name: the one it was started as, or the one
437
+ * whose programs include its start command. The signatures are compiled and
438
+ * ordered exactly as `useAgentSignatures` orders the daemon's (the built-ins
439
+ * a config entry does not replace, then the config's entries in order, first
440
+ * match), so a client and the daemon name the same agent. Null when neither
441
+ * names one. For a client, which has no signature registry of its own; the
442
+ * daemon reads screens with `signatureFor`.
443
+ */
444
+ export function agentNameFor(agent, command, extra = []) {
445
+ if (agent !== undefined)
446
+ return agent;
447
+ const configured = compileSignatures(extra).signatures;
448
+ const replaced = new Set(configured.map((signature) => signature.name));
449
+ const ordered = [
450
+ ...compileSignatures(BUILT_IN_SIGNATURES, 'built-in').signatures.filter((s) => !replaced.has(s.name)),
451
+ ...configured,
452
+ ];
453
+ const program = programName(command);
454
+ return ordered.find((signature) => signature.programs.includes(program))?.name ?? null;
455
+ }
456
+ /**
457
+ * The signature for a session: the agent it was started as, or the one whose
458
+ * programs include its start command. Null when neither names one.
459
+ */
460
+ export function signatureFor(agent, command) {
461
+ if (agent !== undefined)
462
+ return active.find((s) => s.name === agent && !setAside(s)) ?? null;
463
+ const program = programName(command);
464
+ return active.find((s) => !setAside(s) && s.programs.includes(program)) ?? null;
465
+ }
466
+ // ---------------------------------------------------------------- matching
467
+ function styleFits(style, test) {
468
+ if (test.bold !== undefined && style.bold !== test.bold)
469
+ return false;
470
+ if (test.dim !== undefined && style.dim !== test.dim)
471
+ return false;
472
+ if (test.italic !== undefined && style.italic !== test.italic)
473
+ return false;
474
+ const fg = style.fg ?? 'default';
475
+ if (test.fg !== undefined && !test.fg.has(fg))
476
+ return false;
477
+ if (test.notFg !== undefined && test.notFg.has(fg))
478
+ return false;
479
+ return true;
480
+ }
481
+ /** The style of each character that is not a space, in order. */
482
+ function inkStyles(line) {
483
+ const out = [];
484
+ for (const span of line.spans) {
485
+ for (let i = span.from; i < span.to; i++) {
486
+ if (!/\s/u.test(line.text[i] ?? ' '))
487
+ out.push(span);
488
+ }
489
+ }
490
+ return out;
491
+ }
492
+ function lineFits(line, test) {
493
+ if (test.text !== undefined && !test.text.test(line.text))
494
+ return false;
495
+ if (test.lead === undefined && test.body === undefined && test.word === undefined)
496
+ return true;
497
+ const ink = inkStyles(line);
498
+ if (ink.length === 0)
499
+ return false;
500
+ if (test.lead !== undefined && !styleFits(ink[0], test.lead))
501
+ return false;
502
+ if (test.word !== undefined && (ink.length < 2 || !styleFits(ink[1], test.word)))
503
+ return false;
504
+ if (test.body !== undefined) {
505
+ const body = ink.slice(1);
506
+ if (body.length === 0 || !body.every((style) => styleFits(style, test.body)))
507
+ return false;
508
+ }
509
+ return true;
510
+ }
511
+ /**
512
+ * Whether a line holds nothing of the transcript: blank, or blank once the
513
+ * signature's `tidy` has taken away what is drawn beside the text (a side
514
+ * panel, a scrollbar).
515
+ */
516
+ const blank = (line, tidy) => line === undefined || (tidy === undefined ? line.text : line.text.replace(tidy, '')).trim() === '';
517
+ /** The end (exclusive) of the block that starts at `at`, stopping at `limit`. */
518
+ function blockEnd(lines, at, block, limit, tidy) {
519
+ let end = at + 1;
520
+ if (block.continues === undefined)
521
+ return end;
522
+ let i = at + 1;
523
+ while (i < limit) {
524
+ const line = lines[i];
525
+ if (!blank(line, tidy) && lineFits(line, block.continues)) {
526
+ i++;
527
+ end = i;
528
+ continue;
529
+ }
530
+ if (blank(line, tidy)) {
531
+ // A blank line stays inside the block only if the block carries on after it.
532
+ let next = i;
533
+ while (next < limit && blank(lines[next], tidy))
534
+ next++;
535
+ if (next < limit && lineFits(lines[next], block.continues)) {
536
+ i = next;
537
+ continue;
538
+ }
539
+ }
540
+ break;
541
+ }
542
+ return end;
543
+ }
544
+ /** Run `body` under the budget; a signature that overruns is set aside. */
545
+ function guarded(signature, body) {
546
+ try {
547
+ return withRegexBudget(signature.source.slice(0, 120), body);
548
+ }
549
+ catch (error) {
550
+ if (!(error instanceof RegexBudgetError))
551
+ throw error;
552
+ // Reported each time it trips: a person reading daemon.log sees whether
553
+ // a signature keeps running long or tripped once under load.
554
+ signature.overBudgetAt = Date.now();
555
+ reportOverBudget(signature.name);
556
+ return null;
557
+ }
558
+ }
559
+ /** The index of the composer's line and the first line of chrome, or null. */
560
+ function composerAt(lines, signature) {
561
+ for (let i = lines.length - 1; i >= 0; i--) {
562
+ if (!lineFits(lines[i], signature.composer))
563
+ continue;
564
+ // Reasoning is never drawn below the composer. A line with reasoning under
565
+ // it is the echo of the person's prompt, taken for the composer while a
566
+ // dialog stands in its place: no composer is found, so the filter reads
567
+ // the whole screen and a result is refused.
568
+ for (let j = i + 1; j < lines.length; j++) {
569
+ if (signature.reasoning.some((block) => lineFits(lines[j], block.start)))
570
+ return null;
571
+ }
572
+ let top = i;
573
+ while (top > 0) {
574
+ const above = lines[top - 1];
575
+ if (!blank(above, signature.tidy) && !signature.chrome.some((test) => lineFits(above, test)))
576
+ break;
577
+ top--;
578
+ }
579
+ return { line: i, chrome: top };
580
+ }
581
+ return null;
582
+ }
583
+ /** `[from, to)` ranges of reasoning above `limit`. */
584
+ function reasoningRanges(lines, signature, limit) {
585
+ const ranges = [];
586
+ let i = 0;
587
+ while (i < limit) {
588
+ const block = signature.reasoning.find((b) => lineFits(lines[i], b.start));
589
+ if (block === undefined) {
590
+ i++;
591
+ continue;
592
+ }
593
+ const end = blockEnd(lines, i, block, limit, signature.tidy);
594
+ ranges.push([i, end]);
595
+ i = end;
596
+ }
597
+ return ranges;
598
+ }
599
+ /** The line that stands in for a hidden block. */
600
+ export function hiddenMarker(count) {
601
+ return `[reasoning hidden: ${String(count)} line${count === 1 ? '' : 's'}]`;
602
+ }
603
+ /**
604
+ * The lines from `firstVisible` on, with every reasoning block above the
605
+ * composer replaced by one marker line. The lines before `firstVisible` are
606
+ * context only: a block whose first line is among them is still recognised
607
+ * where it carries on into what is returned. `rows` count from
608
+ * `firstVisible`. Null when the signature was set aside for running past its
609
+ * time budget, which the caller must treat as "cannot filter".
610
+ */
611
+ export function hideReasoning(lines, signature, firstVisible = 0) {
612
+ return guarded(signature, () => {
613
+ // Everything above the composer's own line, the chrome over it included:
614
+ // a spinner there can carry the model's words about what it is thinking.
615
+ const composer = composerAt(lines, signature);
616
+ const limit = composer?.line ?? lines.length;
617
+ const ranges = reasoningRanges(lines, signature, limit);
618
+ const out = { lines: [], rows: [], markers: [], hiddenLines: 0, hiddenBlocks: 0 };
619
+ const keep = (i) => {
620
+ out.lines.push(lines[i].text);
621
+ out.rows.push(i - firstVisible);
622
+ out.markers.push(false);
623
+ };
624
+ let next = firstVisible;
625
+ for (const [from, to] of ranges) {
626
+ if (to <= firstVisible)
627
+ continue;
628
+ const start = Math.max(from, firstVisible);
629
+ for (let i = next; i < start; i++)
630
+ keep(i);
631
+ out.lines.push(hiddenMarker(to - start));
632
+ out.rows.push(start - firstVisible);
633
+ out.markers.push(true);
634
+ out.hiddenLines += to - start;
635
+ out.hiddenBlocks++;
636
+ next = to;
637
+ }
638
+ for (let i = next; i < lines.length; i++)
639
+ keep(i);
640
+ return out;
641
+ });
642
+ }
643
+ /** What the CLI and the MCP tool say when there is no result to give. */
644
+ export function resultRefusal(reason) {
645
+ switch (reason) {
646
+ case 'busy':
647
+ return 'No result yet: the agent is still working on its turn.';
648
+ case 'no-answer':
649
+ return "No result: nothing below the latest prompt reads as the agent's answer.";
650
+ case 'no-composer':
651
+ return ("No result: the agent's composer is not on screen (a dialog, another view, or a " +
652
+ 'program still starting), so its turn cannot be read.');
653
+ case 'over-budget':
654
+ return 'No result: the signature ran past the regular-expression time budget and was set aside for a minute.';
655
+ case 'unfinished':
656
+ return ('No result: the latest turn has no closing line, so it has not finished (it was ' +
657
+ 'interrupted, or ended without an answer).');
658
+ case 'prompt-typed':
659
+ return 'No result: the composer holds a prompt that has not been sent, so the latest turn is about to change.';
660
+ default:
661
+ return 'No result.';
662
+ }
663
+ }
664
+ /**
665
+ * The answer that ends the latest turn. It has to start below the latest
666
+ * prompt the person typed, sit above the composer, and lie outside every
667
+ * reasoning block; nothing else is ever returned in its place.
668
+ */
669
+ export function latestResult(lines, signature) {
670
+ const result = guarded(signature, () => {
671
+ const composer = composerAt(lines, signature);
672
+ if (composer === null)
673
+ return { found: false, reason: 'no-composer', status: [] };
674
+ const status = lines
675
+ .slice(composer.line + 1)
676
+ .filter((line) => !blank(line) && !(signature.frame !== undefined && lineFits(line, signature.frame)))
677
+ .map((line) => line.text);
678
+ if (signature.typed !== undefined) {
679
+ for (let i = composer.chrome; i <= composer.line; i++) {
680
+ if (lineFits(lines[i], signature.typed))
681
+ return { found: false, reason: 'prompt-typed', status };
682
+ }
683
+ }
684
+ let turnStart = 0;
685
+ let prompt = null;
686
+ if (signature.turn !== undefined) {
687
+ for (let i = composer.chrome - 1; i >= 0; i--) {
688
+ if (lineFits(lines[i], signature.turn)) {
689
+ turnStart = i + 1;
690
+ prompt = lines[i].text.replace(/\s+$/u, '');
691
+ break;
692
+ }
693
+ }
694
+ }
695
+ // The latest turn and the chrome under it: a spinner can be drawn in
696
+ // either, and a stale copy in the scrollback above says nothing.
697
+ const current = lines.slice(turnStart);
698
+ if (signature.busy.some((test) => current.some((line) => lineFits(line, test)))) {
699
+ return { found: false, reason: 'busy', status };
700
+ }
701
+ const ranges = reasoningRanges(lines, signature, composer.chrome);
702
+ const inReasoning = (i) => ranges.some(([from, to]) => i >= from && i < to);
703
+ let start = -1;
704
+ for (let i = composer.chrome - 1; i >= turnStart; i--) {
705
+ if (!inReasoning(i) && lineFits(lines[i], signature.answer.start)) {
706
+ start = i;
707
+ break;
708
+ }
709
+ }
710
+ if (start === -1)
711
+ return { found: false, reason: 'no-answer', status };
712
+ let end = blockEnd(lines, start, signature.answer, composer.chrome, signature.tidy);
713
+ if (signature.answer.upward) {
714
+ for (;;) {
715
+ let above = start - 1;
716
+ while (above >= turnStart && blank(lines[above], signature.tidy))
717
+ above--;
718
+ if (above < turnStart || inReasoning(above) || !lineFits(lines[above], signature.answer.start))
719
+ break;
720
+ start = above;
721
+ }
722
+ }
723
+ const firstReasoningAfter = ranges.find(([from]) => from > start);
724
+ if (firstReasoningAfter !== undefined)
725
+ end = Math.min(end, firstReasoningAfter[0]);
726
+ const tidy = (text) => (signature.tidy === undefined ? text : text.replace(signature.tidy, '')).replace(/\s+$/u, '');
727
+ const trailer = [];
728
+ if (signature.trailer !== undefined) {
729
+ for (let i = end; i < composer.chrome; i++) {
730
+ if (lineFits(lines[i], signature.trailer))
731
+ trailer.push(tidy(lines[i].text));
732
+ }
733
+ }
734
+ if (signature.requireTrailer && trailer.length === 0)
735
+ return { found: false, reason: 'unfinished', status };
736
+ return { found: true, answer: lines.slice(start, end).map((line) => tidy(line.text)), trailer, status, prompt };
737
+ });
738
+ return result ?? { found: false, reason: 'over-budget', status: [] };
739
+ }
740
+ //# sourceMappingURL=reasoning.js.map