shellpuppet 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (238) hide show
  1. package/README.md +83 -18
  2. package/dist/agents/agy/index.d.ts +2 -0
  3. package/dist/agents/agy/index.js +11 -0
  4. package/dist/agents/agy/index.js.map +1 -0
  5. package/dist/agents/agy/nudge.d.ts +2 -0
  6. package/dist/agents/agy/nudge.js +29 -0
  7. package/dist/agents/agy/nudge.js.map +1 -0
  8. package/dist/agents/agy/reading.d.ts +2 -0
  9. package/dist/agents/agy/reading.js +28 -0
  10. package/dist/agents/agy/reading.js.map +1 -0
  11. package/dist/agents/barNudge.d.ts +9 -0
  12. package/dist/agents/barNudge.js +21 -0
  13. package/dist/agents/barNudge.js.map +1 -0
  14. package/dist/agents/claude/index.d.ts +2 -0
  15. package/dist/agents/claude/index.js +31 -0
  16. package/dist/agents/claude/index.js.map +1 -0
  17. package/dist/agents/claude/nudge.d.ts +2 -0
  18. package/dist/agents/claude/nudge.js +38 -0
  19. package/dist/agents/claude/nudge.js.map +1 -0
  20. package/dist/agents/claude/prompts.d.ts +9 -0
  21. package/dist/agents/claude/prompts.js +16 -0
  22. package/dist/agents/claude/prompts.js.map +1 -0
  23. package/dist/agents/claude/reading.d.ts +2 -0
  24. package/dist/agents/claude/reading.js +25 -0
  25. package/dist/agents/claude/reading.js.map +1 -0
  26. package/dist/agents/codex/index.d.ts +2 -0
  27. package/dist/agents/codex/index.js +28 -0
  28. package/dist/agents/codex/index.js.map +1 -0
  29. package/dist/agents/codex/nudge.d.ts +2 -0
  30. package/dist/agents/codex/nudge.js +35 -0
  31. package/dist/agents/codex/nudge.js.map +1 -0
  32. package/dist/agents/codex/prompts.d.ts +9 -0
  33. package/dist/agents/codex/prompts.js +14 -0
  34. package/dist/agents/codex/prompts.js.map +1 -0
  35. package/dist/agents/codex/reading.d.ts +2 -0
  36. package/dist/agents/codex/reading.js +22 -0
  37. package/dist/agents/codex/reading.js.map +1 -0
  38. package/dist/agents/generic/index.d.ts +3 -0
  39. package/dist/agents/generic/index.js +9 -0
  40. package/dist/agents/generic/index.js.map +1 -0
  41. package/dist/agents/generic/prompts.d.ts +2 -0
  42. package/dist/agents/generic/prompts.js +10 -0
  43. package/dist/agents/generic/prompts.js.map +1 -0
  44. package/dist/agents/grok/actionBox.d.ts +13 -0
  45. package/dist/agents/grok/actionBox.js +127 -0
  46. package/dist/agents/grok/actionBox.js.map +1 -0
  47. package/dist/agents/grok/index.d.ts +2 -0
  48. package/dist/agents/grok/index.js +20 -0
  49. package/dist/agents/grok/index.js.map +1 -0
  50. package/dist/agents/grok/nudge.d.ts +2 -0
  51. package/dist/agents/grok/nudge.js +76 -0
  52. package/dist/agents/grok/nudge.js.map +1 -0
  53. package/dist/agents/grok/prompts.d.ts +4 -0
  54. package/dist/agents/grok/prompts.js +89 -0
  55. package/dist/agents/grok/prompts.js.map +1 -0
  56. package/dist/agents/grok/reading.d.ts +2 -0
  57. package/dist/agents/grok/reading.js +49 -0
  58. package/dist/agents/grok/reading.js.map +1 -0
  59. package/dist/agents/grok/readingRules.d.ts +2 -0
  60. package/dist/agents/grok/readingRules.js +44 -0
  61. package/dist/agents/grok/readingRules.js.map +1 -0
  62. package/dist/agents/index.d.ts +28 -0
  63. package/dist/agents/index.js +46 -0
  64. package/dist/agents/index.js.map +1 -0
  65. package/dist/agents/input.d.ts +2 -0
  66. package/dist/agents/input.js +9 -0
  67. package/dist/agents/input.js.map +1 -0
  68. package/dist/agents/mimo/index.d.ts +2 -0
  69. package/dist/agents/mimo/index.js +13 -0
  70. package/dist/agents/mimo/index.js.map +1 -0
  71. package/dist/agents/mimo/nudge.d.ts +3 -0
  72. package/dist/agents/mimo/nudge.js +59 -0
  73. package/dist/agents/mimo/nudge.js.map +1 -0
  74. package/dist/agents/mimo/prompts.d.ts +2 -0
  75. package/dist/agents/mimo/prompts.js +40 -0
  76. package/dist/agents/mimo/prompts.js.map +1 -0
  77. package/dist/agents/mimo/reading.d.ts +2 -0
  78. package/dist/agents/mimo/reading.js +31 -0
  79. package/dist/agents/mimo/reading.js.map +1 -0
  80. package/dist/agents/mimo/readingRules.d.ts +2 -0
  81. package/dist/agents/mimo/readingRules.js +79 -0
  82. package/dist/agents/mimo/readingRules.js.map +1 -0
  83. package/dist/agents/mimo/stalls.d.ts +2 -0
  84. package/dist/agents/mimo/stalls.js +81 -0
  85. package/dist/agents/mimo/stalls.js.map +1 -0
  86. package/dist/agents/muse/index.d.ts +2 -0
  87. package/dist/agents/muse/index.js +20 -0
  88. package/dist/agents/muse/index.js.map +1 -0
  89. package/dist/agents/muse/input.d.ts +3 -0
  90. package/dist/agents/muse/input.js +7 -0
  91. package/dist/agents/muse/input.js.map +1 -0
  92. package/dist/agents/muse/nudge.d.ts +2 -0
  93. package/dist/agents/muse/nudge.js +33 -0
  94. package/dist/agents/muse/nudge.js.map +1 -0
  95. package/dist/agents/muse/prompts.d.ts +14 -0
  96. package/dist/agents/muse/prompts.js +132 -0
  97. package/dist/agents/muse/prompts.js.map +1 -0
  98. package/dist/agents/muse/reading.d.ts +2 -0
  99. package/dist/agents/muse/reading.js +33 -0
  100. package/dist/agents/muse/reading.js.map +1 -0
  101. package/dist/agents/muse/readingRules.d.ts +2 -0
  102. package/dist/agents/muse/readingRules.js +49 -0
  103. package/dist/agents/muse/readingRules.js.map +1 -0
  104. package/dist/agents/nudgeReading.d.ts +74 -0
  105. package/dist/agents/nudgeReading.js +262 -0
  106. package/dist/agents/nudgeReading.js.map +1 -0
  107. package/dist/agents/opencode/index.d.ts +2 -0
  108. package/dist/agents/opencode/index.js +21 -0
  109. package/dist/agents/opencode/index.js.map +1 -0
  110. package/dist/agents/opencode/nudge.d.ts +6 -0
  111. package/dist/agents/opencode/nudge.js +187 -0
  112. package/dist/agents/opencode/nudge.js.map +1 -0
  113. package/dist/agents/opencode/prompts.d.ts +6 -0
  114. package/dist/agents/opencode/prompts.js +198 -0
  115. package/dist/agents/opencode/prompts.js.map +1 -0
  116. package/dist/agents/opencode/reading.d.ts +2 -0
  117. package/dist/agents/opencode/reading.js +29 -0
  118. package/dist/agents/opencode/reading.js.map +1 -0
  119. package/dist/agents/opencode/stalls.d.ts +3 -0
  120. package/dist/agents/opencode/stalls.js +14 -0
  121. package/dist/agents/opencode/stalls.js.map +1 -0
  122. package/dist/agents/qoder/index.d.ts +2 -0
  123. package/dist/agents/qoder/index.js +12 -0
  124. package/dist/agents/qoder/index.js.map +1 -0
  125. package/dist/agents/qoder/nudge.d.ts +2 -0
  126. package/dist/agents/qoder/nudge.js +16 -0
  127. package/dist/agents/qoder/nudge.js.map +1 -0
  128. package/dist/agents/qoder/prompts.d.ts +2 -0
  129. package/dist/agents/qoder/prompts.js +6 -0
  130. package/dist/agents/qoder/prompts.js.map +1 -0
  131. package/dist/agents/qoder/reading.d.ts +2 -0
  132. package/dist/agents/qoder/reading.js +41 -0
  133. package/dist/agents/qoder/reading.js.map +1 -0
  134. package/dist/agents/types.d.ts +187 -0
  135. package/dist/agents/types.js +2 -0
  136. package/dist/agents/types.js.map +1 -0
  137. package/dist/cli/index.js +255 -33
  138. package/dist/cli/index.js.map +1 -1
  139. package/dist/client/http.d.ts +17 -3
  140. package/dist/client/http.js +232 -35
  141. package/dist/client/http.js.map +1 -1
  142. package/dist/core/dialogs.d.ts +2 -4
  143. package/dist/core/dialogs.js +6 -12
  144. package/dist/core/dialogs.js.map +1 -1
  145. package/dist/core/mailbox.d.ts +222 -0
  146. package/dist/core/mailbox.js +545 -0
  147. package/dist/core/mailbox.js.map +1 -0
  148. package/dist/core/manager.d.ts +3 -0
  149. package/dist/core/manager.js +37 -2
  150. package/dist/core/manager.js.map +1 -1
  151. package/dist/core/messageText.d.ts +2 -0
  152. package/dist/core/messageText.js +6 -0
  153. package/dist/core/messageText.js.map +1 -0
  154. package/dist/core/nudge.d.ts +37 -0
  155. package/dist/core/nudge.js +57 -0
  156. package/dist/core/nudge.js.map +1 -0
  157. package/dist/core/promptDetector.d.ts +14 -12
  158. package/dist/core/promptDetector.js +113 -363
  159. package/dist/core/promptDetector.js.map +1 -1
  160. package/dist/core/promptText.d.ts +1 -0
  161. package/dist/core/promptText.js +4 -0
  162. package/dist/core/promptText.js.map +1 -0
  163. package/dist/core/readiness.d.ts +14 -0
  164. package/dist/core/readiness.js +95 -0
  165. package/dist/core/readiness.js.map +1 -0
  166. package/dist/core/reasoning.d.ts +68 -7
  167. package/dist/core/reasoning.js +572 -325
  168. package/dist/core/reasoning.js.map +1 -1
  169. package/dist/core/renderer.d.ts +63 -3
  170. package/dist/core/renderer.js +368 -42
  171. package/dist/core/renderer.js.map +1 -1
  172. package/dist/core/selection.d.ts +1 -1
  173. package/dist/core/selection.js +3 -3
  174. package/dist/core/selection.js.map +1 -1
  175. package/dist/core/session.d.ts +166 -14
  176. package/dist/core/session.js +1000 -86
  177. package/dist/core/session.js.map +1 -1
  178. package/dist/core/types.d.ts +60 -4
  179. package/dist/core/types.js +41 -0
  180. package/dist/core/types.js.map +1 -1
  181. package/dist/core/waiter.d.ts +9 -2
  182. package/dist/core/waiter.js +35 -10
  183. package/dist/core/waiter.js.map +1 -1
  184. package/dist/daemon/audit.d.ts +1 -1
  185. package/dist/daemon/audit.js +2 -1
  186. package/dist/daemon/audit.js.map +1 -1
  187. package/dist/daemon/config.d.ts +42 -0
  188. package/dist/daemon/config.js +159 -4
  189. package/dist/daemon/config.js.map +1 -1
  190. package/dist/daemon/folderPicker.js +21 -2
  191. package/dist/daemon/folderPicker.js.map +1 -1
  192. package/dist/daemon/homeOwner.d.ts +15 -0
  193. package/dist/daemon/homeOwner.js +106 -0
  194. package/dist/daemon/homeOwner.js.map +1 -0
  195. package/dist/daemon/index.js +10 -6
  196. package/dist/daemon/index.js.map +1 -1
  197. package/dist/daemon/launchProfiles.d.ts +5 -0
  198. package/dist/daemon/launchProfiles.js +42 -40
  199. package/dist/daemon/launchProfiles.js.map +1 -1
  200. package/dist/daemon/liveness.d.ts +1 -1
  201. package/dist/daemon/liveness.js +2 -2
  202. package/dist/daemon/liveness.js.map +1 -1
  203. package/dist/daemon/nudgeScheduler.d.ts +21 -0
  204. package/dist/daemon/nudgeScheduler.js +61 -0
  205. package/dist/daemon/nudgeScheduler.js.map +1 -0
  206. package/dist/daemon/paths.d.ts +22 -16
  207. package/dist/daemon/paths.js +137 -49
  208. package/dist/daemon/paths.js.map +1 -1
  209. package/dist/daemon/restartHold.d.ts +16 -0
  210. package/dist/daemon/restartHold.js +126 -0
  211. package/dist/daemon/restartHold.js.map +1 -0
  212. package/dist/daemon/restartSource.d.ts +7 -0
  213. package/dist/daemon/restartSource.js +89 -0
  214. package/dist/daemon/restartSource.js.map +1 -0
  215. package/dist/daemon/screenshot.d.ts +4 -1
  216. package/dist/daemon/screenshot.js +45 -7
  217. package/dist/daemon/screenshot.js.map +1 -1
  218. package/dist/daemon/server.d.ts +71 -13
  219. package/dist/daemon/server.js +1601 -296
  220. package/dist/daemon/server.js.map +1 -1
  221. package/dist/daemon/sessionFeed.js +4 -1
  222. package/dist/daemon/sessionFeed.js.map +1 -1
  223. package/dist/mcp/config.js +2 -1
  224. package/dist/mcp/config.js.map +1 -1
  225. package/dist/mcp/index.js +12 -2
  226. package/dist/mcp/index.js.map +1 -1
  227. package/dist/mcp/tools.d.ts +21 -1
  228. package/dist/mcp/tools.js +213 -28
  229. package/dist/mcp/tools.js.map +1 -1
  230. package/dist/viewer/dashboard-folders.js +7 -1
  231. package/dist/viewer/dashboard-layout.js +6 -52
  232. package/dist/viewer/dashboard.css +20 -4
  233. package/dist/viewer/dashboard.html +12 -3
  234. package/dist/viewer/dashboard.js +550 -378
  235. package/dist/viewer/pane.js +744 -136
  236. package/dist/viewer/viewer.css +1 -1
  237. package/dist/viewer/viewer.js +3 -1
  238. package/package.json +1 -1
@@ -13,6 +13,9 @@
13
13
  *
14
14
  * No stdout/stderr: logging via the injected Logger only (lint-enforced).
15
15
  */
16
+ import { agentResumeIds, moduleFor } from '../agents/index.js';
17
+ import { nudgeVerdict, NUDGE_QUIET_MS } from './nudge.js';
18
+ import { validateStall, possibleStall, resolveSessionAgent, signatureForSession, stallTranscriptContent, stallTurnVisible, StallScreenCache, StallTracker } from './reasoning.js';
16
19
  import { execFile } from 'node:child_process';
17
20
  import * as fs from 'node:fs';
18
21
  import * as os from 'node:os';
@@ -20,11 +23,12 @@ import * as path from 'node:path';
20
23
  import { ensureSpawnHelperExecutable, explainSpawnFailure, loadNodePty } from './nativePty.js';
21
24
  import { ScreenRenderer } from './renderer.js';
22
25
  import { commandLine } from './policy.js';
23
- import { detectPrompt, MusePromptSettler, StalePromptGuard } from './promptDetector.js';
26
+ import { detectPrompt, createPromptReader, StalePromptGuard } from './promptDetector.js';
24
27
  import { waitFor } from './waiter.js';
28
+ import { readinessFor, trackReadiness, waitUntilReady } from './readiness.js';
25
29
  import { canReadExitCode, listenForTerminalErrors, observeConptyStartError, recordedExitCode, releaseFailedStarts, } from './windowsPtyStart.js';
26
30
  import { queueConsoleHostEnd, registerConsoleHostWindow } from './windowsConsoleHost.js';
27
- import { DEFAULT_COLS, DEFAULT_ROWS, DEFAULT_SCROLLBACK, MAX_WAIT_TIMEOUT_MS, NULL_LOGGER, RESERVED_FEATURE_CREDENTIALS, } from './types.js';
31
+ import { DEFAULT_COLS, DEFAULT_ROWS, DEFAULT_SCROLLBACK, MAX_WAIT_TIMEOUT_MS, NULL_LOGGER, RESERVED_FEATURE_CREDENTIALS, SESSION_IDENTITY_ENV_NAMES, validResumeId, } from './types.js';
28
32
  /**
29
33
  * Hard cap on `taskkill`. Without it a wedged kill never calls back, so
30
34
  * `kill()` never resolves, `killAll()` never resolves and daemon shutdown
@@ -74,11 +78,11 @@ const PROGRAM_PID_WAIT_MS = 8_000;
74
78
  * overran the 30 s cap; one run given all thirty pids took 10 s. So daemon
75
79
  * shutdown kills every tree in one run (`SessionManager.killAll`).
76
80
  */
77
- export const taskkillTrees = (pids) => new Promise((resolve) => {
81
+ export const taskkillTrees = (pids, timeoutMs = TREE_KILL_TIMEOUT_MS) => new Promise((resolve) => {
78
82
  const startedAt = Date.now();
79
83
  execFile('taskkill', ['/T', '/F', ...pids.flatMap((pid) => ['/PID', String(pid)])],
80
84
  // A line of output per process killed, descendants included.
81
- { windowsHide: true, timeout: TREE_KILL_TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024 }, (error) => {
85
+ { windowsHide: true, timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024 }, (error) => {
82
86
  resolve(error
83
87
  ? {
84
88
  // Node also kills a child whose output overruns maxBuffer. Only
@@ -105,15 +109,47 @@ export const taskkillTrees = (pids) => new Promise((resolve) => {
105
109
  */
106
110
  const WRITE_CHUNK_CHARS = 1024;
107
111
  const WRITE_CHUNK_DELAY_MS = 8;
108
- /** Muse needs a short pause after text before its submitting Enter. */
109
- export const MUSE_SUBMIT_DELAY_MS = 400;
110
- function museSubmittingText(data) {
111
- if (!data.endsWith('\r'))
112
- return false;
113
- const body = data.slice(0, -1);
114
- return !/[\r\n]/.test(body) &&
115
- Array.from(body).some((character) => character > ' ' && character !== '\x7f');
112
+ export { MUSE_SUBMIT_DELAY_MS } from '../agents/index.js';
113
+ /** Time between a nudge's body and submit key when the module needs no longer pause. */
114
+ export const NUDGE_SUBMIT_DELAY_MS = 150;
115
+ /** How long a nudge may wait after that pause for the program to paint its line. */
116
+ export const NUDGE_SUBMIT_WAIT_MS = 2000;
117
+ const NUDGE_SUBMIT_POLL_MS = 50;
118
+ /** Rows at the foot of the screen that hold a composer, its frame and its footer. */
119
+ const COMPOSER_BLOCK_ROWS = 5;
120
+ /** A horizontal rule or frame edge drawn around a composer. */
121
+ const COMPOSER_RULE = /^\s*[─━┌╭└╰][^\n]*[─━]{10,}/u;
122
+ /**
123
+ * The composer block: from the rule or frame edge above the composer to the
124
+ * foot of the screen. Agents draw a rule (or frame edge) above and below their
125
+ * composer, so the block starts at the second rule from the bottom. A running
126
+ * turn repaints its spinner and timer above that rule, not in the block.
127
+ * Without two rules, the last few non-blank rows stand in.
128
+ */
129
+ function composerBlockKey(rows) {
130
+ const rules = [];
131
+ for (let i = rows.length - 1; i >= 0 && rules.length < 2; i--) {
132
+ if (COMPOSER_RULE.test(rows[i] ?? ''))
133
+ rules.push(i);
134
+ }
135
+ if (rules.length === 2)
136
+ return rows.slice(rules[1]).join('\n').trimEnd();
137
+ return rows.filter((row) => row.trim() !== '').slice(-COMPOSER_BLOCK_ROWS).join('\n');
116
138
  }
139
+ /** Let the program repaint its composer before deciding whether Enter landed. */
140
+ const TYPED_SUBMIT_SETTLE_MS = 300;
141
+ const TYPED_SUBMIT_WAIT_MS = 2_000;
142
+ /** Shell prompts a launch command is typed at before an agent starts. */
143
+ const SHELL_PROMPTS = [
144
+ /^PS [^>]+>$/u, // PowerShell: PS D:\work>
145
+ /^[A-Za-z]:\\[^>]*>$/u, // cmd.exe: D:\work>
146
+ /^\S*[@:~/]\S*[$#%]$/u, // POSIX: user@host:~/work$
147
+ ];
148
+ /**
149
+ * A paste placeholder proves this body only when no input was written and nothing
150
+ * was painted for this long before it: an earlier paste cannot still be pending.
151
+ */
152
+ const TYPED_PLACEHOLDER_SETTLE_MS = 1_000;
117
153
  /**
118
154
  * Bracketed paste (DEC private mode 2004). A TUI that enables it is telling us
119
155
  * it wants multi-character input delivered as ONE paste event rather than as a
@@ -236,7 +272,9 @@ export class SessionProgramEndedError extends Error {
236
272
  sessionId;
237
273
  exitCode;
238
274
  constructor(sessionId, exitCode) {
239
- super(`Cannot resize session ${sessionId}: its program has exited (code ${String(exitCode)}).`);
275
+ super(exitCode === null
276
+ ? `Cannot resize session ${sessionId}: it has ended or is being killed.`
277
+ : `Cannot resize session ${sessionId}: its program has exited (code ${String(exitCode)}).`);
240
278
  this.sessionId = sessionId;
241
279
  this.exitCode = exitCode;
242
280
  this.name = 'SessionProgramEndedError';
@@ -480,16 +518,17 @@ export function credentialShapedNames(source = process.env) {
480
518
  * A name reserved for a connected feature's credential (ADR-007) is never
481
519
  * carried, whichever mode is in force: `passthrough` copies the daemon's
482
520
  * environment and a list mode can name anything, so the filter has to sit
483
- * here rather than in one caller. A session's own `passed` value is not the
484
- * daemon's copy and is left alone.
521
+ * here rather than in one caller. The session identity names and home are also
522
+ * removed from `passed`; the daemon assigns fresh values to each session.
485
523
  */
486
524
  export function buildSessionEnv(mode, platform, source = process.env, passed = {}, reserved = RESERVED_FEATURE_CREDENTIALS) {
487
525
  const env = {};
488
- // Windows reads variable names without case, so a reserved name is matched
489
- // that way there and exactly elsewhere, as every other name is.
490
- const isReserved = (name) => platform === 'win32'
491
- ? [...reserved].some((entry) => entry.toUpperCase() === name.toUpperCase())
492
- : reserved.has(name);
526
+ // Session-owned names are reserved in every casing. Windows also reads
527
+ // other reserved names without case; elsewhere those names are exact.
528
+ const isReserved = (name) => [...SESSION_IDENTITY_ENV_NAMES].some((entry) => entry.toUpperCase() === name.toUpperCase()) ||
529
+ (platform === 'win32'
530
+ ? [...reserved].some((entry) => entry.toUpperCase() === name.toUpperCase())
531
+ : reserved.has(name));
493
532
  if (mode === 'passthrough') {
494
533
  for (const [key, value] of Object.entries(source)) {
495
534
  if (value !== undefined && !isReserved(key))
@@ -505,17 +544,11 @@ export function buildSessionEnv(mode, platform, source = process.env, passed = {
505
544
  }
506
545
  }
507
546
  }
508
- const setOnly = (name, value) => {
509
- if (platform === 'win32') {
510
- for (const key of Object.keys(env)) {
511
- if (key.toUpperCase() === name.toUpperCase())
512
- delete env[key];
513
- }
514
- }
515
- env[name] = value;
516
- };
517
- for (const [name, value] of Object.entries(passed))
518
- setOnly(name, value);
547
+ const setOnly = (name, value) => setSessionEnvValue(env, platform, name, value);
548
+ for (const [name, value] of Object.entries(passed)) {
549
+ if (!isReserved(name))
550
+ setOnly(name, value);
551
+ }
519
552
  // Always injected (§7): Windows sets no TERM, and TUIs then assume a dumb
520
553
  // terminal and disable colour. On Windows any other casing goes first, or
521
554
  // the child would see that copy's value instead of these.
@@ -523,18 +556,36 @@ export function buildSessionEnv(mode, platform, source = process.env, passed = {
523
556
  setOnly('COLORTERM', 'truecolor');
524
557
  return env;
525
558
  }
559
+ /** Assign a daemon-owned value with the same Windows name collapsing as buildSessionEnv. */
560
+ export function setSessionEnvValue(env, platform, name, value) {
561
+ if (platform === 'win32') {
562
+ for (const key of Object.keys(env)) {
563
+ if (key.toUpperCase() === name.toUpperCase())
564
+ delete env[key];
565
+ }
566
+ }
567
+ env[name] = value;
568
+ }
526
569
  export class Session {
527
570
  id;
528
571
  label;
572
+ role;
529
573
  /** What this session is for, for the human watching it. */
530
574
  purpose;
531
575
  /** The audit actor that started it: set by the daemon, not by the body. */
532
576
  startedBy;
577
+ parent;
533
578
  /** The pre-wrap command as given by the caller. */
534
579
  command;
535
580
  args;
536
581
  /** The agent it was started as, which chooses how its screen is read. */
582
+ launchProfile;
583
+ inheritedResumeIds = [];
584
+ observedResumeId;
537
585
  agent;
586
+ agentSource;
587
+ agentModule;
588
+ promptReader;
538
589
  createdAt;
539
590
  pty;
540
591
  renderer;
@@ -563,15 +614,51 @@ export class Session {
563
614
  dataListeners = new Set();
564
615
  exitListeners = new Set();
565
616
  readyListeners = new Set();
617
+ stallListeners = new Set();
618
+ stallTracker = new StallTracker();
619
+ stallState;
620
+ stallTimer = null;
621
+ stallScheduled = null;
622
+ stallNextCheck = 0;
623
+ stallContent;
624
+ stallValidatedContent;
625
+ stallTranscript;
626
+ stallValidatedTranscript;
627
+ stallValidationPending = false;
628
+ // One second covers the measured delayed ConPTY growth redraws under load.
629
+ // Only a new geometry change can renew it; output and duplicate requests cannot.
630
+ stallResizeUntil = 0;
631
+ // The PTY size last accounted for, so a size we requested is not counted
632
+ // again when the PTY reports it with the program's first later output.
633
+ stallPtyCols = 0;
634
+ stallPtyRows = 0;
635
+ stallScreen = new StallScreenCache();
636
+ stallInk;
566
637
  /** Whether the program has hidden the cursor (DECTCEM off), carried to viewers. */
567
638
  cursorHidden = false;
568
639
  /** Serialises write() so chunked writes cannot interleave. See write(). */
569
640
  writeChain = Promise.resolve();
570
- museSubmissionsQueued = 0;
571
- musePromptSettler = new MusePromptSettler();
641
+ inputVersion = 0;
642
+ inputQueueVersion = 0;
643
+ /** A nudge body accepted by the PTY without a confirmed submit. */
644
+ pendingNudgeLine = null;
645
+ pendingNudgeIds = [];
646
+ /** Any input from outside the daemon permanently claims this pending composer. */
647
+ pendingNudgeTouched = false;
648
+ pendingTouchRefusalAudited = false;
649
+ pendingTurnSubmitted = false;
650
+ pendingTurnBusy = false;
651
+ pendingQuietSince = 0;
652
+ pendingNudgeSettleMs;
653
+ screenRevision = 0;
654
+ nudgeComposerKey = '';
655
+ nudgeComposerSince = 0;
656
+ submissionsQueued = 0;
572
657
  /** Why the input pipe failed (Windows), once it has: input is refused from then on. */
573
658
  inputFailure = null;
574
659
  lastChange = Date.now();
660
+ /** When input was last written to the PTY. */
661
+ lastInputAt = 0;
575
662
  /** Sticky: the rendered screen has shown something at least once. */
576
663
  painted = false;
577
664
  /**
@@ -585,11 +672,13 @@ export class Session {
585
672
  exitedFlag = false;
586
673
  exitedAtValue = null;
587
674
  exitCodeValue = null;
675
+ rendererFault = null;
588
676
  conptyStartError = null;
589
677
  /** The tree kill under way for a program whose session ended with no exit code. */
590
678
  endingProgram = null;
591
679
  readyFlag;
592
680
  readyReasonValue = 'not-tracked';
681
+ startupReadiness;
593
682
  geometryHeldFlag;
594
683
  killPromise = null;
595
684
  consoleHostSettlement = null;
@@ -605,9 +694,19 @@ export class Session {
605
694
  this.command = options.command;
606
695
  this.args = options.args ?? [];
607
696
  this.label = options.label ?? options.command;
697
+ this.launchProfile = options.launchProfile;
698
+ this.role = (options.parent === undefined || options.launchProfile !== undefined) && options.role === 'chair' ? 'chair' : 'delegate';
608
699
  this.purpose = options.purpose ?? '';
609
700
  this.startedBy = options.startedBy ?? 'unknown';
610
- this.agent = options.agent;
701
+ this.parent = options.parent;
702
+ const resolved = deps.resolvedAgent ?? resolveSessionAgent(options.agent, options.command);
703
+ this.agent = resolved.agent;
704
+ this.agentSource = resolved.agentSource;
705
+ this.agentModule = moduleFor(this.agent);
706
+ // Refuse an unsupported wait before allocating a renderer or a terminal.
707
+ const readiness = readinessFor(options, this.agentModule);
708
+ this.startupReadiness = options.waitReady === true ? readiness : undefined;
709
+ this.promptReader = createPromptReader(this.agent);
611
710
  this.createdAt = new Date();
612
711
  this.logger = deps.logger ?? NULL_LOGGER;
613
712
  this.platform = deps.platform ?? process.platform;
@@ -616,6 +715,7 @@ export class Session {
616
715
  this.registerConsoleHost = deps.registerConsoleHostWindow ?? registerConsoleHostWindow;
617
716
  this.spawnPty = deps.spawn;
618
717
  this.pidWaitMs = deps.pidWaitMs ?? PROGRAM_PID_WAIT_MS;
718
+ this.pendingNudgeSettleMs = deps.pendingNudgeSettleMs ?? 30_000;
619
719
  // node-pty 1.2.0 is ConPTY-only on Windows: the winpty fallback is gone,
620
720
  // so a build below the ConPTY floor cannot start anything. Refused here,
621
721
  // with the floor named, rather than deep inside ConPTY as a bare
@@ -631,7 +731,12 @@ export class Session {
631
731
  }
632
732
  const cols = options.cols ?? DEFAULT_COLS;
633
733
  const rows = options.rows ?? DEFAULT_ROWS;
634
- this.renderer = new ScreenRenderer({ cols, rows, scrollback: DEFAULT_SCROLLBACK });
734
+ this.renderer = new ScreenRenderer({ cols, rows, scrollback: DEFAULT_SCROLLBACK, agent: this.agent,
735
+ onFault: (error) => this.failRenderer(error) });
736
+ this.stallInk = this.agentModule?.stalls === undefined ? undefined :
737
+ this.renderer.watchForeground(this.agentModule.stalls.flatMap(shape => shape.marker.fg));
738
+ if (this.agentModule?.stalls !== undefined)
739
+ this.renderer.onResize(() => this.noteStallResize(true));
635
740
  // cols/rows say where to START, and nothing more: a size that also froze
636
741
  // the grid would leave a viewer with a grid it could not change, and a
637
742
  // window of a different shape could only letterbox. Holding is asked
@@ -666,6 +771,23 @@ export class Session {
666
771
  // for Windows without a Windows process.
667
772
  const trackConsoleHost = this.platform === 'win32';
668
773
  const consoleHostT0 = trackConsoleHost ? Date.now() : 0;
774
+ const sessionEnv = buildSessionEnv(deps.sessionEnv ?? DEFAULT_SESSION_ENV, this.platform, process.env, options.env);
775
+ if (deps.identity !== undefined) {
776
+ if (options.launchProfile && this.agentModule?.resumeIdMarkers) {
777
+ const original = this.platform === 'win32'
778
+ ? Object.fromEntries(Object.entries(sessionEnv).map(([key, value]) => [key.toUpperCase(), value]))
779
+ : sessionEnv;
780
+ this.inheritedResumeIds = agentResumeIds(this.agentModule, original);
781
+ sessionEnv['SHELLPUPPET_PROFILE_AGENT'] = this.agent;
782
+ }
783
+ sessionEnv['SHELLPUPPET_SESSION'] = id;
784
+ sessionEnv['SHELLPUPPET_SESSION_TOKEN'] = deps.identity.token;
785
+ sessionEnv['SHELLPUPPET_DAEMON_INSTANCE'] = deps.identity.instanceId;
786
+ sessionEnv['SHELLPUPPET_CLI'] = deps.identity.cliPath;
787
+ if (deps.identity.home !== undefined) {
788
+ setSessionEnvValue(sessionEnv, this.platform, 'SHELLPUPPET_HOME', deps.identity.home);
789
+ }
790
+ }
669
791
  const spawnOptions = {
670
792
  name: 'xterm-256color',
671
793
  cols,
@@ -673,7 +795,7 @@ export class Session {
673
795
  cwd: options.cwd ?? process.cwd(),
674
796
  // The daemon always passes the mode it resolved and reports; this
675
797
  // default serves code that uses SessionManager or Session directly.
676
- env: buildSessionEnv(deps.sessionEnv ?? DEFAULT_SESSION_ENV, this.platform, process.env, options.env),
798
+ env: sessionEnv,
677
799
  };
678
800
  try {
679
801
  if (this.spawnPty !== undefined) {
@@ -689,7 +811,21 @@ export class Session {
689
811
  catch (error) {
690
812
  // On Windows node-pty loads its native module here, as the terminal is
691
813
  // built, so a missing binary surfaces now rather than at the load above.
692
- throw explainSpawnFailure(error);
814
+ let failure = explainSpawnFailure(error);
815
+ // A spawn implementation may include its environment in an error.
816
+ // The identity secret must not reach the daemon's error response or log.
817
+ if (deps.identity !== undefined) {
818
+ const token = deps.identity.token;
819
+ if (failure instanceof Error) {
820
+ failure.message = failure.message.replaceAll(token, '[redacted]');
821
+ if (failure.stack !== undefined)
822
+ failure.stack = failure.stack.replaceAll(token, '[redacted]');
823
+ }
824
+ else {
825
+ failure = new Error(String(failure).replaceAll(token, '[redacted]'));
826
+ }
827
+ }
828
+ throw failure;
693
829
  }
694
830
  if (trackConsoleHost) {
695
831
  this.consoleHostWindow = { t0: consoleHostT0, t1: Date.now() };
@@ -713,7 +849,20 @@ export class Session {
713
849
  this.logger.warn(`session ${stream} failed`, { id, error: String(error) });
714
850
  });
715
851
  }
852
+ this.stallPtyCols = this.pty.cols;
853
+ this.stallPtyRows = this.pty.rows;
716
854
  this.pty.onData((data) => {
855
+ if (this.exitedFlag || this.isKilled)
856
+ return;
857
+ if (this.pendingNudgeLine !== null)
858
+ this.pendingQuietSince = Date.now();
859
+ // node-pty can apply a requested resize later, after its first output.
860
+ // Observe the dimensions it reports as well as our explicit requests.
861
+ if (this.pty.cols !== this.stallPtyCols || this.pty.rows !== this.stallPtyRows) {
862
+ this.stallPtyCols = this.pty.cols;
863
+ this.stallPtyRows = this.pty.rows;
864
+ this.noteStallResize(true);
865
+ }
717
866
  // Track bracketed-paste mode from the app's own output (see PASTE_START).
718
867
  //
719
868
  // Scanned with a carry-over tail because PTY read boundaries are
@@ -730,6 +879,15 @@ export class Session {
730
879
  this.cursorHidden = cursorHiddenAfter(scan, this.cursorHidden);
731
880
  this.modeScanTail = scan.slice(-MODE_SCAN_TAIL_CHARS);
732
881
  const rendered = this.renderer.write(data);
882
+ if (this.agentModule?.stalls !== undefined) {
883
+ void rendered.then(() => {
884
+ if (this.stallTracker.tracking || this.stallInk?.possible)
885
+ this.deferStall();
886
+ }).catch(() => {
887
+ this.publishStall(undefined);
888
+ this.logger.warn('stall reading failed', { id: this.id });
889
+ });
890
+ }
733
891
  // First paint is decided by the RENDERER, not by bytes arriving: ConPTY
734
892
  // emits mode-set sequences ~140 ms after spawn that draw nothing, and a
735
893
  // quiet/readyQuiet that counted them as output would report a CLI ready
@@ -737,7 +895,7 @@ export class Session {
737
895
  // holds, so the snapshot cost stops at the first visible character.
738
896
  if (!this.painted) {
739
897
  void rendered.then(() => {
740
- if (!this.painted && this.renderer.snapshot().screen !== '')
898
+ if (!this.exitedFlag && !this.isKilled && !this.painted && this.renderer.snapshot().screen !== '')
741
899
  this.painted = true;
742
900
  });
743
901
  }
@@ -746,6 +904,8 @@ export class Session {
746
904
  listener(data);
747
905
  });
748
906
  this.pty.onExit(({ exitCode: reported }) => {
907
+ if (this.exitedFlag)
908
+ return;
749
909
  // node-pty closes a Windows terminal whose output socket failed and
750
910
  // reports an exit with no code, while the program runs on: the session
751
911
  // can no longer be read or typed into, so it has ended, and its program
@@ -753,6 +913,8 @@ export class Session {
753
913
  // reach it (`endProgram`).
754
914
  const exitCode = typeof reported === 'number' ? reported : null;
755
915
  this.exitedFlag = true;
916
+ this.clearStallTimer();
917
+ this.publishStall(undefined);
756
918
  this.exitedAtValue = Date.now();
757
919
  this.exitCodeValue = exitCode;
758
920
  this.lastChange = Date.now();
@@ -770,28 +932,15 @@ export class Session {
770
932
  // session counts as ready at spawn; otherwise readiness flips when the
771
933
  // condition holds. A session whose condition never holds stays not-ready,
772
934
  // which is the truth and is visible in list/snapshot output.
773
- if (options.readyText !== undefined || options.readyQuiet !== undefined) {
935
+ if (readiness !== undefined) {
774
936
  this.readyFlag = false;
775
937
  this.readyReasonValue = 'pending';
776
- const condition = options.readyText !== undefined
777
- ? { text: options.readyText }
778
- : { quiet: options.readyQuiet };
779
- void waitFor(this, condition, { timeout: MAX_WAIT_TIMEOUT_MS }).then((result) => {
780
- if (result.matched) {
781
- this.readyFlag = true;
782
- this.readyReasonValue = 'condition-met';
783
- this.logger.info('session ready', { id, reason: result.reason });
784
- }
785
- else {
786
- this.readyReasonValue = 'never-held';
787
- this.logger.warn('session readiness condition never held', {
788
- id,
789
- reason: result.reason,
790
- });
791
- }
792
- for (const listener of this.readyListeners)
793
- listener();
794
- });
938
+ // Preserve the existing explicit-condition path without the switch.
939
+ if (options.waitReady === true)
940
+ this.trackStartupReadiness();
941
+ else {
942
+ void waitFor(this, options.readyText !== undefined ? { text: options.readyText } : { quiet: options.readyQuiet }, { timeout: MAX_WAIT_TIMEOUT_MS }).then(result => this.recordReadiness(result.matched, result.reason));
943
+ }
795
944
  }
796
945
  else {
797
946
  // No condition was asked for, so nothing is being checked. `ready` is
@@ -883,6 +1032,30 @@ export class Session {
883
1032
  get exitCode() {
884
1033
  return this.exitCodeValue;
885
1034
  }
1035
+ get fault() {
1036
+ return this.rendererFault;
1037
+ }
1038
+ /** A broken emulator ends only its own session, including a queued resize. */
1039
+ failRenderer(error) {
1040
+ if (this.exitedFlag || this.isKilled)
1041
+ return;
1042
+ this.rendererFault = 'terminal rendering failed';
1043
+ this.logger.error('session renderer failed', { id: this.id, error: String(error) });
1044
+ this.exitedFlag = true;
1045
+ this.exitedAtValue = Date.now();
1046
+ this.exitCodeValue = null;
1047
+ this.lastChange = Date.now();
1048
+ this.clearStallTimer();
1049
+ this.publishStall(undefined);
1050
+ // End the process even if node-pty has no exit code yet. kill() observes
1051
+ // this work and closes the PTY and renderer after the tree has ended.
1052
+ this.endingProgram = this.endProgram();
1053
+ for (const listener of this.exitListeners)
1054
+ listener(null);
1055
+ void this.kill().catch((killError) => {
1056
+ this.logger.error('session renderer fault cleanup failed', { id: this.id, error: String(killError) });
1057
+ });
1058
+ }
886
1059
  /**
887
1060
  * Whether the session's program is known to have ended: node-pty has
888
1061
  * recorded its exit code, or its exit came with a code. Until then its
@@ -954,40 +1127,453 @@ export class Session {
954
1127
  * Rejects with `SessionInputFailedError` once the input pipe has failed,
955
1128
  * including for the rest of a chunked write it fails part-way through.
956
1129
  */
957
- write(data) {
958
- const museSubmit = this.agent === 'muse' && museSubmittingText(data);
959
- if (museSubmit)
960
- this.museSubmissionsQueued++;
961
- const queued = this.writeChain.then(() => this.writeInput(data));
1130
+ write(data, options = {}) {
1131
+ return this.writeWithResult(data, options).then((result) => result.before);
1132
+ }
1133
+ /** Write and report what a module can establish about a typed submission. */
1134
+ writeWithResult(data, options = {}) {
1135
+ this.inputQueueVersion++;
1136
+ const delayedSubmit = this.delayedSubmission(data);
1137
+ if (delayedSubmit)
1138
+ this.submissionsQueued++;
1139
+ const queued = this.writeChain.then(async () => {
1140
+ const result = { before: '', submitRetried: false };
1141
+ result.before = (await this.writeInput(data, options.terminalReport === true, undefined, undefined, false, [], () => 'line-not-seen', (outcome) => Object.assign(result, outcome))) ?? '';
1142
+ return result;
1143
+ });
962
1144
  // The chain must survive a failed write, or one rejection would wedge every
963
1145
  // subsequent write on this session.
964
- this.writeChain = queued.then(() => { if (museSubmit)
965
- this.museSubmissionsQueued--; }, () => { if (museSubmit)
966
- this.museSubmissionsQueued--; });
1146
+ this.writeChain = queued.then(() => { if (delayedSubmit)
1147
+ this.submissionsQueued--; }, () => { if (delayedSubmit)
1148
+ this.submissionsQueued--; });
967
1149
  return queued;
968
1150
  }
969
- async writeInput(data) {
1151
+ /** Queue a nudge and retain the original result expected by direct callers. */
1152
+ async writeNudge(data, ready) {
1153
+ const result = await this.writeNudgeWithReason(data, ready);
1154
+ return result === 'sent' || result === 'wait' ? result : 'aborted';
1155
+ }
1156
+ /** Queue a daemon nudge, reporting why a typed body could not be submitted. */
1157
+ writeNudgeWithReason(data, ready, messageIds = [], failedCheck = () => 'line-not-seen') {
1158
+ let abortReason = null;
1159
+ const queued = this.writeChain.then(async () => {
1160
+ try {
1161
+ if (this.pendingNudgeLine !== null)
1162
+ return 'wait';
1163
+ const result = await this.writeInput(data, false, ready, (reason) => { abortReason = reason; }, true, messageIds, failedCheck);
1164
+ return abortReason !== null ? `aborted-${abortReason}`
1165
+ : result === null ? 'wait' : 'sent';
1166
+ }
1167
+ catch (error) {
1168
+ if (abortReason !== null)
1169
+ return `aborted-${abortReason}`;
1170
+ throw error;
1171
+ }
1172
+ });
1173
+ this.writeChain = queued.then(() => undefined, () => undefined);
1174
+ return queued;
1175
+ }
1176
+ nudgePendingLine() { return this.pendingNudgeLine; }
1177
+ nudgePendingIds() { return this.pendingNudgeIds; }
1178
+ nudgePendingUntouched() { return !this.pendingNudgeTouched; }
1179
+ nudgePendingTouchRefusal() {
1180
+ if (!this.pendingNudgeTouched || this.pendingTouchRefusalAudited)
1181
+ return false;
1182
+ this.pendingTouchRefusalAudited = true;
1183
+ return true;
1184
+ }
1185
+ /** Clear after an observed submitted turn or a whole quiet period of proven emptiness. */
1186
+ async clearConsumedNudge() {
1187
+ if (this.pendingNudgeLine === null)
1188
+ return false;
1189
+ await this.renderer.flush();
1190
+ const verdict = this.pendingComposerVerdict();
1191
+ if (!verdict.ready && verdict.reason === 'busy' && this.pendingTurnSubmitted)
1192
+ this.pendingTurnBusy = true;
1193
+ if (!verdict.ready) {
1194
+ this.pendingQuietSince = Date.now();
1195
+ return false;
1196
+ }
1197
+ if (!(this.pendingTurnBusy || Date.now() - this.pendingQuietSince >= this.pendingNudgeSettleMs))
1198
+ return false;
1199
+ this.pendingNudgeLine = null;
1200
+ this.pendingNudgeIds = [];
1201
+ this.pendingNudgeTouched = false;
1202
+ this.pendingTouchRefusalAudited = false;
1203
+ this.pendingTurnSubmitted = false;
1204
+ this.pendingTurnBusy = false;
1205
+ return true;
1206
+ }
1207
+ /** A pending body may receive its submit key only after it is visible exactly once. */
1208
+ submitPendingNudge(line, ready) {
1209
+ const queued = this.writeChain.then(async () => {
1210
+ this.refuseIfInputFailed();
1211
+ await this.renderer.flush();
1212
+ this.refuseIfEnded();
1213
+ if (this.pendingNudgeLine !== line || this.pendingNudgeTouched ||
1214
+ !ready(this.renderer.snapshot().screen) ||
1215
+ !this.nudgeReadyWithLine(line))
1216
+ return false;
1217
+ this.pty.write(this.nudgeSubmit());
1218
+ this.pendingNudgeLine = null;
1219
+ this.pendingNudgeIds = [];
1220
+ this.pendingNudgeTouched = false;
1221
+ this.pendingTouchRefusalAudited = false;
1222
+ this.pendingTurnSubmitted = false;
1223
+ this.pendingTurnBusy = false;
1224
+ this.inputVersion++;
1225
+ return true;
1226
+ });
1227
+ this.writeChain = queued.then(() => undefined, () => undefined);
1228
+ return queued;
1229
+ }
1230
+ nudgeReady(now) {
1231
+ return this.nudgeState(now).ready;
1232
+ }
1233
+ /**
1234
+ * Whether a nudge may be typed now, and whether it would be queued behind a
1235
+ * running turn. Each call also measures how long the composer block (the
1236
+ * last rows on screen) has stayed the same, which a queued nudge waits on.
1237
+ */
1238
+ nudgeState(now) {
1239
+ const view = this.nudgeView();
1240
+ const nudge = this.agentModule?.nudge;
1241
+ const pane = nudge?.idlePane?.(view);
1242
+ const key = pane ?? nudge?.composerBlock?.(view.rows, view.cursor) ?? composerBlockKey(view.rows);
1243
+ if (key !== this.nudgeComposerKey) {
1244
+ this.nudgeComposerKey = key;
1245
+ this.nudgeComposerSince = now;
1246
+ }
1247
+ const verdict = nudgeVerdict(this.agentModule, {
1248
+ ...view,
1249
+ stall: this.getStalled(),
1250
+ unchangedMs: now - (pane === undefined ? this.lastChangeAt() : this.nudgeComposerSince),
1251
+ composerUnchangedMs: now - this.nudgeComposerSince,
1252
+ });
1253
+ const queued = verdict.ready && verdict.queued === true;
1254
+ return { ready: verdict.ready, queued, paneQuiet: pane !== undefined, regionKey: key };
1255
+ }
1256
+ nudgeView() {
1257
+ const styled = this.renderer.styledLines().lines;
1258
+ return { styled, rows: styled.map(line => line.text), cursor: this.renderer.cursor, viewportRows: this.renderer.rows,
1259
+ untrimmedRow: (y) => this.renderer.untrimmedRow(y) };
1260
+ }
1261
+ pendingComposerVerdict() {
1262
+ return nudgeVerdict(this.agentModule, {
1263
+ ...this.nudgeView(),
1264
+ stall: this.getStalled(), unchangedMs: NUDGE_QUIET_MS, exactEmpty: true,
1265
+ });
1266
+ }
1267
+ /**
1268
+ * Positive evidence that the agent has not started yet: its module cannot read a composer and the
1269
+ * text before the cursor is a shell prompt (PowerShell, cmd.exe, or a POSIX `user@host:dir$`).
1270
+ * An agent screen the module cannot read for a moment (a clipped frame, a status timeout) is
1271
+ * not a shell prompt, so its typed text still waits for composer proof.
1272
+ */
1273
+ shellPromptBeforeAgent() {
1274
+ const verdict = this.pendingComposerVerdict();
1275
+ if (verdict.ready || verdict.reason !== 'unknown')
1276
+ return false;
1277
+ const view = this.nudgeView();
1278
+ // A wrapped continuation belongs to whatever row above it began, such as an agent draft.
1279
+ if (view.styled[view.cursor.y]?.wrapped === true)
1280
+ return false;
1281
+ const row = view.rows[view.cursor.y] ?? '';
1282
+ const before = row.slice(0, view.cursor.x).replace(/\s+$/u, '');
1283
+ return SHELL_PROMPTS.some((pattern) => pattern.test(before));
1284
+ }
1285
+ nudgeSubmit() {
1286
+ return this.agentModule?.input?.submit?.key ?? '\r';
1287
+ }
1288
+ nudgeInputVersion() { return this.inputVersion; }
1289
+ nudgeQueuedInputVersion() { return this.inputQueueVersion; }
1290
+ nudgeScreenRevision() { return this.screenRevision; }
1291
+ nudgeReadyWithLine(line) {
1292
+ return nudgeVerdict(this.agentModule, {
1293
+ ...this.nudgeView(),
1294
+ stall: this.getStalled(), unchangedMs: 0, expectedDraft: line,
1295
+ }).ready;
1296
+ }
1297
+ /** Paste placeholders on the viewport before this body is written. */
1298
+ visiblePastePlaceholders() {
1299
+ const placeholder = this.agentModule?.input?.submit?.pastePlaceholder;
1300
+ const visible = new Set();
1301
+ if (placeholder === undefined)
1302
+ return visible;
1303
+ for (const line of this.renderer.styledLines().lines) {
1304
+ const match = placeholder.exec(line.text);
1305
+ if (match?.[1] !== undefined)
1306
+ visible.add(match[1]);
1307
+ }
1308
+ return visible;
1309
+ }
1310
+ /** The exact draft or a new, length-matched paste placeholder. */
1311
+ typedDraftVisible(body, placeholdersBefore) {
1312
+ const placeholder = this.agentModule?.input?.submit?.pastePlaceholder;
1313
+ if (placeholder !== undefined && placeholdersBefore !== null) {
1314
+ for (const line of this.renderer.styledLines().lines) {
1315
+ const match = placeholder.exec(line.text);
1316
+ if (match?.[1] === undefined || !this.nudgeReadyWithLine(match[1]))
1317
+ continue;
1318
+ const shownChars = match.groups?.['chars'];
1319
+ return !placeholdersBefore.has(match[1]) &&
1320
+ (shownChars === undefined || Number(shownChars.replaceAll(',', '')) === Array.from(body).length);
1321
+ }
1322
+ }
1323
+ return this.nudgeReadyWithLine(body);
1324
+ }
1325
+ /** A paste is ready only after its draft has appeared and output has settled. */
1326
+ async waitForTypedDraft(body, placeholdersBefore, startedAt, minimumMs, bodyInputVersion) {
1327
+ const quietMs = this.agentModule?.input?.submit?.quietMs ?? 150;
1328
+ const deadline = startedAt + minimumMs +
1329
+ (this.agentModule?.input?.submit?.maxWaitMs ?? TYPED_SUBMIT_WAIT_MS);
1330
+ for (;;) {
1331
+ await this.renderer.flush();
1332
+ this.refuseIfInputFailed();
1333
+ this.refuseIfEnded();
1334
+ if (this.inputVersion !== bodyInputVersion)
1335
+ return false;
1336
+ const visible = this.typedDraftVisible(body, placeholdersBefore);
1337
+ const now = Date.now();
1338
+ if (visible && now - startedAt >= minimumMs && now - this.lastChangeAt() >= quietMs)
1339
+ return true;
1340
+ if (now >= deadline)
1341
+ return false;
1342
+ await new Promise((resolve) => setTimeout(resolve, NUDGE_SUBMIT_POLL_MS));
1343
+ }
1344
+ }
1345
+ delayedSubmission(data) {
1346
+ const submit = this.agentModule?.input?.submit;
1347
+ return submit?.delayMs !== undefined && submit.matches?.(data) === true;
1348
+ }
1349
+ async writeInput(data, terminalReport, ready, onNudgeAbort, nudge = false, messageIds = [], failedCheck = () => 'line-not-seen', onTypedSubmit) {
970
1350
  this.refuseIfInputFailed();
1351
+ if (ready !== undefined)
1352
+ await this.renderer.flush();
1353
+ if (!terminalReport && data.length > 0 &&
1354
+ this.agentModule?.stalls !== undefined && !this.stallTracker.tracking) {
1355
+ await this.renderer.flush();
1356
+ if (this.stallInk?.possible)
1357
+ this.refreshStall();
1358
+ }
1359
+ if (ready !== undefined) {
1360
+ this.refuseIfEnded();
1361
+ if (!ready(this.renderer.snapshot().screen, 'before'))
1362
+ return null;
1363
+ }
1364
+ if (!nudge && !terminalReport && data !== '' && this.pendingNudgeLine !== null) {
1365
+ this.pendingNudgeTouched = true;
1366
+ }
971
1367
  // Recorded BEFORE the bytes go in, when the screen still shows what this
972
1368
  // input is answering: the waiter's stale-prompt guard needs that prompt,
973
1369
  // and its echo guard needs the input itself.
974
1370
  this.lastInputData = data;
975
- const { screen } = this.renderer.snapshot();
976
- this.stalePrompts.noteInput(screen);
977
- if (this.agent === 'muse' && museSubmittingText(data)) {
978
- const body = data.slice(0, -1);
1371
+ if (!terminalReport && data.length > 0) {
1372
+ // Discovery may still be queued. Capture the screen this input answers
1373
+ // before suppressing it, so a delayed check cannot announce that old turn.
1374
+ // A key cannot repair the local server. Keep a recognised banner and
1375
+ // its settle timer until the rendered banner actually goes away.
1376
+ if (this.stallTracker.reason !== 'server-lost' && this.stallState?.reason !== 'server-lost') {
1377
+ this.stallTracker.noteInput();
1378
+ this.clearStallTimer();
1379
+ this.publishStall(undefined);
1380
+ }
1381
+ }
1382
+ const { screen, lines } = this.renderer.snapshot();
1383
+ // Nothing written and nothing painted for a while: no earlier paste can still be
1384
+ // waiting to paint its placeholder, so a new placeholder can only be this body's.
1385
+ const settledBefore = Date.now() - this.lastInputAt >= TYPED_PLACEHOLDER_SETTLE_MS &&
1386
+ Date.now() - this.lastChange >= TYPED_PLACEHOLDER_SETTLE_MS;
1387
+ this.lastInputAt = Date.now();
1388
+ this.inputVersion++;
1389
+ this.stalePrompts.noteInput(screen, this.agent, this.renderer.promptStyles(lines));
1390
+ if (nudge || this.delayedSubmission(data)) {
1391
+ const submit = this.agentModule?.input?.submit;
1392
+ const key = nudge ? this.nudgeSubmit() : submit.key;
1393
+ const body = data.slice(0, -key.length);
1394
+ const delayMs = nudge ? Math.max(NUDGE_SUBMIT_DELAY_MS, submit?.delayMs ?? 0)
1395
+ : Math.max(submit.delayMs, Math.ceil(Array.from(body).length * (submit?.perCharacterMs ?? 0)));
1396
+ const queuedInputVersion = this.inputQueueVersion;
1397
+ if (!nudge && this.agentModule?.nudge !== undefined)
1398
+ await this.renderer.flush();
1399
+ // Typed text waits for proof only when the agent's own composer is on screen. Before the
1400
+ // agent has started (a shell prompt typing its launch command), the module cannot read a
1401
+ // composer, so the line and its Enter are written as for any other program.
1402
+ const readableComposer = !nudge && this.agentModule?.nudge !== undefined &&
1403
+ !this.shellPromptBeforeAgent();
1404
+ // Without a settled screen before the body, no placeholder can prove this write:
1405
+ // only the exact typed line can.
1406
+ const placeholdersBefore = readableComposer && settledBefore
1407
+ ? this.visiblePastePlaceholders() : null;
1408
+ if (nudge) {
1409
+ this.pendingNudgeLine = body;
1410
+ this.pendingNudgeIds = [...messageIds];
1411
+ this.pendingNudgeTouched = false;
1412
+ this.pendingTouchRefusalAudited = false;
1413
+ this.pendingTurnSubmitted = false;
1414
+ this.pendingTurnBusy = false;
1415
+ this.pendingQuietSince = Date.now();
1416
+ }
979
1417
  await this.writeData(body);
980
- await new Promise((resolve) => setTimeout(resolve, MUSE_SUBMIT_DELAY_MS));
981
- this.refuseIfInputFailed();
982
- this.refuseIfEnded();
983
- this.pty.write('\r');
1418
+ const bodyInputVersion = this.inputVersion;
1419
+ const bodyWrittenAt = Date.now();
1420
+ try {
1421
+ let typedDraftSeen = false;
1422
+ if (readableComposer) {
1423
+ typedDraftSeen = await this.waitForTypedDraft(body, placeholdersBefore, bodyWrittenAt, delayMs, bodyInputVersion);
1424
+ }
1425
+ else {
1426
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
1427
+ }
1428
+ this.refuseIfInputFailed();
1429
+ // A program without a readable composer (a plain shell) keeps writing input as
1430
+ // before: the write itself fails if the terminal has gone. Only a nudge or a
1431
+ // readable agent composer is refused here once the session has ended.
1432
+ if (nudge || this.agentModule?.nudge !== undefined)
1433
+ this.refuseIfEnded();
1434
+ if (ready !== undefined) {
1435
+ // A program may paint a pasted line some time after it arrives, so
1436
+ // the check repeats until the screen holds the line or the wait ends.
1437
+ // Any other input during the wait still abandons the submit.
1438
+ const deadline = Date.now() + (nudge ? NUDGE_SUBMIT_WAIT_MS : 0);
1439
+ for (;;) {
1440
+ await this.renderer.flush();
1441
+ this.refuseIfEnded();
1442
+ if (this.inputQueueVersion !== queuedInputVersion) {
1443
+ onNudgeAbort?.('other-input-arrived');
1444
+ return null;
1445
+ }
1446
+ if (ready(this.renderer.snapshot().screen, 'submit'))
1447
+ break;
1448
+ if (Date.now() >= deadline) {
1449
+ onNudgeAbort?.(failedCheck());
1450
+ return null;
1451
+ }
1452
+ await new Promise((resolve) => setTimeout(resolve, NUDGE_SUBMIT_POLL_MS));
1453
+ this.refuseIfInputFailed();
1454
+ }
1455
+ }
1456
+ if (readableComposer) {
1457
+ await this.renderer.flush();
1458
+ this.refuseIfInputFailed();
1459
+ this.refuseIfEnded();
1460
+ }
1461
+ const beforeSubmitScreen = !nudge ? this.renderer.snapshot().screen : '';
1462
+ const beforeSubmitVerdict = !nudge ? this.pendingComposerVerdict() : null;
1463
+ const wasBusy = beforeSubmitVerdict?.ready === false && beforeSubmitVerdict.reason === 'busy';
1464
+ if (readableComposer) {
1465
+ if (this.inputVersion !== bodyInputVersion) {
1466
+ onTypedSubmit?.({ submitted: false, submitRetried: false,
1467
+ message: 'Other input arrived after the typed text; Enter was not sent.' });
1468
+ return screen;
1469
+ }
1470
+ if (!typedDraftSeen || !this.typedDraftVisible(body, placeholdersBefore)) {
1471
+ onTypedSubmit?.({ submitted: false, submitRetried: false,
1472
+ message: 'The typed text was not seen in the composer; Enter was not sent.' });
1473
+ return screen;
1474
+ }
1475
+ }
1476
+ // On Windows the program can end before its exit event; never send Enter after it.
1477
+ if (this.agentModule?.nudge !== undefined && this.programEnded) {
1478
+ throw new Error(`Session ${this.id} exited while input was being written.`);
1479
+ }
1480
+ this.pty.write(key);
1481
+ if (!nudge) {
1482
+ onTypedSubmit?.(readableComposer || this.agentModule?.nudge === undefined
1483
+ ? await this.checkTypedSubmission(body, key, queuedInputVersion, typedDraftSeen, beforeSubmitScreen, wasBusy, placeholdersBefore)
1484
+ : { submitRetried: false,
1485
+ message: "Submit key sent; the agent's composer was not on screen when the text was typed." });
1486
+ }
1487
+ if (!nudge && this.pendingNudgeLine !== null) {
1488
+ this.pendingQuietSince = Date.now();
1489
+ this.pendingTurnSubmitted = true;
1490
+ }
1491
+ if (nudge) {
1492
+ this.pendingNudgeLine = null;
1493
+ this.pendingNudgeIds = [];
1494
+ this.pendingNudgeTouched = false;
1495
+ this.pendingTouchRefusalAudited = false;
1496
+ this.pendingTurnSubmitted = false;
1497
+ this.pendingTurnBusy = false;
1498
+ }
1499
+ }
1500
+ catch (error) {
1501
+ onNudgeAbort?.(failedCheck());
1502
+ throw error;
1503
+ }
984
1504
  return screen;
985
1505
  }
986
1506
  await this.writeData(data);
1507
+ if (!terminalReport && this.pendingNudgeLine !== null &&
1508
+ data.endsWith(this.nudgeSubmit()))
1509
+ this.pendingTurnSubmitted = true;
987
1510
  return screen;
988
1511
  }
1512
+ typedLineInTranscript(body, beforeScreen) {
1513
+ const transcript = (screen) => {
1514
+ const signature = this.agentModule?.reading.composer.text;
1515
+ if (signature === undefined)
1516
+ return '';
1517
+ const composer = new RegExp(signature, 'u');
1518
+ const lines = screen.split('\n');
1519
+ let at = -1;
1520
+ for (let i = 0; i < lines.length; i++)
1521
+ if (composer.test(lines[i]))
1522
+ at = i;
1523
+ return at < 0 ? '' : lines.slice(0, at).join('\n');
1524
+ };
1525
+ const after = transcript(this.renderer.snapshot().screen);
1526
+ return after.includes(body) && !transcript(beforeScreen).includes(body);
1527
+ }
1528
+ async checkTypedSubmission(body, key, queuedInputVersion, draftSeen, beforeSubmitScreen, wasBusy, placeholdersBefore) {
1529
+ if (this.agentModule?.nudge === undefined) {
1530
+ return { submitRetried: false,
1531
+ message: 'Submit key sent; this programme has no readable composer.' };
1532
+ }
1533
+ const settleMs = this.agentModule.input?.submit?.settleMs ?? TYPED_SUBMIT_SETTLE_MS;
1534
+ await new Promise((resolve) => setTimeout(resolve, settleMs));
1535
+ await this.renderer.flush();
1536
+ if (this.inputQueueVersion !== queuedInputVersion) {
1537
+ return { submitRetried: false,
1538
+ message: 'Submit key sent; later input arrived before the composer check.' };
1539
+ }
1540
+ if (!this.typedDraftVisible(body, placeholdersBefore)) {
1541
+ const verdict = this.pendingComposerVerdict();
1542
+ if ((draftSeen && verdict.ready) || (!wasBusy && !verdict.ready && verdict.reason === 'busy') ||
1543
+ this.typedLineInTranscript(body, beforeSubmitScreen)) {
1544
+ return { submitted: true, submitRetried: false };
1545
+ }
1546
+ return { submitRetried: false,
1547
+ message: 'Submit key sent; the composer did not confirm submission.' };
1548
+ }
1549
+ this.refuseIfInputFailed();
1550
+ this.refuseIfEnded();
1551
+ // A prompt or changed composer can appear while the first Enter settles.
1552
+ if (this.inputQueueVersion !== queuedInputVersion ||
1553
+ !this.typedDraftVisible(body, placeholdersBefore)) {
1554
+ return { submitRetried: false,
1555
+ message: 'Submit key sent; the composer changed before a retry.' };
1556
+ }
1557
+ this.pty.write(key);
1558
+ await new Promise((resolve) => setTimeout(resolve, settleMs));
1559
+ await this.renderer.flush();
1560
+ if (this.inputQueueVersion !== queuedInputVersion) {
1561
+ return { submitRetried: true,
1562
+ message: 'Submit key retried; later input arrived before confirmation.' };
1563
+ }
1564
+ if (this.typedDraftVisible(body, placeholdersBefore)) {
1565
+ return { submitted: false, submitRetried: true,
1566
+ message: 'The typed text is still in the composer after one submit retry.' };
1567
+ }
1568
+ const verdict = this.pendingComposerVerdict();
1569
+ return { ...((verdict.ready || (!verdict.ready && verdict.reason === 'busy') ||
1570
+ this.typedLineInTranscript(body, beforeSubmitScreen)) ? { submitted: true } : {}), submitRetried: true,
1571
+ message: 'Submit key retried once after the typed text remained in the composer.' };
1572
+ }
989
1573
  async writeData(data) {
990
1574
  if (data.length <= WRITE_CHUNK_CHARS) {
1575
+ if (data !== '' && this.pendingNudgeLine !== null)
1576
+ this.pendingQuietSince = Date.now();
991
1577
  this.pty.write(data);
992
1578
  return;
993
1579
  }
@@ -1001,6 +1587,8 @@ export class Session {
1001
1587
  const body = newlineAt === -1 ? data : data.slice(0, newlineAt);
1002
1588
  const trailer = newlineAt === -1 ? '' : data.slice(newlineAt);
1003
1589
  this.lastWriteWrapped = true;
1590
+ if (this.pendingNudgeLine !== null)
1591
+ this.pendingQuietSince = Date.now();
1004
1592
  this.pty.write(`${PASTE_START}${body}${PASTE_END}${trailer}`);
1005
1593
  return;
1006
1594
  }
@@ -1018,6 +1606,8 @@ export class Session {
1018
1606
  if (code >= 0xd800 && code <= 0xdbff)
1019
1607
  end -= 1;
1020
1608
  }
1609
+ if (this.pendingNudgeLine !== null)
1610
+ this.pendingQuietSince = Date.now();
1021
1611
  this.pty.write(data.slice(offset, end));
1022
1612
  offset = end;
1023
1613
  if (offset < data.length) {
@@ -1031,8 +1621,10 @@ export class Session {
1031
1621
  throw new SessionInputFailedError(this.id, this.inputFailure);
1032
1622
  }
1033
1623
  refuseIfEnded() {
1034
- if (this.exitedFlag || this.isKilled)
1624
+ // On Windows the program can end before its exit event; an agent session never gets input after it.
1625
+ if (this.exitedFlag || this.isKilled || (this.agentModule?.nudge !== undefined && this.programEnded)) {
1035
1626
  throw new Error(`Session ${this.id} exited while input was being written.`);
1627
+ }
1036
1628
  }
1037
1629
  /**
1038
1630
  * Resize the PTY.
@@ -1054,27 +1646,65 @@ export class Session {
1054
1646
  * dropped (`windowsPtyStart.ts`).
1055
1647
  */
1056
1648
  resize(cols, rows, options = {}) {
1057
- if (this.agent === 'muse' && this.museSubmissionsQueued > 0) {
1058
- const queued = this.writeChain.then(() => this.resizeNow(cols, rows, options));
1649
+ if (this.agentModule?.input?.resizeBehindSubmit === true && this.submissionsQueued > 0) {
1650
+ const queued = this.writeChain.then(() => { this.resizeNow(cols, rows, options); options.onApplied?.(); });
1059
1651
  this.writeChain = queued.then(() => undefined, () => undefined);
1060
1652
  return queued;
1061
1653
  }
1062
1654
  this.resizeNow(cols, rows, options);
1655
+ options.onApplied?.();
1656
+ }
1657
+ /** Decide and apply a geometry act together at its place in the submit queue. */
1658
+ resizeIfCurrent(cols, rows, shouldApply, onApplied, skipIfSame = false) {
1659
+ const apply = () => {
1660
+ if (!shouldApply())
1661
+ return false;
1662
+ const changed = cols !== this.renderer.cols || rows !== this.renderer.rows;
1663
+ if (changed || !skipIfSame)
1664
+ this.resizeNow(cols, rows, {});
1665
+ onApplied(changed);
1666
+ return true;
1667
+ };
1668
+ if (this.agentModule?.input?.resizeBehindSubmit === true && this.submissionsQueued > 0) {
1669
+ const queued = this.writeChain.then(apply);
1670
+ this.writeChain = queued.then(() => undefined, () => undefined);
1671
+ return queued;
1672
+ }
1673
+ return apply();
1063
1674
  }
1064
1675
  resizeNow(cols, rows, options) {
1676
+ if (this.exitedFlag || this.isKilled)
1677
+ throw new SessionProgramEndedError(this.id, this.exitCodeValue);
1065
1678
  const ended = recordedExitCode(this.pty);
1066
1679
  if (ended !== undefined)
1067
1680
  throw new SessionProgramEndedError(this.id, ended);
1681
+ const oldCols = this.renderer.cols;
1682
+ const oldRows = this.renderer.rows;
1068
1683
  this.pty.resize(cols, rows);
1684
+ if (this.pendingNudgeLine !== null)
1685
+ this.pendingQuietSince = Date.now();
1686
+ this.screenRevision++;
1687
+ this.stallPtyCols = this.pty.cols;
1688
+ this.stallPtyRows = this.pty.rows;
1689
+ this.noteStallResize(cols !== this.renderer.cols || rows !== this.renderer.rows);
1069
1690
  this.renderer.resize(cols, rows);
1691
+ this.logger.debug('session resized', { id: this.id, oldCols, oldRows, cols, rows });
1692
+ // Unsettled candidates rebase on local reflow. Established notices keep
1693
+ // their validated baselines until the bounded native redraw finishes.
1694
+ if (this.agentModule?.stalls !== undefined && this.stallState === undefined) {
1695
+ this.stallContent = this.stallScreen.content(this.renderer.plainViewport(), this.agentModule.stalls);
1696
+ this.stallTranscript = this.readStallTranscript();
1697
+ this.scheduleStall();
1698
+ }
1070
1699
  if (options.hold !== undefined)
1071
1700
  this.geometryHeldFlag = options.hold;
1072
1701
  }
1073
- answerablePrompt(screen, now = Date.now()) {
1074
- if (this.agent !== 'muse')
1075
- return detectPrompt(screen);
1076
- const styled = this.renderer.styledLines().lines;
1077
- return this.musePromptSettler.detect(screen, now, styled);
1702
+ answerablePrompt(screen, now = Date.now(), visibleStyles) {
1703
+ if (this.stallState?.reason === 'server-lost')
1704
+ return null;
1705
+ const styled = visibleStyles ?? (this.agentModule?.createPromptSettler !== undefined
1706
+ ? this.renderer.styledLines().lines : this.renderer.promptStyles(screen.split('\n')));
1707
+ return this.promptReader(screen, now, styled, this.renderer.rows);
1078
1708
  }
1079
1709
  // ----------------------------------------------------------------- output
1080
1710
  /** Live raw-stream subscription (viewer mirroring). Returns unsubscribe. */
@@ -1091,6 +1721,250 @@ export class Session {
1091
1721
  this.readyListeners.add(listener);
1092
1722
  return () => this.readyListeners.delete(listener);
1093
1723
  }
1724
+ onStall(listener) {
1725
+ this.stallListeners.add(listener);
1726
+ return () => this.stallListeners.delete(listener);
1727
+ }
1728
+ observeResumeId(...candidates) {
1729
+ if (!this.launchProfile || !this.agentModule?.resumeIdMarkers)
1730
+ return;
1731
+ const own = candidates.find((id) => validResumeId(id) && !this.inheritedResumeIds.includes(id));
1732
+ if (own !== undefined)
1733
+ this.observedResumeId = own;
1734
+ }
1735
+ get resumeId() {
1736
+ return this.observedResumeId ?? this.launchProfile?.resumeId ?? null;
1737
+ }
1738
+ getStalled() { return this.stallState; }
1739
+ noteStallResize(changed) {
1740
+ if (this.stallState === undefined || (this.stallResizeUntil !== 0 && !changed))
1741
+ return;
1742
+ this.stallResizeUntil = Date.now() + 1000;
1743
+ this.clearStallTimer();
1744
+ this.queueStallCheck(() => this.refreshStall(), 1000);
1745
+ }
1746
+ /** Let PTY delivery finish before comparing a rendered batch. */
1747
+ deferStall() {
1748
+ if (this.stallScheduled !== null)
1749
+ return;
1750
+ this.stallScheduled = new Promise(resolve => {
1751
+ setImmediate(() => {
1752
+ this.stallScheduled = null;
1753
+ try {
1754
+ this.scheduleStall();
1755
+ }
1756
+ catch {
1757
+ this.publishStall(undefined);
1758
+ this.logger.warn('stall reading failed', { id: this.id });
1759
+ }
1760
+ finally {
1761
+ resolve();
1762
+ }
1763
+ });
1764
+ });
1765
+ }
1766
+ clearStallTimer() {
1767
+ if (this.stallTimer !== null)
1768
+ clearTimeout(this.stallTimer);
1769
+ this.stallTimer = null;
1770
+ }
1771
+ /** Let ready I/O run before a due validation, retaining cancellation. */
1772
+ queueStallCheck(check, delay) {
1773
+ const timer = setTimeout(() => {
1774
+ setImmediate(() => {
1775
+ // Input, exit or a restored frame may have cancelled this deadline
1776
+ // after it became due but before the queued validation can run.
1777
+ if (this.stallTimer === timer)
1778
+ check();
1779
+ });
1780
+ }, delay);
1781
+ this.stallTimer = timer;
1782
+ timer.unref();
1783
+ }
1784
+ publishStall(state) {
1785
+ if (state === undefined)
1786
+ this.stallResizeUntil = 0;
1787
+ if (this.stallState === state)
1788
+ return;
1789
+ this.stallState = state;
1790
+ for (const listener of this.stallListeners)
1791
+ listener(state);
1792
+ }
1793
+ readStallTranscript() {
1794
+ const signature = signatureForSession(this) ?? undefined;
1795
+ return stallTranscriptContent(this.renderer.framedViewport([...new Set(this.agentModule.stalls.flatMap(shape => shape.frameColumns))]), this.agentModule.stalls, signature);
1796
+ }
1797
+ /** Both output tasks and due timers must compare before rebasing. */
1798
+ compareStallTranscript(transcript = this.readStallTranscript()) {
1799
+ if (transcript !== '' && transcript !== this.stallTranscript && transcript !== this.stallValidatedTranscript) {
1800
+ this.stallTracker.invalidate();
1801
+ this.publishStall(undefined);
1802
+ this.stallValidationPending = false;
1803
+ this.clearStallTimer();
1804
+ }
1805
+ this.stallTranscript = transcript;
1806
+ }
1807
+ scheduleStall() {
1808
+ if (this.exitedFlag || this.isKilled)
1809
+ return;
1810
+ // Framing anchors, marker ink, footer and transcript ownership can all
1811
+ // disappear during a resize. Retain the validated comparison baselines
1812
+ // until the fixed deadline, including if an early complete frame returns.
1813
+ if (this.stallState !== undefined && this.stallResizeUntil !== 0)
1814
+ return;
1815
+ if (!this.stallTracker.tracking) {
1816
+ // Coalesce discovery screening too. An ordinary repaint must neither
1817
+ // rebuild viewport rows per chunk nor enter validation without ink.
1818
+ if (this.stallTimer === null) {
1819
+ this.queueStallCheck(() => {
1820
+ this.clearStallTimer();
1821
+ this.stallNextCheck = Date.now() + 250;
1822
+ if (this.hasStallInk(this.renderer.plainViewport()))
1823
+ this.refreshStall();
1824
+ // Absence also releases input suppression for a later occurrence.
1825
+ else {
1826
+ this.stallTracker.observe(null);
1827
+ this.stallInk?.checkAbsent();
1828
+ }
1829
+ }, Math.max(0, this.stallNextCheck - Date.now()));
1830
+ }
1831
+ return;
1832
+ }
1833
+ // Physical row changes can be composer presentation. Retain the candidate
1834
+ // and clock until coalesced validation compares its canonical identity.
1835
+ // Only new transcript text (including busy markers and prompts) clears at
1836
+ // once; known cosmetic repaints need no full validation.
1837
+ if (this.stallTracker.tracking) {
1838
+ const plain = this.renderer.plainViewport();
1839
+ const content = this.stallScreen.content(plain, this.agentModule.stalls);
1840
+ if (content === this.stallContent || content === this.stallValidatedContent) {
1841
+ // A native terminal can redraw its pre-resize text after xterm has
1842
+ // reflowed padded rows and clipped the viewport. Both are layout.
1843
+ this.stallContent = content;
1844
+ if (content === this.stallValidatedContent && this.stallState !== undefined) {
1845
+ // The invalidating frame has been restored. A pending presentation
1846
+ // check is obsolete; a settling candidate still needs its timer.
1847
+ this.stallValidationPending = false;
1848
+ this.clearStallTimer();
1849
+ this.stallTranscript = this.stallValidatedTranscript;
1850
+ }
1851
+ return;
1852
+ }
1853
+ // A live dialog can replace only rows inside the old error block. Its
1854
+ // text is then omitted from the transcript comparison, even when the
1855
+ // user-turn boundary has scrolled out of the viewport.
1856
+ if (this.stallState !== undefined && this.stallState.reason !== 'server-lost' &&
1857
+ detectPrompt(plain.join('\n'), this.agent) !== null) {
1858
+ this.stallTracker.invalidate();
1859
+ this.publishStall(undefined);
1860
+ this.stallValidationPending = false;
1861
+ this.clearStallTimer();
1862
+ return;
1863
+ }
1864
+ this.stallContent = content;
1865
+ // A visible turn boundary makes changed transcript text an immediate
1866
+ // end. A clipped repaint can expose different panel rows while retaining
1867
+ // the same refusal block; leave that case to bounded styled validation.
1868
+ const signature = signatureForSession(this);
1869
+ const framed = this.renderer.framedViewport([...new Set(this.agentModule.stalls.flatMap(shape => shape.frameColumns))]);
1870
+ const transcript = stallTranscriptContent(framed, this.agentModule.stalls, signature ?? undefined);
1871
+ const baseline = this.stallValidatedTranscript;
1872
+ const completeTurn = signature !== null && stallTurnVisible(framed, this.agentModule.stalls, signature);
1873
+ if (completeTurn || (baseline !== undefined && baseline !== '' && transcript.startsWith(`${baseline}\n`))) {
1874
+ this.compareStallTranscript(transcript);
1875
+ }
1876
+ else if (transcript === this.stallTranscript || transcript === baseline) {
1877
+ this.stallTranscript = transcript;
1878
+ }
1879
+ }
1880
+ if (this.stallTimer !== null)
1881
+ return;
1882
+ this.queueStallCheck(() => this.refreshStall(), Math.max(0, this.stallNextCheck - Date.now()));
1883
+ }
1884
+ hasStallInk(plain) {
1885
+ return this.agentModule.stalls.some(shape => this.renderer.hasForeground(plain.flatMap((line, row) => (typeof shape.marker.text === 'string' ? line.trimEnd() === shape.marker.text :
1886
+ shape.marker.text.test(line.trimEnd())) ? [row] : []), shape.marker.fg));
1887
+ }
1888
+ refreshStall() {
1889
+ this.clearStallTimer();
1890
+ if (this.exitedFlag || this.isKilled)
1891
+ return;
1892
+ const resized = this.stallState !== undefined && this.stallResizeUntil !== 0;
1893
+ if (this.stallState !== undefined && this.stallResizeUntil !== 0) {
1894
+ const remaining = this.stallResizeUntil - Date.now();
1895
+ if (remaining > 0) {
1896
+ this.queueStallCheck(() => this.refreshStall(), remaining);
1897
+ return;
1898
+ }
1899
+ }
1900
+ this.stallNextCheck = Date.now() + 250;
1901
+ const signature = signatureForSession(this);
1902
+ if (signature === null) {
1903
+ this.publishStall(undefined);
1904
+ return;
1905
+ }
1906
+ const plain = this.renderer.plainViewport();
1907
+ const content = this.stallScreen.content(plain, this.agentModule.stalls);
1908
+ if (!resized && this.stallState !== undefined && content === this.stallValidatedContent) {
1909
+ // A due validation can beat the deferred output task to a restored
1910
+ // frame. Cancel here too, before materialising its styled context.
1911
+ this.stallContent = content;
1912
+ this.stallTranscript = this.stallValidatedTranscript;
1913
+ this.stallValidationPending = false;
1914
+ return;
1915
+ }
1916
+ const ink = this.hasStallInk(plain) && possibleStall(plain, signature);
1917
+ let candidate = null;
1918
+ if (ink) {
1919
+ const { lines, firstVisible } = this.renderer.styledLines({ above: 128, extendWrapped: false });
1920
+ candidate = validateStall(lines, signature, false, firstVisible);
1921
+ if (candidate !== null && (!('reason' in candidate) || candidate.reason !== 'server-lost') &&
1922
+ detectPrompt(plain.join('\n'), this.agent) !== null)
1923
+ candidate = null;
1924
+ }
1925
+ // A narrow redraw can clip the user turn and expose only a tail of the
1926
+ // earlier transcript. The same styled block then owns that visible tail.
1927
+ // A new paragraph cannot pass this comparison, and missing ink or a
1928
+ // changed block still goes through bounded invalidation below.
1929
+ const sameClippedBlock = candidate !== null && 'inconclusive' in candidate &&
1930
+ this.stallTracker.matchesBlock(candidate);
1931
+ const currentTranscript = this.stallTracker.matchesBlock(candidate) && resized
1932
+ ? this.readStallTranscript() : undefined;
1933
+ const normaliseTranscript = (value) => value.replace(/\s+/gu, ' ').trim();
1934
+ const visibleTail = currentTranscript !== undefined && currentTranscript !== '' &&
1935
+ this.stallValidatedTranscript !== undefined && normaliseTranscript(this.stallValidatedTranscript)
1936
+ .endsWith(normaliseTranscript(currentTranscript));
1937
+ if (this.stallTracker.tracking && content !== this.stallContent && content !== this.stallValidatedContent &&
1938
+ !sameClippedBlock && !visibleTail)
1939
+ this.compareStallTranscript();
1940
+ this.stallContent = content;
1941
+ if (candidate !== null) {
1942
+ this.stallTranscript = this.readStallTranscript();
1943
+ // Keep the complete-context baselines across an inconclusive read: a
1944
+ // native redraw on growth can restore that viewport after clipped reflow.
1945
+ if (!('inconclusive' in candidate) && (this.stallState === undefined || this.stallTracker.matchesBlock(candidate)) &&
1946
+ !(resized && visibleTail)) {
1947
+ this.stallValidatedContent = this.stallContent;
1948
+ this.stallValidatedTranscript = this.stallTranscript;
1949
+ }
1950
+ }
1951
+ // A partial redraw may temporarily lose the block or composer. Confirm
1952
+ // invalidation at the next bounded check; output cannot postpone it.
1953
+ if (this.stallState !== undefined && !this.stallTracker.matchesBlock(candidate) && !this.stallValidationPending) {
1954
+ this.stallValidationPending = true;
1955
+ this.queueStallCheck(() => this.refreshStall(), 250);
1956
+ return;
1957
+ }
1958
+ this.stallValidationPending = false;
1959
+ this.stallResizeUntil = 0;
1960
+ this.publishStall(this.stallTracker.observe(candidate));
1961
+ if (!this.stallTracker.tracking)
1962
+ this.stallInk?.checkAbsent();
1963
+ const remaining = this.stallTracker.remaining();
1964
+ if (remaining !== null) {
1965
+ this.queueStallCheck(() => this.refreshStall(), remaining);
1966
+ }
1967
+ }
1094
1968
  /**
1095
1969
  * The rendered terminal as bytes that rebuild it in a fresh terminal of the
1096
1970
  * same size (design §5): what a viewer receives on connect and after every
@@ -1116,13 +1990,16 @@ export class Session {
1116
1990
  }
1117
1991
  async snapshot() {
1118
1992
  await this.renderer.flush();
1993
+ await this.stallScheduled;
1119
1994
  const rendered = this.renderer.snapshot();
1120
1995
  // Every look at the screen is evidence for the stale-prompt guard. A
1121
1996
  // snapshot that finds no prompt, or a different one, is what lets a later
1122
1997
  // prompt with identical text count as new rather than as the one just
1123
1998
  // answered, and that includes the ones the daemon's stall scan and verify
1124
1999
  // take.
1125
- this.stalePrompts.observe(detectPrompt(rendered.screen)?.signature ?? null);
2000
+ const styled = this.renderer.promptStyles(rendered.lines);
2001
+ this.stalePrompts.observe(this.stallState?.reason === 'server-lost' ? null :
2002
+ detectPrompt(rendered.screen, this.agent, rendered.rows, styled)?.signature ?? null);
1126
2003
  return {
1127
2004
  id: this.id,
1128
2005
  label: this.label,
@@ -1142,6 +2019,7 @@ export class Session {
1142
2019
  /** Current viewport lines (for `terminal_find`). */
1143
2020
  async viewportLines() {
1144
2021
  await this.renderer.flush();
2022
+ await this.stallScheduled;
1145
2023
  return this.renderer.snapshot().lines;
1146
2024
  }
1147
2025
  /**
@@ -1168,22 +2046,56 @@ export class Session {
1168
2046
  waitFor(condition, options) {
1169
2047
  return waitFor(this, condition, options);
1170
2048
  }
2049
+ waitUntilReady(timeout, signal) {
2050
+ return waitUntilReady(this, timeout, signal);
2051
+ }
2052
+ /** A question at start completion invalidates an earlier opted-in match. */
2053
+ deferReadiness() {
2054
+ if (this.startupReadiness === undefined || this.readyReasonValue !== 'condition-met')
2055
+ return;
2056
+ this.readyFlag = false;
2057
+ this.readyReasonValue = 'pending';
2058
+ for (const listener of this.readyListeners)
2059
+ listener();
2060
+ this.trackStartupReadiness();
2061
+ }
2062
+ trackStartupReadiness() {
2063
+ if (this.startupReadiness === undefined)
2064
+ return;
2065
+ // Restart after a question without extending the session's tracking budget.
2066
+ void trackReadiness(this, this.startupReadiness, true, this.createdAt.getTime() + MAX_WAIT_TIMEOUT_MS)
2067
+ .then(matched => this.recordReadiness(matched, matched ? 'condition-met' : this.exited ? 'exited' : 'timeout'));
2068
+ }
2069
+ recordReadiness(matched, reason) {
2070
+ this.readyFlag = matched;
2071
+ this.readyReasonValue = matched ? 'condition-met' : 'never-held';
2072
+ if (matched)
2073
+ this.logger.info('session ready', { id: this.id, reason });
2074
+ else
2075
+ this.logger.warn('session readiness condition never held', { id: this.id, reason });
2076
+ for (const listener of this.readyListeners)
2077
+ listener();
2078
+ }
1171
2079
  summary() {
1172
2080
  return {
1173
2081
  id: this.id,
1174
2082
  label: this.label,
2083
+ role: this.role,
1175
2084
  purpose: this.purpose,
1176
2085
  startedBy: this.startedBy,
1177
- agent: this.agent ?? null,
2086
+ ...(this.parent === undefined ? {} : { parent: this.parent }),
2087
+ agent: this.agent,
1178
2088
  command: this.command,
1179
2089
  args: this.args,
1180
2090
  cols: this.cols,
1181
2091
  rows: this.rows,
1182
2092
  ready: this.readyFlag,
2093
+ ...(this.stallState === undefined ? {} : { stalled: this.stallState }),
1183
2094
  readyReason: this.readyReasonValue,
1184
2095
  geometryHeld: this.geometryHeldFlag,
1185
2096
  exited: this.exitedFlag,
1186
2097
  exitCode: this.exitCode,
2098
+ ...(this.rendererFault === null ? {} : { fault: this.rendererFault }),
1187
2099
  watchers: this.watchers,
1188
2100
  createdAt: this.createdAt.toISOString(),
1189
2101
  };
@@ -1234,6 +2146,8 @@ export class Session {
1234
2146
  return this.killPromise !== null;
1235
2147
  }
1236
2148
  async killOnce() {
2149
+ this.clearStallTimer();
2150
+ this.publishStall(undefined);
1237
2151
  // node-pty creates a Windows terminal's program only once its output
1238
2152
  // worker has connected, a few tens of milliseconds after the spawn
1239
2153
  // returns, and reports pid 0 until then; a start whose connection fails
@@ -1281,7 +2195,7 @@ export class Session {
1281
2195
  });
1282
2196
  }
1283
2197
  this.queueConsoleHost();
1284
- this.renderer.dispose();
2198
+ await this.renderer.dispose();
1285
2199
  }
1286
2200
  /**
1287
2201
  * Queue an end of this session's console host, once. The list runs later