loopzero-sdk-pty 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,363 @@
1
+ 'use strict';
2
+
3
+ var fs = require('fs');
4
+ var sandbox = require('loopzero-sdk/sandbox');
5
+ var crypto = require('crypto');
6
+ var module$1 = require('module');
7
+ var interactive = require('loopzero-sdk/interactive');
8
+
9
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
10
+ // src/confined-pty-backend.ts
11
+ var nodeRequire = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
12
+ var YIELD_MIN_MS = 250;
13
+ var YIELD_MAX_MS = 3e4;
14
+ var DEFAULT_YIELD_MS = 500;
15
+ var DEFAULT_TTL_MS = 3e5;
16
+ var DEFAULT_MAX_BYTES = 1e5;
17
+ function clampYield(ms) {
18
+ const v = ms ?? DEFAULT_YIELD_MS;
19
+ return Math.max(YIELD_MIN_MS, Math.min(YIELD_MAX_MS, v));
20
+ }
21
+ function capTail(buf, max) {
22
+ return buf.length > max ? `\u2026(truncated)
23
+ ${buf.slice(-max)}` : buf;
24
+ }
25
+ var MaxSessionsError = class extends interactive.InteractiveUnavailableError {
26
+ constructor(max, liveSessionIds) {
27
+ super(
28
+ `interactive session limit reached (${String(max)} live). Reuse one of the open sessions instead of starting another: ${liveSessionIds.join(", ")}`
29
+ );
30
+ this.max = max;
31
+ this.liveSessionIds = liveSessionIds;
32
+ }
33
+ max;
34
+ liveSessionIds;
35
+ };
36
+ var PtyInteractiveBackend = class extends interactive.InteractiveBackend {
37
+ sessions = /* @__PURE__ */ new Map();
38
+ wrapCommand;
39
+ /** M77 — live-session ceiling; `undefined` means unlimited (the historical behaviour). */
40
+ maxSessions;
41
+ constructor(options = {}) {
42
+ super();
43
+ this.wrapCommand = options.wrapCommand;
44
+ this.maxSessions = options.maxSessions;
45
+ }
46
+ ptyModule;
47
+ exitReaperArmed = false;
48
+ /** Lazy, cached node-pty load — a failed native build must degrade, not crash at import time. */
49
+ loadPty() {
50
+ if (this.ptyModule !== void 0) return this.ptyModule;
51
+ try {
52
+ this.ptyModule = nodeRequire("node-pty");
53
+ } catch {
54
+ this.ptyModule = null;
55
+ }
56
+ return this.ptyModule;
57
+ }
58
+ /**
59
+ * Whether `node-pty` loaded — i.e. whether `startInteractive` can work at all here.
60
+ *
61
+ * Extra to the `InteractiveBackend` contract; a caller writing against the base class must catch
62
+ * {@link InteractiveUnavailableError} instead. `require`s the native module on the first call and
63
+ * CACHES the answer for the life of this instance, so it is cheap to poll and will not notice a
64
+ * module installed afterwards.
65
+ *
66
+ * `true` does not promise a session: the spawn can still fail, and a missing `cwd` is rejected —
67
+ * both surface as {@link InteractiveUnavailableError} from `startInteractive`.
68
+ */
69
+ available() {
70
+ return this.loadPty() !== null;
71
+ }
72
+ /** Reap orphaned PTYs when the host process exits. ONLY the `exit` event — installing SIGINT/SIGTERM
73
+ * handlers would remove Node's default terminate-on-signal behavior. Armed once, lazily. */
74
+ armExitReaper() {
75
+ if (this.exitReaperArmed) return;
76
+ this.exitReaperArmed = true;
77
+ process.on("exit", () => this.killAll());
78
+ }
79
+ async collect(session, yieldMs, maxBytes) {
80
+ await new Promise((r) => setTimeout(r, clampYield(yieldMs)));
81
+ const out = session.pending;
82
+ session.pending = "";
83
+ return capTail(out, maxBytes);
84
+ }
85
+ armTtl(session, ttlMs) {
86
+ clearTimeout(session.ttlTimer);
87
+ session.ttlTimer = setTimeout(() => this.kill(session.id), ttlMs);
88
+ }
89
+ /** Allocate a PTY for `command` or throw a typed {@link InteractiveUnavailableError}. Validates the
90
+ * cwd at the boundary (node-pty does NOT throw on a non-existent cwd — it spawns a broken session). */
91
+ spawnPty(command, opts) {
92
+ const pty = this.loadPty();
93
+ if (pty === null) {
94
+ throw new interactive.InteractiveUnavailableError(
95
+ "interactive shell unavailable: node-pty native module failed to load; use non-interactive exec"
96
+ );
97
+ }
98
+ const cwd = opts?.cwd ?? process.cwd();
99
+ if (!fs.existsSync(cwd)) {
100
+ throw new interactive.InteractiveUnavailableError(
101
+ `interactive shell unavailable: cwd does not exist: ${cwd}`
102
+ );
103
+ }
104
+ const effective = this.wrapCommand?.(command, cwd) ?? command;
105
+ const shell = process.env.SHELL ?? "/bin/bash";
106
+ try {
107
+ return pty.spawn(shell, ["-c", effective], {
108
+ name: "xterm-color",
109
+ cols: opts?.cols ?? 80,
110
+ rows: opts?.rows ?? 24,
111
+ cwd,
112
+ env: process.env
113
+ });
114
+ } catch (err) {
115
+ throw new interactive.InteractiveUnavailableError(
116
+ `interactive shell unavailable: failed to spawn a PTY (${err instanceof Error ? err.message : String(err)})`
117
+ );
118
+ }
119
+ }
120
+ /**
121
+ * Spawn `command` on a real pty and return its id plus whatever it printed during the yield
122
+ * window.
123
+ *
124
+ * ```ts
125
+ * const { sessionId, output } = await backend.startInteractive("python3 -i");
126
+ * await backend.writeStdin(sessionId, "print(1+1)\n");
127
+ * backend.kill(sessionId);
128
+ * ```
129
+ *
130
+ * The command runs as `$SHELL -c <command>`, falling back to `/bin/bash` when `SHELL` is unset —
131
+ * so shell syntax works, and so does the user's rc-file behaviour. The child inherits
132
+ * `process.env` WHOLE; there is no allowlist, so every secret in the parent's environment is
133
+ * visible to it.
134
+ *
135
+ * Defaults applied here: `yieldMs` 500 (clamped into [{@link YIELD_MIN_MS},
136
+ * {@link YIELD_MAX_MS}]), `ttlMs` 300000 (5 min idle, then reaped), `maxBytes` 100000, `cols` 80,
137
+ * `rows` 24, `cwd` `process.cwd()`.
138
+ *
139
+ * IT ALWAYS RESOLVES AFTER THE YIELD WINDOW, never when the program is ready. `output` is
140
+ * whatever arrived by then, TAIL-capped to `maxBytes` with a `…(truncated)` marker — so a slow
141
+ * starter returns an empty string that reads exactly like "the program said nothing". Poll with
142
+ * `writeStdin(id, "")` rather than raising `yieldMs`.
143
+ *
144
+ * Throws {@link InteractiveUnavailableError} when `node-pty` is absent, when `cwd` does not exist
145
+ * (checked here because node-pty spawns a broken session instead of failing), or when the spawn
146
+ * itself fails. Throws {@link MaxSessionsError} — a SUBCLASS of it, so a `catch` on the parent
147
+ * swallows the distinction — when `maxSessions` is set and reached.
148
+ *
149
+ * The session outlives this call and must be reclaimed: `kill()` it, or let the idle TTL do it.
150
+ */
151
+ async startInteractive(command, opts) {
152
+ this.armExitReaper();
153
+ if (this.maxSessions !== void 0 && this.sessions.size >= this.maxSessions) {
154
+ throw new MaxSessionsError(this.maxSessions, [...this.sessions.keys()]);
155
+ }
156
+ const ttlMs = opts?.ttlMs ?? DEFAULT_TTL_MS;
157
+ const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES;
158
+ const proc = this.spawnPty(command, opts);
159
+ const id = `pty-${crypto.randomUUID()}`;
160
+ const session = {
161
+ id,
162
+ pty: proc,
163
+ pending: "",
164
+ alive: true,
165
+ ttlTimer: setTimeout(() => this.kill(id), ttlMs),
166
+ writeChain: Promise.resolve()
167
+ };
168
+ proc.onData((data) => {
169
+ session.pending = capTail(session.pending + data, maxBytes);
170
+ });
171
+ proc.onExit(() => {
172
+ session.alive = false;
173
+ clearTimeout(session.ttlTimer);
174
+ this.sessions.delete(id);
175
+ });
176
+ this.sessions.set(id, session);
177
+ const output = await this.collect(session, opts?.yieldMs ?? DEFAULT_YIELD_MS, maxBytes);
178
+ return { sessionId: id, output };
179
+ }
180
+ /**
181
+ * Write `chars` to a live session's stdin and return the output produced during the yield window,
182
+ * plus whether the process is still alive.
183
+ *
184
+ * YOU SUPPLY THE NEWLINE. `"print(1+1)"` leaves a REPL waiting; `"print(1+1)\n"` runs it. An
185
+ * EMPTY `chars` writes nothing and just waits — the supported way to poll a program that is still
186
+ * producing output.
187
+ *
188
+ * Every call resets the idle TTL, so a polled session never gets reaped mid-work. Defaults match
189
+ * `startInteractive`: `yieldMs` 500 (clamped), `ttlMs` 300000, `maxBytes` 100000 tail-capped.
190
+ *
191
+ * Concurrent calls on the same session are SERIALIZED, each reading only its own output window —
192
+ * two writes in flight cannot steal each other's output. They are not, however, interleaved with
193
+ * anything the program prints unprompted, which is drained by whichever call is waiting.
194
+ *
195
+ * Throws {@link NoSuchSessionError} when the id is unknown, already killed, or was reaped for
196
+ * idleness. That is a different fact from a failing command: the correct response is to start a
197
+ * new session, not to report an error from the program.
198
+ */
199
+ async writeStdin(sessionId, chars, opts) {
200
+ const session = this.sessions.get(sessionId);
201
+ if (session === void 0 || !session.alive) throw new interactive.NoSuchSessionError(sessionId);
202
+ const run = session.writeChain.then(async () => {
203
+ if (!session.alive) throw new interactive.NoSuchSessionError(sessionId);
204
+ this.armTtl(session, opts?.ttlMs ?? DEFAULT_TTL_MS);
205
+ if (chars.length > 0) session.pty.write(chars);
206
+ const output = await this.collect(
207
+ session,
208
+ opts?.yieldMs ?? DEFAULT_YIELD_MS,
209
+ opts?.maxBytes ?? DEFAULT_MAX_BYTES
210
+ );
211
+ return { output, alive: session.alive };
212
+ });
213
+ session.writeChain = run.catch(() => void 0);
214
+ return run;
215
+ }
216
+ /**
217
+ * End a session and free its `maxSessions` slot. Idempotent — an unknown or already-killed id is a
218
+ * silent no-op, never a throw.
219
+ *
220
+ * SIGKILLs the whole process GROUP, so a detached grandchild dies with it; there is no graceful
221
+ * shutdown and no chance for the program to flush or save. Falls back to killing just the pty
222
+ * process if the group kill fails. Any output buffered but not yet collected is discarded.
223
+ */
224
+ kill(sessionId) {
225
+ const session = this.sessions.get(sessionId);
226
+ if (session === void 0) return;
227
+ clearTimeout(session.ttlTimer);
228
+ session.alive = false;
229
+ this.sessions.delete(sessionId);
230
+ try {
231
+ process.kill(-session.pty.pid, "SIGKILL");
232
+ } catch {
233
+ try {
234
+ session.pty.kill();
235
+ } catch {
236
+ }
237
+ }
238
+ }
239
+ /**
240
+ * `kill()` every live session of THIS backend instance. Extra to the `InteractiveBackend`
241
+ * contract.
242
+ *
243
+ * Also runs automatically on the host process's `exit` event, armed lazily on the first
244
+ * `startInteractive`. Only `exit` — installing SIGINT/SIGTERM handlers would suppress Node's
245
+ * default terminate-on-signal, so a `kill -9` of the host still orphans the ptys.
246
+ */
247
+ killAll() {
248
+ for (const id of [...this.sessions.keys()]) this.kill(id);
249
+ }
250
+ /**
251
+ * How many sessions this instance currently holds — the number `maxSessions` is compared against.
252
+ * Extra to the `InteractiveBackend` contract.
253
+ *
254
+ * Drops on its own when a process exits or a TTL fires, so it is a live gauge rather than a
255
+ * counter, and it never counts sessions belonging to another backend instance.
256
+ */
257
+ activeSessionCount() {
258
+ return this.sessions.size;
259
+ }
260
+ };
261
+
262
+ // src/confined-pty-backend.ts
263
+ var DEFAULT_ENV_ALLOWLIST = [
264
+ "PATH",
265
+ "USER",
266
+ "LOGNAME",
267
+ "LANG",
268
+ "LC_ALL",
269
+ "LC_CTYPE",
270
+ "TERM",
271
+ "TZ"
272
+ ];
273
+ var DEFAULT_MAX_SESSIONS = 4;
274
+ var DEFAULT_PROBE_TIMEOUT_MS = 3e3;
275
+ var PROBE_SETTLE_MS = 300;
276
+ var PROBE_POLL_MS = 50;
277
+ function shQuote(value) {
278
+ return `'${value.replace(/'/g, `'\\''`)}'`;
279
+ }
280
+ function scrubbedCommand(command, options) {
281
+ const source = options.sourceEnv ?? process.env;
282
+ const kept = [];
283
+ for (const name of options.envAllowlist ?? DEFAULT_ENV_ALLOWLIST) {
284
+ const value = source[name];
285
+ if (value !== void 0 && name !== "HOME") kept.push(`${name}=${shQuote(value)}`);
286
+ }
287
+ kept.push(`HOME=${shQuote(options.root)}`);
288
+ return `/usr/bin/env -i ${kept.join(" ")} /bin/sh -c ${shQuote(command)}`;
289
+ }
290
+ var ConfinedPtyBackend = class {
291
+ constructor(inner, options) {
292
+ this.inner = inner;
293
+ this.options = options;
294
+ }
295
+ inner;
296
+ options;
297
+ startInteractive(command, opts) {
298
+ return this.inner.startInteractive(scrubbedCommand(command, this.options), {
299
+ ...opts,
300
+ cwd: this.options.root
301
+ });
302
+ }
303
+ writeStdin(sessionId, chars, opts) {
304
+ return this.inner.writeStdin(sessionId, chars, opts);
305
+ }
306
+ kill(sessionId) {
307
+ this.inner.kill(sessionId);
308
+ }
309
+ };
310
+ function createConfinedPtyBackend(options) {
311
+ const config = {
312
+ wrapCommand: sandbox.interactiveWrapCommand({ mode: options.mode }),
313
+ maxSessions: options.maxSessions ?? DEFAULT_MAX_SESSIONS
314
+ };
315
+ const inner = options.createInner ? options.createInner(config) : new PtyInteractiveBackend(config);
316
+ return new ConfinedPtyBackend(inner, options);
317
+ }
318
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
319
+ async function waitForFile(path, timeoutMs) {
320
+ const deadline = Date.now() + timeoutMs;
321
+ while (!fs.existsSync(path)) {
322
+ if (Date.now() >= deadline) return false;
323
+ await sleep(PROBE_POLL_MS);
324
+ }
325
+ return true;
326
+ }
327
+ async function probeConfinement(backend, paths, options) {
328
+ const command = `touch ${shQuote(paths.inside)}; touch ${shQuote(paths.outside)}`;
329
+ let sessionId;
330
+ try {
331
+ sessionId = (await backend.startInteractive(command)).sessionId;
332
+ const wrote = await waitForFile(paths.inside, options?.timeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS);
333
+ await sleep(PROBE_SETTLE_MS);
334
+ if (fs.existsSync(paths.outside)) return { confined: false, reason: "wrote_outside" };
335
+ return wrote ? { confined: true } : { confined: false, reason: "cannot_write_inside" };
336
+ } catch (error) {
337
+ return {
338
+ confined: false,
339
+ reason: "start_failed",
340
+ detail: error instanceof Error ? error.message : String(error)
341
+ };
342
+ } finally {
343
+ if (sessionId !== void 0) killQuietly(backend, sessionId);
344
+ fs.rmSync(paths.inside, { force: true });
345
+ fs.rmSync(paths.outside, { force: true });
346
+ }
347
+ }
348
+ function killQuietly(backend, sessionId) {
349
+ try {
350
+ backend.kill(sessionId);
351
+ } catch {
352
+ }
353
+ }
354
+
355
+ exports.MaxSessionsError = MaxSessionsError;
356
+ exports.PtyInteractiveBackend = PtyInteractiveBackend;
357
+ exports.YIELD_MAX_MS = YIELD_MAX_MS;
358
+ exports.YIELD_MIN_MS = YIELD_MIN_MS;
359
+ exports.clampYield = clampYield;
360
+ exports.createConfinedPtyBackend = createConfinedPtyBackend;
361
+ exports.probeConfinement = probeConfinement;
362
+ //# sourceMappingURL=index.cjs.map
363
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/pty-interactive-backend.ts","../src/confined-pty-backend.ts"],"names":["createRequire","InteractiveUnavailableError","InteractiveBackend","existsSync","randomUUID","NoSuchSessionError","interactiveWrapCommand","rmSync"],"mappings":";;;;;;;;;;AAiCA,IAAM,WAAA,GAAcA,sBAAA,CAAc,2PAAe,CAAA;AAW1C,IAAM,YAAA,GAAe;AASrB,IAAM,YAAA,GAAe;AAC5B,IAAM,gBAAA,GAAmB,GAAA;AACzB,IAAM,cAAA,GAAiB,GAAA;AACvB,IAAM,iBAAA,GAAoB,GAAA;AAwBnB,SAAS,WAAW,EAAA,EAAgC;AACzD,EAAA,MAAM,IAAI,EAAA,IAAM,gBAAA;AAChB,EAAA,OAAO,KAAK,GAAA,CAAI,YAAA,EAAc,KAAK,GAAA,CAAI,YAAA,EAAc,CAAC,CAAC,CAAA;AACzD;AAGA,SAAS,OAAA,CAAQ,KAAa,GAAA,EAAqB;AACjD,EAAA,OAAO,GAAA,CAAI,SAAS,GAAA,GAAM,CAAA;AAAA,EAAiB,GAAA,CAAI,KAAA,CAAM,CAAC,GAAG,CAAC,CAAA,CAAA,GAAK,GAAA;AACjE;AA4CO,IAAM,gBAAA,GAAN,cAA+BC,uCAAA,CAA4B;AAAA,EAChE,WAAA,CACW,KACA,cAAA,EACT;AACA,IAAA,KAAA;AAAA,MACE,CAAA,mCAAA,EAAsC,OAAO,GAAG,CAAC,uEACgB,cAAA,CAAe,IAAA,CAAK,IAAI,CAAC,CAAA;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Q,qBAAA,EAAsB;AAAA,EACvF,SAAS,KAAA,EAAO;AACd,IAAA,OAAO;AAAA,MACL,QAAA,EAAU,KAAA;AAAA,MACV,MAAA,EAAQ,cAAA;AAAA,MACR,QAAQ,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU,OAAO,KAAK;AAAA,KAC/D;AAAA,EACF,CAAA,SAAE;AACA,IAAA,IAAI,SAAA,KAAc,MAAA,EAAW,WAAA,CAAY,OAAA,EAAS,SAAS,CAAA;AAC3D,IAAAI,SAAA,CAAO,KAAA,CAAM,MAAA,EAAQ,EAAE,KAAA,EAAO,MAAM,CAAA;AACpC,IAAAA,SAAA,CAAO,KAAA,CAAM,OAAA,EAAS,EAAE,KAAA,EAAO,MAAM,CAAA;AAAA,EACvC;AACF;AAEA,SAAS,WAAA,CAAY,SAA6B,SAAA,EAAyB;AACzE,EAAA,IAAI;AACF,IAAA,OAAA,CAAQ,KAAK,SAAS,CAAA;AAAA,EACxB,CAAA,CAAA,MAAQ;AAAA,EAER;AACF","file":"index.cjs","sourcesContent":["/**\n * `PtyInteractiveBackend` — the LOCAL implementation of `loopzero-sdk`'s\n * `InteractiveBackend`, backed by `node-pty`. This is the terminal-surface\n * backend: it allocates a real pseudo-terminal so REPLs, `git rebase -i`, and\n * prompting commands can be driven to completion. Ported from the AgentBuilder\n * Codex clone (M11) into the ecosystem (M14) so any terminal agent injects it.\n *\n * `node-pty` is an OPTIONAL dependency of this package — the ONLY place in the\n * loopzero ecosystem that touches it. Core / sdk-tools / cluster / desktop never\n * do. When the native module is unavailable (or a spawn fails), `startInteractive`\n * throws the SDK's typed {@link InteractiveUnavailableError} so the caller falls\n * back to non-interactive exec; `available()` reports `false` up front, and\n * `writeStdin` / `kill` are unreachable because no session was ever created.\n *\n * Safety (mirrors M11): graceful typed degradation; per-session write\n * serialization (concurrent writes never steal each other's output); idle TTL\n * reaper; process-GROUP kill so detached grandchildren die; a process-exit\n * reaper; tail-capped output (the live prompt, not the stale banner).\n */\nimport { randomUUID } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\n\nimport {\n InteractiveBackend,\n InteractiveUnavailableError,\n NoSuchSessionError,\n type StartInteractiveOptions,\n type StartInteractiveResult,\n type WriteStdinOptions,\n type WriteStdinResult,\n} from \"loopzero-sdk/interactive\";\n\nconst nodeRequire = createRequire(import.meta.url);\n\n/**\n * Floor for `StartInteractiveOptions.yieldMs` — how long a call waits for the process to produce\n * output before returning what it has.\n *\n * A shorter wait does not make the call faster, it makes it return an empty or truncated buffer that\n * the model then reasons about as if the program had said nothing. Anything below this is clamped\n * up, silently and on purpose: the alternative is an agent concluding a command produced no output\n * when it simply had not flushed yet.\n */\nexport const YIELD_MIN_MS = 250;\n\n/**\n * Ceiling for `StartInteractiveOptions.yieldMs`, clamped down.\n *\n * A pty session is interactive; a caller asking to block for longer than this wants a batch command,\n * which `shell` already does without holding a session open. The cap is what keeps a mistyped\n * `yieldMs` from parking an agent turn indefinitely.\n */\nexport const YIELD_MAX_MS = 30_000;\nconst DEFAULT_YIELD_MS = 500;\nconst DEFAULT_TTL_MS = 300_000; // 5 min idle → reap\nconst DEFAULT_MAX_BYTES = 100_000;\n\n/** The minimal `node-pty` surface driven here (kept structural so the import stays lazy). */\ninterface PtyProcess {\n readonly pid: number;\n write(data: string): void;\n kill(signal?: string): void;\n onData(cb: (data: string) => void): void;\n onExit(cb: (e: { exitCode: number }) => void): void;\n}\ninterface PtyModule {\n spawn(file: string, args: string[], opts: Record<string, unknown>): PtyProcess;\n}\n\ninterface PtySession {\n id: string;\n pty: PtyProcess;\n pending: string;\n alive: boolean;\n ttlTimer: ReturnType<typeof setTimeout>;\n writeChain: Promise<unknown>;\n}\n\n/** Bound the yield window to [{@link YIELD_MIN_MS}, {@link YIELD_MAX_MS}]. */\nexport function clampYield(ms: number | undefined): number {\n const v = ms ?? DEFAULT_YIELD_MS;\n return Math.max(YIELD_MIN_MS, Math.min(YIELD_MAX_MS, v));\n}\n\n/** Keep the TAIL of output — the newest bytes carry the live prompt. */\nfunction capTail(buf: string, max: number): string {\n return buf.length > max ? `…(truncated)\\n${buf.slice(-max)}` : buf;\n}\n\n/**\n * Constructor options for {@link PtyInteractiveBackend}. Both are optional; `new\n * PtyInteractiveBackend()` gives unconfined commands and an unlimited number of sessions.\n *\n * @public\n */\nexport interface PtyInteractiveBackendOptions {\n /**\n * Transforms the command immediately before the spawn. It receives the ALREADY-RESOLVED `cwd` — the PTY spawns\n * in it, so a wrap targeting another directory would produce confinement that confines nothing.\n *\n * Returning `null` means **do not wrap** — an explicit decision, distinct from \"I wrapped and it made no\n * difference\". It is the case of the unconfined mode.\n */\n readonly wrapCommand?: (command: string, cwd: string) => string | null;\n\n /**\n * M77 — ceiling on simultaneously LIVE sessions. Absent => no ceiling (the long-standing behavior).\n *\n * Each session is a real process with a 5-minute TTL. A model that does not notice it already has a\n * shell open opens another, and the TTL only collects later — too late when the limit is the machine's\n * PID count. On overflow, {@link MaxSessionsError} lists the live sessions, because the correct\n * action is to **reuse** one of them, and an error that does not say so only teaches the model to retry.\n */\n readonly maxSessions?: number;\n}\n\n/**\n * M77 — the {@link PtyInteractiveBackendOptions.maxSessions} ceiling was reached.\n *\n * Carries `liveSessionIds` by design: `rules/error-handling.md § 2` asks for a message with enough\n * context to act, and here the action is reusing an existing session. An error merely stating\n * \"limit reached\" would leave the model with no way out — it would retry, and fail again.\n *\n * It EXTENDS {@link InteractiveUnavailableError} and inherits its\n * `code === \"interactive_unavailable\"`, so a caller catching the parent — or branching on `code` —\n * cannot tell \"no pty on this machine\" from \"you already have N open\". Use `instanceof\n * MaxSessionsError` when the two need different handling; only this one is retryable after a\n * `kill()`.\n *\n * @public\n */\nexport class MaxSessionsError extends InteractiveUnavailableError {\n constructor(\n readonly max: number,\n readonly liveSessionIds: readonly string[],\n ) {\n super(\n `interactive session limit reached (${String(max)} live). ` +\n `Reuse one of the open sessions instead of starting another: ${liveSessionIds.join(\", \")}`,\n );\n }\n}\n\n/**\n * `InteractiveBackend` backed by a real pty, for programs that only behave correctly on a terminal.\n *\n * Use it when the target REQUIRES a tty — a REPL that prints a prompt, an installer that asks a\n * question, `ssh` asking for a passphrase, anything that checks `isatty` and changes behaviour. For\n * a command that reads stdin and exits, the plain `shell` tool is simpler and does not leave a\n * session to reap.\n *\n * `node-pty` is an OPTIONAL dependency (`optionalDependencies`, not a peer), imported lazily on\n * first use: an install that cannot build the native module still succeeds, and a caller that never\n * starts a session never needs one. When it is absent,\n * starting a session raises `InteractiveUnavailableError` rather than failing at import time — so an\n * agent that merely has the backend registered still runs.\n *\n * Sessions are stateful and idle-reaped (5 minutes by default). A session id that has been reaped\n * raises `NoSuchSessionError`, which is a different fact from \"the command failed\" and should be\n * handled as \"start again\", not as an error from the program.\n */\nexport class PtyInteractiveBackend extends InteractiveBackend {\n private readonly sessions = new Map<string, PtySession>();\n private readonly wrapCommand: ((command: string, cwd: string) => string | null) | undefined;\n /** M77 — live-session ceiling; `undefined` means unlimited (the historical behaviour). */\n private readonly maxSessions: number | undefined;\n\n constructor(options: PtyInteractiveBackendOptions = {}) {\n super();\n this.wrapCommand = options.wrapCommand;\n this.maxSessions = options.maxSessions;\n }\n\n private ptyModule: PtyModule | null | undefined;\n private exitReaperArmed = false;\n\n /** Lazy, cached node-pty load — a failed native build must degrade, not crash at import time. */\n private loadPty(): PtyModule | null {\n if (this.ptyModule !== undefined) return this.ptyModule;\n try {\n this.ptyModule = nodeRequire(\"node-pty\") as PtyModule;\n } catch {\n this.ptyModule = null;\n }\n return this.ptyModule;\n }\n\n /**\n * Whether `node-pty` loaded — i.e. whether `startInteractive` can work at all here.\n *\n * Extra to the `InteractiveBackend` contract; a caller writing against the base class must catch\n * {@link InteractiveUnavailableError} instead. `require`s the native module on the first call and\n * CACHES the answer for the life of this instance, so it is cheap to poll and will not notice a\n * module installed afterwards.\n *\n * `true` does not promise a session: the spawn can still fail, and a missing `cwd` is rejected —\n * both surface as {@link InteractiveUnavailableError} from `startInteractive`.\n */\n available(): boolean {\n return this.loadPty() !== null;\n }\n\n /** Reap orphaned PTYs when the host process exits. ONLY the `exit` event — installing SIGINT/SIGTERM\n * handlers would remove Node's default terminate-on-signal behavior. Armed once, lazily. */\n private armExitReaper(): void {\n if (this.exitReaperArmed) return;\n this.exitReaperArmed = true;\n process.on(\"exit\", () => this.killAll());\n }\n\n private async collect(session: PtySession, yieldMs: number, maxBytes: number): Promise<string> {\n await new Promise((r) => setTimeout(r, clampYield(yieldMs)));\n const out = session.pending;\n session.pending = \"\";\n return capTail(out, maxBytes);\n }\n\n private armTtl(session: PtySession, ttlMs: number): void {\n clearTimeout(session.ttlTimer);\n session.ttlTimer = setTimeout(() => this.kill(session.id), ttlMs);\n }\n\n /** Allocate a PTY for `command` or throw a typed {@link InteractiveUnavailableError}. Validates the\n * cwd at the boundary (node-pty does NOT throw on a non-existent cwd — it spawns a broken session). */\n private spawnPty(command: string, opts?: StartInteractiveOptions): PtyProcess {\n const pty = this.loadPty();\n if (pty === null) {\n throw new InteractiveUnavailableError(\n \"interactive shell unavailable: node-pty native module failed to load; use non-interactive exec\",\n );\n }\n const cwd = opts?.cwd ?? process.cwd();\n if (!existsSync(cwd)) {\n throw new InteractiveUnavailableError(\n `interactive shell unavailable: cwd does not exist: ${cwd}`,\n );\n }\n // M75 T3.1 — the wrap goes HERE: after the cwd is resolved and validated, before the spawn. It is the\n // single point every command passes through, so no path escapes the confinement.\n const effective = this.wrapCommand?.(command, cwd) ?? command;\n\n const shell = process.env.SHELL ?? \"/bin/bash\";\n try {\n return pty.spawn(shell, [\"-c\", effective], {\n name: \"xterm-color\",\n cols: opts?.cols ?? 80,\n rows: opts?.rows ?? 24,\n cwd,\n env: process.env,\n });\n } catch (err) {\n throw new InteractiveUnavailableError(\n `interactive shell unavailable: failed to spawn a PTY (${err instanceof Error ? err.message : String(err)})`,\n );\n }\n }\n\n /**\n * Spawn `command` on a real pty and return its id plus whatever it printed during the yield\n * window.\n *\n * ```ts\n * const { sessionId, output } = await backend.startInteractive(\"python3 -i\");\n * await backend.writeStdin(sessionId, \"print(1+1)\\n\");\n * backend.kill(sessionId);\n * ```\n *\n * The command runs as `$SHELL -c <command>`, falling back to `/bin/bash` when `SHELL` is unset —\n * so shell syntax works, and so does the user's rc-file behaviour. The child inherits\n * `process.env` WHOLE; there is no allowlist, so every secret in the parent's environment is\n * visible to it.\n *\n * Defaults applied here: `yieldMs` 500 (clamped into [{@link YIELD_MIN_MS},\n * {@link YIELD_MAX_MS}]), `ttlMs` 300000 (5 min idle, then reaped), `maxBytes` 100000, `cols` 80,\n * `rows` 24, `cwd` `process.cwd()`.\n *\n * IT ALWAYS RESOLVES AFTER THE YIELD WINDOW, never when the program is ready. `output` is\n * whatever arrived by then, TAIL-capped to `maxBytes` with a `…(truncated)` marker — so a slow\n * starter returns an empty string that reads exactly like \"the program said nothing\". Poll with\n * `writeStdin(id, \"\")` rather than raising `yieldMs`.\n *\n * Throws {@link InteractiveUnavailableError} when `node-pty` is absent, when `cwd` does not exist\n * (checked here because node-pty spawns a broken session instead of failing), or when the spawn\n * itself fails. Throws {@link MaxSessionsError} — a SUBCLASS of it, so a `catch` on the parent\n * swallows the distinction — when `maxSessions` is set and reached.\n *\n * The session outlives this call and must be reclaimed: `kill()` it, or let the idle TTL do it.\n */\n async startInteractive(\n command: string,\n opts?: StartInteractiveOptions,\n ): Promise<StartInteractiveResult> {\n this.armExitReaper();\n // M77 — the ceiling, checked against LIVE sessions (`onExit` and `kill` both delete from the\n // Map), so killing one frees a slot.\n //\n // ATOMICITY, and why it is not an accident to preserve carelessly: everything from here down to\n // `this.sessions.set(id, session)` is SYNCHRONOUS — `spawnPty` does not await. Two concurrent\n // `startInteractive` calls therefore cannot interleave between this check and the insert, so the\n // ceiling holds without a lock. If a future refactor makes any step in that span asynchronous\n // (an `await this.loadPty()` would be the plausible one), both callers would observe the old\n // count and both would pass. `tests/max-sessions.test.ts` covers exactly that regression.\n if (this.maxSessions !== undefined && this.sessions.size >= this.maxSessions) {\n throw new MaxSessionsError(this.maxSessions, [...this.sessions.keys()]);\n }\n const ttlMs = opts?.ttlMs ?? DEFAULT_TTL_MS;\n const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES;\n const proc = this.spawnPty(command, opts);\n const id = `pty-${randomUUID()}`;\n const session: PtySession = {\n id,\n pty: proc,\n pending: \"\",\n alive: true,\n ttlTimer: setTimeout(() => this.kill(id), ttlMs),\n writeChain: Promise.resolve(),\n };\n proc.onData((data) => {\n session.pending = capTail(session.pending + data, maxBytes);\n });\n proc.onExit(() => {\n session.alive = false;\n clearTimeout(session.ttlTimer);\n this.sessions.delete(id);\n });\n this.sessions.set(id, session);\n const output = await this.collect(session, opts?.yieldMs ?? DEFAULT_YIELD_MS, maxBytes);\n return { sessionId: id, output };\n }\n\n /**\n * Write `chars` to a live session's stdin and return the output produced during the yield window,\n * plus whether the process is still alive.\n *\n * YOU SUPPLY THE NEWLINE. `\"print(1+1)\"` leaves a REPL waiting; `\"print(1+1)\\n\"` runs it. An\n * EMPTY `chars` writes nothing and just waits — the supported way to poll a program that is still\n * producing output.\n *\n * Every call resets the idle TTL, so a polled session never gets reaped mid-work. Defaults match\n * `startInteractive`: `yieldMs` 500 (clamped), `ttlMs` 300000, `maxBytes` 100000 tail-capped.\n *\n * Concurrent calls on the same session are SERIALIZED, each reading only its own output window —\n * two writes in flight cannot steal each other's output. They are not, however, interleaved with\n * anything the program prints unprompted, which is drained by whichever call is waiting.\n *\n * Throws {@link NoSuchSessionError} when the id is unknown, already killed, or was reaped for\n * idleness. That is a different fact from a failing command: the correct response is to start a\n * new session, not to report an error from the program.\n */\n async writeStdin(\n sessionId: string,\n chars: string,\n opts?: WriteStdinOptions,\n ): Promise<WriteStdinResult> {\n const session = this.sessions.get(sessionId);\n if (session === undefined || !session.alive) throw new NoSuchSessionError(sessionId);\n // Serialize per session: chain onto the previous write so two concurrent calls run strictly in\n // order and each reads only its own output window (no stolen output).\n const run = session.writeChain.then(async () => {\n if (!session.alive) throw new NoSuchSessionError(sessionId);\n this.armTtl(session, opts?.ttlMs ?? DEFAULT_TTL_MS);\n if (chars.length > 0) session.pty.write(chars);\n const output = await this.collect(\n session,\n opts?.yieldMs ?? DEFAULT_YIELD_MS,\n opts?.maxBytes ?? DEFAULT_MAX_BYTES,\n );\n return { output, alive: session.alive };\n });\n session.writeChain = run.catch(() => undefined);\n return run;\n }\n\n /**\n * End a session and free its `maxSessions` slot. Idempotent — an unknown or already-killed id is a\n * silent no-op, never a throw.\n *\n * SIGKILLs the whole process GROUP, so a detached grandchild dies with it; there is no graceful\n * shutdown and no chance for the program to flush or save. Falls back to killing just the pty\n * process if the group kill fails. Any output buffered but not yet collected is discarded.\n */\n kill(sessionId: string): void {\n const session = this.sessions.get(sessionId);\n if (session === undefined) return;\n clearTimeout(session.ttlTimer);\n session.alive = false;\n this.sessions.delete(sessionId);\n try {\n process.kill(-session.pty.pid, \"SIGKILL\");\n } catch {\n try {\n session.pty.kill();\n } catch {\n // already dead — nothing to do\n }\n }\n }\n\n /**\n * `kill()` every live session of THIS backend instance. Extra to the `InteractiveBackend`\n * contract.\n *\n * Also runs automatically on the host process's `exit` event, armed lazily on the first\n * `startInteractive`. Only `exit` — installing SIGINT/SIGTERM handlers would suppress Node's\n * default terminate-on-signal, so a `kill -9` of the host still orphans the ptys.\n */\n killAll(): void {\n for (const id of [...this.sessions.keys()]) this.kill(id);\n }\n\n /**\n * How many sessions this instance currently holds — the number `maxSessions` is compared against.\n * Extra to the `InteractiveBackend` contract.\n *\n * Drops on its own when a process exits or a TTL fires, so it is a live gauge rather than a\n * counter, and it never counts sessions belonging to another backend instance.\n */\n activeSessionCount(): number {\n return this.sessions.size;\n }\n}\n","/**\n * `createConfinedPtyBackend` / `probeConfinement` — an interactive shell that starts in a fixed root,\n * inside the OS sandbox, with a scrubbed environment, plus a runtime proof that the confinement\n * works on this host.\n */\nimport { existsSync, rmSync } from \"node:fs\";\n\nimport type {\n InteractiveBackend,\n StartInteractiveOptions,\n StartInteractiveResult,\n WriteStdinOptions,\n WriteStdinResult,\n} from \"loopzero-sdk/interactive\";\nimport { interactiveWrapCommand, type SandboxMode } from \"loopzero-sdk/sandbox\";\n\nimport { PtyInteractiveBackend } from \"./pty-interactive-backend.js\";\n\nconst DEFAULT_ENV_ALLOWLIST: readonly string[] = [\n \"PATH\",\n \"USER\",\n \"LOGNAME\",\n \"LANG\",\n \"LC_ALL\",\n \"LC_CTYPE\",\n \"TERM\",\n \"TZ\",\n];\nconst DEFAULT_MAX_SESSIONS = 4;\nconst DEFAULT_PROBE_TIMEOUT_MS = 3000;\nconst PROBE_SETTLE_MS = 300;\nconst PROBE_POLL_MS = 50;\n\n/**\n * Options for {@link createConfinedPtyBackend}.\n *\n * @public\n */\nexport interface ConfinedPtyBackendOptions {\n /** Every session starts here; a cwd passed to startInteractive is ignored. */\n root: string;\n /** Sandbox mode handed to interactiveWrapCommand from loopzero-sdk/sandbox. */\n mode: SandboxMode;\n /** Variable names kept from `sourceEnv`. Default: PATH, USER, LOGNAME, LANG, LC_ALL, LC_CTYPE, TERM, TZ. HOME is always set to `root`. */\n envAllowlist?: readonly string[];\n /** Default `process.env`. */\n sourceEnv?: Readonly<Record<string, string | undefined>>;\n /** Default 4. */\n maxSessions?: number;\n /**\n * Test seam: builds the backend that actually spawns. Receives the sandbox wrap and the session\n * ceiling. Defaults to a `PtyInteractiveBackend`.\n */\n createInner?: (inner: {\n wrapCommand: (command: string, cwd: string) => string | null;\n maxSessions: number;\n }) => InteractiveBackend;\n}\n\n/** POSIX single-quote: the shell receives `value` unchanged. */\nfunction shQuote(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\nfunction scrubbedCommand(command: string, options: ConfinedPtyBackendOptions): string {\n const source = options.sourceEnv ?? process.env;\n const kept: string[] = [];\n for (const name of options.envAllowlist ?? DEFAULT_ENV_ALLOWLIST) {\n const value = source[name];\n if (value !== undefined && name !== \"HOME\") kept.push(`${name}=${shQuote(value)}`);\n }\n kept.push(`HOME=${shQuote(options.root)}`);\n return `/usr/bin/env -i ${kept.join(\" \")} /bin/sh -c ${shQuote(command)}`;\n}\n\nclass ConfinedPtyBackend implements InteractiveBackend {\n constructor(\n private readonly inner: InteractiveBackend,\n private readonly options: ConfinedPtyBackendOptions,\n ) {}\n\n startInteractive(\n command: string,\n opts?: StartInteractiveOptions,\n ): Promise<StartInteractiveResult> {\n return this.inner.startInteractive(scrubbedCommand(command, this.options), {\n ...opts,\n cwd: this.options.root,\n });\n }\n\n writeStdin(\n sessionId: string,\n chars: string,\n opts?: WriteStdinOptions,\n ): Promise<WriteStdinResult> {\n return this.inner.writeStdin(sessionId, chars, opts);\n }\n\n kill(sessionId: string): void {\n this.inner.kill(sessionId);\n }\n}\n\n/**\n * An {@link InteractiveBackend} whose every session starts in `root`, runs under\n * `interactiveWrapCommand({ mode })` and sees only the allowlisted environment (plus `HOME=root`).\n * Gate its use on {@link probeConfinement}: a sandbox that is unavailable wraps nothing.\n */\nexport function createConfinedPtyBackend(options: ConfinedPtyBackendOptions): InteractiveBackend {\n const config = {\n wrapCommand: interactiveWrapCommand({ mode: options.mode }),\n maxSessions: options.maxSessions ?? DEFAULT_MAX_SESSIONS,\n };\n const inner = options.createInner\n ? options.createInner(config)\n : new PtyInteractiveBackend(config);\n return new ConfinedPtyBackend(inner, options);\n}\n\n/**\n * Outcome of {@link probeConfinement}: confined, or the reason it could not be proven.\n *\n * @public\n */\nexport type ConfinementProbeResult =\n | { confined: true }\n | {\n confined: false;\n reason: \"cannot_write_inside\" | \"wrote_outside\" | \"start_failed\";\n detail?: string;\n };\n\nconst sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));\n\nasync function waitForFile(path: string, timeoutMs: number): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (!existsSync(path)) {\n if (Date.now() >= deadline) return false;\n await sleep(PROBE_POLL_MS);\n }\n return true;\n}\n\n/**\n * Starts a real session that touches `paths.inside` (inside the root) and `paths.outside` (beside\n * it), and reports whether the confinement held. Both paths must be caller-owned, distinct and\n * disposable: they are removed afterwards. The session is always killed.\n *\n * `start_failed` means `startInteractive` rejected (no `node-pty`, no sandbox, spawn error) and\n * carries the message in `detail`. A spawn that succeeds but whose command then fails to run shows\n * up as `cannot_write_inside`.\n */\nexport async function probeConfinement(\n backend: InteractiveBackend,\n paths: { inside: string; outside: string },\n options?: { timeoutMs?: number },\n): Promise<ConfinementProbeResult> {\n const command = `touch ${shQuote(paths.inside)}; touch ${shQuote(paths.outside)}`;\n let sessionId: string | undefined;\n try {\n sessionId = (await backend.startInteractive(command)).sessionId;\n const wrote = await waitForFile(paths.inside, options?.timeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS);\n await sleep(PROBE_SETTLE_MS);\n if (existsSync(paths.outside)) return { confined: false, reason: \"wrote_outside\" };\n return wrote ? { confined: true } : { confined: false, reason: \"cannot_write_inside\" };\n } catch (error) {\n return {\n confined: false,\n reason: \"start_failed\",\n detail: error instanceof Error ? error.message : String(error),\n };\n } finally {\n if (sessionId !== undefined) killQuietly(backend, sessionId);\n rmSync(paths.inside, { force: true });\n rmSync(paths.outside, { force: true });\n }\n}\n\nfunction killQuietly(backend: InteractiveBackend, sessionId: string): void {\n try {\n backend.kill(sessionId);\n } catch {\n // best effort: the probe result matters more than a failed kill of a dead session\n }\n}\n"]}