@rob-c/pi-managed-tools 0.0.0-stage → 0.23.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/BUSYBOX-CONTRACT.md +440 -0
- package/CHANGELOG.md +775 -0
- package/LICENSE +338 -0
- package/README.md +849 -2
- package/package.json +79 -5
- package/skills/busybox-applets/SKILL.md +266 -0
- package/skills/managed-tools/SKILL.md +328 -0
- package/skills/managed-tools-reference/SKILL.md +738 -0
- package/src/agentops.ts +813 -0
- package/src/agenttools.ts +391 -0
- package/src/bashtool.ts +103 -0
- package/src/build.ts +142 -0
- package/src/context.ts +157 -0
- package/src/display.ts +79 -0
- package/src/extension.ts +1229 -0
- package/src/guard.ts +437 -0
- package/src/jobs.ts +1052 -0
- package/src/timing.ts +364 -0
- package/src/tools.ts +2223 -0
- package/src/userstdin.ts +524 -0
- package/src/wrap.ts +683 -0
package/src/userstdin.ts
ADDED
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* pi-managed-tools — keep a set of developer binaries at their latest upstream release.
|
|
3
|
+
* Copyright (C) 2026 Robert Currie
|
|
4
|
+
*
|
|
5
|
+
* This program is free software; you can redistribute it and/or modify it under
|
|
6
|
+
* the terms of the GNU General Public License as published by the Free Software
|
|
7
|
+
* Foundation; version 2 of the License only.
|
|
8
|
+
*
|
|
9
|
+
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
|
|
10
|
+
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
|
|
11
|
+
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
|
|
12
|
+
*
|
|
13
|
+
* You should have received a copy of the GNU General Public License along with this
|
|
14
|
+
* program; if not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0.html>.
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* Standard input for the human's `!` commands, and their output while they run.
|
|
18
|
+
*
|
|
19
|
+
* Two things were missing between pi and the guest, both measured:
|
|
20
|
+
*
|
|
21
|
+
* 1. pi starts every shell command with its stdin closed (`stdio: ["ignore", …]`) and
|
|
22
|
+
* its backend has no stdin argument, so nothing a person types can reach a command.
|
|
23
|
+
* `busybox run` itself does forward input to the guest, pty or not — it just never had
|
|
24
|
+
* any. A `[y/N]` prompt read end-of-file and took its default, with exit 0.
|
|
25
|
+
* 2. `busybox run -q` prints its capture when the command *exits*, so a `!` command
|
|
26
|
+
* showed nothing while it ran — not even the question it was asking.
|
|
27
|
+
*
|
|
28
|
+
* Both are closed from this side, with the binary as it is:
|
|
29
|
+
*
|
|
30
|
+
* - input goes through a named pipe: the wrapper is given `--stdin <fifo>`, this process
|
|
31
|
+
* holds the pipe's other end, and what the person types into pi's input dialog is
|
|
32
|
+
* written to it. pi's own backend still does the spawning, so process-group killing,
|
|
33
|
+
* Esc and the environment are exactly pi's;
|
|
34
|
+
* - output is followed from the run's capture files, which `run` writes as the bytes
|
|
35
|
+
* arrive (an unterminated prompt included). The run gets a private artifact root so
|
|
36
|
+
* its one run directory is known, and what `run -q` prints at exit — the same bytes a
|
|
37
|
+
* second time — is dropped.
|
|
38
|
+
*
|
|
39
|
+
* `--jsonl` was the obvious way to get live output and does not serve: it emits a record
|
|
40
|
+
* per *line*, so a prompt with no newline stays invisible until it has been answered.
|
|
41
|
+
*
|
|
42
|
+
* The pieces are separate so each can be tested without a terminal: the channel (pipe and
|
|
43
|
+
* folder), the follower (files to bytes), the asker (when to show the dialog), and the
|
|
44
|
+
* `exec` that ties them to pi's backend.
|
|
45
|
+
*/
|
|
46
|
+
import { execFileSync } from "node:child_process";
|
|
47
|
+
import { closeSync, constants, mkdtempSync, openSync, readdirSync, readSync, rmSync, writeSync } from "node:fs";
|
|
48
|
+
import { tmpdir } from "node:os";
|
|
49
|
+
import { join } from "node:path";
|
|
50
|
+
|
|
51
|
+
/** pi's own shell backend, as far as this module uses it. */
|
|
52
|
+
export interface ShellExec {
|
|
53
|
+
exec(
|
|
54
|
+
command: string,
|
|
55
|
+
cwd: string,
|
|
56
|
+
options: { onData: (data: Buffer) => void; signal?: AbortSignal; timeout?: number; env?: NodeJS.ProcessEnv },
|
|
57
|
+
): Promise<{ exitCode: number | null }>;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The part of `ctx.ui` this module asks through. */
|
|
61
|
+
export interface AskUi {
|
|
62
|
+
/** `timeout` (ms) makes pi draw a countdown in the title and dismiss the dialog at zero. */
|
|
63
|
+
input(title: string, placeholder?: string, options?: { signal?: AbortSignal; timeout?: number }): Promise<string | undefined>;
|
|
64
|
+
notify?(message: string, level?: "info" | "warning" | "error"): void;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Where a live run's input comes from and where its capture is written. */
|
|
68
|
+
export interface LiveTarget {
|
|
69
|
+
/** The named pipe to hand to `run --stdin`; absent when nobody can type (no UI). */
|
|
70
|
+
stdinFile?: string;
|
|
71
|
+
/** A private artifact root for `run --dir`: the run inside it is the only one. */
|
|
72
|
+
artifactDir: string;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* How long the pipe is kept open after it was created, at least.
|
|
77
|
+
*
|
|
78
|
+
* `run` opens the pipe for reading when it starts. If this end were closed before that,
|
|
79
|
+
* the open would wait for a writer that never comes. Half a second is far longer than the
|
|
80
|
+
* spawn takes and far shorter than anyone presses Esc.
|
|
81
|
+
*/
|
|
82
|
+
const PIPE_SETTLE_MS = 500;
|
|
83
|
+
|
|
84
|
+
export interface InputChannel extends LiveTarget {
|
|
85
|
+
/** Write to the guest's stdin; false when it could not be delivered. */
|
|
86
|
+
send(text: string): boolean;
|
|
87
|
+
/** End of input: the guest's next read returns end-of-file. */
|
|
88
|
+
end(): void;
|
|
89
|
+
/** Close the pipe and delete the folder with everything in it. */
|
|
90
|
+
dispose(): void;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Make the folder, and the pipe when someone can type into it.
|
|
95
|
+
*
|
|
96
|
+
* Undefined when either cannot be made (no `mkfifo` applet, a read-only temp folder): the
|
|
97
|
+
* caller then runs the command the way it did before.
|
|
98
|
+
*/
|
|
99
|
+
export function openInputChannel(options: { busybox: string; withInput: boolean; base?: string }): InputChannel | undefined {
|
|
100
|
+
let dir: string | undefined;
|
|
101
|
+
let fd: number | undefined;
|
|
102
|
+
try {
|
|
103
|
+
// mkdtemp makes it 0700: the pipe carries what a person types, passwords included.
|
|
104
|
+
dir = mkdtempSync(join(options.base ?? tmpdir(), "pi-user-run-"));
|
|
105
|
+
const artifactDir = join(dir, "runs");
|
|
106
|
+
if (!options.withInput) {
|
|
107
|
+
const folder = dir;
|
|
108
|
+
return { artifactDir, send: () => false, end: () => {}, dispose: () => rmSync(folder, { recursive: true, force: true }) };
|
|
109
|
+
}
|
|
110
|
+
const fifo = join(dir, "stdin");
|
|
111
|
+
// Node has no mkfifo; the packaged busybox does, the same on macOS and Linux.
|
|
112
|
+
execFileSync(options.busybox, ["mkfifo", "-m", "600", fifo], { stdio: "ignore", timeout: 5_000 });
|
|
113
|
+
// Read-write, so the open never waits for the other side and the reader sees no
|
|
114
|
+
// end-of-file until this descriptor is closed. Non-blocking, so a guest that has
|
|
115
|
+
// stopped reading can never freeze pi on a write.
|
|
116
|
+
fd = openSync(fifo, constants.O_RDWR | constants.O_NONBLOCK);
|
|
117
|
+
} catch {
|
|
118
|
+
if (dir) rmSync(dir, { recursive: true, force: true });
|
|
119
|
+
return undefined;
|
|
120
|
+
}
|
|
121
|
+
const folder = dir;
|
|
122
|
+
const openedAt = Date.now();
|
|
123
|
+
let descriptor: number | undefined = fd;
|
|
124
|
+
let closing: ReturnType<typeof setTimeout> | undefined;
|
|
125
|
+
const close = () => {
|
|
126
|
+
if (closing) clearTimeout(closing);
|
|
127
|
+
closing = undefined;
|
|
128
|
+
if (descriptor === undefined) return;
|
|
129
|
+
try {
|
|
130
|
+
closeSync(descriptor);
|
|
131
|
+
} catch {
|
|
132
|
+
// Already gone: nothing left to close.
|
|
133
|
+
}
|
|
134
|
+
descriptor = undefined;
|
|
135
|
+
};
|
|
136
|
+
return {
|
|
137
|
+
stdinFile: join(folder, "stdin"),
|
|
138
|
+
artifactDir: join(folder, "runs"),
|
|
139
|
+
send(text) {
|
|
140
|
+
if (descriptor === undefined || closing) return false;
|
|
141
|
+
try {
|
|
142
|
+
const data = Buffer.from(text, "utf8");
|
|
143
|
+
return writeSync(descriptor, data) === data.length;
|
|
144
|
+
} catch {
|
|
145
|
+
// A full pipe (the guest is not reading) or a closed one.
|
|
146
|
+
return false;
|
|
147
|
+
}
|
|
148
|
+
},
|
|
149
|
+
end() {
|
|
150
|
+
if (descriptor === undefined || closing) return;
|
|
151
|
+
const wait = openedAt + PIPE_SETTLE_MS - Date.now();
|
|
152
|
+
if (wait <= 0) close();
|
|
153
|
+
else closing = setTimeout(close, wait);
|
|
154
|
+
},
|
|
155
|
+
dispose() {
|
|
156
|
+
close();
|
|
157
|
+
rmSync(folder, { recursive: true, force: true });
|
|
158
|
+
},
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export interface Follower {
|
|
163
|
+
/** Emit whatever the capture files have gained since the last call. */
|
|
164
|
+
poll(): void;
|
|
165
|
+
/** Whether a run directory ever appeared: false means `run` never started the command. */
|
|
166
|
+
started(): boolean;
|
|
167
|
+
/** When output last arrived, in ms since the epoch; 0 before any. */
|
|
168
|
+
lastOutputAt(): number;
|
|
169
|
+
/** Whether the last byte shown left a line unfinished — what a prompt looks like. */
|
|
170
|
+
isMidLine(): boolean;
|
|
171
|
+
close(): void;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Follow the one run under `root`, turning its growing capture files into output.
|
|
176
|
+
*
|
|
177
|
+
* `run` creates `<root>/R<n>/stdout` and `stderr` and appends to them as the guest
|
|
178
|
+
* writes, so reading from where the last read stopped is the live output. The two
|
|
179
|
+
* streams are read in turn; between them the order is as fine as the polling interval,
|
|
180
|
+
* which is all a person watching needs.
|
|
181
|
+
*/
|
|
182
|
+
export function followRun(root: string, onData: (data: Buffer) => void): Follower {
|
|
183
|
+
let runDir: string | undefined;
|
|
184
|
+
const streams = [
|
|
185
|
+
{ name: "stdout", fd: undefined as number | undefined, offset: 0 },
|
|
186
|
+
{ name: "stderr", fd: undefined as number | undefined, offset: 0 },
|
|
187
|
+
];
|
|
188
|
+
const chunk = Buffer.allocUnsafe(64 * 1024);
|
|
189
|
+
let lastAt = 0;
|
|
190
|
+
let lastByte = 0x0a;
|
|
191
|
+
return {
|
|
192
|
+
poll() {
|
|
193
|
+
if (!runDir) {
|
|
194
|
+
try {
|
|
195
|
+
const found = readdirSync(root).find((name) => /^R\d+$/.test(name));
|
|
196
|
+
if (found) runDir = join(root, found);
|
|
197
|
+
} catch {
|
|
198
|
+
// The root is made by `run` itself; until then there is nothing to read.
|
|
199
|
+
}
|
|
200
|
+
if (!runDir) return;
|
|
201
|
+
}
|
|
202
|
+
for (const stream of streams) {
|
|
203
|
+
if (stream.fd === undefined) {
|
|
204
|
+
try {
|
|
205
|
+
stream.fd = openSync(join(runDir, stream.name), "r");
|
|
206
|
+
} catch {
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
for (;;) {
|
|
211
|
+
let read = 0;
|
|
212
|
+
try {
|
|
213
|
+
read = readSync(stream.fd, chunk, 0, chunk.length, stream.offset);
|
|
214
|
+
} catch {
|
|
215
|
+
break;
|
|
216
|
+
}
|
|
217
|
+
if (read <= 0) break;
|
|
218
|
+
stream.offset += read;
|
|
219
|
+
lastAt = Date.now();
|
|
220
|
+
lastByte = chunk[read - 1] as number;
|
|
221
|
+
// A copy: the buffer is reused for the next read.
|
|
222
|
+
onData(Buffer.from(chunk.subarray(0, read)));
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
},
|
|
226
|
+
started: () => runDir !== undefined,
|
|
227
|
+
lastOutputAt: () => lastAt,
|
|
228
|
+
isMidLine: () => lastByte !== 0x0a,
|
|
229
|
+
close() {
|
|
230
|
+
for (const stream of streams) {
|
|
231
|
+
if (stream.fd === undefined) continue;
|
|
232
|
+
try {
|
|
233
|
+
closeSync(stream.fd);
|
|
234
|
+
} catch {
|
|
235
|
+
// Nothing to do about a descriptor that is already closed.
|
|
236
|
+
}
|
|
237
|
+
stream.fd = undefined;
|
|
238
|
+
}
|
|
239
|
+
},
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** How long output must have stopped on an unfinished line before the dialog opens. */
|
|
244
|
+
export const PROMPT_QUIET_MS = 400;
|
|
245
|
+
/** How long a command may be silent, having printed nothing unfinished, before it opens anyway. */
|
|
246
|
+
export const SILENT_QUIET_MS = 3_000;
|
|
247
|
+
/** The same, once the person has already typed something to this command. */
|
|
248
|
+
export const ANSWERED_QUIET_MS = 1_200;
|
|
249
|
+
/** How close to the full wait a dismissed dialog must have been open to count as timed out. */
|
|
250
|
+
const TIMEOUT_SLACK_MS = 250;
|
|
251
|
+
/** The status a command stopped for an unanswered question exits with: `timeout(1)`'s. */
|
|
252
|
+
export const STDIN_TIMEOUT_EXIT = 124;
|
|
253
|
+
|
|
254
|
+
/** `5m`, `90s`, `2m 30s`: a wait in the words a person would use. */
|
|
255
|
+
export function describeWait(ms: number): string {
|
|
256
|
+
const seconds = Math.round(ms / 1000);
|
|
257
|
+
const minutes = Math.floor(seconds / 60);
|
|
258
|
+
const rest = seconds % 60;
|
|
259
|
+
if (minutes === 0) return `${seconds}s`;
|
|
260
|
+
return rest === 0 ? `${minutes}m` : `${minutes}m ${rest}s`;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* The line added to a command's output when it was stopped for an unanswered question.
|
|
265
|
+
*
|
|
266
|
+
* In the output on purpose: that is what the session records and the model reads, and
|
|
267
|
+
* "(exit 124)" alone would look like the command's own failure.
|
|
268
|
+
*/
|
|
269
|
+
export function stdinTimeoutNotice(ms: number): string {
|
|
270
|
+
return `[stopped: the command waited ${describeWait(ms)} for input and none was typed. It was not a failure of the command. PI_MANAGED_TOOLS_STDIN_TIMEOUT=<seconds> changes the wait; 0 removes it.]`;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function pause(ms: number, signal: AbortSignal): Promise<void> {
|
|
274
|
+
return new Promise((resolve) => {
|
|
275
|
+
if (signal.aborted) return resolve();
|
|
276
|
+
const done = () => {
|
|
277
|
+
clearTimeout(timer);
|
|
278
|
+
signal.removeEventListener("abort", done);
|
|
279
|
+
resolve();
|
|
280
|
+
};
|
|
281
|
+
const timer = setTimeout(done, ms);
|
|
282
|
+
signal.addEventListener("abort", done, { once: true });
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* A command as a dialog title: one line, and short. pi draws "enter submit · escape
|
|
288
|
+
* cancel" under it, so the title only has to say what cancel means here.
|
|
289
|
+
*/
|
|
290
|
+
export function inputTitle(command: string): string {
|
|
291
|
+
const flat = command.replace(/\s+/g, " ").trim();
|
|
292
|
+
const short = flat.length > 40 ? `${flat.slice(0, 39)}…` : flat;
|
|
293
|
+
return `Input for: ${short} (Esc ends its input)`;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Offer the input dialog while the command runs, at the moments it looks like it is
|
|
298
|
+
* waiting.
|
|
299
|
+
*
|
|
300
|
+
* Not from the first instant: most `!` commands never read anything, and a dialog that
|
|
301
|
+
* flashed over every `ls` would be worse than no dialog. It opens when output has
|
|
302
|
+
* stopped on an unfinished line (`Proceed? [y/N] `, `Password: `) for a moment, or when
|
|
303
|
+
* the command has been silent for a few seconds — sooner once the person has already
|
|
304
|
+
* typed to it. Each line the person submits goes to the guest; Esc ends the input (the
|
|
305
|
+
* guest reads end-of-file) and gives the editor back, and the command keeps running
|
|
306
|
+
* until it finishes or a second Esc stops it, as before.
|
|
307
|
+
*
|
|
308
|
+
* What is typed is not added to the output: the row is recorded in the session and read
|
|
309
|
+
* by the model, and a password must not be. Only the line break the Enter key would have
|
|
310
|
+
* produced is shown, and only after a prompt, so the next output starts on its own line.
|
|
311
|
+
*
|
|
312
|
+
* The wait is bounded: each time the dialog opens the person has `inputTimeoutMs` to
|
|
313
|
+
* answer, with pi's countdown in the title. When it runs out `onTimeout` is called and
|
|
314
|
+
* nothing more is asked. That is deliberately not "end of input": a `[Y/n]` that read
|
|
315
|
+
* end-of-file would take *yes* for an answer nobody gave, so the caller stops the command
|
|
316
|
+
* instead. The clock only runs while the dialog is open — a command that is working, or
|
|
317
|
+
* that the person has already said Esc to, is never timed by it.
|
|
318
|
+
*/
|
|
319
|
+
export async function askWhileRunning(options: {
|
|
320
|
+
ui: AskUi;
|
|
321
|
+
title: string;
|
|
322
|
+
channel: Pick<InputChannel, "send" | "end">;
|
|
323
|
+
follower: Pick<Follower, "lastOutputAt" | "isMidLine">;
|
|
324
|
+
/** Aborted when the command has ended. */
|
|
325
|
+
done: AbortSignal;
|
|
326
|
+
/** Called after a line was delivered in answer to a prompt, to end the prompt's line on screen. */
|
|
327
|
+
onAnswered: () => void;
|
|
328
|
+
startedAt?: number;
|
|
329
|
+
promptQuietMs?: number;
|
|
330
|
+
silentQuietMs?: number;
|
|
331
|
+
answeredQuietMs?: number;
|
|
332
|
+
/** How long one question may go unanswered; 0 or absent waits for as long as it takes. */
|
|
333
|
+
inputTimeoutMs?: number;
|
|
334
|
+
/** Called once when a question went unanswered for that long. */
|
|
335
|
+
onTimeout?: () => void;
|
|
336
|
+
}): Promise<void> {
|
|
337
|
+
const inputTimeout = options.inputTimeoutMs !== undefined && options.inputTimeoutMs > 0 ? options.inputTimeoutMs : 0;
|
|
338
|
+
const promptQuiet = options.promptQuietMs ?? PROMPT_QUIET_MS;
|
|
339
|
+
const silentQuiet = options.silentQuietMs ?? SILENT_QUIET_MS;
|
|
340
|
+
const answeredQuiet = options.answeredQuietMs ?? ANSWERED_QUIET_MS;
|
|
341
|
+
let quietFrom = options.startedAt ?? Date.now();
|
|
342
|
+
let sentAt = 0;
|
|
343
|
+
// A prompt is output that stopped mid-line *since the last answer*: the line an answer
|
|
344
|
+
// was given to is finished, whatever its last byte was.
|
|
345
|
+
const atPrompt = () => options.follower.isMidLine() && options.follower.lastOutputAt() >= sentAt;
|
|
346
|
+
while (!options.done.aborted) {
|
|
347
|
+
const since = Math.max(quietFrom, options.follower.lastOutputAt());
|
|
348
|
+
const needed = atPrompt() ? promptQuiet : sentAt > 0 ? answeredQuiet : silentQuiet;
|
|
349
|
+
const wait = since + needed - Date.now();
|
|
350
|
+
if (wait > 0) {
|
|
351
|
+
await pause(Math.min(wait, 100), options.done);
|
|
352
|
+
continue;
|
|
353
|
+
}
|
|
354
|
+
// One dialog, dismissed by whichever comes first: the command ending, or the wait
|
|
355
|
+
// running out. The wait is kept here as well as handed to pi (which draws the
|
|
356
|
+
// countdown), so it holds under a UI that ignores the option.
|
|
357
|
+
const openedAt = Date.now();
|
|
358
|
+
const dialog = new AbortController();
|
|
359
|
+
const onDone = () => dialog.abort();
|
|
360
|
+
options.done.addEventListener("abort", onDone, { once: true });
|
|
361
|
+
let isExpired = false;
|
|
362
|
+
const clock =
|
|
363
|
+
inputTimeout > 0
|
|
364
|
+
? setTimeout(() => {
|
|
365
|
+
isExpired = true;
|
|
366
|
+
dialog.abort();
|
|
367
|
+
}, inputTimeout)
|
|
368
|
+
: undefined;
|
|
369
|
+
let line: string | undefined;
|
|
370
|
+
try {
|
|
371
|
+
line = await options.ui.input(options.title, "", {
|
|
372
|
+
signal: dialog.signal,
|
|
373
|
+
...(inputTimeout > 0 ? { timeout: inputTimeout } : {}),
|
|
374
|
+
});
|
|
375
|
+
} finally {
|
|
376
|
+
if (clock) clearTimeout(clock);
|
|
377
|
+
options.done.removeEventListener("abort", onDone);
|
|
378
|
+
}
|
|
379
|
+
if (options.done.aborted) return;
|
|
380
|
+
if (line === undefined) {
|
|
381
|
+
// pi answers a timed-out dialog and a dismissed one alike, so the clock tells
|
|
382
|
+
// them apart: only a dialog that was open for the whole wait timed out.
|
|
383
|
+
if (isExpired || (inputTimeout > 0 && Date.now() - openedAt >= inputTimeout - TIMEOUT_SLACK_MS)) {
|
|
384
|
+
options.onTimeout?.();
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
// Esc: nothing more will be typed, so the guest must not wait for it.
|
|
388
|
+
options.channel.end();
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
const wasAtPrompt = atPrompt();
|
|
392
|
+
if (!options.channel.send(`${line}\n`)) {
|
|
393
|
+
options.ui.notify?.("The command is not reading its input: that line was not delivered.", "warning");
|
|
394
|
+
options.channel.end();
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
if (wasAtPrompt) options.onAnswered();
|
|
398
|
+
sentAt = Date.now();
|
|
399
|
+
quietFrom = sentAt;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/** How often the capture files are read, in ms: fast enough to feel live. */
|
|
404
|
+
const POLL_MS = 50;
|
|
405
|
+
/** The most of `run`'s own exit-time output that is kept in case the run never started. */
|
|
406
|
+
const HELD_LIMIT = 256 * 1024;
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* An `exec` for the human's `!` commands that lets them see and answer the command.
|
|
410
|
+
*
|
|
411
|
+
* `local` is pi's backend and still runs everything. `fallback` is how the command ran
|
|
412
|
+
* before this existed; it is used whenever the pipe or the folder cannot be set up, or
|
|
413
|
+
* the command is one the wrapper leaves alone (the `command` escape).
|
|
414
|
+
*/
|
|
415
|
+
export function interactiveExec(options: {
|
|
416
|
+
local: ShellExec;
|
|
417
|
+
fallback: ShellExec["exec"];
|
|
418
|
+
busybox: string;
|
|
419
|
+
/** Build the wrapped command for a live run, or undefined to leave it unwrapped. */
|
|
420
|
+
wrap(command: string, live: LiveTarget): string | undefined;
|
|
421
|
+
/** The dialog to ask through; absent (no UI), stdin is empty, as it always was. */
|
|
422
|
+
ui?: AskUi;
|
|
423
|
+
base?: string;
|
|
424
|
+
pollMs?: number;
|
|
425
|
+
promptQuietMs?: number;
|
|
426
|
+
silentQuietMs?: number;
|
|
427
|
+
answeredQuietMs?: number;
|
|
428
|
+
/** How long one question may go unanswered before the command is stopped; 0 never stops it. */
|
|
429
|
+
inputTimeoutMs?: number;
|
|
430
|
+
/**
|
|
431
|
+
* Given what `run` itself printed when the command exited — its own view of the run,
|
|
432
|
+
* which the person's screen never shows because the capture files were followed
|
|
433
|
+
* instead. With a timeline-taking wrapper that is the timeline, for the model.
|
|
434
|
+
*/
|
|
435
|
+
onView?: (result: { command: string; view: string; notice?: string }) => void;
|
|
436
|
+
}): ShellExec["exec"] {
|
|
437
|
+
return async (command, cwd, execOptions) => {
|
|
438
|
+
const channel = openInputChannel({ busybox: options.busybox, withInput: options.ui !== undefined, base: options.base });
|
|
439
|
+
if (!channel) return options.fallback(command, cwd, execOptions);
|
|
440
|
+
const wrapped = options.wrap(command, { stdinFile: channel.stdinFile, artifactDir: channel.artifactDir });
|
|
441
|
+
if (!wrapped) {
|
|
442
|
+
channel.dispose();
|
|
443
|
+
return options.fallback(command, cwd, execOptions);
|
|
444
|
+
}
|
|
445
|
+
const startedAt = Date.now();
|
|
446
|
+
const follower = followRun(channel.artifactDir, execOptions.onData);
|
|
447
|
+
const done = new AbortController();
|
|
448
|
+
const timer = setInterval(() => follower.poll(), options.pollMs ?? POLL_MS);
|
|
449
|
+
// The command is stopped through the signal pi's backend already kills on: the
|
|
450
|
+
// person's Esc, or a question nobody answered in time.
|
|
451
|
+
const stop = new AbortController();
|
|
452
|
+
const onOuterAbort = () => stop.abort();
|
|
453
|
+
if (execOptions.signal?.aborted) stop.abort();
|
|
454
|
+
else execOptions.signal?.addEventListener("abort", onOuterAbort, { once: true });
|
|
455
|
+
let isUnanswered = false;
|
|
456
|
+
const asking = options.ui
|
|
457
|
+
? askWhileRunning({
|
|
458
|
+
ui: options.ui,
|
|
459
|
+
title: inputTitle(command),
|
|
460
|
+
channel,
|
|
461
|
+
follower,
|
|
462
|
+
done: done.signal,
|
|
463
|
+
onAnswered: () => execOptions.onData(Buffer.from("\n")),
|
|
464
|
+
startedAt,
|
|
465
|
+
promptQuietMs: options.promptQuietMs,
|
|
466
|
+
silentQuietMs: options.silentQuietMs,
|
|
467
|
+
answeredQuietMs: options.answeredQuietMs,
|
|
468
|
+
inputTimeoutMs: options.inputTimeoutMs,
|
|
469
|
+
onTimeout: () => {
|
|
470
|
+
isUnanswered = true;
|
|
471
|
+
stop.abort();
|
|
472
|
+
},
|
|
473
|
+
}).catch(() => {})
|
|
474
|
+
: Promise.resolve();
|
|
475
|
+
// What `run -q` prints when the command exits is the capture, a second time. It is
|
|
476
|
+
// only worth showing when no run ever started: then it is the reason why.
|
|
477
|
+
const held: Buffer[] = [];
|
|
478
|
+
let heldBytes = 0;
|
|
479
|
+
let result: { exitCode: number | null } | undefined;
|
|
480
|
+
let failure: unknown;
|
|
481
|
+
try {
|
|
482
|
+
result = await options.local.exec(wrapped, cwd, {
|
|
483
|
+
...execOptions,
|
|
484
|
+
signal: stop.signal,
|
|
485
|
+
onData: (data) => {
|
|
486
|
+
if (heldBytes >= HELD_LIMIT) return;
|
|
487
|
+
held.push(data);
|
|
488
|
+
heldBytes += data.length;
|
|
489
|
+
},
|
|
490
|
+
});
|
|
491
|
+
} catch (error) {
|
|
492
|
+
failure = error;
|
|
493
|
+
} finally {
|
|
494
|
+
clearInterval(timer);
|
|
495
|
+
done.abort();
|
|
496
|
+
execOptions.signal?.removeEventListener("abort", onOuterAbort);
|
|
497
|
+
// The command has ended, so the files are complete: one last read.
|
|
498
|
+
follower.poll();
|
|
499
|
+
if (!follower.started()) for (const data of held) execOptions.onData(data);
|
|
500
|
+
const wasMidLine = follower.isMidLine();
|
|
501
|
+
follower.close();
|
|
502
|
+
channel.dispose();
|
|
503
|
+
await asking;
|
|
504
|
+
const notice = isUnanswered ? stdinTimeoutNotice(options.inputTimeoutMs ?? 0) : undefined;
|
|
505
|
+
if (notice) {
|
|
506
|
+
// Said in the output, where the session records it and the model reads it;
|
|
507
|
+
// on a line of its own, after the question it was stopped at.
|
|
508
|
+
execOptions.onData(Buffer.from(`${wasMidLine ? "\n" : ""}${notice}\n`));
|
|
509
|
+
}
|
|
510
|
+
if (follower.started() && held.length > 0) {
|
|
511
|
+
try {
|
|
512
|
+
options.onView?.({ command, view: Buffer.concat(held).toString("utf8"), notice });
|
|
513
|
+
} catch {
|
|
514
|
+
// A view nobody could keep is not a reason to fail the command.
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
// Stopped for an unanswered question: the backend reports that as an abort, which
|
|
519
|
+
// pi would show as a failed command. It is a timeout, with timeout(1)'s status.
|
|
520
|
+
if (isUnanswered) return { exitCode: STDIN_TIMEOUT_EXIT };
|
|
521
|
+
if (failure !== undefined) throw failure;
|
|
522
|
+
return result as { exitCode: number | null };
|
|
523
|
+
};
|
|
524
|
+
}
|