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