shellpuppet 0.0.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +31 -0
  3. package/README.md +499 -8
  4. package/dist/cli/desktopShortcut.d.ts +22 -0
  5. package/dist/cli/desktopShortcut.js +157 -0
  6. package/dist/cli/desktopShortcut.js.map +1 -0
  7. package/dist/cli/index.d.ts +13 -0
  8. package/dist/cli/index.js +846 -0
  9. package/dist/cli/index.js.map +1 -0
  10. package/dist/client/http.d.ts +143 -0
  11. package/dist/client/http.js +581 -0
  12. package/dist/client/http.js.map +1 -0
  13. package/dist/core/dialogs.d.ts +96 -0
  14. package/dist/core/dialogs.js +226 -0
  15. package/dist/core/dialogs.js.map +1 -0
  16. package/dist/core/echo.d.ts +71 -0
  17. package/dist/core/echo.js +249 -0
  18. package/dist/core/echo.js.map +1 -0
  19. package/dist/core/find.d.ts +34 -0
  20. package/dist/core/find.js +41 -0
  21. package/dist/core/find.js.map +1 -0
  22. package/dist/core/keys.d.ts +22 -0
  23. package/dist/core/keys.js +80 -0
  24. package/dist/core/keys.js.map +1 -0
  25. package/dist/core/manager.d.ts +96 -0
  26. package/dist/core/manager.js +271 -0
  27. package/dist/core/manager.js.map +1 -0
  28. package/dist/core/nativePty.d.ts +73 -0
  29. package/dist/core/nativePty.js +161 -0
  30. package/dist/core/nativePty.js.map +1 -0
  31. package/dist/core/policy.d.ts +61 -0
  32. package/dist/core/policy.js +143 -0
  33. package/dist/core/policy.js.map +1 -0
  34. package/dist/core/promptDetector.d.ts +109 -0
  35. package/dist/core/promptDetector.js +897 -0
  36. package/dist/core/promptDetector.js.map +1 -0
  37. package/dist/core/reasoning.d.ts +265 -0
  38. package/dist/core/reasoning.js +933 -0
  39. package/dist/core/reasoning.js.map +1 -0
  40. package/dist/core/regexBudget.d.ts +64 -0
  41. package/dist/core/regexBudget.js +103 -0
  42. package/dist/core/regexBudget.js.map +1 -0
  43. package/dist/core/renderer.d.ts +127 -0
  44. package/dist/core/renderer.js +316 -0
  45. package/dist/core/renderer.js.map +1 -0
  46. package/dist/core/selection.d.ts +6 -0
  47. package/dist/core/selection.js +48 -0
  48. package/dist/core/selection.js.map +1 -0
  49. package/dist/core/session.d.ts +565 -0
  50. package/dist/core/session.js +1450 -0
  51. package/dist/core/session.js.map +1 -0
  52. package/dist/core/types.d.ts +316 -0
  53. package/dist/core/types.js +71 -0
  54. package/dist/core/types.js.map +1 -0
  55. package/dist/core/waiter.d.ts +94 -0
  56. package/dist/core/waiter.js +310 -0
  57. package/dist/core/waiter.js.map +1 -0
  58. package/dist/core/windowsConsoleHost.d.ts +147 -0
  59. package/dist/core/windowsConsoleHost.js +588 -0
  60. package/dist/core/windowsConsoleHost.js.map +1 -0
  61. package/dist/core/windowsPtyStart.d.ts +161 -0
  62. package/dist/core/windowsPtyStart.js +236 -0
  63. package/dist/core/windowsPtyStart.js.map +1 -0
  64. package/dist/daemon/audit.d.ts +23 -0
  65. package/dist/daemon/audit.js +51 -0
  66. package/dist/daemon/audit.js.map +1 -0
  67. package/dist/daemon/auth.d.ts +197 -0
  68. package/dist/daemon/auth.js +366 -0
  69. package/dist/daemon/auth.js.map +1 -0
  70. package/dist/daemon/config.d.ts +119 -0
  71. package/dist/daemon/config.js +568 -0
  72. package/dist/daemon/config.js.map +1 -0
  73. package/dist/daemon/folderPicker.d.ts +27 -0
  74. package/dist/daemon/folderPicker.js +115 -0
  75. package/dist/daemon/folderPicker.js.map +1 -0
  76. package/dist/daemon/index.d.ts +7 -0
  77. package/dist/daemon/index.js +88 -0
  78. package/dist/daemon/index.js.map +1 -0
  79. package/dist/daemon/launchProfiles.d.ts +155 -0
  80. package/dist/daemon/launchProfiles.js +554 -0
  81. package/dist/daemon/launchProfiles.js.map +1 -0
  82. package/dist/daemon/liveness.d.ts +36 -0
  83. package/dist/daemon/liveness.js +71 -0
  84. package/dist/daemon/liveness.js.map +1 -0
  85. package/dist/daemon/logger.d.ts +7 -0
  86. package/dist/daemon/logger.js +29 -0
  87. package/dist/daemon/logger.js.map +1 -0
  88. package/dist/daemon/meta.d.ts +9 -0
  89. package/dist/daemon/meta.js +24 -0
  90. package/dist/daemon/meta.js.map +1 -0
  91. package/dist/daemon/paths.d.ts +85 -0
  92. package/dist/daemon/paths.js +154 -0
  93. package/dist/daemon/paths.js.map +1 -0
  94. package/dist/daemon/screenshot.d.ts +144 -0
  95. package/dist/daemon/screenshot.js +402 -0
  96. package/dist/daemon/screenshot.js.map +1 -0
  97. package/dist/daemon/server.d.ts +453 -0
  98. package/dist/daemon/server.js +3954 -0
  99. package/dist/daemon/server.js.map +1 -0
  100. package/dist/daemon/sessionFeed.d.ts +48 -0
  101. package/dist/daemon/sessionFeed.js +101 -0
  102. package/dist/daemon/sessionFeed.js.map +1 -0
  103. package/dist/daemon/terminalReports.d.ts +38 -0
  104. package/dist/daemon/terminalReports.js +84 -0
  105. package/dist/daemon/terminalReports.js.map +1 -0
  106. package/dist/daemon/viewerLauncher.d.ts +226 -0
  107. package/dist/daemon/viewerLauncher.js +562 -0
  108. package/dist/daemon/viewerLauncher.js.map +1 -0
  109. package/dist/daemon/viewerSync.d.ts +38 -0
  110. package/dist/daemon/viewerSync.js +83 -0
  111. package/dist/daemon/viewerSync.js.map +1 -0
  112. package/dist/mcp/config.d.ts +50 -0
  113. package/dist/mcp/config.js +95 -0
  114. package/dist/mcp/config.js.map +1 -0
  115. package/dist/mcp/index.d.ts +10 -0
  116. package/dist/mcp/index.js +78 -0
  117. package/dist/mcp/index.js.map +1 -0
  118. package/dist/mcp/tools.d.ts +66 -0
  119. package/dist/mcp/tools.js +638 -0
  120. package/dist/mcp/tools.js.map +1 -0
  121. package/dist/viewer/dashboard-folders.js +20 -0
  122. package/dist/viewer/dashboard-layout.js +52 -0
  123. package/dist/viewer/dashboard.css +67 -0
  124. package/dist/viewer/dashboard.html +44 -0
  125. package/dist/viewer/dashboard.js +1518 -0
  126. package/dist/viewer/icon-16.png +0 -0
  127. package/dist/viewer/icon-180.png +0 -0
  128. package/dist/viewer/icon-32.png +0 -0
  129. package/dist/viewer/icon-512.png +0 -0
  130. package/dist/viewer/icon.ico +0 -0
  131. package/dist/viewer/icon.svg +66 -0
  132. package/dist/viewer/index.html +61 -0
  133. package/dist/viewer/pane.js +736 -0
  134. package/dist/viewer/viewer.css +95 -0
  135. package/dist/viewer/viewer.js +84 -0
  136. package/package.json +66 -7
  137. package/index.js +0 -4
@@ -0,0 +1,933 @@
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
+ * A question the program is waiting on is never hidden, whatever its
23
+ * signature says: the rows the prompt detection (`promptDetector.ts`)
24
+ * claims for a question on screen stay, so a permission box drawn in the
25
+ * same style as the reasoning keeps every row of its own.
26
+ *
27
+ * Both readers fail closed. A session whose program has no signature is
28
+ * refused rather than shown unfiltered, and `terminal_result` refuses when it
29
+ * cannot find an answer it recognises, rather than returning something else.
30
+ * What the filter cannot promise: a program that draws its reasoning in a
31
+ * shape its signature does not describe, a new version that changes the
32
+ * shape, or a screen that imitates one, defeats it. Screen content is
33
+ * untrusted input either way (design §4.4).
34
+ *
35
+ * Signature patterns run under the regular-expression time budget
36
+ * (`regexBudget.ts`), as patterns from config are text a person wrote.
37
+ * The prompt detector times its dialog signatures the same way; its own
38
+ * patterns are not timed.
39
+ */
40
+ import { RegexBudgetError, SET_ASIDE_MS, withRegexBudget } from './regexBudget.js';
41
+ import { detectPrompt } from './promptDetector.js';
42
+ // ---------------------------------------------------------------- built in
43
+ const RULE = '^[─━]{10,}$';
44
+ const RULE_INDENTED = '^\\s*[─━]{10,}';
45
+ /**
46
+ * Grok draws its permission box behind the same bar as its reasoning: a
47
+ * question row (`> `), a command's rows (`│` starts one, `:` continues it)
48
+ * and option rows (`1 (○)`). No Grok reasoning rule starts or continues on
49
+ * them, so a permission box keeps every row of its own, whatever wording
50
+ * its question is asked in.
51
+ */
52
+ const GROK_BOX_ROW = ' {2}(?:> |\\d+ \\([○•●]\\) |[│:])';
53
+ /**
54
+ * Built-in signatures. Each comment names the screens its fixtures come from.
55
+ */
56
+ export const BUILT_IN_SIGNATURES = [
57
+ {
58
+ // Claude Code 2.1.312, default view and the ctrl+o transcript: no
59
+ // reasoning text is drawn in either, only a spinner line while the model
60
+ // thinks ("✻ Pondering… (2s · thinking with xhigh effort)"). The answer
61
+ // is a `●` in the text colour; tool calls get a grey or coloured `●`.
62
+ name: 'claude',
63
+ programs: ['claude'],
64
+ measured: 'Claude Code 2.1.312',
65
+ // The composer's prompt glyph is followed by a non-breaking space once
66
+ // something is typed; the echo of a sent prompt by an ordinary one.
67
+ composer: { text: '^❯( |\\xa0|$)' },
68
+ typed: { text: '^❯[ \\xa0]\\S', word: { dim: false } },
69
+ chrome: [{ text: RULE }, { text: '/effort\\s*$' }],
70
+ frame: { text: RULE },
71
+ busy: [{ text: '^[✻✽✶✢✳·*] \\S+…' }],
72
+ turn: { text: '^❯ \\S' },
73
+ answer: {
74
+ start: { text: '^● ', lead: { fg: ['default', '#ffffff', '#000000'] } },
75
+ continues: { text: '^ {2}' },
76
+ },
77
+ trailer: { text: '^✻ \\S' },
78
+ requireTrailer: true,
79
+ },
80
+ {
81
+ // Codex CLI 0.165.0 (GPT-6-Sol, high effort), default view. The answer is
82
+ // a dim "•" with plain text after it; a tool group is a dim "•" with a
83
+ // bold heading ("Explored"), a command a bold green "•" ("Ran"). While a
84
+ // turn runs, "Working (Ns • esc to interrupt)" sits above the composer.
85
+ name: 'codex',
86
+ programs: ['codex'],
87
+ measured: 'Codex CLI 0.165.0',
88
+ composer: { text: '^› ' },
89
+ // The placeholder ("Ask Codex to do anything") is dim; typed text is not.
90
+ typed: { text: '^› \\S', word: { dim: false } },
91
+ chrome: [{ text: 'esc to interrupt' }],
92
+ busy: [{ text: 'esc to interrupt' }],
93
+ turn: { text: '^› \\S' },
94
+ answer: {
95
+ start: { text: '^• ', lead: { dim: true }, word: { bold: false, italic: false } },
96
+ continues: { text: '^ {2}(?!Worked for )[^\\s└]' },
97
+ },
98
+ trailer: { text: '^ {2}Worked for ' },
99
+ requireTrailer: true,
100
+ },
101
+ {
102
+ // Antigravity CLI 1.4.10 (Gemini 3.8 Flash, high effort). A summary of
103
+ // the model's reasoning stays on screen as one line, "○ Thought for 4.2s
104
+ // (Create the file, then…)"; while it works, the spinner's label is the
105
+ // subject of what it is thinking about. "▸ Thought for 5s, 228 tokens"
106
+ // carries no text. Tool calls are a green "●"; the answer is plain text
107
+ // indented two spaces. While a turn runs, "esc to cancel" is under the
108
+ // composer.
109
+ name: 'agy',
110
+ programs: ['agy', 'antigravity'],
111
+ measured: 'Antigravity CLI 1.4.10',
112
+ composer: { text: '^>' },
113
+ chrome: [{ text: RULE_INDENTED }, { text: '^[⠀-⣿] {2}' }, { text: '^└ ' }],
114
+ frame: { text: RULE_INDENTED },
115
+ busy: [{ text: '^[⠀-⣿] {2}\\S' }, { text: '^esc to cancel' }],
116
+ turn: { text: '^> \\S' },
117
+ reasoning: [
118
+ { start: { text: '^○ Thought for ' } },
119
+ { start: { text: '^[⠀-⣿] {2}\\S' } },
120
+ ],
121
+ answer: {
122
+ start: { text: '^ {2}\\S', lead: { fg: ['default', '#ffffff', '#000000', 'p7', 'p15'] } },
123
+ continues: { text: '^ {2}\\S', lead: { fg: ['default', '#ffffff', '#000000', 'p7', 'p15'] } },
124
+ upward: true,
125
+ },
126
+ },
127
+ {
128
+ // Grok Build 1.0.70 (grok-4.7, xhigh effort). While the model thinks, its
129
+ // reasoning streams into a block behind a fading "│" bar, headed
130
+ // "♦ Thinking…"; once it is done the block collapses to "♦ Thought for
131
+ // Ns" with nothing under it. Messages and the answer are plain text
132
+ // indented five spaces; tool work is a "♦" line ("♦ Edited primes.py, ran
133
+ // 1 command"); "Worked for Ns" closes the turn. While a turn runs, a
134
+ // spinner line ("| Thinking… 3.1s") sits above the composer's box.
135
+ name: 'grok',
136
+ programs: ['grok'],
137
+ measured: 'Grok Build 1.0.70',
138
+ composer: { text: '^ {2}│ >' },
139
+ chrome: [{ text: '^ {2}╭' }, { text: '^ {3}[|/\\\\-] \\S' }, { text: '^ {3}\\S.*shift\\+tab', }],
140
+ frame: { text: '^ {2}[╭╰]' },
141
+ busy: [{ text: '^ {3}[|/\\\\-] .* \\d+(?:\\.\\d+)?s\\s*$' }, { text: '♦ Thinking…' }],
142
+ turn: { text: '^ {5}> \\S' },
143
+ reasoning: [
144
+ {
145
+ start: { text: '^ {2}│ {2}♦ Thinking' },
146
+ continues: { text: `^ {2}│(?!${GROK_BOX_ROW})` },
147
+ },
148
+ // The spinner's label can be the model's own words about what it is
149
+ // doing; it goes too, and the busy state still shows in the result.
150
+ { start: { text: '^ {3}[|/\\\\-] \\S' } },
151
+ // The bar on its own: the heading may have scrolled away.
152
+ {
153
+ start: { text: `^ {2}│(?!${GROK_BOX_ROW}) {2}\\S` },
154
+ continues: { text: `^ {2}│(?!${GROK_BOX_ROW})` },
155
+ },
156
+ ],
157
+ answer: {
158
+ start: { text: '^ {5}(?!Worked for )[^\\s♦>]', lead: { fg: ['default', '#c8c8c8', '#ffffff', '#000000'] } },
159
+ continues: { text: '^ {5}(?!Worked for )[^\\s♦>]', lead: { fg: ['default', '#c8c8c8', '#ffffff', '#000000'] } },
160
+ upward: true,
161
+ },
162
+ trailer: { text: '^ {5}Worked for ' },
163
+ requireTrailer: true,
164
+ // A right-aligned time on each message row.
165
+ tidy: ' {2,}\\d{1,2}:\\d{2}(?: ?[A-Za-z]{2})?\\s*$',
166
+ },
167
+ {
168
+ // OpenCode 2.0.26 (GLM-5.3): no reasoning text is drawn. While the model
169
+ // thinks it shows "⠇ Thinking"; afterwards a collapsed "+ Thought · Ns"
170
+ // with nothing under it. The answer is plain paragraphs, in the same
171
+ // colour and indent as any other text, closed by a footer naming the
172
+ // agent, the model and the time ("Build · GLM-5.3 · 7.0s"). A sidebar
173
+ // can share the rows on the right.
174
+ name: 'opencode',
175
+ programs: ['opencode'],
176
+ measured: 'OpenCode 2.0.26',
177
+ composer: { text: '^ {2}[┃╹]' },
178
+ chrome: [{ text: '^ {2}┃' }, { text: '^\\s{60,}\\S' }],
179
+ busy: [
180
+ { text: '\\besc interrupt\\b' },
181
+ { text: '^ {3,}[⠀-⣿] ' },
182
+ { text: '^ {3,}\\+ Thought\\s*$' },
183
+ ],
184
+ turn: { text: '^ {2}┃ {2}\\S' },
185
+ answer: {
186
+ start: { text: '^ {5}[^\\s→+⠀-⣿]', lead: { fg: ['default', '#eeeeee', '#ffffff', '#000000'] } },
187
+ continues: { text: '^ {5}[^\\s→+⠀-⣿]', lead: { fg: ['default', '#eeeeee', '#ffffff', '#000000'] } },
188
+ upward: true,
189
+ },
190
+ trailer: { text: '^ {5}\\S+ · [^·]+ · \\d[\\d.]*m?s\\b' },
191
+ requireTrailer: true,
192
+ // The sidebar, on the same rows to the right.
193
+ tidy: ' {20,}\\S.*$',
194
+ },
195
+ {
196
+ // MiMoCode 0.1.16 (MiMo-V2.6-Pro), built from OpenCode: no reasoning text
197
+ // is drawn. A collapsed "+ Thought: Ns" sits before each tool group and
198
+ // before the answer; tool calls are boxes behind a bar drawn in the
199
+ // background colour, the person's prompt and the composer behind one in
200
+ // the agent's colour. The answer is plain paragraphs closed by "▣ Build ·
201
+ // MiMo-V2.6-Pro · Ns", which carries no time while the turn runs. A side
202
+ // panel on the right shares the rows (the session's title, context and
203
+ // cost). The composer can hold a suggestion of its own after a turn.
204
+ name: 'mimo',
205
+ programs: ['mimo', 'mimocode', 'mimo-code'],
206
+ measured: 'MiMoCode 0.1.16',
207
+ composer: { text: '^ {2}[┃╹]' },
208
+ chrome: [{ text: '^ {2}┃' }, { text: '^\\s{60,}\\S' }],
209
+ busy: [
210
+ { text: '\\besc (?:to )?interrupt\\b' },
211
+ { text: '^ {5}▣ {2}\\S+ · [^·]+?\\s*(?:[⎘█].*)?$' },
212
+ { text: '^ {3,}[⠀-⣿] ' },
213
+ ],
214
+ turn: { text: '^ {2}┃ {2}\\S', lead: { notFg: ['#0a0a0a'] } },
215
+ answer: {
216
+ start: { text: '^ {5}[^\\s→+⠀-⣿▣]' },
217
+ continues: { text: '^ {5}[^\\s→+⠀-⣿▣]' },
218
+ upward: true,
219
+ },
220
+ trailer: { text: '^ {5}▣ {2}\\S+ · [^·]+ · \\d' },
221
+ requireTrailer: true,
222
+ // The scrollbar, the side panel and the copy button, on the same rows.
223
+ tidy: '\\s+[⎘█].*$',
224
+ },
225
+ {
226
+ // Qoder CLI 1.1.80 (GLM-5.3), default thinking: a "Thinking" heading in
227
+ // italics, then the reasoning behind a grey "│" bar in grey italics, as
228
+ // the model works and after it has answered. Messages start with a "▪"
229
+ // in the text colour, tool calls with a green one. While a turn runs, a
230
+ // braille spinner line says "(esc to cancel, Ns)".
231
+ name: 'qoder',
232
+ programs: ['qodercli', 'qoder'],
233
+ measured: 'Qoder CLI 1.1.80',
234
+ composer: { text: '^ > ' },
235
+ // The placeholder ("Type your message or @path/to/file") is grey; typed text is not.
236
+ typed: { text: '^ > ', word: { notFg: ['#95958f'] } },
237
+ chrome: [
238
+ { text: RULE_INDENTED },
239
+ { text: 'Shift\\+Tab' },
240
+ { text: '\\? for shortcuts\\s*$' },
241
+ { text: '\\(esc to cancel' },
242
+ ],
243
+ frame: { text: RULE_INDENTED },
244
+ busy: [{ text: '\\(esc to cancel' }],
245
+ turn: { text: '^ > \\S' },
246
+ reasoning: [
247
+ // The bar by its text alone: a code span or a table inside the
248
+ // reasoning is drawn upright, and an upright line is still reasoning.
249
+ {
250
+ start: { text: '^ Thinking\\s*$', lead: { italic: true } },
251
+ continues: { text: '^ │( |$)' },
252
+ },
253
+ // The same bar on its own: the heading may have scrolled away.
254
+ {
255
+ start: { text: '^ │ ' },
256
+ continues: { text: '^ │( |$)' },
257
+ },
258
+ ],
259
+ answer: {
260
+ start: { text: '^ ▪ ', lead: { fg: ['default', '#eeeeeb', '#ffffff', '#000000'] } },
261
+ continues: { text: '^ {3}[^\\s└│]' },
262
+ },
263
+ },
264
+ {
265
+ // Muse Code 1.4.14. A completed answer is a bold ◆ block. Tool calls
266
+ // use a green ◆, and the live reasoning summary uses a grey ◆. The
267
+ // composer is the last ❯ row followed only by chrome, with or without
268
+ // typed text. Submitted turns sit above it. The Muse Code banner
269
+ // sits above the transcript, and the status line ending in Launch overrides
270
+ // sits below the composer. A
271
+ // finished turn may have no Worked for line.
272
+ name: 'muse',
273
+ programs: ['muse', 'muse-bin-*'],
274
+ measured: 'Muse Code 1.4.14',
275
+ composer: { text: '^❯(?:\\s*$| \\S)' },
276
+ typed: { text: '^❯ \\S', body: { dim: false, fg: ['#ccd3db'] } },
277
+ chrome: [{ text: '^── Voice input \\(Alt\\+V to start\\)' }, { text: RULE }],
278
+ frame: { text: RULE },
279
+ busy: [
280
+ { text: '^[◇◈◆] .*esc to interrupt\\)' },
281
+ { text: '^└ (?:Hooks running|last event|Meta Model )' },
282
+ ],
283
+ turn: { text: '^❯ \\S' },
284
+ reasoning: [{
285
+ start: { text: '^◆ (?!Worked for )', lead: { fg: ['#676c74'] } },
286
+ continues: { text: '^ {2}(?![◆◇◈❯])\\S', lead: { fg: ['#676c74', '#8a9098'] } },
287
+ }],
288
+ answer: {
289
+ start: { text: '^◆ (?!Worked for |(?:Wrote|Ran command|Write)\\b)', lead: { bold: true, fg: ['#ccd3db'] } },
290
+ continues: { text: '^ {2}\\S', lead: { fg: ['#ccd3db'] } },
291
+ upward: true,
292
+ },
293
+ trailer: { text: '^◆ Worked for ' },
294
+ },
295
+ ];
296
+ export { SET_ASIDE_MS };
297
+ /** Whether a signature is set aside for running past its time budget just now. */
298
+ export function setAside(signature, now = Date.now()) {
299
+ return signature.overBudgetAt !== null && now - signature.overBudgetAt < SET_ASIDE_MS;
300
+ }
301
+ function isRecord(value) {
302
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
303
+ }
304
+ /** A regular expression from a signature, or an error that says which one would not compile. */
305
+ function pattern(source, at) {
306
+ try {
307
+ return new RegExp(source, 'u');
308
+ }
309
+ catch (error) {
310
+ throw new Error(`${at} does not compile (${error instanceof Error ? error.message : String(error)})`, {
311
+ cause: error,
312
+ });
313
+ }
314
+ }
315
+ function compileStyle(value, at) {
316
+ if (!isRecord(value))
317
+ throw new Error(`${at} must be an object`);
318
+ const style = {};
319
+ for (const key of Object.keys(value)) {
320
+ const v = value[key];
321
+ if (key === 'bold' || key === 'dim' || key === 'italic') {
322
+ if (typeof v !== 'boolean')
323
+ throw new Error(`${at}.${key} must be true or false`);
324
+ style[key] = v;
325
+ }
326
+ else if (key === 'fg' || key === 'notFg' || key === 'bg') {
327
+ if (!Array.isArray(v) || v.length === 0 || !v.every((c) => typeof c === 'string' && /^(default|p\d{1,3}|#[0-9a-f]{6})$/.test(c))) {
328
+ throw new Error(`${at}.${key} must list colours as "default", "p<n>" or "#rrggbb"`);
329
+ }
330
+ style[key] = new Set(v);
331
+ }
332
+ else {
333
+ throw new Error(`${at} has an unknown key ${key}`);
334
+ }
335
+ }
336
+ return style;
337
+ }
338
+ function compileLine(value, at) {
339
+ if (!isRecord(value))
340
+ throw new Error(`${at} must be an object`);
341
+ const line = {};
342
+ for (const key of Object.keys(value)) {
343
+ const v = value[key];
344
+ if (key === 'text') {
345
+ if (typeof v !== 'string' || v === '')
346
+ throw new Error(`${at}.text must be a non-empty regular expression`);
347
+ line.text = pattern(v, `${at}.text`);
348
+ }
349
+ else if (key === 'lead' || key === 'body' || key === 'word') {
350
+ line[key] = compileStyle(v, `${at}.${key}`);
351
+ }
352
+ else {
353
+ throw new Error(`${at} has an unknown key ${key}`);
354
+ }
355
+ }
356
+ if (line.text === undefined && line.lead === undefined && line.body === undefined && line.word === undefined) {
357
+ throw new Error(`${at} needs text, lead, word or body`);
358
+ }
359
+ return line;
360
+ }
361
+ function compileBlock(value, at) {
362
+ if (!isRecord(value))
363
+ throw new Error(`${at} must be an object with start`);
364
+ for (const key of Object.keys(value)) {
365
+ if (key !== 'start' && key !== 'continues' && key !== 'upward')
366
+ throw new Error(`${at} has an unknown key ${key}`);
367
+ }
368
+ const upward = value['upward'] ?? false;
369
+ if (typeof upward !== 'boolean')
370
+ throw new Error(`${at}.upward must be true or false`);
371
+ return {
372
+ start: compileLine(value['start'], `${at}.start`),
373
+ ...(value['continues'] !== undefined ? { continues: compileLine(value['continues'], `${at}.continues`) } : {}),
374
+ upward,
375
+ };
376
+ }
377
+ const SIGNATURE_KEYS = new Set([
378
+ 'name', 'programs', 'measured', 'composer', 'chrome', 'frame', 'busy', 'turn', 'reasoning', 'answer', 'trailer',
379
+ 'requireTrailer', 'typed', 'tidy',
380
+ ]);
381
+ /**
382
+ * Compile signatures, setting aside any that cannot be used and saying why,
383
+ * in words a person can act on.
384
+ */
385
+ export function compileSignatures(list, where = 'agents.signatures') {
386
+ const signatures = [];
387
+ const problems = [];
388
+ const usable = [];
389
+ list.forEach((entry, index) => {
390
+ const at = `${where}[${String(index)}]`;
391
+ try {
392
+ if (!isRecord(entry))
393
+ throw new Error(`${at} must be an object`);
394
+ const name = entry['name'];
395
+ if (typeof name !== 'string' || !/^[a-z][a-z0-9-]{0,31}$/.test(name)) {
396
+ throw new Error(`${at}.name must be a short lower-case name such as "codex"`);
397
+ }
398
+ const named = `${at} (${name})`;
399
+ for (const key of Object.keys(entry)) {
400
+ if (!SIGNATURE_KEYS.has(key))
401
+ throw new Error(`${named} has an unknown key ${key}`);
402
+ }
403
+ const programs = entry['programs'] ?? [];
404
+ if (!Array.isArray(programs) || !programs.every((p) => typeof p === 'string' && p !== '')) {
405
+ throw new Error(`${named}.programs must be a list of command names`);
406
+ }
407
+ const composer = entry['composer'];
408
+ const chrome = entry['chrome'] ?? [];
409
+ const busy = entry['busy'] ?? [];
410
+ const reasoning = entry['reasoning'] ?? [];
411
+ if (!Array.isArray(chrome))
412
+ throw new Error(`${named}.chrome must be a list of line tests`);
413
+ if (!Array.isArray(busy))
414
+ throw new Error(`${named}.busy must be a list of line tests`);
415
+ if (!Array.isArray(reasoning))
416
+ throw new Error(`${named}.reasoning must be a list of blocks`);
417
+ if (entry['answer'] === undefined)
418
+ throw new Error(`${named} needs an answer block`);
419
+ const measured = entry['measured'];
420
+ const tidy = entry['tidy'];
421
+ if (tidy !== undefined && (typeof tidy !== 'string' || tidy === '')) {
422
+ throw new Error(`${named}.tidy must be a non-empty regular expression`);
423
+ }
424
+ const requireTrailer = entry['requireTrailer'] ?? false;
425
+ if (typeof requireTrailer !== 'boolean')
426
+ throw new Error(`${named}.requireTrailer must be true or false`);
427
+ if (requireTrailer && entry['trailer'] === undefined) {
428
+ throw new Error(`${named}.requireTrailer needs a trailer to require`);
429
+ }
430
+ signatures.push({
431
+ name,
432
+ programs: programs.map((p) => p.toLowerCase()),
433
+ ...(typeof measured === 'string' ? { measured } : {}),
434
+ source: JSON.stringify(entry),
435
+ composer: compileLine(composer, `${named}.composer`),
436
+ chrome: chrome.map((c, i) => compileLine(c, `${named}.chrome[${String(i)}]`)),
437
+ ...(entry['frame'] !== undefined ? { frame: compileLine(entry['frame'], `${named}.frame`) } : {}),
438
+ busy: busy.map((b, i) => compileLine(b, `${named}.busy[${String(i)}]`)),
439
+ ...(entry['turn'] !== undefined ? { turn: compileLine(entry['turn'], `${named}.turn`) } : {}),
440
+ reasoning: reasoning.map((r, i) => compileBlock(r, `${named}.reasoning[${String(i)}]`)),
441
+ answer: compileBlock(entry['answer'], `${named}.answer`),
442
+ ...(entry['trailer'] !== undefined ? { trailer: compileLine(entry['trailer'], `${named}.trailer`) } : {}),
443
+ requireTrailer,
444
+ ...(entry['typed'] !== undefined ? { typed: compileLine(entry['typed'], `${named}.typed`) } : {}),
445
+ ...(typeof tidy === 'string' ? { tidy: pattern(tidy, `${named}.tidy`) } : {}),
446
+ overBudgetAt: null,
447
+ builtIn: where === 'built-in',
448
+ });
449
+ usable.push(index);
450
+ }
451
+ catch (error) {
452
+ problems.push(`${error instanceof Error ? error.message : String(error)}: ignored`);
453
+ }
454
+ });
455
+ return { signatures, problems, usable };
456
+ }
457
+ let active = compileSignatures(BUILT_IN_SIGNATURES, 'built-in').signatures;
458
+ let reportOverBudget = () => undefined;
459
+ /**
460
+ * Use the built-in signatures plus `extra`, the entries from config; an entry
461
+ * named like a built-in one replaces it. `onOverBudget` is told, with whether
462
+ * the signature is built in, each time one runs past its budget (the daemon
463
+ * logs it). Returns what was wrong with `extra`.
464
+ */
465
+ export function useAgentSignatures(extra, onOverBudget = () => undefined) {
466
+ const { signatures, problems } = compileSignatures(extra);
467
+ const replaced = new Set(signatures.map((s) => s.name));
468
+ active = [
469
+ ...compileSignatures(BUILT_IN_SIGNATURES, 'built-in').signatures.filter((s) => !replaced.has(s.name)),
470
+ ...signatures,
471
+ ];
472
+ reportOverBudget = onOverBudget;
473
+ return problems;
474
+ }
475
+ /** The names `terminal_start`'s `agent` accepts. */
476
+ export function agentNames() {
477
+ return active.map((s) => s.name).sort();
478
+ }
479
+ /** A program's name from its start command: `C:\x\Claude.EXE` is `claude`. */
480
+ export function programName(command) {
481
+ const base = command.split(/[\\/]/).pop() ?? command;
482
+ return base.replace(/\.(exe|cmd|bat|ps1|com)$/i, '').toLowerCase();
483
+ }
484
+ /** A versioned Muse executable has a changing suffix after muse-bin-. */
485
+ function claimsProgram(signature, program) {
486
+ return signature.programs.includes(program) ||
487
+ (signature.programs.includes('muse-bin-*') && /^muse-bin-\d+(?:\.\d+)*(?:[-+][a-z0-9]+(?:[.-][a-z0-9]+)*)?$/.test(program));
488
+ }
489
+ /**
490
+ * The agent a session runs as, by name: the one it was started as, or the one
491
+ * whose programs include its start command. The signatures are compiled and
492
+ * ordered exactly as `useAgentSignatures` orders the daemon's (the built-ins
493
+ * a config entry does not replace, then the config's entries in order, first
494
+ * match), so a client and the daemon name the same agent. Null when neither
495
+ * names one. For a client, which has no signature registry of its own; the
496
+ * daemon reads screens with `signatureFor`.
497
+ */
498
+ export function agentNameFor(agent, command, extra = []) {
499
+ if (agent !== undefined)
500
+ return agent;
501
+ const configured = compileSignatures(extra).signatures;
502
+ const replaced = new Set(configured.map((signature) => signature.name));
503
+ const ordered = [
504
+ ...compileSignatures(BUILT_IN_SIGNATURES, 'built-in').signatures.filter((s) => !replaced.has(s.name)),
505
+ ...configured,
506
+ ];
507
+ const program = programName(command);
508
+ return ordered.find((signature) => claimsProgram(signature, program))?.name ?? null;
509
+ }
510
+ /**
511
+ * The signature for a session: the agent it was started as, or the one whose
512
+ * programs include its start command. Null when neither names one.
513
+ */
514
+ export function signatureFor(agent, command) {
515
+ if (agent !== undefined)
516
+ return active.find((s) => s.name === agent && !setAside(s)) ?? null;
517
+ const program = programName(command);
518
+ return active.find((s) => !setAside(s) && claimsProgram(s, program)) ?? null;
519
+ }
520
+ // ---------------------------------------------------------------- matching
521
+ /** A row that holds nothing but whitespace and box drawing: border, not text. */
522
+ const BORDER_ROW = /^[\s─-╿-]*$/u;
523
+ function styleFits(style, test) {
524
+ if (test.bold !== undefined && style.bold !== test.bold)
525
+ return false;
526
+ if (test.dim !== undefined && style.dim !== test.dim)
527
+ return false;
528
+ if (test.italic !== undefined && style.italic !== test.italic)
529
+ return false;
530
+ const fg = style.fg ?? 'default';
531
+ if (test.fg !== undefined && !test.fg.has(fg))
532
+ return false;
533
+ if (test.notFg !== undefined && test.notFg.has(fg))
534
+ return false;
535
+ if (test.bg !== undefined && !test.bg.has(style.bg ?? 'default'))
536
+ return false;
537
+ return true;
538
+ }
539
+ /** The style of each character that is not a space, in order. */
540
+ function inkStyles(line) {
541
+ const out = [];
542
+ for (const span of line.spans) {
543
+ for (let i = span.from; i < span.to; i++) {
544
+ if (!/\s/u.test(line.text[i] ?? ' '))
545
+ out.push(span);
546
+ }
547
+ }
548
+ return out;
549
+ }
550
+ function lineFits(line, test) {
551
+ // A continuation has no independent meaning, even when its text happens
552
+ // to look like a turn, question, composer, answer or reasoning start.
553
+ if (line.wrapped)
554
+ return false;
555
+ if (test.text !== undefined && !test.text.test(line.text))
556
+ return false;
557
+ if (test.lead === undefined && test.body === undefined && test.word === undefined)
558
+ return true;
559
+ const ink = inkStyles(line);
560
+ if (ink.length === 0)
561
+ return false;
562
+ if (test.lead !== undefined && !styleFits(ink[0], test.lead))
563
+ return false;
564
+ if (test.word !== undefined && (ink.length < 2 || !styleFits(ink[1], test.word)))
565
+ return false;
566
+ if (test.body !== undefined) {
567
+ const body = ink.slice(1);
568
+ if (body.length === 0 || !body.every((style) => styleFits(style, test.body)))
569
+ return false;
570
+ }
571
+ return true;
572
+ }
573
+ /**
574
+ * Whether a line holds nothing of the transcript: blank, or blank once the
575
+ * signature's `tidy` has taken away what is drawn beside the text (a side
576
+ * panel, a scrollbar).
577
+ */
578
+ const blank = (line, tidy) => line === undefined || (tidy === undefined ? line.text : line.text.replace(tidy, '')).trim() === '';
579
+ /** The end (exclusive) of the block that starts at `at`, stopping at `limit`. */
580
+ function blockEnd(lines, at, block, limit, tidy, claimed) {
581
+ let end = at + 1;
582
+ let i = at + 1;
583
+ while (i < limit) {
584
+ if (lines[i].wrapped) {
585
+ i++;
586
+ end = i;
587
+ continue;
588
+ }
589
+ if (block.continues === undefined)
590
+ break;
591
+ // A line a question on screen claims for itself is never part of a
592
+ // block: the block ends before it rather than running over it.
593
+ if (claimed?.has(i))
594
+ break;
595
+ const line = lines[i];
596
+ if (!blank(line, tidy) && lineFits(line, block.continues)) {
597
+ i++;
598
+ end = i;
599
+ continue;
600
+ }
601
+ if (blank(line, tidy)) {
602
+ // A blank line stays inside the block only if the block carries on after it.
603
+ let next = i;
604
+ while (next < limit && blank(lines[next], tidy))
605
+ next++;
606
+ if (next < limit && lineFits(lines[next], block.continues)) {
607
+ i = next;
608
+ continue;
609
+ }
610
+ }
611
+ break;
612
+ }
613
+ return end;
614
+ }
615
+ /** Run `body` under the budget; a signature that overruns is set aside. */
616
+ function guarded(signature, body) {
617
+ try {
618
+ return withRegexBudget(signature.source.slice(0, 120), body);
619
+ }
620
+ catch (error) {
621
+ if (!(error instanceof RegexBudgetError))
622
+ throw error;
623
+ // Reported each time it trips: a person reading daemon.log sees whether
624
+ // a signature keeps running long or tripped once under load.
625
+ signature.overBudgetAt = Date.now();
626
+ reportOverBudget(signature.name, signature.builtIn);
627
+ return null;
628
+ }
629
+ }
630
+ /** The index of the composer's line and the first line of chrome, or null. */
631
+ function composerAt(lines, signature) {
632
+ for (let i = lines.length - 1; i >= 0; i--) {
633
+ const candidate = lines[i];
634
+ // A full-width rule above Muse's composer can leave its row marked as a
635
+ // continuation. The voice bar still anchors that row as the composer.
636
+ const wrappedMuseComposer = signature.name === 'muse' && candidate.wrapped === true &&
637
+ signature.composer.text?.test(candidate.text) === true &&
638
+ lines.slice(Math.max(0, i - 2), i).some((line) => /^── Voice input \(Alt\+V to start\)/.test(line.text));
639
+ if (!lineFits(candidate, signature.composer) && !wrappedMuseComposer)
640
+ continue;
641
+ if (signature.name === 'muse') {
642
+ let inComposerBody = true;
643
+ const tailIsChrome = lines.slice(i + 1).every((line) => {
644
+ if (line.text.trim() === '')
645
+ return true;
646
+ if (/^[─━]{10,}$/.test(line.text)) {
647
+ inComposerBody = false;
648
+ return true;
649
+ }
650
+ if (/· Launch overrides\s*$/.test(line.text))
651
+ return true;
652
+ // Muse indents later rows of a typed composer. Their text keeps the
653
+ // ordinary foreground, unlike the grey hint or status line.
654
+ return inComposerBody && /^ {2}\S/.test(line.text) &&
655
+ inkStyles(line).every((style) => style.fg === '#ccd3db');
656
+ });
657
+ if (!tailIsChrome)
658
+ continue;
659
+ }
660
+ // Reasoning is never drawn below the composer. A line with reasoning under
661
+ // it is the echo of the person's prompt, taken for the composer while a
662
+ // dialog stands in its place: no composer is found, so the filter reads
663
+ // the whole screen and a result is refused.
664
+ for (let j = i + 1; j < lines.length; j++) {
665
+ if (signature.reasoning.some((block) => lineFits(lines[j], block.start)))
666
+ return null;
667
+ }
668
+ let top = i;
669
+ while (top > 0) {
670
+ const above = lines[top - 1];
671
+ if (!blank(above, signature.tidy) && !signature.chrome.some((test) => lineFits(above, test)))
672
+ break;
673
+ top--;
674
+ }
675
+ return { line: i, chrome: top };
676
+ }
677
+ return null;
678
+ }
679
+ /**
680
+ * Whether every row of `[first, last]` sits inside one reasoning block that
681
+ * began above `first`. The block scan here ignores claims: this is what
682
+ * decides whether a claim is made at all.
683
+ */
684
+ function enclosedByReasoning(lines, signature, first, last) {
685
+ const composer = composerAt(lines, signature);
686
+ const limit = composer?.line ?? lines.length;
687
+ return reasoningRanges(lines, signature, limit).some(([from, to]) => from < first && last < to);
688
+ }
689
+ /**
690
+ * The rows a question on screen claims for itself: the prompt detection's
691
+ * own rows (`promptDetector.ts`), and the rows of nothing but border beside
692
+ * them, which belong to the question's box. A filter that hides reasoning
693
+ * must never hide a question, so a hidden block is cut at the first of
694
+ * these rows and never starts on one. Null when no question is on screen,
695
+ * so the block scan below runs as before.
696
+ *
697
+ * A detection whose only signal is a question with nothing below it is not
698
+ * claimed when that whole span sits inside a reasoning block that began
699
+ * above the question: a numbered list the reasoning drew, on a screen that
700
+ * happens to end there, is not a question the program is waiting on. A line
701
+ * that begins a reasoning block between the question and the last option
702
+ * stays reasoning too.
703
+ */
704
+ function claimedRows(lines, signature, prompt) {
705
+ if (prompt === null)
706
+ return null;
707
+ const [first, last] = prompt.rows;
708
+ if (prompt.basis === 'question' && enclosedByReasoning(lines, signature, first, last))
709
+ return null;
710
+ let top = first;
711
+ while (top > 0 && BORDER_ROW.test(lines[top - 1].text))
712
+ top--;
713
+ let bottom = last;
714
+ while (bottom + 1 < lines.length && BORDER_ROW.test(lines[bottom + 1].text))
715
+ bottom++;
716
+ const rows = new Set();
717
+ for (let i = top; i <= bottom; i++) {
718
+ // A one-line reasoning summary drawn between the question and the last
719
+ // option is still reasoning. A start that also continues (the bar a
720
+ // command is written on) is the prompt's own text, and stays.
721
+ const summary = signature.reasoning.some((block) => block.continues === undefined && lineFits(lines[i], block.start));
722
+ if (i > first && i < last && summary)
723
+ continue;
724
+ rows.add(i);
725
+ }
726
+ // A question keeps its own wrapped continuation rows. A continuation
727
+ // cannot be claimed independently of the physical row above it.
728
+ for (let i = top; i <= bottom; i++) {
729
+ if (!rows.has(i))
730
+ continue;
731
+ for (let j = i + 1; j < lines.length && lines[j].wrapped; j++)
732
+ rows.add(j);
733
+ }
734
+ return rows;
735
+ }
736
+ /** `[from, to)` ranges of reasoning above `limit`. */
737
+ function reasoningRanges(lines, signature, limit, claimed) {
738
+ const ranges = [];
739
+ let i = 0;
740
+ // The parent may have left the retained scrollback. There is no safe way
741
+ // to classify a leading continuation, so hide it for reasoning signatures.
742
+ if (signature.reasoning.length > 0) {
743
+ while (i < limit && lines[i].wrapped)
744
+ i++;
745
+ if (i > 0)
746
+ ranges.push([0, i]);
747
+ }
748
+ while (i < limit) {
749
+ if (claimed?.has(i)) {
750
+ i++;
751
+ continue;
752
+ }
753
+ const block = signature.reasoning.find((b) => lineFits(lines[i], b.start));
754
+ if (block === undefined) {
755
+ i++;
756
+ continue;
757
+ }
758
+ const end = blockEnd(lines, i, block, limit, signature.tidy, claimed);
759
+ ranges.push([i, end]);
760
+ i = end;
761
+ }
762
+ return ranges;
763
+ }
764
+ /** The line that stands in for a hidden block. */
765
+ export function hiddenMarker(count) {
766
+ return `[reasoning hidden: ${String(count)} line${count === 1 ? '' : 's'}]`;
767
+ }
768
+ /**
769
+ * The lines from `firstVisible` on, with every reasoning block above the
770
+ * composer replaced by one marker line. The lines before `firstVisible` are
771
+ * context only: a block whose first line is among them is still recognised
772
+ * where it carries on into what is returned. `rows` count from
773
+ * `firstVisible`. Null when the signature was set aside for running past its
774
+ * time budget, which the caller must treat as "cannot filter".
775
+ */
776
+ export function hideReasoning(lines, signature, firstVisible = 0) {
777
+ // Outside the signature's budget, so the two never nest. A signature with
778
+ // no reasoning rules can hide nothing, so the detector is not run. Dialog
779
+ // signatures are the only patterns the detector times (`dialogs.ts`); its
780
+ // own patterns are not.
781
+ const detected = signature.reasoning.length === 0 ? null : detectPrompt(lines.map((line) => line.wrapped ? '' : line.text).join('\n'));
782
+ return guarded(signature, () => {
783
+ const claimed = claimedRows(lines, signature, detected);
784
+ // Everything above the composer's own line, the chrome over it included:
785
+ // a spinner there can carry the model's words about what it is thinking.
786
+ const composer = composerAt(lines, signature);
787
+ const limit = composer?.line ?? lines.length;
788
+ const ranges = reasoningRanges(lines, signature, limit, claimed);
789
+ const out = { lines: [], rows: [], markers: [], hiddenLines: 0, hiddenBlocks: 0 };
790
+ const keep = (i) => {
791
+ out.lines.push(lines[i].text);
792
+ out.rows.push(i - firstVisible);
793
+ out.markers.push(false);
794
+ };
795
+ let next = firstVisible;
796
+ for (const [from, to] of ranges) {
797
+ if (to <= firstVisible)
798
+ continue;
799
+ const start = Math.max(from, firstVisible);
800
+ for (let i = next; i < start; i++)
801
+ keep(i);
802
+ out.lines.push(hiddenMarker(to - start));
803
+ out.rows.push(start - firstVisible);
804
+ out.markers.push(true);
805
+ out.hiddenLines += to - start;
806
+ out.hiddenBlocks++;
807
+ next = to;
808
+ }
809
+ for (let i = next; i < lines.length; i++)
810
+ keep(i);
811
+ return out;
812
+ });
813
+ }
814
+ /** What the CLI and the MCP tool say when there is no result to give. */
815
+ export function resultRefusal(reason) {
816
+ switch (reason) {
817
+ case 'busy':
818
+ return 'No result yet: the agent is still working on its turn.';
819
+ case 'no-answer':
820
+ return "No result: nothing below the latest prompt reads as the agent's answer.";
821
+ case 'no-composer':
822
+ return ("No result: the agent's composer is not on screen (a dialog, another view, or a " +
823
+ 'program still starting), so its turn cannot be read.');
824
+ case 'over-budget':
825
+ return 'No result: the signature ran past the regular-expression time budget and was set aside for a minute.';
826
+ case 'unfinished':
827
+ return ('No result: the latest turn has no closing line, so it has not finished (it was ' +
828
+ 'interrupted, or ended without an answer).');
829
+ case 'prompt-typed':
830
+ return 'No result: the composer holds a prompt that has not been sent, so the latest turn is about to change.';
831
+ default:
832
+ return 'No result.';
833
+ }
834
+ }
835
+ /**
836
+ * The answer that ends the latest turn. It has to start below the latest
837
+ * prompt the person typed, sit above the composer, and lie outside every
838
+ * reasoning block; nothing else is ever returned in its place.
839
+ */
840
+ export function latestResult(lines, signature) {
841
+ const result = guarded(signature, () => {
842
+ const composer = composerAt(lines, signature);
843
+ if (composer === null) {
844
+ const museBusy = signature.name === 'muse' && lines.some((line) => signature.busy.some((test) => lineFits(line, test)));
845
+ return { found: false, reason: museBusy ? 'busy' : 'no-composer', status: [] };
846
+ }
847
+ const status = lines
848
+ .slice(composer.line + 1)
849
+ .filter((line) => !blank(line) && !(signature.frame !== undefined && lineFits(line, signature.frame)))
850
+ .map((line) => line.text);
851
+ let turnStart = 0;
852
+ let prompt = null;
853
+ if (signature.turn !== undefined) {
854
+ for (let i = composer.chrome - 1; i >= 0; i--) {
855
+ if (lineFits(lines[i], signature.turn)) {
856
+ turnStart = i + 1;
857
+ prompt = lines[i].text.replace(/\s+$/u, '');
858
+ break;
859
+ }
860
+ }
861
+ }
862
+ // A spinner can be drawn in the latest turn or the chrome under it;
863
+ // a stale copy in the scrollback above says nothing.
864
+ const current = lines.slice(turnStart);
865
+ if (signature.name !== 'muse' && signature.busy.some((test) => current.some((line) => lineFits(line, test)))) {
866
+ return { found: false, reason: 'busy', status };
867
+ }
868
+ let lastBusy = -1;
869
+ if (signature.name === 'muse') {
870
+ for (let i = lines.length - 1; i >= turnStart; i--) {
871
+ if (signature.busy.some((test) => lineFits(lines[i], test))) {
872
+ lastBusy = i;
873
+ break;
874
+ }
875
+ }
876
+ }
877
+ // Muse can retain an activity row above a finished answer. Only a later
878
+ // answer before the composer makes that row historical.
879
+ let museAnswerAfterBusy = false;
880
+ if (signature.name === 'muse' && lastBusy >= 0) {
881
+ const ranges = reasoningRanges(lines, signature, composer.chrome);
882
+ const inReasoning = (i) => ranges.some(([from, to]) => i >= from && i < to);
883
+ museAnswerAfterBusy = lines.slice(lastBusy + 1, composer.chrome).some((line, offset) => !inReasoning(lastBusy + 1 + offset) && lineFits(line, signature.answer.start));
884
+ }
885
+ if (lastBusy >= 0 && !museAnswerAfterBusy) {
886
+ return { found: false, reason: 'busy', status };
887
+ }
888
+ if (signature.typed !== undefined) {
889
+ for (let i = composer.chrome; i <= composer.line; i++) {
890
+ if (lineFits(lines[i], signature.typed))
891
+ return { found: false, reason: 'prompt-typed', status };
892
+ }
893
+ }
894
+ const ranges = reasoningRanges(lines, signature, composer.chrome);
895
+ const inReasoning = (i) => ranges.some(([from, to]) => i >= from && i < to);
896
+ let start = -1;
897
+ for (let i = composer.chrome - 1; i >= turnStart; i--) {
898
+ if (!inReasoning(i) && lineFits(lines[i], signature.answer.start)) {
899
+ start = i;
900
+ break;
901
+ }
902
+ }
903
+ if (start === -1)
904
+ return { found: false, reason: 'no-answer', status };
905
+ let end = blockEnd(lines, start, signature.answer, composer.chrome, signature.tidy);
906
+ if (signature.answer.upward) {
907
+ for (;;) {
908
+ let above = start - 1;
909
+ while (above >= turnStart && blank(lines[above], signature.tidy))
910
+ above--;
911
+ if (above < turnStart || inReasoning(above) || !lineFits(lines[above], signature.answer.start))
912
+ break;
913
+ start = above;
914
+ }
915
+ }
916
+ const firstReasoningAfter = ranges.find(([from]) => from > start);
917
+ if (firstReasoningAfter !== undefined)
918
+ end = Math.min(end, firstReasoningAfter[0]);
919
+ const tidy = (text) => (signature.tidy === undefined ? text : text.replace(signature.tidy, '')).replace(/\s+$/u, '');
920
+ const trailer = [];
921
+ if (signature.trailer !== undefined) {
922
+ for (let i = end; i < composer.chrome; i++) {
923
+ if (lineFits(lines[i], signature.trailer))
924
+ trailer.push(tidy(lines[i].text));
925
+ }
926
+ }
927
+ if (signature.requireTrailer && trailer.length === 0)
928
+ return { found: false, reason: 'unfinished', status };
929
+ return { found: true, answer: lines.slice(start, end).map((line) => tidy(line.text)), trailer, status, prompt };
930
+ });
931
+ return result ?? { found: false, reason: 'over-budget', status: [] };
932
+ }
933
+ //# sourceMappingURL=reasoning.js.map