@ian-pascoe/pi-termctrl 0.0.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/LICENSE +21 -0
- package/README.md +191 -0
- package/package.json +59 -0
- package/skills/pi-termctrl/SKILL.md +16 -0
- package/src/bash-replacement.ts +369 -0
- package/src/exit-notification.ts +113 -0
- package/src/index.ts +1 -0
- package/src/pi-termctrl-extension.ts +186 -0
- package/src/pi-termctrl-settings.ts +128 -0
- package/src/ps-panel.ts +343 -0
- package/src/termctrl-binary.ts +25 -0
- package/src/termctrl-driver.ts +127 -0
- package/src/termctrl-registry.ts +710 -0
- package/src/terminal-driver.ts +51 -0
- package/src/terminal-tools.ts +726 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ian Pascoe
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
# @ian-pascoe/pi-termctrl
|
|
2
|
+
|
|
3
|
+
Interactive Terminals, Background jobs, and a `/ps` panel for
|
|
4
|
+
[Pi](https://github.com/earendil-works/pi). It is a minimal alternative to
|
|
5
|
+
`pi-interactive-shell`.
|
|
6
|
+
|
|
7
|
+
- **Terminals** are PTY programs, such as REPLs, TUIs and prompts, that the agent
|
|
8
|
+
drives by sending input and reading the screen. They run through
|
|
9
|
+
[`@kitlangton/terminal-control`](https://www.npmjs.com/package/@kitlangton/terminal-control).
|
|
10
|
+
- **Background jobs** are `bash` commands that keep running after their tool
|
|
11
|
+
call returns.
|
|
12
|
+
- **`/ps`** lists both, previews them live, and stops them.
|
|
13
|
+
|
|
14
|
+
## Install
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pi install npm:@ian-pascoe/pi-termctrl
|
|
18
|
+
# or
|
|
19
|
+
pi install git:github.com/ian-pascoe/pi-extensions
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
For a local checkout, run `pi -e ./packages/pi-termctrl/src/index.ts`.
|
|
23
|
+
|
|
24
|
+
## Terminal tools
|
|
25
|
+
|
|
26
|
+
| Tool | Parameters |
|
|
27
|
+
| ---------------- | --------------------------------------------------------- |
|
|
28
|
+
| `terminal_start` | `command`, `cwd?`, `wait_ms?`, `notify?` (default `true`) |
|
|
29
|
+
| `terminal_send` | `id`, `text?`, `keys?`, `wait_for_text?`, `wait_ms?` |
|
|
30
|
+
| `terminal_stop` | `id`: a Terminal id (`t1`) or Background job id (`b1`) |
|
|
31
|
+
| `terminal_list` | none |
|
|
32
|
+
|
|
33
|
+
`terminal_start` runs `command` through the shell Pi's `bash` uses (the
|
|
34
|
+
`shellPath` setting, otherwise Pi's default bash), applies `shellCommandPrefix`,
|
|
35
|
+
and opens a PTY sized by `termctrl.defaultViewport`.
|
|
36
|
+
|
|
37
|
+
`terminal_start` and `terminal_send` wait until the Terminal **settles**: at the
|
|
38
|
+
first of 250 ms of screen quiet, a `wait_for_text` match, process exit, or
|
|
39
|
+
`wait_ms` running out. `wait_for_text` is a literal substring, or a regex when
|
|
40
|
+
written as `/source/flags`; with `wait_for_text`, quiet alone does not end the
|
|
41
|
+
wait, and text already on the screen before `terminal_send` counts only after
|
|
42
|
+
the screen changes. Default waits are 2 s for `terminal_start`, 500 ms for `terminal_send`
|
|
43
|
+
with input, and 30 s for a `terminal_send` with neither `text` nor `keys` (a
|
|
44
|
+
poll, which settles on quiet only after new output). Every `wait_ms` clamps to
|
|
45
|
+
5 minutes.
|
|
46
|
+
|
|
47
|
+
Results contain the visible screen, the log lines that scrolled off since the
|
|
48
|
+
agent's previous result, `state`, `exit_code` or `signal` once exited, and
|
|
49
|
+
`changed: false` when the screen matches the previous result. Scrolled-off lines
|
|
50
|
+
include lines the agent saw on an earlier screen, so a line rewritten in place,
|
|
51
|
+
such as a progress line, arrives in its final form. Tools that declare
|
|
52
|
+
structured output give `codemode` scripts typed values.
|
|
53
|
+
|
|
54
|
+
Scrolled-off lines are best effort: they come from termctrl's scrollback, which
|
|
55
|
+
is limited (several hundred lines; fewer when lines are long) and drops its
|
|
56
|
+
oldest lines first. Reading a Terminal before its scrollback fills loses
|
|
57
|
+
nothing. When lines the agent never received were dropped, or the screen was
|
|
58
|
+
cleared, the result reports every line termctrl still holds, sets
|
|
59
|
+
`output_missing: true`, and says that earlier output is missing. A Terminal's
|
|
60
|
+
first result cannot detect dropped lines: when a program prints more than the
|
|
61
|
+
scrollback holds before that result, its oldest lines are lost without
|
|
62
|
+
`output_missing`, because termctrl does not report the trimming. Run commands
|
|
63
|
+
whose complete output matters with `bash`, or redirect their output to a file.
|
|
64
|
+
|
|
65
|
+
A result is limited to Pi's 2000 lines or 50 KB. The screen is kept first, from
|
|
66
|
+
its bottom, and the newest scrolled-off lines fill the rest. When anything is
|
|
67
|
+
cut, every line of the result goes to
|
|
68
|
+
`$TMPDIR/pi-termctrl/<pid>-<id>-output-<n>.log`, named in the result's notice
|
|
69
|
+
and `full_output_path`.
|
|
70
|
+
|
|
71
|
+
`keys` are termctrl key names: `Enter`, `Escape`, `ArrowUp`, `ArrowDown`,
|
|
72
|
+
`ArrowLeft`, `ArrowRight`, `Tab`, `Shift+Tab`, `Backspace`, `Delete`, `Home`,
|
|
73
|
+
`End`, `PageUp`, `PageDown`, and `Control+A` to `Control+Z`. Text is typed
|
|
74
|
+
before keys.
|
|
75
|
+
|
|
76
|
+
Terminal ids are `t1`, `t2`, … and Background job ids are `b1`, `b2`, …; ids are
|
|
77
|
+
never reused in a Pi process, including across `/reload`. At most 16 running
|
|
78
|
+
Terminals and Background jobs may exist across the whole process; starting
|
|
79
|
+
another fails and lists the caller's live entries.
|
|
80
|
+
|
|
81
|
+
`terminal_stop` stops a running entry (termctrl stop, then `SIGKILL` of the
|
|
82
|
+
Terminal's process group if it is still alive after 3 s) and forgets it. For a
|
|
83
|
+
Terminal it returns the final screen and scrolled-off lines; for a Background
|
|
84
|
+
job, its recent output. Exited entries stay
|
|
85
|
+
readable and listed until the agent stops them, the user removes them in `/ps`,
|
|
86
|
+
or their session shuts down. `terminal_list` lists the caller's Terminals and,
|
|
87
|
+
in a separate `background_jobs` section, its Background jobs with their log
|
|
88
|
+
paths.
|
|
89
|
+
|
|
90
|
+
## `bash` replacement
|
|
91
|
+
|
|
92
|
+
With `termctrl.replaceBash` (default `true`), Pi Termctrl replaces Pi's `bash`
|
|
93
|
+
tool with Pi's own definition plus one parameter, `background?: boolean`.
|
|
94
|
+
Commands still run on pipes through Pi's local `exec`, so Pi keeps spawning,
|
|
95
|
+
process-tree kills, truncation and rendering, and foreground results are
|
|
96
|
+
unchanged. A command becomes a Background job in two ways:
|
|
97
|
+
|
|
98
|
+
- **`background: true`** waits 2 s. A command that finishes first returns an
|
|
99
|
+
ordinary result; otherwise the call returns a background result. If the cap
|
|
100
|
+
is reached during those 2 s, the command stays in the foreground.
|
|
101
|
+
- **Ctrl+B** while an agent `bash` call runs moves every running call to the
|
|
102
|
+
background. At other times Ctrl+B stays the editor's cursor-left.
|
|
103
|
+
|
|
104
|
+
Up to 16 MiB of a command's output is kept in memory until it is backgrounded;
|
|
105
|
+
older output becomes an omission line in the log. Once backgrounded, a
|
|
106
|
+
command's `timeout` is cleared, Esc and turn aborts no
|
|
107
|
+
longer reach it, and its output so far and all later output go to
|
|
108
|
+
`$TMPDIR/pi-termctrl/<pid>-<id>.log`. The result says
|
|
109
|
+
`Command moved to the background as b<n>`, includes the output so far, and
|
|
110
|
+
gives the log path; read the log with `read` and stop the job with
|
|
111
|
+
`terminal_stop`. Its structured result follows Pi's `bash` output schema, except
|
|
112
|
+
that `exit_code` is absent and `background: { id, log_path }` is present.
|
|
113
|
+
|
|
114
|
+
A Background job's log is deleted when the job is stopped, when the user
|
|
115
|
+
removes it in `/ps`, or when its session shuts down for any reason except
|
|
116
|
+
reload. `bash` calls from `codemode` scripts behave the same. User `!` commands
|
|
117
|
+
are not affected.
|
|
118
|
+
|
|
119
|
+
**Conflict:** only one extension can own `bash`. Set `"replaceBash": false` when
|
|
120
|
+
another extension registers `bash`; Pi's `bash` is then untouched and the
|
|
121
|
+
backgrounding paths do not exist.
|
|
122
|
+
|
|
123
|
+
## Exit notifications
|
|
124
|
+
|
|
125
|
+
When a Terminal or Background job exits and the agent has neither seen the exit
|
|
126
|
+
in a `terminal_*` result nor stopped it, Pi Termctrl sends an Exit notification:
|
|
127
|
+
the id, command, exit code or signal, duration, and the last
|
|
128
|
+
`termctrl.exitTailLines` lines of the final screen or log. Exits in the same tick
|
|
129
|
+
share one message. It steers a working agent and starts a turn when the agent is
|
|
130
|
+
idle. `terminal_start {notify: false}` opts a Terminal out. Notifications go
|
|
131
|
+
only to the session that started the entry, and wait across `/reload`.
|
|
132
|
+
|
|
133
|
+
## `/ps` and footer
|
|
134
|
+
|
|
135
|
+
`/ps` opens an overlay listing every entry in the Pi process, including those of
|
|
136
|
+
in-process child agents, with kind, id, owner (`root` or `child`), state and
|
|
137
|
+
age, plus a live preview of the selected Terminal's screen or Background job's
|
|
138
|
+
log tail. Keys: `↑`/`↓` select, `k` stops without confirmation (the agent gets an
|
|
139
|
+
Exit notification), `x` removes an exited entry, `Esc` closes. The footer shows
|
|
140
|
+
`N running` while anything is live. In RPC mode `/ps` sends a one-line summary;
|
|
141
|
+
print mode has no UI but keeps the tools and notifications.
|
|
142
|
+
|
|
143
|
+
## Lifecycle
|
|
144
|
+
|
|
145
|
+
Terminals and Background jobs live in the Pi process
|
|
146
|
+
([ADR-0001](docs/adr/0001-terminals-live-in-the-pi-process.md)). They survive
|
|
147
|
+
`/reload`; every other session shutdown (quit, new, resume, fork) stops the
|
|
148
|
+
session's own entries. Nothing persists across Pi restarts. Besides Background
|
|
149
|
+
job logs and full output files, the only file written is a short-lived pid
|
|
150
|
+
handoff file per Terminal launch in `$TMPDIR/pi-termctrl`, deleted as soon as
|
|
151
|
+
it is read. Full output files outlive their Terminal, so a `terminal_stop`
|
|
152
|
+
result can name one, and are deleted when their session shuts down for any
|
|
153
|
+
reason except reload.
|
|
154
|
+
|
|
155
|
+
## Settings
|
|
156
|
+
|
|
157
|
+
Pi Termctrl reads the `termctrl` key from Pi's global `settings.json` and
|
|
158
|
+
trusted project `.pi/settings.json`; project values override global ones field
|
|
159
|
+
by field:
|
|
160
|
+
|
|
161
|
+
```json
|
|
162
|
+
{
|
|
163
|
+
"termctrl": {
|
|
164
|
+
"replaceBash": true,
|
|
165
|
+
"defaultViewport": { "cols": 120, "rows": 40 },
|
|
166
|
+
"exitTailLines": 20
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
| Setting | Default | Meaning |
|
|
172
|
+
| ----------------- | ------------------------- | ----------------------------------------------- |
|
|
173
|
+
| `replaceBash` | `true` | Replace `bash` to enable Background jobs |
|
|
174
|
+
| `defaultViewport` | `{ cols: 120, rows: 40 }` | Terminal size; each dimension 1 to 1000 |
|
|
175
|
+
| `exitTailLines` | `20` | Lines of output in an Exit notification, 0–1000 |
|
|
176
|
+
|
|
177
|
+
Invalid values keep the lower layer and unknown keys produce warnings at session
|
|
178
|
+
start. Use `/reload` after editing settings.
|
|
179
|
+
|
|
180
|
+
## Platform
|
|
181
|
+
|
|
182
|
+
`@kitlangton/terminal-control` installs a `termctrl` binary for macOS and
|
|
183
|
+
GNU/Linux on arm64 or x64 through optional dependencies. Set `TERMCTRL_BINARY`
|
|
184
|
+
to use another binary. Where no binary resolves (Windows, musl, or
|
|
185
|
+
`--omit=optional`), Pi Termctrl shows one diagnostic and registers no
|
|
186
|
+
`terminal_start` or `terminal_send`; the `bash` replacement, Background jobs,
|
|
187
|
+
`terminal_stop` and `terminal_list` keep working wherever Pi's `bash` does.
|
|
188
|
+
|
|
189
|
+
Not supported: attaching to or taking over a Terminal, recordings, mouse input,
|
|
190
|
+
resize, raw bytes, persistence across Pi restarts, and graceful `SIGTERM`
|
|
191
|
+
stopping of Background jobs.
|
package/package.json
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@ian-pascoe/pi-termctrl",
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"private": false,
|
|
5
|
+
"description": "Interactive Terminals, Background jobs, and a /ps panel for Pi.",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"background-jobs",
|
|
8
|
+
"pi",
|
|
9
|
+
"pi-extension",
|
|
10
|
+
"pi-package",
|
|
11
|
+
"pty",
|
|
12
|
+
"terminal"
|
|
13
|
+
],
|
|
14
|
+
"homepage": "https://github.com/ian-pascoe/pi-extensions/tree/main/packages/pi-termctrl",
|
|
15
|
+
"bugs": {
|
|
16
|
+
"url": "https://github.com/ian-pascoe/pi-extensions/issues"
|
|
17
|
+
},
|
|
18
|
+
"license": "MIT",
|
|
19
|
+
"author": "Ian Pascoe <ian.g.pascoe@gmail.com>",
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "git+https://github.com/ian-pascoe/pi-extensions.git",
|
|
23
|
+
"directory": "packages/pi-termctrl"
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"src",
|
|
27
|
+
"skills",
|
|
28
|
+
"README.md",
|
|
29
|
+
"LICENSE"
|
|
30
|
+
],
|
|
31
|
+
"type": "module",
|
|
32
|
+
"publishConfig": {
|
|
33
|
+
"access": "public",
|
|
34
|
+
"provenance": true
|
|
35
|
+
},
|
|
36
|
+
"scripts": {
|
|
37
|
+
"test": "vitest run --config ../../vitest.config.ts --root .",
|
|
38
|
+
"typecheck": "tsc --noEmit -p tsconfig.json"
|
|
39
|
+
},
|
|
40
|
+
"dependencies": {
|
|
41
|
+
"@kitlangton/terminal-control": "^1.2.1"
|
|
42
|
+
},
|
|
43
|
+
"peerDependencies": {
|
|
44
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
45
|
+
"@earendil-works/pi-tui": "*",
|
|
46
|
+
"typebox": "*"
|
|
47
|
+
},
|
|
48
|
+
"engines": {
|
|
49
|
+
"node": ">=22.19.0"
|
|
50
|
+
},
|
|
51
|
+
"pi": {
|
|
52
|
+
"extensions": [
|
|
53
|
+
"./src/index.ts"
|
|
54
|
+
],
|
|
55
|
+
"skills": [
|
|
56
|
+
"./skills"
|
|
57
|
+
]
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: pi-termctrl
|
|
3
|
+
description: Configure or diagnose Pi Termctrl when Terminal tools are missing, the bash replacement conflicts with another extension, Background jobs misbehave, or termctrl settings need changing.
|
|
4
|
+
license: MIT
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# Pi Termctrl
|
|
8
|
+
|
|
9
|
+
1. Read [`../../README.md`](../../README.md)'s Settings and Platform sections, then identify the effective `termctrl` settings scope.
|
|
10
|
+
2. If `terminal_start` is missing, check the startup diagnostic. Confirm the platform has a packaged `termctrl` binary or that `TERMCTRL_BINARY` names an executable one.
|
|
11
|
+
3. If `bash` lacks the `background` parameter, check `termctrl.replaceBash` and look for another extension that also registers `bash`.
|
|
12
|
+
4. Call `terminal_list` to inspect live and exited Terminals and Background jobs. Ask the user to open `/ps` for a live preview.
|
|
13
|
+
5. Classify the failure as settings, binary resolution, `bash` conflict, cap, or process behaviour.
|
|
14
|
+
6. For a requested change, edit one settings layer, validate its JSON, and reload Pi. Finish when the expected tools appear or one exact cause remains.
|
|
15
|
+
|
|
16
|
+
Ask before stopping a Terminal or Background job you did not start.
|
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
import { createWriteStream, mkdirSync, openSync, type WriteStream } from "node:fs";
|
|
2
|
+
import { rm } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import {
|
|
5
|
+
createBashToolDefinition,
|
|
6
|
+
createLocalBashOperations,
|
|
7
|
+
formatSize,
|
|
8
|
+
truncateTail,
|
|
9
|
+
DEFAULT_MAX_BYTES,
|
|
10
|
+
DEFAULT_MAX_LINES,
|
|
11
|
+
type BashOperations,
|
|
12
|
+
type BashToolOptions,
|
|
13
|
+
type ExtensionToolContext,
|
|
14
|
+
type ExtensionUIContext,
|
|
15
|
+
} from "@earendil-works/pi-coding-agent";
|
|
16
|
+
import { matchesKey } from "@earendil-works/pi-tui";
|
|
17
|
+
import { Type, type TSchema } from "typebox";
|
|
18
|
+
import { KILLED_EXIT, TermctrlRegistry } from "./termctrl-registry.js";
|
|
19
|
+
import { termctrlTemporaryDirectory } from "./termctrl-driver.js";
|
|
20
|
+
import type { TerminalExit } from "./terminal-driver.js";
|
|
21
|
+
|
|
22
|
+
/** How long `background: true` waits before moving a still-running command to the background. */
|
|
23
|
+
export const BACKGROUND_YIELD_MS = 2_000;
|
|
24
|
+
const MAX_TIMEOUT_MS = 2_147_483_647;
|
|
25
|
+
/** Output kept in memory before backgrounding; older output is dropped from the log's head. */
|
|
26
|
+
const BUFFER_LIMIT_BYTES = 16 * 1024 * 1024;
|
|
27
|
+
/** Recent output kept for previews and Exit notifications. */
|
|
28
|
+
const TAIL_LIMIT_CHARS = 64 * 1024;
|
|
29
|
+
|
|
30
|
+
type ExecOptions = Parameters<BashOperations["exec"]>[2];
|
|
31
|
+
|
|
32
|
+
/** Path of a Background job's log. The pid keeps concurrent Pi processes apart. */
|
|
33
|
+
export function backgroundLogPath(id: string): string {
|
|
34
|
+
return join(termctrlTemporaryDirectory(), `${process.pid}-${id}.log`);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** What a backgrounded call reports to the agent. */
|
|
38
|
+
interface BackgroundOutcome {
|
|
39
|
+
readonly id: string;
|
|
40
|
+
readonly logPath: string;
|
|
41
|
+
readonly output: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* One agent `bash` call. Wraps Pi's local `exec` so the call can leave the tool call: it owns the
|
|
46
|
+
* abort controller and the timeout, and tees output into a buffer and, after backgrounding, a log.
|
|
47
|
+
*/
|
|
48
|
+
class BashCall {
|
|
49
|
+
private readonly controller = new AbortController();
|
|
50
|
+
private readonly chunks: Buffer[] = [];
|
|
51
|
+
private bufferedBytes = 0;
|
|
52
|
+
private droppedBytes = 0;
|
|
53
|
+
private recent = "";
|
|
54
|
+
private readonly decoder = new TextDecoder();
|
|
55
|
+
private log: WriteStream | undefined;
|
|
56
|
+
private timer: ReturnType<typeof setTimeout> | undefined;
|
|
57
|
+
private timedOut = false;
|
|
58
|
+
private started = false;
|
|
59
|
+
private startedAt = Date.now();
|
|
60
|
+
private settled = false;
|
|
61
|
+
private jobId: string | undefined;
|
|
62
|
+
private forwardData: ((data: Buffer) => void) | undefined;
|
|
63
|
+
private resolveBackground!: (outcome: BackgroundOutcome) => void;
|
|
64
|
+
readonly backgrounded: Promise<BackgroundOutcome>;
|
|
65
|
+
private isBackgrounded = false;
|
|
66
|
+
|
|
67
|
+
constructor(
|
|
68
|
+
private readonly owner: string,
|
|
69
|
+
private readonly command: string,
|
|
70
|
+
private readonly local: BashOperations,
|
|
71
|
+
) {
|
|
72
|
+
this.backgrounded = new Promise((resolve) => {
|
|
73
|
+
this.resolveBackground = resolve;
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The `BashOperations.exec` Pi's `execute` calls. */
|
|
78
|
+
async exec(
|
|
79
|
+
command: string,
|
|
80
|
+
cwd: string,
|
|
81
|
+
options: ExecOptions,
|
|
82
|
+
): Promise<{ exitCode: number | null }> {
|
|
83
|
+
const { timeout, signal, onData, env } = options;
|
|
84
|
+
if (timeout !== undefined) {
|
|
85
|
+
if (!Number.isFinite(timeout) || timeout <= 0) {
|
|
86
|
+
throw new Error("Invalid timeout: must be a finite number of seconds");
|
|
87
|
+
}
|
|
88
|
+
if (timeout * 1000 > MAX_TIMEOUT_MS) {
|
|
89
|
+
throw new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_MS / 1000} seconds`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (signal?.aborted) throw new Error("aborted");
|
|
93
|
+
this.forwardData = onData;
|
|
94
|
+
const forwardAbort = () => {
|
|
95
|
+
if (!this.isBackgrounded) this.controller.abort();
|
|
96
|
+
};
|
|
97
|
+
signal?.addEventListener("abort", forwardAbort, { once: true });
|
|
98
|
+
if (timeout !== undefined) {
|
|
99
|
+
this.timer = setTimeout(() => {
|
|
100
|
+
this.timedOut = true;
|
|
101
|
+
this.controller.abort();
|
|
102
|
+
}, timeout * 1000);
|
|
103
|
+
}
|
|
104
|
+
this.started = true;
|
|
105
|
+
this.startedAt = Date.now();
|
|
106
|
+
try {
|
|
107
|
+
const localOptions: ExecOptions = {
|
|
108
|
+
onData: (data) => this.receive(data),
|
|
109
|
+
signal: this.controller.signal,
|
|
110
|
+
};
|
|
111
|
+
if (env !== undefined) localOptions.env = env;
|
|
112
|
+
const result = await this.local.exec(command, cwd, localOptions);
|
|
113
|
+
this.finish({ code: result.exitCode, signal: null });
|
|
114
|
+
return result;
|
|
115
|
+
} catch (error) {
|
|
116
|
+
this.finish(this.controller.signal.aborted ? KILLED_EXIT : { code: null, signal: null });
|
|
117
|
+
if (this.timedOut && !this.isBackgrounded)
|
|
118
|
+
throw new Error(`timeout:${timeout}`, { cause: error });
|
|
119
|
+
throw error;
|
|
120
|
+
} finally {
|
|
121
|
+
this.settled = true;
|
|
122
|
+
clearTimeout(this.timer);
|
|
123
|
+
signal?.removeEventListener("abort", forwardAbort);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
private receive(data: Buffer): void {
|
|
128
|
+
if (this.isBackgrounded) {
|
|
129
|
+
this.log?.write(data);
|
|
130
|
+
this.remember(this.decoder.decode(data, { stream: true }));
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
this.chunks.push(data);
|
|
134
|
+
this.bufferedBytes += data.length;
|
|
135
|
+
while (this.bufferedBytes > BUFFER_LIMIT_BYTES && this.chunks.length > 1) {
|
|
136
|
+
const dropped = this.chunks.shift();
|
|
137
|
+
this.bufferedBytes -= dropped?.length ?? 0;
|
|
138
|
+
this.droppedBytes += dropped?.length ?? 0;
|
|
139
|
+
}
|
|
140
|
+
this.forwardData?.(data);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
private remember(text: string): void {
|
|
144
|
+
this.recent = (this.recent + text).slice(-TAIL_LIMIT_CHARS);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
private finish(exit: TerminalExit): void {
|
|
148
|
+
if (this.jobId === undefined) return;
|
|
149
|
+
this.remember(this.decoder.decode());
|
|
150
|
+
const log = this.log;
|
|
151
|
+
this.log = undefined;
|
|
152
|
+
log?.end();
|
|
153
|
+
TermctrlRegistry.current()?.jobExited(this.jobId, exit);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Move the running command to the background. Returns false when it already finished. */
|
|
157
|
+
background(registry: TermctrlRegistry): boolean {
|
|
158
|
+
if (this.isBackgrounded || this.settled || !this.started) return false;
|
|
159
|
+
// An aborted or timed-out command is already dying; let Pi report it.
|
|
160
|
+
if (this.controller.signal.aborted) return false;
|
|
161
|
+
const entry = registry.createJob(
|
|
162
|
+
this.owner,
|
|
163
|
+
this.command,
|
|
164
|
+
(id) => {
|
|
165
|
+
const logPath = backgroundLogPath(id);
|
|
166
|
+
mkdirSync(termctrlTemporaryDirectory(), { recursive: true });
|
|
167
|
+
this.log = createWriteStream(logPath, { fd: openSync(logPath, "w") });
|
|
168
|
+
this.log.on("error", () => {});
|
|
169
|
+
return {
|
|
170
|
+
logPath,
|
|
171
|
+
stop: () => this.controller.abort(),
|
|
172
|
+
tail: () => this.recent,
|
|
173
|
+
removeLog: async () => {
|
|
174
|
+
this.log?.end();
|
|
175
|
+
await rm(logPath, { force: true });
|
|
176
|
+
},
|
|
177
|
+
};
|
|
178
|
+
},
|
|
179
|
+
this.startedAt,
|
|
180
|
+
);
|
|
181
|
+
this.jobId = entry.id;
|
|
182
|
+
this.isBackgrounded = true;
|
|
183
|
+
clearTimeout(this.timer);
|
|
184
|
+
if (this.droppedBytes > 0) {
|
|
185
|
+
this.log?.write(
|
|
186
|
+
`[pi-termctrl: ${formatSize(this.droppedBytes)} of earlier output omitted]\n`,
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
for (const chunk of this.chunks) this.log?.write(chunk);
|
|
190
|
+
const output = this.decoder.decode(Buffer.concat(this.chunks), { stream: true });
|
|
191
|
+
this.chunks.length = 0;
|
|
192
|
+
this.remember(output);
|
|
193
|
+
this.resolveBackground({ id: entry.id, logPath: entry.child.logPath, output });
|
|
194
|
+
return true;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** The agent `bash` calls running in one session, and the Ctrl+B subscription while any run. */
|
|
199
|
+
export class RunningBashCalls {
|
|
200
|
+
private readonly calls = new Set<BashCall>();
|
|
201
|
+
private unsubscribe: (() => void) | undefined;
|
|
202
|
+
|
|
203
|
+
constructor(private readonly registry: () => TermctrlRegistry) {}
|
|
204
|
+
|
|
205
|
+
/** Track a call; the first one subscribes to Ctrl+B. */
|
|
206
|
+
add(call: BashCall, ui: ExtensionUIContext): void {
|
|
207
|
+
this.calls.add(call);
|
|
208
|
+
if (this.unsubscribe !== undefined) return;
|
|
209
|
+
this.unsubscribe = ui.onTerminalInput((data) => {
|
|
210
|
+
if (!matchesKey(data, "ctrl+b")) return undefined;
|
|
211
|
+
this.backgroundAll(ui);
|
|
212
|
+
return { consume: true };
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Stop tracking a call; the last one releases Ctrl+B back to the editor. */
|
|
217
|
+
delete(call: BashCall): void {
|
|
218
|
+
this.calls.delete(call);
|
|
219
|
+
if (this.calls.size > 0) return;
|
|
220
|
+
this.dispose();
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Move every running call to the background. */
|
|
224
|
+
backgroundAll(ui: Pick<ExtensionUIContext, "notify">): void {
|
|
225
|
+
for (const call of this.calls) {
|
|
226
|
+
try {
|
|
227
|
+
call.background(this.registry());
|
|
228
|
+
} catch (error) {
|
|
229
|
+
ui.notify(error instanceof Error ? error.message : String(error), "warning");
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
dispose(): void {
|
|
235
|
+
this.unsubscribe?.();
|
|
236
|
+
this.unsubscribe = undefined;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** Settings the replacement shares with Pi's built-in `bash`. */
|
|
241
|
+
export interface BashReplacementOptions {
|
|
242
|
+
readonly cwd: string;
|
|
243
|
+
readonly commandPrefix: string | undefined;
|
|
244
|
+
readonly shellPath: string | undefined;
|
|
245
|
+
readonly registry: () => TermctrlRegistry;
|
|
246
|
+
readonly calls: RunningBashCalls;
|
|
247
|
+
/** Builds Pi's `bash` definition; tests wrap it to observe what reaches Pi's accumulator. */
|
|
248
|
+
readonly definitionFactory?: typeof createBashToolDefinition;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function backgroundOutputSchema(builtin: TSchema | undefined) {
|
|
252
|
+
const properties = builtin !== undefined && Type.IsObject(builtin) ? builtin.properties : {};
|
|
253
|
+
return Type.Object({
|
|
254
|
+
...properties,
|
|
255
|
+
exit_code: Type.Optional(
|
|
256
|
+
Type.Number({ description: "Absent only when the command was moved to the background" }),
|
|
257
|
+
),
|
|
258
|
+
background: Type.Optional(
|
|
259
|
+
Type.Object(
|
|
260
|
+
{
|
|
261
|
+
id: Type.String({ description: "Background job id, for terminal_stop" }),
|
|
262
|
+
log_path: Type.String({ description: "File receiving the job's output; read it" }),
|
|
263
|
+
},
|
|
264
|
+
{ description: "Present when the command was moved to the background" },
|
|
265
|
+
),
|
|
266
|
+
),
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function backgroundResult(outcome: BackgroundOutcome, startedAt: number) {
|
|
271
|
+
const truncation = truncateTail(outcome.output);
|
|
272
|
+
let text = truncation.content;
|
|
273
|
+
if (truncation.truncated) {
|
|
274
|
+
text += `\n\n[Showing lines ${truncation.totalLines - truncation.outputLines + 1}-${truncation.totalLines} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} or ${DEFAULT_MAX_LINES} line limit). Full output: ${outcome.logPath}]`;
|
|
275
|
+
}
|
|
276
|
+
const status = `Command moved to the background as ${outcome.id}. Its output so far and all later output go to ${outcome.logPath}; read that file to check progress, and stop it with terminal_stop {"id": "${outcome.id}"}. You will get an Exit notification when it ends.`;
|
|
277
|
+
return {
|
|
278
|
+
content: [{ type: "text" as const, text: text === "" ? status : `${text}\n\n${status}` }],
|
|
279
|
+
details: undefined,
|
|
280
|
+
structuredContent: {
|
|
281
|
+
output: truncation.content,
|
|
282
|
+
truncated: truncation.truncated,
|
|
283
|
+
wall_time_seconds: Math.round((performance.now() - startedAt) / 100) / 10,
|
|
284
|
+
background: { id: outcome.id, log_path: outcome.logPath },
|
|
285
|
+
},
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** Pi's `bash` definition plus `background`, executed through Pi's own pipes. */
|
|
290
|
+
export function createBashReplacement(options: BashReplacementOptions) {
|
|
291
|
+
const builtinOptions: BashToolOptions = {};
|
|
292
|
+
if (options.commandPrefix !== undefined) builtinOptions.commandPrefix = options.commandPrefix;
|
|
293
|
+
if (options.shellPath !== undefined) builtinOptions.shellPath = options.shellPath;
|
|
294
|
+
const builtin = createBashToolDefinition(options.cwd, builtinOptions);
|
|
295
|
+
const local = createLocalBashOperations(
|
|
296
|
+
options.shellPath === undefined ? undefined : { shellPath: options.shellPath },
|
|
297
|
+
);
|
|
298
|
+
const parameters = Type.Object({
|
|
299
|
+
...builtin.parameters.properties,
|
|
300
|
+
background: Type.Optional(
|
|
301
|
+
Type.Boolean({
|
|
302
|
+
description:
|
|
303
|
+
"Run in the background if still running after 2 seconds; returns a Background job id and log path",
|
|
304
|
+
}),
|
|
305
|
+
),
|
|
306
|
+
});
|
|
307
|
+
return {
|
|
308
|
+
...builtin,
|
|
309
|
+
parameters,
|
|
310
|
+
outputSchema: backgroundOutputSchema(builtin.outputSchema),
|
|
311
|
+
async execute(
|
|
312
|
+
toolCallId: string,
|
|
313
|
+
params: { command: string; timeout?: number; background?: boolean },
|
|
314
|
+
signal: AbortSignal | undefined,
|
|
315
|
+
onUpdate: Parameters<typeof builtin.execute>[3],
|
|
316
|
+
context: ExtensionToolContext,
|
|
317
|
+
) {
|
|
318
|
+
const registry = options.registry();
|
|
319
|
+
const owner = context.sessionManager.getSessionId();
|
|
320
|
+
if (params.background === true) registry.checkCapacity(owner);
|
|
321
|
+
const call = new BashCall(owner, params.command, local);
|
|
322
|
+
const inner = (options.definitionFactory ?? createBashToolDefinition)(options.cwd, {
|
|
323
|
+
...builtinOptions,
|
|
324
|
+
operations: { exec: (command, cwd, execOptions) => call.exec(command, cwd, execOptions) },
|
|
325
|
+
});
|
|
326
|
+
let backgrounded = false;
|
|
327
|
+
const forwardUpdate: typeof onUpdate =
|
|
328
|
+
onUpdate === undefined
|
|
329
|
+
? undefined
|
|
330
|
+
: (update) => {
|
|
331
|
+
if (!backgrounded) onUpdate(update);
|
|
332
|
+
};
|
|
333
|
+
const startedAt = performance.now();
|
|
334
|
+
const running = inner.execute(
|
|
335
|
+
toolCallId,
|
|
336
|
+
params.timeout === undefined
|
|
337
|
+
? { command: params.command }
|
|
338
|
+
: { command: params.command, timeout: params.timeout },
|
|
339
|
+
signal,
|
|
340
|
+
forwardUpdate,
|
|
341
|
+
context,
|
|
342
|
+
);
|
|
343
|
+
running.catch(() => {});
|
|
344
|
+
options.calls.add(call, context.ui);
|
|
345
|
+
const yieldTimer =
|
|
346
|
+
params.background === true
|
|
347
|
+
? setTimeout(() => {
|
|
348
|
+
try {
|
|
349
|
+
call.background(registry);
|
|
350
|
+
} catch {
|
|
351
|
+
// The cap filled during the yield window; the command stays in the foreground.
|
|
352
|
+
}
|
|
353
|
+
}, BACKGROUND_YIELD_MS)
|
|
354
|
+
: undefined;
|
|
355
|
+
try {
|
|
356
|
+
const winner = await Promise.race([
|
|
357
|
+
running.then((result) => ({ kind: "finished" as const, result })),
|
|
358
|
+
call.backgrounded.then((outcome) => ({ kind: "background" as const, outcome })),
|
|
359
|
+
]);
|
|
360
|
+
if (winner.kind === "finished") return winner.result;
|
|
361
|
+
backgrounded = true;
|
|
362
|
+
return backgroundResult(winner.outcome, startedAt);
|
|
363
|
+
} finally {
|
|
364
|
+
clearTimeout(yieldTimer);
|
|
365
|
+
options.calls.delete(call);
|
|
366
|
+
}
|
|
367
|
+
},
|
|
368
|
+
};
|
|
369
|
+
}
|