@tt-a1i/openpi 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/README.md +643 -0
- package/SETUP.md +74 -0
- package/THIRD_PARTY_NOTICES.md +16 -0
- package/assets/openpi-package.png +0 -0
- package/assets/readme-hero-mobile.svg +72 -0
- package/assets/readme-hero.svg +118 -0
- package/assets/readme-runtime-mobile.svg +91 -0
- package/assets/readme-runtime.svg +111 -0
- package/extensions/ask-user/handoff.ts +205 -0
- package/extensions/ask-user/index.ts +1110 -0
- package/extensions/ask-user/limits.ts +89 -0
- package/extensions/ask-user/prompt.ts +76 -0
- package/extensions/background-terminals/index.ts +653 -0
- package/extensions/background-terminals/src/domain.ts +99 -0
- package/extensions/background-terminals/src/manager.ts +989 -0
- package/extensions/background-terminals/src/output.ts +84 -0
- package/extensions/background-terminals/src/prompt.ts +195 -0
- package/extensions/background-terminals/src/result-delivery.ts +43 -0
- package/extensions/background-terminals/src/runtime.ts +36 -0
- package/extensions/background-terminals/src/ui/output-view.ts +55 -0
- package/extensions/background-terminals/src/ui/ps.ts +642 -0
- package/extensions/background-terminals/src/ui/tool-result.ts +146 -0
- package/extensions/background-terminals/src/watch.ts +192 -0
- package/extensions/context-pivot/index.ts +222 -0
- package/extensions/copy-all/index.ts +65 -0
- package/extensions/cron/index.ts +173 -0
- package/extensions/cron/schedule.ts +127 -0
- package/extensions/file-mutation-display/index.ts +105 -0
- package/extensions/file-mutation-display/render.ts +107 -0
- package/extensions/file-search/index.ts +515 -0
- package/extensions/file-search/src/args.ts +129 -0
- package/extensions/file-search/src/binaries.ts +419 -0
- package/extensions/file-search/src/output.ts +142 -0
- package/extensions/file-search/src/process.ts +309 -0
- package/extensions/file-search/src/prompt.ts +53 -0
- package/extensions/git-info/index.ts +272 -0
- package/extensions/git-info/src/changed-files-view.ts +414 -0
- package/extensions/git-info/src/process.ts +107 -0
- package/extensions/git-info/src/refresh-coordinator.ts +13 -0
- package/extensions/git-info/src/runtime.ts +28 -0
- package/extensions/goal/controller.ts +794 -0
- package/extensions/goal/index.ts +521 -0
- package/extensions/goal/prompts.ts +122 -0
- package/extensions/goal/state.ts +763 -0
- package/extensions/goal/ui.ts +158 -0
- package/extensions/model-info/index.ts +234 -0
- package/extensions/plan-mode/bash-policy.ts +313 -0
- package/extensions/plan-mode/index.ts +539 -0
- package/extensions/post-edit/index.ts +129 -0
- package/extensions/sessions/LICENSE.upstream +21 -0
- package/extensions/sessions/git-stats.ts +226 -0
- package/extensions/sessions/index.ts +1092 -0
- package/extensions/sessions/sessions.ts +385 -0
- package/extensions/setup/index.ts +408 -0
- package/extensions/shared/activity-status.ts +65 -0
- package/extensions/shared/below-editor-navigation.ts +343 -0
- package/extensions/shared/child-session.ts +352 -0
- package/extensions/shared/context-utilization.ts +47 -0
- package/extensions/shared/dashboard-state.ts +102 -0
- package/extensions/shared/plan-mode-state.ts +65 -0
- package/extensions/shared/setup-config.ts +971 -0
- package/extensions/shared/subagent-roles.ts +22 -0
- package/extensions/shared/terminal-text.ts +38 -0
- package/extensions/shared/tool-call-timeout.ts +104 -0
- package/extensions/shared/worktree.ts +526 -0
- package/extensions/subagents/index.ts +1225 -0
- package/extensions/subagents/navigation.ts +121 -0
- package/extensions/subagents/src/agent-types.ts +543 -0
- package/extensions/subagents/src/backend.ts +63 -0
- package/extensions/subagents/src/backends/pi.ts +493 -0
- package/extensions/subagents/src/backends/stub.ts +296 -0
- package/extensions/subagents/src/by-the-way.ts +21 -0
- package/extensions/subagents/src/domain.ts +271 -0
- package/extensions/subagents/src/format.ts +48 -0
- package/extensions/subagents/src/manager.ts +769 -0
- package/extensions/subagents/src/prompt.ts +190 -0
- package/extensions/subagents/src/result-delivery.ts +20 -0
- package/extensions/subagents/src/runtime.ts +51 -0
- package/extensions/subagents/src/ui/takeover.ts +615 -0
- package/extensions/subagents/src/ui/transcript.ts +293 -0
- package/extensions/subagents/src/ui/wait-result.ts +89 -0
- package/extensions/suggestions/index.ts +172 -0
- package/extensions/suggestions/src/config.ts +12 -0
- package/extensions/suggestions/src/predictor.ts +147 -0
- package/extensions/suggestions/src/prompt.ts +20 -0
- package/extensions/suggestions/src/transcript.ts +233 -0
- package/extensions/suggestions/src/ui.ts +224 -0
- package/extensions/tasks/index.ts +512 -0
- package/extensions/tasks/tasks.ts +649 -0
- package/extensions/tasks/ui.ts +421 -0
- package/extensions/turn-time/index.ts +61 -0
- package/extensions/ui-customization/footer.ts +512 -0
- package/extensions/ui-customization/index.ts +217 -0
- package/extensions/workflows/acceptance.ts +298 -0
- package/extensions/workflows/artifacts.ts +225 -0
- package/extensions/workflows/controller.ts +210 -0
- package/extensions/workflows/dashboard.ts +1226 -0
- package/extensions/workflows/index.ts +1884 -0
- package/extensions/workflows/journal.ts +188 -0
- package/extensions/workflows/meta.ts +250 -0
- package/extensions/workflows/model.ts +423 -0
- package/extensions/workflows/navigation.ts +93 -0
- package/extensions/workflows/prompt.ts +212 -0
- package/extensions/workflows/replay-safety.ts +577 -0
- package/extensions/workflows/runner.ts +786 -0
- package/extensions/workflows/sandbox-child.cjs +402 -0
- package/extensions/workflows/sandbox.ts +397 -0
- package/extensions/workflows/serialization.ts +162 -0
- package/extensions/workflows/worktree-handoff.ts +216 -0
- package/package.json +87 -0
- package/scripts/prepare-effect-tsgo.mjs +16 -0
- package/skills/background-terminals/SKILL.md +30 -0
- package/skills/subagents/SKILL.md +15 -0
- package/themes/github-dark-default.json +89 -0
|
@@ -0,0 +1,653 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Background terminals — start long-running shell processes the model can
|
|
3
|
+
* inspect and stop, but never write to (stdin is ignored at the OS level).
|
|
4
|
+
*
|
|
5
|
+
* Tools (for the LLM):
|
|
6
|
+
* - bg_start: fire-and-forget spawn (command, title, working_dir). Max 8
|
|
7
|
+
* running at once. The model is notified exactly once when a process exits.
|
|
8
|
+
* - bg_status: peek at one terminal's status + tail-truncated output.
|
|
9
|
+
* - bg_list: list all tracked terminals (running and settled).
|
|
10
|
+
* - bg_kill: SIGTERM→SIGKILL the whole process tree; returns final state.
|
|
11
|
+
*
|
|
12
|
+
* While ≥1 process runs, a one-line widget above the editor shows
|
|
13
|
+
* "N background terminal(s) running • /ps to view". `/ps` opens a two-stage
|
|
14
|
+
* full-screen overlay (list → read-only detail with stdout/stderr toggle).
|
|
15
|
+
*
|
|
16
|
+
* Architecture: Effect v4 core (manager service behind one ManagedRuntime);
|
|
17
|
+
* this file is the async boundary where tool handlers run effects via
|
|
18
|
+
* runTool. Node stream plumbing inside the manager is plain callbacks.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import * as fs from "node:fs";
|
|
22
|
+
import * as path from "node:path";
|
|
23
|
+
import type {
|
|
24
|
+
ExtensionAPI,
|
|
25
|
+
ExtensionContext,
|
|
26
|
+
ExtensionUIContext,
|
|
27
|
+
} from "@earendil-works/pi-coding-agent";
|
|
28
|
+
import { Type } from "typebox";
|
|
29
|
+
import { loadSetupConfig } from "../shared/setup-config.ts";
|
|
30
|
+
import { sanitizeTerminalText } from "../shared/terminal-text.ts";
|
|
31
|
+
import type { TerminalSnapshot } from "./src/domain.ts";
|
|
32
|
+
import { TerminalManager, type TerminalManagerShape } from "./src/manager.ts";
|
|
33
|
+
import {
|
|
34
|
+
BG_KILL_PARAMETER_DESCRIPTIONS,
|
|
35
|
+
BG_KILL_TOOL_DESCRIPTION,
|
|
36
|
+
BG_LIST_TOOL_DESCRIPTION,
|
|
37
|
+
BG_START_PARAMETER_DESCRIPTIONS,
|
|
38
|
+
BG_START_PROMPT_GUIDELINES,
|
|
39
|
+
BG_START_PROMPT_SNIPPET,
|
|
40
|
+
BG_START_TOOL_DESCRIPTION,
|
|
41
|
+
BG_STATUS_PARAMETER_DESCRIPTIONS,
|
|
42
|
+
BG_STATUS_TOOL_DESCRIPTION,
|
|
43
|
+
BG_WATCH_PARAMETER_DESCRIPTIONS,
|
|
44
|
+
BG_WATCH_TOOL_DESCRIPTION,
|
|
45
|
+
buildKillReport,
|
|
46
|
+
buildStartResult,
|
|
47
|
+
buildStatusResult,
|
|
48
|
+
buildTerminalResultMessage,
|
|
49
|
+
buildWatchArmedResult,
|
|
50
|
+
buildWatchMatchMessage,
|
|
51
|
+
describeTerminal,
|
|
52
|
+
} from "./src/prompt.ts";
|
|
53
|
+
import {
|
|
54
|
+
createDeferredResultDelivery,
|
|
55
|
+
resultDeliveryOptions,
|
|
56
|
+
} from "./src/result-delivery.ts";
|
|
57
|
+
import {
|
|
58
|
+
assertWatchableOutput,
|
|
59
|
+
compileWatchPattern,
|
|
60
|
+
createChunkMatcher,
|
|
61
|
+
matchCapturedOutput,
|
|
62
|
+
} from "./src/watch.ts";
|
|
63
|
+
import {
|
|
64
|
+
createTerminalRuntime,
|
|
65
|
+
runTool,
|
|
66
|
+
type TerminalRuntime,
|
|
67
|
+
} from "./src/runtime.ts";
|
|
68
|
+
import { openTerminalPicker } from "./src/ui/ps.ts";
|
|
69
|
+
import { renderTerminalResult } from "./src/ui/tool-result.ts";
|
|
70
|
+
|
|
71
|
+
const WIDGET_KEY = "background-terminals";
|
|
72
|
+
|
|
73
|
+
interface WatchToolDetails {
|
|
74
|
+
id: string;
|
|
75
|
+
pattern: string;
|
|
76
|
+
stream: "stdout" | "stderr" | "pending";
|
|
77
|
+
matched: boolean;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export default function (pi: ExtensionAPI) {
|
|
81
|
+
let runtime: TerminalRuntime | undefined;
|
|
82
|
+
let managerPromise: Promise<TerminalManagerShape> | undefined;
|
|
83
|
+
let sessionContext: ExtensionContext | undefined;
|
|
84
|
+
let ui: ExtensionUIContext | undefined;
|
|
85
|
+
let unsubStatus: (() => void) | undefined;
|
|
86
|
+
const resultDelivery = createDeferredResultDelivery<TerminalSnapshot>();
|
|
87
|
+
/** Active bg_watch disarm callbacks, keyed by terminal id (one per id). */
|
|
88
|
+
const watchers = new Map<string, () => void>();
|
|
89
|
+
|
|
90
|
+
const getRuntime = () => (runtime ??= createTerminalRuntime());
|
|
91
|
+
|
|
92
|
+
/** Resolve the manager service once per runtime and wire the extension hooks. */
|
|
93
|
+
const getManager = () => {
|
|
94
|
+
managerPromise ??= getRuntime()
|
|
95
|
+
.runPromise(TerminalManager)
|
|
96
|
+
.then((manager) => {
|
|
97
|
+
manager.view.setOnSettled(onSettled);
|
|
98
|
+
unsubStatus?.();
|
|
99
|
+
unsubStatus = manager.view.subscribe(() => updateWidget(manager));
|
|
100
|
+
updateWidget(manager);
|
|
101
|
+
return manager;
|
|
102
|
+
});
|
|
103
|
+
return managerPromise;
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
/** One-line widget directly above the editor, only while ≥1 is running.
|
|
107
|
+
* Called on every manager notification (including per-output-chunk), so it
|
|
108
|
+
* only touches setWidget when the running count actually changes —
|
|
109
|
+
* replacing the widget factory hundreds of times a second would churn
|
|
110
|
+
* component creation for no visible difference. */
|
|
111
|
+
let widgetRunning = 0;
|
|
112
|
+
const updateWidget = (manager: TerminalManagerShape) => {
|
|
113
|
+
if (!ui) return;
|
|
114
|
+
try {
|
|
115
|
+
const running = manager.view
|
|
116
|
+
.list()
|
|
117
|
+
.filter((snap) => snap.status === "running").length;
|
|
118
|
+
if (running === widgetRunning) return;
|
|
119
|
+
widgetRunning = running;
|
|
120
|
+
if (running === 0) {
|
|
121
|
+
ui.setWidget(WIDGET_KEY, undefined);
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
ui.setWidget(WIDGET_KEY, (_tui, theme) => {
|
|
125
|
+
const line =
|
|
126
|
+
theme.fg("warning", "■ ") +
|
|
127
|
+
theme.fg(
|
|
128
|
+
"text",
|
|
129
|
+
`${running} background terminal${running === 1 ? "" : "s"} running`,
|
|
130
|
+
) +
|
|
131
|
+
theme.fg("dim", " • ") +
|
|
132
|
+
theme.fg("accent", "/ps") +
|
|
133
|
+
theme.fg("dim", " to view");
|
|
134
|
+
return { render: () => [line], invalidate: () => {} };
|
|
135
|
+
});
|
|
136
|
+
} catch {
|
|
137
|
+
// UI may be unavailable (print/RPC modes or teardown).
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Deliver settled terminals to the model.
|
|
143
|
+
*
|
|
144
|
+
* `wake` decides whether this costs the model a turn. A result it is
|
|
145
|
+
* plausibly waiting for (it just went idle with work outstanding) is worth
|
|
146
|
+
* waking for. A backlog that piled up while it worked is not: delivering
|
|
147
|
+
* those with `triggerTurn` forces one whole turn per stale process, and the
|
|
148
|
+
* model can only answer each with "that one already finished" — exactly the
|
|
149
|
+
* noise a long-running session drowns in. `nextTurn` still puts them in
|
|
150
|
+
* context, alongside the user's next message, without demanding a reply.
|
|
151
|
+
*/
|
|
152
|
+
const deliverResults = (
|
|
153
|
+
snaps: readonly TerminalSnapshot[],
|
|
154
|
+
wake: boolean,
|
|
155
|
+
) => {
|
|
156
|
+
if (snaps.length === 0) return true;
|
|
157
|
+
try {
|
|
158
|
+
pi.sendMessage(
|
|
159
|
+
{
|
|
160
|
+
customType: "background-terminal-result",
|
|
161
|
+
// One message per flush, not per terminal: five processes exiting
|
|
162
|
+
// together are one event to react to, not five.
|
|
163
|
+
content: snaps.map(buildTerminalResultMessage).join("\n\n"),
|
|
164
|
+
display: true,
|
|
165
|
+
details:
|
|
166
|
+
snaps.length === 1
|
|
167
|
+
? {
|
|
168
|
+
id: snaps[0]!.id,
|
|
169
|
+
title: snaps[0]!.title,
|
|
170
|
+
status: snaps[0]!.status,
|
|
171
|
+
exitCode: snaps[0]!.exitCode,
|
|
172
|
+
signal: snaps[0]!.signal,
|
|
173
|
+
}
|
|
174
|
+
: {
|
|
175
|
+
count: snaps.length,
|
|
176
|
+
results: snaps.map((snap) => ({
|
|
177
|
+
id: snap.id,
|
|
178
|
+
title: snap.title,
|
|
179
|
+
status: snap.status,
|
|
180
|
+
exitCode: snap.exitCode,
|
|
181
|
+
signal: snap.signal,
|
|
182
|
+
})),
|
|
183
|
+
},
|
|
184
|
+
},
|
|
185
|
+
// followUp: queued until the agent has no more tool calls — never
|
|
186
|
+
// interrupts a mid-turn stream. triggerTurn only when the model is
|
|
187
|
+
// plausibly waiting; otherwise nextTurn, which enters context without
|
|
188
|
+
// costing a turn.
|
|
189
|
+
resultDeliveryOptions(wake),
|
|
190
|
+
);
|
|
191
|
+
return true;
|
|
192
|
+
} catch (error) {
|
|
193
|
+
// Session may be shutting down, but retain the snapshot so any later
|
|
194
|
+
// agent-settled flush can retry instead of silently dropping it.
|
|
195
|
+
console.error("background-terminals: failed to deliver result", error);
|
|
196
|
+
return false;
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
const flushResults = (wake: boolean) => {
|
|
201
|
+
const snaps = resultDelivery.drain();
|
|
202
|
+
if (!deliverResults(snaps, wake)) {
|
|
203
|
+
for (const snap of snaps) resultDelivery.defer(snap);
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
const onSettled = (snap: TerminalSnapshot, consumed: boolean) => {
|
|
208
|
+
// A settled terminal has delivered its final result and will emit no more
|
|
209
|
+
// output, so any watch armed on it can never match — disarm it now instead
|
|
210
|
+
// of leaking the listener until session shutdown.
|
|
211
|
+
watchers.get(snap.id)?.();
|
|
212
|
+
if (consumed) {
|
|
213
|
+
// An in-flight bg_kill is returning this settlement itself.
|
|
214
|
+
resultDelivery.consume([snap.id]);
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
// Defer a deep-enough copy: the live snapshot's output views keep
|
|
218
|
+
// mutating (late flushes) after settle.
|
|
219
|
+
resultDelivery.defer({
|
|
220
|
+
...snap,
|
|
221
|
+
stdout: { ...snap.stdout },
|
|
222
|
+
stderr: { ...snap.stderr },
|
|
223
|
+
});
|
|
224
|
+
// Settled while the model sits idle: it has nothing else in flight, so
|
|
225
|
+
// this is the result it is waiting on — wake it.
|
|
226
|
+
if (sessionContext?.isIdle()) flushResults(true);
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
pi.on("session_start", (_event, ctx) => {
|
|
230
|
+
sessionContext = ctx;
|
|
231
|
+
if (ctx.hasUI) ui = ctx.ui;
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
// Drain deferred results when the agent settles: together with the
|
|
235
|
+
// isIdle() fast path above and the Map-keyed delivery (drain clears),
|
|
236
|
+
// double delivery is structurally impossible — whoever drains first wins.
|
|
237
|
+
// These finished while the model was working on something else, so they go
|
|
238
|
+
// into context without forcing a turn per stale process.
|
|
239
|
+
pi.on("agent_settled", () => flushResults(false));
|
|
240
|
+
|
|
241
|
+
// /new, /resume, /fork, /reload, and quit all emit session_shutdown for
|
|
242
|
+
// the old extension instance. Processes never survive a session
|
|
243
|
+
// transition: disposing the runtime runs the manager finalizer →
|
|
244
|
+
// disposeAll → every entry scope → SIGTERM→SIGKILL tree kill, each close
|
|
245
|
+
// bounded so a wedged process cannot hang shutdown.
|
|
246
|
+
pi.on("session_shutdown", async () => {
|
|
247
|
+
sessionContext = undefined;
|
|
248
|
+
resultDelivery.clear();
|
|
249
|
+
for (const disarm of [...watchers.values()]) disarm();
|
|
250
|
+
watchers.clear();
|
|
251
|
+
unsubStatus?.();
|
|
252
|
+
unsubStatus = undefined;
|
|
253
|
+
try {
|
|
254
|
+
ui?.setWidget(WIDGET_KEY, undefined);
|
|
255
|
+
} catch {
|
|
256
|
+
// UI may already be gone.
|
|
257
|
+
}
|
|
258
|
+
widgetRunning = 0;
|
|
259
|
+
ui = undefined;
|
|
260
|
+
const closing = runtime;
|
|
261
|
+
runtime = undefined;
|
|
262
|
+
managerPromise = undefined;
|
|
263
|
+
await closing?.dispose();
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
// --- Tools -------------------------------------------------------------
|
|
267
|
+
|
|
268
|
+
pi.registerTool({
|
|
269
|
+
name: "bg_start",
|
|
270
|
+
label: "Start Background Terminal",
|
|
271
|
+
description: BG_START_TOOL_DESCRIPTION,
|
|
272
|
+
promptSnippet: BG_START_PROMPT_SNIPPET,
|
|
273
|
+
promptGuidelines: BG_START_PROMPT_GUIDELINES,
|
|
274
|
+
parameters: Type.Object({
|
|
275
|
+
command: Type.String({
|
|
276
|
+
description: BG_START_PARAMETER_DESCRIPTIONS.command,
|
|
277
|
+
}),
|
|
278
|
+
title: Type.String({
|
|
279
|
+
description: BG_START_PARAMETER_DESCRIPTIONS.title,
|
|
280
|
+
}),
|
|
281
|
+
working_dir: Type.Optional(
|
|
282
|
+
Type.String({
|
|
283
|
+
description: BG_START_PARAMETER_DESCRIPTIONS.workingDir,
|
|
284
|
+
}),
|
|
285
|
+
),
|
|
286
|
+
timeout_seconds: Type.Optional(
|
|
287
|
+
Type.Number({
|
|
288
|
+
minimum: 1,
|
|
289
|
+
maximum: 604_800,
|
|
290
|
+
description: BG_START_PARAMETER_DESCRIPTIONS.timeoutSeconds,
|
|
291
|
+
}),
|
|
292
|
+
),
|
|
293
|
+
}),
|
|
294
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
295
|
+
const manager = await getManager();
|
|
296
|
+
|
|
297
|
+
const command = params.command.trim();
|
|
298
|
+
if (!command) throw new Error("command must not be empty.");
|
|
299
|
+
|
|
300
|
+
const cwd = path.resolve(ctx.cwd, params.working_dir ?? ".");
|
|
301
|
+
if (!fs.existsSync(cwd) || !fs.statSync(cwd).isDirectory()) {
|
|
302
|
+
throw new Error(`working_dir is not a directory: ${cwd}`);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// Collapse whitespace (a newline inside a one-line UI row desyncs the
|
|
306
|
+
// TUI renderer) before bounding the length.
|
|
307
|
+
const title =
|
|
308
|
+
sanitizeTerminalText(params.title)
|
|
309
|
+
.replace(/\s+/g, " ")
|
|
310
|
+
.trim()
|
|
311
|
+
.slice(0, 80) || "terminal";
|
|
312
|
+
const snap = await runTool(
|
|
313
|
+
getRuntime(),
|
|
314
|
+
manager.start({
|
|
315
|
+
command,
|
|
316
|
+
title,
|
|
317
|
+
cwd,
|
|
318
|
+
timeoutSeconds: params.timeout_seconds,
|
|
319
|
+
}),
|
|
320
|
+
);
|
|
321
|
+
|
|
322
|
+
return {
|
|
323
|
+
content: [{ type: "text", text: buildStartResult(snap) }],
|
|
324
|
+
details: {
|
|
325
|
+
id: snap.id,
|
|
326
|
+
title: snap.title,
|
|
327
|
+
cwd,
|
|
328
|
+
pid: snap.pid,
|
|
329
|
+
timeoutAt: snap.timeoutAt,
|
|
330
|
+
},
|
|
331
|
+
};
|
|
332
|
+
},
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
pi.registerTool({
|
|
336
|
+
name: "bg_status",
|
|
337
|
+
label: "Check Background Terminal",
|
|
338
|
+
description: BG_STATUS_TOOL_DESCRIPTION,
|
|
339
|
+
parameters: Type.Object({
|
|
340
|
+
id: Type.String({ description: BG_STATUS_PARAMETER_DESCRIPTIONS.id }),
|
|
341
|
+
}),
|
|
342
|
+
async execute(_toolCallId, params) {
|
|
343
|
+
const manager = await getManager();
|
|
344
|
+
const snap = manager.view.get(params.id);
|
|
345
|
+
if (!snap) {
|
|
346
|
+
const known = manager.view.list().map((s) => s.id);
|
|
347
|
+
throw new Error(
|
|
348
|
+
`Unknown terminal id "${params.id}". Known: ${known.join(", ") || "none"}.`,
|
|
349
|
+
);
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// This status is returning the settlement itself; a pending automatic
|
|
353
|
+
// follow-up for the same settle would be a duplicate.
|
|
354
|
+
if (snap.status !== "running") resultDelivery.consume([snap.id]);
|
|
355
|
+
|
|
356
|
+
return {
|
|
357
|
+
content: [{ type: "text", text: buildStatusResult(snap) }],
|
|
358
|
+
details: {
|
|
359
|
+
id: snap.id,
|
|
360
|
+
status: snap.status,
|
|
361
|
+
pid: snap.pid,
|
|
362
|
+
exitCode: snap.exitCode,
|
|
363
|
+
signal: snap.signal,
|
|
364
|
+
timeoutAt: snap.timeoutAt,
|
|
365
|
+
},
|
|
366
|
+
};
|
|
367
|
+
},
|
|
368
|
+
renderResult(result, { expanded }, theme) {
|
|
369
|
+
const first = result.content[0];
|
|
370
|
+
const content = first?.type === "text" ? first.text : "(no output)";
|
|
371
|
+
return renderTerminalResult(
|
|
372
|
+
content,
|
|
373
|
+
expanded || loadSetupConfig().ui.bashToolDisplay === "full",
|
|
374
|
+
theme,
|
|
375
|
+
);
|
|
376
|
+
},
|
|
377
|
+
});
|
|
378
|
+
|
|
379
|
+
pi.registerTool({
|
|
380
|
+
name: "bg_list",
|
|
381
|
+
label: "List Background Terminals",
|
|
382
|
+
description: BG_LIST_TOOL_DESCRIPTION,
|
|
383
|
+
parameters: Type.Object({}),
|
|
384
|
+
async execute() {
|
|
385
|
+
const manager = await getManager();
|
|
386
|
+
const terminals = manager.view.list();
|
|
387
|
+
const text =
|
|
388
|
+
terminals.length === 0
|
|
389
|
+
? "No background terminals."
|
|
390
|
+
: terminals.map((snap) => describeTerminal(snap)).join("\n");
|
|
391
|
+
return {
|
|
392
|
+
content: [{ type: "text", text }],
|
|
393
|
+
details: {
|
|
394
|
+
terminals: terminals.map((snap) => ({
|
|
395
|
+
id: snap.id,
|
|
396
|
+
title: snap.title,
|
|
397
|
+
status: snap.status,
|
|
398
|
+
pid: snap.pid,
|
|
399
|
+
timeoutAt: snap.timeoutAt,
|
|
400
|
+
})),
|
|
401
|
+
},
|
|
402
|
+
};
|
|
403
|
+
},
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
pi.registerTool({
|
|
407
|
+
name: "bg_kill",
|
|
408
|
+
label: "Kill Background Terminals",
|
|
409
|
+
description: BG_KILL_TOOL_DESCRIPTION,
|
|
410
|
+
parameters: Type.Object({
|
|
411
|
+
ids: Type.Array(Type.String(), {
|
|
412
|
+
description: BG_KILL_PARAMETER_DESCRIPTIONS.ids,
|
|
413
|
+
}),
|
|
414
|
+
}),
|
|
415
|
+
async execute(_toolCallId, params, signal) {
|
|
416
|
+
const manager = await getManager();
|
|
417
|
+
const ids = [...new Set(params.ids)];
|
|
418
|
+
if (ids.length === 0)
|
|
419
|
+
throw new Error("Provide at least one terminal id.");
|
|
420
|
+
|
|
421
|
+
const known = manager.view.list().map((snap) => snap.id);
|
|
422
|
+
const unknown = ids.filter((id) => !manager.view.get(id));
|
|
423
|
+
if (unknown.length > 0) {
|
|
424
|
+
throw new Error(
|
|
425
|
+
`Unknown terminal id(s): ${unknown.join(", ")}. Known: ${known.join(", ") || "none"}.`,
|
|
426
|
+
);
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
const report = await runTool(getRuntime(), manager.kill(ids), {
|
|
430
|
+
signal,
|
|
431
|
+
interruptMessage:
|
|
432
|
+
"Kill wait aborted; termination continues in the background.",
|
|
433
|
+
});
|
|
434
|
+
|
|
435
|
+
// Settlement may have happened before this kill began (or during it,
|
|
436
|
+
// via the killInterest consumed flag). Remove any deferred automatic
|
|
437
|
+
// delivery now that this tool returns the final state itself.
|
|
438
|
+
resultDelivery.consume(ids);
|
|
439
|
+
|
|
440
|
+
return {
|
|
441
|
+
content: [{ type: "text", text: buildKillReport(report) }],
|
|
442
|
+
details: {
|
|
443
|
+
results: report.map((entry) => ({
|
|
444
|
+
id: entry.id,
|
|
445
|
+
title: entry.title,
|
|
446
|
+
status: entry.status,
|
|
447
|
+
killed: entry.killed,
|
|
448
|
+
})),
|
|
449
|
+
},
|
|
450
|
+
};
|
|
451
|
+
},
|
|
452
|
+
});
|
|
453
|
+
|
|
454
|
+
pi.registerTool({
|
|
455
|
+
name: "bg_watch",
|
|
456
|
+
label: "Watch Background Terminal",
|
|
457
|
+
description: BG_WATCH_TOOL_DESCRIPTION,
|
|
458
|
+
parameters: Type.Object({
|
|
459
|
+
id: Type.String({ description: BG_WATCH_PARAMETER_DESCRIPTIONS.id }),
|
|
460
|
+
pattern: Type.String({
|
|
461
|
+
minLength: 1,
|
|
462
|
+
description: BG_WATCH_PARAMETER_DESCRIPTIONS.pattern,
|
|
463
|
+
}),
|
|
464
|
+
}),
|
|
465
|
+
async execute(_toolCallId, params) {
|
|
466
|
+
const manager = await getManager();
|
|
467
|
+
const snap = manager.view.get(params.id);
|
|
468
|
+
if (!snap) {
|
|
469
|
+
const known = manager.view.list().map((s) => s.id);
|
|
470
|
+
throw new Error(
|
|
471
|
+
`Unknown terminal id "${params.id}". Known: ${known.join(", ") || "none"}.`,
|
|
472
|
+
);
|
|
473
|
+
}
|
|
474
|
+
if (snap.status !== "running") {
|
|
475
|
+
throw new Error(
|
|
476
|
+
`Terminal ${params.id} is already ${snap.status}; its result was delivered. Watches only apply to running terminals.`,
|
|
477
|
+
);
|
|
478
|
+
}
|
|
479
|
+
// Once a raw stream's head was evicted, it may begin inside a hidden
|
|
480
|
+
// control payload. Reject instead of risking a false readiness match.
|
|
481
|
+
assertWatchableOutput(snap.stdout, snap.stderr);
|
|
482
|
+
// Validate and compile the literal signatures eagerly so bad input is a
|
|
483
|
+
// tool error the model can fix, not a silent no-op watch.
|
|
484
|
+
const regex = compileWatchPattern(params.pattern);
|
|
485
|
+
const matcher = createChunkMatcher(regex);
|
|
486
|
+
|
|
487
|
+
let unsubscribe: (() => void) | undefined;
|
|
488
|
+
const disarm = () => {
|
|
489
|
+
unsubscribe?.();
|
|
490
|
+
unsubscribe = undefined;
|
|
491
|
+
watchers.delete(params.id);
|
|
492
|
+
};
|
|
493
|
+
// Replace any previous watch on this terminal: one watch per terminal
|
|
494
|
+
// keeps the "one-shot" contract unambiguous.
|
|
495
|
+
watchers.get(params.id)?.();
|
|
496
|
+
unsubscribe = manager.view.subscribeToChunks(
|
|
497
|
+
params.id,
|
|
498
|
+
(chunk, stream) => {
|
|
499
|
+
const hit = matcher.push(chunk, stream);
|
|
500
|
+
if (!hit) return;
|
|
501
|
+
disarm();
|
|
502
|
+
const current = manager.view.get(params.id);
|
|
503
|
+
try {
|
|
504
|
+
pi.sendMessage(
|
|
505
|
+
{
|
|
506
|
+
// Distinct from background-terminal-result: a match is not a
|
|
507
|
+
// settlement and must never touch the settle de-dup map.
|
|
508
|
+
customType: "background-terminal-match",
|
|
509
|
+
content: buildWatchMatchMessage({
|
|
510
|
+
id: params.id,
|
|
511
|
+
title: current?.title ?? snap.title,
|
|
512
|
+
pattern: params.pattern,
|
|
513
|
+
stream: hit.stream,
|
|
514
|
+
line: hit.line,
|
|
515
|
+
}),
|
|
516
|
+
display: true,
|
|
517
|
+
details: {
|
|
518
|
+
id: params.id,
|
|
519
|
+
pattern: params.pattern,
|
|
520
|
+
stream: hit.stream,
|
|
521
|
+
},
|
|
522
|
+
},
|
|
523
|
+
{ deliverAs: "followUp", triggerTurn: true },
|
|
524
|
+
);
|
|
525
|
+
} catch (error) {
|
|
526
|
+
console.error("background-terminals: watch delivery failed", error);
|
|
527
|
+
}
|
|
528
|
+
},
|
|
529
|
+
);
|
|
530
|
+
watchers.set(params.id, disarm);
|
|
531
|
+
|
|
532
|
+
// A fast process may have printed its readiness line before the model
|
|
533
|
+
// could arm the watch. Check retained output after subscribing so there
|
|
534
|
+
// is no gap between the historical scan and future chunks.
|
|
535
|
+
const existing = matchCapturedOutput(matcher, snap.stdout, snap.stderr);
|
|
536
|
+
if (existing) {
|
|
537
|
+
disarm();
|
|
538
|
+
const details: WatchToolDetails = {
|
|
539
|
+
id: params.id,
|
|
540
|
+
pattern: params.pattern,
|
|
541
|
+
stream: existing.stream,
|
|
542
|
+
matched: true,
|
|
543
|
+
};
|
|
544
|
+
return {
|
|
545
|
+
content: [
|
|
546
|
+
{
|
|
547
|
+
type: "text",
|
|
548
|
+
text: buildWatchMatchMessage({
|
|
549
|
+
id: params.id,
|
|
550
|
+
title: snap.title,
|
|
551
|
+
pattern: params.pattern,
|
|
552
|
+
stream: existing.stream,
|
|
553
|
+
line: existing.line,
|
|
554
|
+
}),
|
|
555
|
+
},
|
|
556
|
+
],
|
|
557
|
+
details,
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
const details: WatchToolDetails = {
|
|
562
|
+
id: params.id,
|
|
563
|
+
pattern: params.pattern,
|
|
564
|
+
stream: "pending",
|
|
565
|
+
matched: false,
|
|
566
|
+
};
|
|
567
|
+
return {
|
|
568
|
+
content: [
|
|
569
|
+
{
|
|
570
|
+
type: "text",
|
|
571
|
+
text: buildWatchArmedResult({
|
|
572
|
+
id: params.id,
|
|
573
|
+
title: snap.title,
|
|
574
|
+
pattern: params.pattern,
|
|
575
|
+
}),
|
|
576
|
+
},
|
|
577
|
+
],
|
|
578
|
+
details,
|
|
579
|
+
};
|
|
580
|
+
},
|
|
581
|
+
});
|
|
582
|
+
|
|
583
|
+
// --- Result message rendering ------------------------------------------
|
|
584
|
+
|
|
585
|
+
pi.registerMessageRenderer(
|
|
586
|
+
"background-terminal-result",
|
|
587
|
+
(message, { expanded }, theme) => {
|
|
588
|
+
const details = (message.details ?? {}) as {
|
|
589
|
+
id?: string;
|
|
590
|
+
title?: string;
|
|
591
|
+
status?: string;
|
|
592
|
+
exitCode?: number;
|
|
593
|
+
signal?: string;
|
|
594
|
+
};
|
|
595
|
+
const failed = details.status === "failed";
|
|
596
|
+
const killed = details.status === "killed";
|
|
597
|
+
const timedOut = details.status === "timed_out";
|
|
598
|
+
const icon =
|
|
599
|
+
failed || timedOut
|
|
600
|
+
? theme.fg("error", "x")
|
|
601
|
+
: killed
|
|
602
|
+
? theme.fg("muted", "■")
|
|
603
|
+
: theme.fg("success", "■");
|
|
604
|
+
const how = timedOut
|
|
605
|
+
? "timed out"
|
|
606
|
+
: killed
|
|
607
|
+
? "killed"
|
|
608
|
+
: (details.signal ?? `exit ${details.exitCode ?? "?"}`);
|
|
609
|
+
const header =
|
|
610
|
+
`${icon} ` +
|
|
611
|
+
theme.fg("accent", theme.bold(`terminal ${details.id ?? "?"}`)) +
|
|
612
|
+
theme.fg("muted", ` · ${details.title ?? ""} · ${how}`);
|
|
613
|
+
|
|
614
|
+
const content =
|
|
615
|
+
typeof message.content === "string" ? message.content : "";
|
|
616
|
+
return renderTerminalResult(
|
|
617
|
+
content,
|
|
618
|
+
expanded || loadSetupConfig().ui.bashToolDisplay === "full",
|
|
619
|
+
theme,
|
|
620
|
+
header,
|
|
621
|
+
);
|
|
622
|
+
},
|
|
623
|
+
);
|
|
624
|
+
|
|
625
|
+
// --- Command ------------------------------------------------------------
|
|
626
|
+
|
|
627
|
+
pi.registerCommand("ps", {
|
|
628
|
+
description: "List and inspect background terminals",
|
|
629
|
+
handler: async (_args, ctx) => {
|
|
630
|
+
const manager = await getManager();
|
|
631
|
+
if (ctx.mode !== "tui") {
|
|
632
|
+
if (ctx.hasUI) {
|
|
633
|
+
const terminals = manager.view.list();
|
|
634
|
+
ctx.ui.notify(
|
|
635
|
+
terminals.length === 0
|
|
636
|
+
? "No background terminals."
|
|
637
|
+
: terminals.map((snap) => describeTerminal(snap)).join("\n"),
|
|
638
|
+
"info",
|
|
639
|
+
);
|
|
640
|
+
}
|
|
641
|
+
return;
|
|
642
|
+
}
|
|
643
|
+
if (manager.view.size() === 0) {
|
|
644
|
+
ctx.ui.notify(
|
|
645
|
+
"No background terminals yet. The agent starts them with bg_start.",
|
|
646
|
+
"info",
|
|
647
|
+
);
|
|
648
|
+
return;
|
|
649
|
+
}
|
|
650
|
+
await openTerminalPicker(ctx, manager.view);
|
|
651
|
+
},
|
|
652
|
+
});
|
|
653
|
+
}
|