pi-pier 0.4.1 → 0.4.2
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 +1 -2
- package/package.json +1 -1
- package/schemas/efficiency-config.schema.json +6 -0
- package/src/ask-dialog.ts +9 -2
- package/src/ask-user.ts +142 -74
- package/src/compact-coordinator.ts +204 -33
- package/src/compact-economics-core.ts +62 -29
- package/src/config-catalog-core.ts +1 -0
- package/src/delegation-core.ts +1 -1
- package/src/efficiency-config-core.ts +16 -2
- package/src/efficiency-store.ts +42 -5
- package/src/herdr-client.ts +15 -5
- package/src/index-pipe.ts +0 -8
- package/src/index.ts +69 -85
- package/src/jev-client.ts +32 -7
- package/src/jev-core.ts +70 -33
- package/src/observation-core.ts +13 -1
- package/src/pipe-channel.ts +0 -8
- package/src/plugins/heat-plan.ts +18 -3
- package/src/plugins/observation.ts +118 -46
- package/src/plugins/subagent.ts +53 -40
- package/src/plugins/terminal.ts +192 -47
- package/src/plugins/todo.ts +43 -21
- package/src/reducer-invoker.ts +27 -13
- package/src/renderers.ts +1 -13
- package/src/roles/worker-default.json +3 -3
- package/src/settle-wake-core.ts +8 -2
- package/src/subagent-core.ts +41 -3
- package/src/subagent-poller.ts +52 -18
- package/src/subagent-session.ts +67 -4
- package/src/subagent-spawn.ts +6 -5
- package/src/terminal-core.ts +111 -17
- package/src/todo-core.ts +47 -2
- package/src/todo-read-hook.ts +31 -17
- package/src/todo-reminder-core.ts +9 -5
- package/src/todo-window.ts +8 -4
- package/src/todos-service.ts +12 -0
- package/src/vocab.ts +7 -1
package/src/plugins/subagent.ts
CHANGED
|
@@ -84,24 +84,35 @@ export interface SubagentDeps {
|
|
|
84
84
|
logRouting?: (row: RoutingTelemetryRecord) => void;
|
|
85
85
|
}
|
|
86
86
|
|
|
87
|
+
/** Sent with every request: what a call needs. Details live in SUBAGENT_MANUAL (`action: "help"`). */
|
|
87
88
|
const SUBAGENT_DESCRIPTION = [
|
|
88
|
-
'Delegate a self-contained
|
|
89
|
-
'
|
|
90
|
-
'
|
|
91
|
-
'
|
|
92
|
-
'
|
|
93
|
-
'
|
|
94
|
-
'[spawn] `tab` (optional): name of a task tab to place the subagent into (join if a tab with this name exists, otherwise create it). Overrides the default placement. Default placement groups by git worktree: a subagent working in your checkout shares your tab; one working in a separate worktree (pass its path via `cwd`; create worktrees with `git worktree add`) gets its own tab named after the worktree directory.',
|
|
95
|
-
'[spawn] `role` + `allowed_tools`: when role matches a profile (searched: workspace .pi-herdr/roles/ → user-global ~/.pi/agent/herdr-pi/roles/ → builtin), the worker toolset becomes the composed manifest — baseline ∪ allowed_tools minus role-deny tools (deny always wins). Custom roles: drop a JSON profile into .pi-herdr/roles/ (master/worker-default reserved). Unknown role names remain display labels only.',
|
|
96
|
-
'[spawn] `isolate` (default false): creates a FRESH git worktree for this subagent and runs it there (branch pier/<slug> from your HEAD under ~/.herdr/worktrees/<repo>/). Three-way choice: heavy independent writing in parallel with your own edits or other workers, or work needing its own clean reviewable diff → isolate; read-mostly or sequential helper work → omit (shared checkout, writes guarded by the write-lock); targeting an existing directory/worktree → cwd. In isolate mode the subagent\'s writes cannot conflict with your checkout; its panes group into a tab named after the worktree; its prompt is prefixed with commit discipline (commit to its own branch, NEVER push); when it settles you get a diff summary (commits since base, files changed, uncommitted count). Review with git log/diff HEAD..<branch>, merge with git merge --no-ff <branch>; once merged and clean the worktree auto-removes (branch kept). Mutually exclusive with cwd.',
|
|
97
|
-
'[resume] `taskId`: revive a finished (collected) subagent from the delegation ledger — opens its saved conversation in a new pane (pi --session), then use action send to give it new work. The ledger is an append-only JSONL file, one row per status change (same taskId rows = generations, latest row is current): fields taskId, description, status (running|settled|consumed|closed), outcome (closing text), paneId, sessionFile, launchCommand, createdAt. Ledgers are per-checkout at ~/.pi/agent/herdr-pi/history/<flattened-cwd>/history.jsonl, but resume searches every checkout this master has spawned into, not only the current cwd. A still-running task is not resumed — use action send or output. Use action list for live panes.',
|
|
98
|
-
'[list] no extra parameters: list background subagents with live state (running / idle), pane ids, last activity, role, and descriptions. Foreground one-shot panes are not listed.',
|
|
99
|
-
'[output] `agentId` (required, the subagent pane id): view incremental output of a running or background subagent since the last output call. Text returned to the model is bounded (default 6000 chars) with status metadata (running/idle/blocked/settled), revision, and a truncated flag. When the delta cannot be computed the full text is returned with a "buffer scrolled or reset" note — that is normal for fullscreen TUI panes, not a crash indicator. Use this to observe subagent progress before settlement.',
|
|
100
|
-
'[interrupt] `agentId`: abort the current turn (fire-and-return). The pane stays; you can send again.',
|
|
101
|
-
'[role] `agentId` + `role`: switch that worker\'s role profile mid-session (pi 0.86 transcript tool delta — the new toolset applies on its next request and survives resume). Same role resolution as spawn; the reply reports the tool diff. Use when a task outgrew its delegation (needs more tools) or should be narrowed.',
|
|
102
|
-
'[send] `agentId` + `message`: follow-up to a background subagent. If working, delivered at next tool-call gap (steer, seconds); if idle, wakes a new turn. After settle, send to wake it; do not spawn a duplicate.',
|
|
89
|
+
'Delegate a self-contained task to a subagent: an isolated pi session in its own herdr pane (separate context — it does NOT see this conversation; a human can talk to it in that pane).',
|
|
90
|
+
'Actions (default spawn): spawn | send | output | list | interrupt | resume | role | help.',
|
|
91
|
+
'spawn: `prompt` is the COMPLETE task, since only the prompt reaches it; `description` labels the pane and is the todo-reconcile key — when delegating a todo entry, pass its content without the ` <sub>` marker and the entry auto-completes on settle. Several spawns in one message run in parallel (max 4).',
|
|
92
|
+
'A foreground spawn BLOCKS this call for up to ~5 minutes; pass run_in_background: true for long tasks. A background (or timed-out foreground) worker\'s settlement notice arrives automatically at your next tool boundary — no need to sleep or poll.',
|
|
93
|
+
'send: follow-up to a running or settled worker (steered between its tool calls). output: what it printed since your last check, plus its final report once done. resume: revive a collected task by taskId. role: switch a worker\'s role profile mid-session.',
|
|
94
|
+
'help: the full manual (isolate/cwd/tab placement, role profiles, the delegation ledger).',
|
|
103
95
|
].join(' ');
|
|
104
96
|
|
|
97
|
+
/** Returned by `action: "help"`: the reference text that used to ride every request. */
|
|
98
|
+
const SUBAGENT_MANUAL = [
|
|
99
|
+
'subagent manual',
|
|
100
|
+
'',
|
|
101
|
+
'spawn — the subagent shares this workspace and works independently; its result is its final text answer. Do not delegate the current step itself. Placement: by default panes group by git worktree — a subagent in your checkout shares your tab, one in a separate worktree gets its own tab named after the worktree directory. `tab` joins or creates a named task tab instead. `cwd` targets an existing directory or worktree (create worktrees with git worktree add).',
|
|
102
|
+
'',
|
|
103
|
+
'isolate (default false) — creates a FRESH git worktree (branch pier/<slug> from your HEAD under ~/.herdr/worktrees/<repo>/). Choose it for heavy independent writing in parallel with your own edits or other workers, or work needing its own clean reviewable diff; omit it for read-mostly or sequential helper work (shared checkout, writes guarded by the write-lock); use cwd for an existing directory/worktree. Its writes cannot conflict with your checkout, its prompt is prefixed with commit discipline (commit to its own branch, never push), and on settle you get a diff summary (commits since base, files changed, uncommitted count). Review with git log/diff HEAD..<branch>, merge with git merge --no-ff <branch>; once merged and clean the worktree auto-removes (branch kept). Mutually exclusive with cwd.',
|
|
104
|
+
'',
|
|
105
|
+
'role + allowed_tools — when role matches a profile (searched: workspace .pi-herdr/roles/ → user-global ~/.pi/agent/herdr-pi/roles/ → builtin), the worker toolset becomes baseline ∪ allowed_tools minus role-deny tools (deny always wins). Custom roles: drop a JSON profile into .pi-herdr/roles/ (master/worker-default reserved). Unknown role names stay display labels. action role switches a live worker (pi transcript tool delta: applies on its next request, survives resume); the reply reports the tool diff.',
|
|
106
|
+
'',
|
|
107
|
+
'list — background subagents with live state (running / idle), pane ids, last activity, role and description; foreground one-shot panes are not listed.',
|
|
108
|
+
'',
|
|
109
|
+
'output — `agentId` required; returns the delta since your last output call (default 6000 chars, max_chars 100-16000) with status (running/idle/blocked/settled), revision and a truncated flag. TUI chrome is stripped; once the worker has finished, the complete transcript report is attached. A "buffer scrolled or reset" note means the full text was returned — normal for fullscreen TUI panes.',
|
|
110
|
+
'',
|
|
111
|
+
'send — `agentId` + `message`: if working, delivered at its next tool-call gap (seconds); if idle or settled, wakes a new turn. Do not spawn a duplicate for the same task. interrupt — aborts its current turn; the pane stays and you can send again.',
|
|
112
|
+
'',
|
|
113
|
+
'resume — `taskId`: revives a collected subagent from the delegation ledger in a new pane (pi --session); then use send. The ledger is append-only JSONL, one row per status change (taskId, description, status running|settled|consumed|closed, outcome, paneId, sessionFile, launchCommand, createdAt), per checkout at ~/.pi/agent/herdr-pi/history/<flattened-cwd>/history.jsonl; resume searches every checkout this master spawned into. A still-running task is not resumed — use send or output.',
|
|
114
|
+
].join('\n');
|
|
115
|
+
|
|
105
116
|
const SUBAGENT_CONCURRENCY = 4;
|
|
106
117
|
|
|
107
118
|
function defaultAgentSessionsDir(): string {
|
|
@@ -224,8 +235,8 @@ export default function subagentPlugin(ctx: Context): void {
|
|
|
224
235
|
if (port.current === boundPort) port.current = null;
|
|
225
236
|
}, 'subagent-port');
|
|
226
237
|
|
|
227
|
-
const injectNotice = (content: string): Promise<void> => {
|
|
228
|
-
if (d.deliverNotice) return d.deliverNotice(content);
|
|
238
|
+
const injectNotice = (content: string, paneId?: string): Promise<void> => {
|
|
239
|
+
if (d.deliverNotice) return d.deliverNotice(content, paneId);
|
|
229
240
|
pi.sendUserMessage?.(content, { deliverAs: 'followUp' });
|
|
230
241
|
return Promise.resolve();
|
|
231
242
|
};
|
|
@@ -353,7 +364,7 @@ export default function subagentPlugin(ctx: Context): void {
|
|
|
353
364
|
[DELEGATION_ENV]: JSON.stringify({
|
|
354
365
|
parentPaneId: env?.paneId ?? '',
|
|
355
366
|
parentSessionId: bareSessionId(d.getSessionId()),
|
|
356
|
-
//
|
|
367
|
+
// todo_sync needs the master's pipe; kind 'task' maps to the composed default.
|
|
357
368
|
parentPipe: pipeNameFor(process.cwd(), env?.paneId ?? ''),
|
|
358
369
|
taskId: entry.taskId,
|
|
359
370
|
description: entry.description,
|
|
@@ -638,7 +649,9 @@ export default function subagentPlugin(ctx: Context): void {
|
|
|
638
649
|
const lines: string[] = [];
|
|
639
650
|
for (const sub of byTask.values()) {
|
|
640
651
|
const tabTag = sub.tabName ? ` [tab: ${sub.tabName}]` : '';
|
|
641
|
-
|
|
652
|
+
// The branch (`pier/<slug>`) is not a directory; printing it made masters cd into
|
|
653
|
+
// `<repo>/pier/<slug>`. Always print the absolute worktree path they can actually enter.
|
|
654
|
+
const wtTag = sub.isolate ? ` [wt: ${sub.isolate.worktreePath}]` : '';
|
|
642
655
|
if (sub.status === 'closed') {
|
|
643
656
|
lines.push(`${sub.taskId.slice(0, 8)} [idle] (${sub.kind}, closed; action send revives)${tabTag}${wtTag} ${sub.description}`);
|
|
644
657
|
continue;
|
|
@@ -692,6 +705,7 @@ export default function subagentPlugin(ctx: Context): void {
|
|
|
692
705
|
// carry the final report. No preferred file — start from herdr's per-pane report, not a stale registry value.
|
|
693
706
|
readFinalReport: async (paneId: string, entryCwd: string) =>
|
|
694
707
|
(await session.subSessionState(paneId, entryCwd, 0)).text,
|
|
708
|
+
persistSubs,
|
|
695
709
|
};
|
|
696
710
|
|
|
697
711
|
const ACTIONS: Record<string, (params: ToolParams, toolCtx: unknown, onUpdate?: (u: unknown) => void) => Promise<unknown>> = {
|
|
@@ -702,6 +716,7 @@ export default function subagentPlugin(ctx: Context): void {
|
|
|
702
716
|
interrupt: (params, toolCtx) => executeSubagentInterrupt(params, toolCtx),
|
|
703
717
|
output: (params, toolCtx) => executeSubagentOutput(params, toolCtx, outputActionDeps),
|
|
704
718
|
role: (params, toolCtx) => executeSubagentRole(params, toolCtx),
|
|
719
|
+
help: async () => ({ content: [{ type: 'text', text: SUBAGENT_MANUAL }], details: {} }),
|
|
705
720
|
};
|
|
706
721
|
|
|
707
722
|
scoped.registerTool({
|
|
@@ -709,15 +724,12 @@ export default function subagentPlugin(ctx: Context): void {
|
|
|
709
724
|
label: 'Subagent',
|
|
710
725
|
// B4: the model picks tools from the system prompt's snippet/guideline surface; delegation
|
|
711
726
|
// decisions are made here, so state them rather than hoping for recall.
|
|
712
|
-
promptSnippet: 'subagent: delegate a self-contained task to a pi worker pane (spawn/isolate/background/send/output/interrupt/resume/list/role).',
|
|
727
|
+
promptSnippet: 'subagent: delegate a self-contained task to a pi worker pane (spawn/isolate/background/send/output/interrupt/resume/list/role/help).',
|
|
713
728
|
promptGuidelines: [
|
|
714
|
-
'Use subagent
|
|
715
|
-
'
|
|
716
|
-
'Use isolate: true when the worker
|
|
717
|
-
'
|
|
718
|
-
'Do not poll with action: "output" in a tight loop: the pane pushes a settlement notice when it finishes. Check once, then continue other work.',
|
|
719
|
-
'Send follow-up instructions with action: "send" (delivered as a steer between tool calls) instead of spawning a second worker for the same task.',
|
|
720
|
-
'Pass agentId, taskId, message, and max_chars as top-level arguments. Do not wrap them in a parameters object.',
|
|
729
|
+
'Use subagent for self-contained work whose result is what matters: output that would flood this context, long builds/test runs, or independent parts of a bigger change that can run in parallel.',
|
|
730
|
+
'The worker does not see this conversation: put paths, acceptance criteria, the test command and what to report back into the prompt.',
|
|
731
|
+
'Use isolate: true when the worker writes files you or another worker edit at the same time, or when its work needs its own reviewable branch.',
|
|
732
|
+
'Pass agentId, taskId, message and max_chars as top-level arguments, not inside a parameters object.',
|
|
721
733
|
],
|
|
722
734
|
description: SUBAGENT_DESCRIPTION,
|
|
723
735
|
parameters: Type.Object({
|
|
@@ -729,19 +741,20 @@ export default function subagentPlugin(ctx: Context): void {
|
|
|
729
741
|
Type.Literal('interrupt'),
|
|
730
742
|
Type.Literal('output'),
|
|
731
743
|
Type.Literal('role'),
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
744
|
+
Type.Literal('help'),
|
|
745
|
+
], { description: 'Default spawn' })),
|
|
746
|
+
description: Type.Optional(Type.String({ description: '[spawn] Pane label; also the todo-reconcile key' })),
|
|
747
|
+
prompt: Type.Optional(Type.String({ description: '[spawn] The complete self-contained task' })),
|
|
748
|
+
run_in_background: Type.Optional(Type.Boolean({ description: '[spawn] Return at once; the settlement notice arrives later (default false)' })),
|
|
749
|
+
cwd: Type.Optional(Type.String({ description: '[spawn] Existing directory or worktree to run in (absolute or workspace-relative); exclusive with isolate' })),
|
|
750
|
+
isolate: Type.Optional(Type.Boolean({ description: '[spawn] Run in a fresh git worktree (branch pier/<slug>) for heavy parallel writes or a reviewable diff; settle reports a diff summary (see help)' })),
|
|
751
|
+
role: Type.Optional(Type.String({ description: '[spawn|role] Role profile name; unknown names are display labels only' })),
|
|
752
|
+
tab: Type.Optional(Type.String({ description: '[spawn] Task tab to join or create (default: grouped by worktree)' })),
|
|
753
|
+
allowed_tools: Type.Optional(Type.Array(Type.String(), { description: '[spawn] Extra tools on top of the role baseline' })),
|
|
754
|
+
taskId: Type.Optional(Type.String({ description: '[resume] Task id from the delegation ledger' })),
|
|
755
|
+
agentId: Type.Optional(Type.String({ description: '[send|interrupt|output|role] Slug, pane id, or slug@paneId as printed by spawn/list' })),
|
|
756
|
+
message: Type.Optional(Type.String({ description: '[send] Follow-up message' })),
|
|
757
|
+
max_chars: Type.Optional(Type.Integer({ description: '[output] Output cap (default 6000, 100-16000)' })),
|
|
745
758
|
}),
|
|
746
759
|
outputSchema: SUBAGENT_OUTPUT_SCHEMA,
|
|
747
760
|
// B2: `action` is optional in the schema; normalize it so the validated arguments and the
|
package/src/plugins/terminal.ts
CHANGED
|
@@ -4,6 +4,9 @@
|
|
|
4
4
|
* pi surface, the herdr client/environment and the state slot used by index GC; terminal-core holds the
|
|
5
5
|
* pure, independently testable logic.
|
|
6
6
|
*/
|
|
7
|
+
import { open } from 'node:fs/promises';
|
|
8
|
+
import { homedir } from 'node:os';
|
|
9
|
+
import { resolve as resolvePath } from 'node:path';
|
|
7
10
|
import { Context } from '@deepseek-ai/cordis';
|
|
8
11
|
import { Type } from 'typebox';
|
|
9
12
|
import { cordisGet } from '../cordis-services.ts';
|
|
@@ -18,14 +21,20 @@ import {
|
|
|
18
21
|
activeTerminalPaneIds,
|
|
19
22
|
classifyReadiness,
|
|
20
23
|
closeTerminal,
|
|
24
|
+
compilePattern,
|
|
21
25
|
computeIncrement,
|
|
22
26
|
classifyWaitMatch,
|
|
27
|
+
detectContinuationPrompt,
|
|
23
28
|
detectFullscreenTUI,
|
|
29
|
+
echoSafeWaitSuggestion,
|
|
30
|
+
excerptAroundMatch,
|
|
24
31
|
foldTerminalsRegistry,
|
|
25
32
|
makeTerminalsRegistry,
|
|
26
33
|
planTerminalReminder,
|
|
27
34
|
planShellInit,
|
|
28
35
|
promptStrategyFor,
|
|
36
|
+
regexLiteralPrefix,
|
|
37
|
+
redirectedSentinel,
|
|
29
38
|
registerTerminal,
|
|
30
39
|
sentinelEchoHazard,
|
|
31
40
|
stripAnsi,
|
|
@@ -45,7 +54,31 @@ type ToolParams = Record<string, unknown> | undefined;
|
|
|
45
54
|
/** Terminal tool actions; the tool schema union and the handler map are both keyed by this list. */
|
|
46
55
|
const TERMINAL_ACTIONS = ['open', 'send', 'wait', 'read', 'signal', 'close', 'list'] as const;
|
|
47
56
|
type TerminalAction = (typeof TERMINAL_ACTIONS)[number];
|
|
48
|
-
type ActionHandler = (params: ToolParams, ctx: unknown) => Promise<unknown>;
|
|
57
|
+
type ActionHandler = (params: ToolParams, ctx: unknown, signal?: AbortSignal) => Promise<unknown>;
|
|
58
|
+
|
|
59
|
+
/** File waits poll the log in-process; one tick per second keeps a 10-minute wait to ~600 reads. */
|
|
60
|
+
const FILE_WAIT_POLL_MS = 1000;
|
|
61
|
+
/** Only the log's tail is matched: a sentinel is the newest line, and a multi-GB log must not be read whole. */
|
|
62
|
+
const FILE_WAIT_TAIL_BYTES = 1024 * 1024;
|
|
63
|
+
|
|
64
|
+
/** The last `maxBytes` of a file as UTF-8, or null when it does not exist (yet). */
|
|
65
|
+
async function readFileTail(path: string, maxBytes: number): Promise<string | null> {
|
|
66
|
+
let handle;
|
|
67
|
+
try {
|
|
68
|
+
handle = await open(path, 'r');
|
|
69
|
+
} catch {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
try {
|
|
73
|
+
const { size } = await handle.stat();
|
|
74
|
+
const length = Math.min(size, maxBytes);
|
|
75
|
+
const buffer = Buffer.alloc(length);
|
|
76
|
+
await handle.read(buffer, 0, length, size - length);
|
|
77
|
+
return buffer.toString('utf8');
|
|
78
|
+
} finally {
|
|
79
|
+
await handle.close();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
49
82
|
|
|
50
83
|
export interface TerminalStateSlot {
|
|
51
84
|
/** Lets index GC preserve panes that host active terminals. */
|
|
@@ -172,19 +205,20 @@ export default function terminalPlugin(ctx: Context): void {
|
|
|
172
205
|
});
|
|
173
206
|
turnStartedAt = null;
|
|
174
207
|
if (!plan.due || plan.content == null) return;
|
|
175
|
-
//
|
|
176
|
-
//
|
|
177
|
-
|
|
178
|
-
const ids = new Set(plan.ids);
|
|
179
|
-
terminals = terminals.map((t) => (ids.has(t.terminalId)
|
|
180
|
-
? { ...t, nudges: (t.nudges ?? (t.nudgedAt != null ? 1 : 0)) + 1, nudgedAt: now }
|
|
181
|
-
: t));
|
|
182
|
-
persistTerminals();
|
|
208
|
+
// Deliver the notice as a queued followUp WITHOUT triggerTurn — a reminder must never wake the
|
|
209
|
+
// agent. The per-terminal count is bumped only when the timer fires: agent_start cancels the
|
|
210
|
+
// grace timer, and a cancelled reminder must not consume one of the two allowed nudges.
|
|
183
211
|
const content = plan.content;
|
|
184
212
|
idleReminderTimer = setTimeout(() => {
|
|
185
213
|
idleReminderTimer = null;
|
|
186
214
|
const send = piSend.sendMessage;
|
|
187
215
|
if (typeof send !== 'function') return;
|
|
216
|
+
const now = Date.now();
|
|
217
|
+
const ids = new Set(plan.ids);
|
|
218
|
+
terminals = terminals.map((t) => (ids.has(t.terminalId) && t.status === 'open'
|
|
219
|
+
? { ...t, nudges: (t.nudges ?? (t.nudgedAt != null ? 1 : 0)) + 1, nudgedAt: now }
|
|
220
|
+
: t));
|
|
221
|
+
persistTerminals();
|
|
188
222
|
try {
|
|
189
223
|
// Fire-and-forget in pi (void); a synchronous throw is still swallowed here.
|
|
190
224
|
send(
|
|
@@ -222,31 +256,29 @@ export default function terminalPlugin(ctx: Context): void {
|
|
|
222
256
|
name: 'terminal',
|
|
223
257
|
label: 'Terminal',
|
|
224
258
|
description: [
|
|
225
|
-
'
|
|
226
|
-
'
|
|
227
|
-
'
|
|
228
|
-
'Long job pattern: send "cmd; echo TERM_DONE_$?" then wait with regex "^TERM_DONE_[0-9]" — the shell echoes the typed command, so a literal wait on "TERM_DONE_" would match its own echo instantly; keep the sentinel distinguishable from its echo. Redirect verbose output to a log file and read the file, because output between two reads is lost.',
|
|
259
|
+
'Persistent interactive shells in dedicated herdr panes; cwd, environment and background processes survive across calls.',
|
|
260
|
+
'Actions: open, send (type a command), wait (block until output matches), read, signal (ctrl+c/ctrl+d/ctrl+z/esc/enter), close, list.',
|
|
261
|
+
'Long job: send "cmd; echo TERM_DONE_$?" and wait with regex "^TERM_DONE_[0-9]" — the shell echoes typed commands, so a literal "TERM_DONE_" would match its own echo. When output and sentinel go to a log ("cmd > run.log 2>&1; echo DONE_$? >> run.log"), wait with file: "run.log" instead of sleeping in bash.',
|
|
229
262
|
].join(' '),
|
|
230
263
|
promptSnippet: 'terminal: a persistent shell in its own pane — use for dev servers, REPLs, and multi-step shell work that must keep state between calls.',
|
|
231
264
|
promptGuidelines: [
|
|
232
|
-
'Prefer bash for one-shot commands
|
|
233
|
-
'
|
|
234
|
-
'
|
|
235
|
-
'wait is for output you expect (a sentinel, a startup line); it returns the recent tail on timeout so you can decide instead of re-polling.',
|
|
236
|
-
'Close the terminal as soon as the work is done — a finished terminal keeps occupying a pane and is never auto-reclaimed.',
|
|
265
|
+
'Prefer bash for one-shot commands. Use terminal only when state must persist (server, REPL, watch loop, interactive prompt) or output appears later; open once and reuse the terminal_id.',
|
|
266
|
+
'wait returns the recent tail on timeout, so decide from it instead of re-polling.',
|
|
267
|
+
'Close the terminal when the work is done — it occupies a pane and is never auto-reclaimed.',
|
|
237
268
|
],
|
|
238
269
|
parameters: Type.Object({
|
|
239
|
-
action: Type.Union(TERMINAL_ACTIONS.map((name) => Type.Literal(name))
|
|
240
|
-
cwd: Type.Optional(Type.String({ description: '[open]
|
|
241
|
-
terminal_id: Type.Optional(Type.String({ description: '[open]
|
|
242
|
-
text: Type.Optional(Type.String({ description: '[send] Command text
|
|
243
|
-
wait_prompt: Type.Optional(Type.Boolean({ description: '[send]
|
|
244
|
-
pattern: Type.Optional(Type.String({ description: '[wait] Literal text or
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
270
|
+
action: Type.Union(TERMINAL_ACTIONS.map((name) => Type.Literal(name))),
|
|
271
|
+
cwd: Type.Optional(Type.String({ description: '[open] Shell working directory (default: session cwd)' })),
|
|
272
|
+
terminal_id: Type.Optional(Type.String({ description: '[open] Optional id for the new terminal (default term-N); [others] id returned by open' })),
|
|
273
|
+
text: Type.Optional(Type.String({ description: '[send] Command text (Enter appended; multi-line runs line by line)' })),
|
|
274
|
+
wait_prompt: Type.Optional(Type.Boolean({ description: '[send] Refuse instead of queueing when the shell is not at a prompt' })),
|
|
275
|
+
pattern: Type.Optional(Type.String({ description: '[wait] Literal text or regex to wait for (must not occur in the sent command text)' })),
|
|
276
|
+
file: Type.Optional(Type.String({ description: '[wait] Watch this log file instead of the pane (relative to the terminal cwd; may not exist yet)' })),
|
|
277
|
+
regex: Type.Optional(Type.Boolean({ description: '[wait] pattern is a regex (default literal)' })),
|
|
278
|
+
timeout_ms: Type.Optional(Type.Number({ description: '[wait] Default 120000, max 600000' })),
|
|
279
|
+
pane_id: Type.Optional(Type.String({ description: '[read] Read another pane in your own tab' })),
|
|
280
|
+
max_chars: Type.Optional(Type.Number({ description: `[read] Output cap (default ${READ_MAX_CHARS})` })),
|
|
281
|
+
key: Type.Optional(Type.String({ description: '[signal] ctrl+c | ctrl+d | ctrl+z | esc | enter' })),
|
|
250
282
|
}),
|
|
251
283
|
async execute(_tc: string, params: ToolParams, _sig: AbortSignal | undefined, _upd: unknown, ctx: unknown) {
|
|
252
284
|
const action = typeof params?.action === 'string' ? params.action : '';
|
|
@@ -257,7 +289,7 @@ export default function terminalPlugin(ctx: Context): void {
|
|
|
257
289
|
? `unknown action "${action}" (valid: ${valid})`
|
|
258
290
|
: `action is required (${valid})`);
|
|
259
291
|
}
|
|
260
|
-
return handler(params, ctx);
|
|
292
|
+
return handler(params, ctx, _sig);
|
|
261
293
|
},
|
|
262
294
|
});
|
|
263
295
|
|
|
@@ -274,8 +306,9 @@ export default function terminalPlugin(ctx: Context): void {
|
|
|
274
306
|
}
|
|
275
307
|
}
|
|
276
308
|
|
|
277
|
-
/** Best-effort
|
|
278
|
-
* returns whether the command was injected, so a shell not
|
|
309
|
+
/** Best-effort history-expansion init right after a shell becomes usable (zsh needs
|
|
310
|
+
* `setopt NO_BANG_HIST`, bash `set +H`); returns whether the command was injected, so a shell not
|
|
311
|
+
* yet at its prompt retries later. */
|
|
279
312
|
async function injectShellInit(entry: TerminalEntry, readiness?: ReadinessTier): Promise<boolean> {
|
|
280
313
|
const init = planShellInit({ strategy: promptStrategyFor(), readiness });
|
|
281
314
|
if (!init.shouldInit || !init.command) return false;
|
|
@@ -301,12 +334,28 @@ export default function terminalPlugin(ctx: Context): void {
|
|
|
301
334
|
createdAt: Date.now(),
|
|
302
335
|
});
|
|
303
336
|
if (!r.ok) return fail(r.error);
|
|
337
|
+
// Stack new terminals below the most recent one instead of halving the pi master pane again:
|
|
338
|
+
// every right-split of the master shrinks both (45 → 22 → 11 columns), which breaks output
|
|
339
|
+
// wrapping and multi-word waits. The first terminal still splits the master to the right.
|
|
340
|
+
const anchor = [...terminals].reverse().find((t) => t.status === 'open') ?? null;
|
|
341
|
+
const targetPaneId = anchor?.paneId ?? env.paneId;
|
|
342
|
+
const direction = anchor ? 'down' : 'right';
|
|
304
343
|
let paneId: string;
|
|
305
344
|
try {
|
|
306
|
-
paneId = await client.splitPane({ direction
|
|
345
|
+
paneId = await client.splitPane({ direction, cwd, focus: false, targetPaneId });
|
|
307
346
|
} catch (e) {
|
|
308
|
-
|
|
309
|
-
|
|
347
|
+
if (!anchor) {
|
|
348
|
+
const hint = herdrUnavailableHint(e);
|
|
349
|
+
return fail(hint ?? `failed to split terminal pane: ${(e as Error).message}`);
|
|
350
|
+
}
|
|
351
|
+
// A terminal restored from an earlier session can point at a pane herdr no longer has: fall
|
|
352
|
+
// back to the master instead of failing to open at all.
|
|
353
|
+
try {
|
|
354
|
+
paneId = await client.splitPane({ direction: 'right', cwd, focus: false, targetPaneId: env.paneId });
|
|
355
|
+
} catch (fallbackError) {
|
|
356
|
+
const hint = herdrUnavailableHint(fallbackError);
|
|
357
|
+
return fail(hint ?? `failed to split terminal pane: ${(fallbackError as Error).message}`);
|
|
358
|
+
}
|
|
310
359
|
}
|
|
311
360
|
r.entry.paneId = paneId;
|
|
312
361
|
terminals = r.entries;
|
|
@@ -330,9 +379,10 @@ export default function terminalPlugin(ctx: Context): void {
|
|
|
330
379
|
const v = validateSendText(typeof params?.text === 'string' ? params.text : '');
|
|
331
380
|
if (!v.ok) return fail(v.error);
|
|
332
381
|
if (!entry.initialized) {
|
|
333
|
-
await injectShellInit(entry)
|
|
334
|
-
|
|
335
|
-
|
|
382
|
+
if (await injectShellInit(entry)) {
|
|
383
|
+
entry.initialized = true;
|
|
384
|
+
persistTerminals();
|
|
385
|
+
}
|
|
336
386
|
}
|
|
337
387
|
if (params?.wait_prompt === true) {
|
|
338
388
|
// Orchestration convention: read before writing. Text typed while a previous command still owns the
|
|
@@ -356,10 +406,31 @@ export default function terminalPlugin(ctx: Context): void {
|
|
|
356
406
|
// received, because the shell echoes typed commands back into the pane.
|
|
357
407
|
lastSentText.set(entry.terminalId, v.text);
|
|
358
408
|
touchTerminal(entry);
|
|
359
|
-
|
|
409
|
+
// An incomplete command leaves the shell at a secondary prompt (`dquote>`, `heredoc>`, …):
|
|
410
|
+
// every later send is swallowed by it, so surface the wedge instead of reporting success.
|
|
411
|
+
let pending: string | null = null;
|
|
412
|
+
try {
|
|
413
|
+
const snapshot = await client.readPane(entry.paneId, { stripAnsi: false });
|
|
414
|
+
pending = detectContinuationPrompt(stripAnsi(snapshot.text));
|
|
415
|
+
} catch {
|
|
416
|
+
/* A pane read is advisory here: a transport failure must not turn a successful send into an error. */
|
|
417
|
+
}
|
|
418
|
+
if (pending) {
|
|
419
|
+
return fail(
|
|
420
|
+
`shell is waiting for more input (${pending}) — the sent command left an incomplete quote, heredoc, or block, `
|
|
421
|
+
+ 'and later text is swallowed by that continuation prompt. Send the missing terminator, or interrupt with '
|
|
422
|
+
+ 'terminal(action: "signal", key: "ctrl+c"), then re-send a complete command.',
|
|
423
|
+
);
|
|
424
|
+
}
|
|
425
|
+
const hint = redirectedSentinel(v.text);
|
|
426
|
+
const fileHint = hint
|
|
427
|
+
? `\nnote: the sentinel ${hint.prefix}$? is written to ${hint.file}, not the pane — wait for it with `
|
|
428
|
+
+ `terminal(action: "wait", terminal_id: "${entry.terminalId}", file: "${hint.file}", pattern: "${echoSafeWaitSuggestion(hint.prefix) ?? hint.prefix}", regex: true) instead of sleeping.`
|
|
429
|
+
: '';
|
|
430
|
+
return { content: [{ type: 'text', text: `sent to ${entry.terminalId} (${v.text.length} chars)${fileHint}` }], details: { terminal_id: entry.terminalId } };
|
|
360
431
|
}
|
|
361
432
|
|
|
362
|
-
async function executeTerminalWait(params: ToolParams) {
|
|
433
|
+
async function executeTerminalWait(params: ToolParams, _ctx?: unknown, signal?: AbortSignal) {
|
|
363
434
|
const entry = findOpenTerminal(params?.terminal_id);
|
|
364
435
|
if (!entry) return fail(`unknown or closed terminal "${String(params?.terminal_id)}" (see action list)`);
|
|
365
436
|
// Waiting on a pane is use: keep it out of the "used this turn" cleanup nudge at settle.
|
|
@@ -369,23 +440,34 @@ export default function terminalPlugin(ctx: Context): void {
|
|
|
369
440
|
const useRegex = params?.regex === true;
|
|
370
441
|
if (useRegex) {
|
|
371
442
|
try {
|
|
372
|
-
|
|
443
|
+
compilePattern(raw);
|
|
373
444
|
} catch (e) {
|
|
374
445
|
return fail(`invalid regex: ${(e as Error).message}`);
|
|
375
446
|
}
|
|
376
447
|
}
|
|
448
|
+
if (typeof params?.file === 'string' && params.file.trim()) {
|
|
449
|
+
const file = params.file.trim();
|
|
450
|
+
const path = file.startsWith('~/') ? resolvePath(homedir(), file.slice(2)) : resolvePath(entry.cwd, file);
|
|
451
|
+
return waitForFile(entry, path, raw, useRegex, params, signal);
|
|
452
|
+
}
|
|
377
453
|
// The shell echoes typed commands into the pane, so a pattern contained in the last sent text
|
|
378
454
|
// matches its own echo and "succeeds" instantly, before the job finishes (observed: a
|
|
379
455
|
// minutes-long batch matched in 112ms on the echo of its own `echo SENTINEL`).
|
|
380
456
|
if (sentinelEchoHazard({ pattern: raw, regex: useRegex, lastSentText: lastSentText.get(entry.terminalId) })) {
|
|
381
457
|
const shown = raw.length > 80 ? `${raw.slice(0, 80)}…` : raw;
|
|
458
|
+
const literal = useRegex ? regexLiteralPrefix(raw) : raw;
|
|
459
|
+
const suggestion = echoSafeWaitSuggestion(literal);
|
|
460
|
+
const advice = suggestion
|
|
461
|
+
? `For future sends, use a sentinel distinguishable from its echo: send \`cmd; echo ${literal}$?\` and wait with regex "${suggestion}" `
|
|
462
|
+
+ '(the echoed command shows `$?`, which that regex cannot match).'
|
|
463
|
+
: 'For future sends, use a sentinel distinguishable from its echo: send `cmd; echo DONE_$?` and wait with regex "^DONE_[0-9]" '
|
|
464
|
+
+ '(the echo contains `DONE_$?`, which that regex cannot match).';
|
|
382
465
|
return fail(
|
|
383
466
|
`pattern "${shown}" also appears in the command text sent to ${entry.terminalId} — the shell echoes typed commands, `
|
|
384
467
|
+ 'so the wait would match its own echo and return before the job finishes. '
|
|
385
468
|
+ 'That command is still running: do NOT re-send it (text typed behind a running command just queues). '
|
|
386
469
|
+ 'Watch progress with action read, or wait for a marker the running command itself prints that does not occur in the command text. '
|
|
387
|
-
+
|
|
388
|
-
+ '(the echo contains `DONE_$?`, which that regex cannot match).',
|
|
470
|
+
+ advice,
|
|
389
471
|
);
|
|
390
472
|
}
|
|
391
473
|
const requested = typeof params?.timeout_ms === 'number' && params.timeout_ms > 0 ? params.timeout_ms : WAIT_DEFAULT_MS;
|
|
@@ -406,7 +488,10 @@ export default function terminalPlugin(ctx: Context): void {
|
|
|
406
488
|
tail = stripAnsi(read.text).slice(-WAIT_TAIL_CHARS);
|
|
407
489
|
} catch {
|
|
408
490
|
}
|
|
409
|
-
|
|
491
|
+
// A wait that consumed its budget is a timeout even when the failing RPC reports itself as
|
|
492
|
+
// unavailable: the distinction tells the model whether to re-check the command or the server.
|
|
493
|
+
const consumedBudget = Date.now() - started >= timeoutMs * 0.95;
|
|
494
|
+
const reason = waitResult.reason === 'timeout' || consumedBudget ? 'timeout' : 'wait unavailable';
|
|
410
495
|
return {
|
|
411
496
|
content: [{ type: 'text', text: `no match within ${timeoutMs}ms (${reason}).${tail ? `\nrecent output tail:\n${tail}` : ''}` }],
|
|
412
497
|
details: { terminal_id: entry.terminalId, matched: false, pattern: raw, reason },
|
|
@@ -418,7 +503,13 @@ export default function terminalPlugin(ctx: Context): void {
|
|
|
418
503
|
// waitForOutput (that busy-loops on the old match).
|
|
419
504
|
const deadline = started + timeoutMs;
|
|
420
505
|
const cursor: ReadCursor | null = entry.readRevision != null
|
|
421
|
-
? {
|
|
506
|
+
? {
|
|
507
|
+
revision: entry.readRevision,
|
|
508
|
+
len: entry.readLen ?? 0,
|
|
509
|
+
tail: entry.readTail ?? '',
|
|
510
|
+
textLen: entry.readTextLen ?? 0,
|
|
511
|
+
textHash: entry.readTextHash ?? 0,
|
|
512
|
+
}
|
|
422
513
|
: null;
|
|
423
514
|
const shown = raw.length > 80 ? `${raw.slice(0, 80)}…` : raw;
|
|
424
515
|
let sawStale = false;
|
|
@@ -460,6 +551,53 @@ export default function terminalPlugin(ctx: Context): void {
|
|
|
460
551
|
}
|
|
461
552
|
}
|
|
462
553
|
|
|
554
|
+
/** `wait` on a log file: the sentinel of a redirected job never reaches the pane. A match already in
|
|
555
|
+
* the file when the wait starts returns at once, labelled, so a leftover from an earlier run is visible. */
|
|
556
|
+
async function waitForFile(
|
|
557
|
+
entry: TerminalEntry,
|
|
558
|
+
path: string,
|
|
559
|
+
pattern: string,
|
|
560
|
+
useRegex: boolean,
|
|
561
|
+
params: ToolParams,
|
|
562
|
+
signal: AbortSignal | undefined,
|
|
563
|
+
) {
|
|
564
|
+
const requested = typeof params?.timeout_ms === 'number' && params.timeout_ms > 0 ? params.timeout_ms : WAIT_DEFAULT_MS;
|
|
565
|
+
const timeoutMs = Math.min(Math.max(requested, 1000), WAIT_MAX_MS);
|
|
566
|
+
const started = Date.now();
|
|
567
|
+
const matches = (text: string) => (useRegex ? compilePattern(pattern).test(text) : text.includes(pattern));
|
|
568
|
+
let text: string | null = null;
|
|
569
|
+
let wake: (() => void) | null = null;
|
|
570
|
+
const onAbort = () => wake?.();
|
|
571
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
572
|
+
try {
|
|
573
|
+
for (let tick = 0; ; tick += 1) {
|
|
574
|
+
text = await readFileTail(path, FILE_WAIT_TAIL_BYTES);
|
|
575
|
+
if (text !== null && matches(text)) {
|
|
576
|
+
const when = tick === 0 ? 'already present when the wait started (truncate the log per run if this is an old one)' : `appeared after ${Math.round((Date.now() - started) / 1000)}s`;
|
|
577
|
+
return {
|
|
578
|
+
content: [{ type: 'text', text: `matched in ${path} — ${when}:\n${excerptAroundMatch(text, pattern, useRegex)}` }],
|
|
579
|
+
details: { terminal_id: entry.terminalId, matched: true, pattern, file: path, alreadyPresent: tick === 0 },
|
|
580
|
+
};
|
|
581
|
+
}
|
|
582
|
+
const left = started + timeoutMs - Date.now();
|
|
583
|
+
if (left <= 0 || signal?.aborted) break;
|
|
584
|
+
const { promise, resolve } = Promise.withResolvers<void>();
|
|
585
|
+
wake = resolve;
|
|
586
|
+
const timer = setTimeout(resolve, Math.min(FILE_WAIT_POLL_MS, left));
|
|
587
|
+
await promise;
|
|
588
|
+
clearTimeout(timer);
|
|
589
|
+
}
|
|
590
|
+
} finally {
|
|
591
|
+
signal?.removeEventListener('abort', onAbort);
|
|
592
|
+
}
|
|
593
|
+
const reason = signal?.aborted ? 'aborted' : 'timeout';
|
|
594
|
+
const tail = text === null ? `\n${path} does not exist.` : text ? `\nrecent file tail:\n${text.slice(-WAIT_TAIL_CHARS)}` : `\n${path} is empty.`;
|
|
595
|
+
return {
|
|
596
|
+
content: [{ type: 'text', text: `no match in ${path} within ${timeoutMs}ms (${reason}).${tail}` }],
|
|
597
|
+
details: { terminal_id: entry.terminalId, matched: false, pattern, file: path, reason },
|
|
598
|
+
};
|
|
599
|
+
}
|
|
600
|
+
|
|
463
601
|
/** T5: a direct `pane_id` read is limited to panes in this session's own tab or to self-created terminal
|
|
464
602
|
* panes, so one task can never read another's pane. Returns the error text instead of throwing. */
|
|
465
603
|
async function resolveDirectPaneId(paneId: string): Promise<{ ok: true; paneId: string } | { ok: false; error: string }> {
|
|
@@ -514,7 +652,13 @@ export default function terminalPlugin(ctx: Context): void {
|
|
|
514
652
|
}
|
|
515
653
|
const prev: ReadCursor | null = entry
|
|
516
654
|
? (entry.readRevision != null
|
|
517
|
-
? {
|
|
655
|
+
? {
|
|
656
|
+
revision: entry.readRevision,
|
|
657
|
+
len: entry.readLen ?? 0,
|
|
658
|
+
tail: entry.readTail ?? '',
|
|
659
|
+
textLen: entry.readTextLen ?? 0,
|
|
660
|
+
textHash: entry.readTextHash ?? 0,
|
|
661
|
+
}
|
|
518
662
|
: null)
|
|
519
663
|
: null;
|
|
520
664
|
const inc = computeIncrement(prev, { text: read.text, revision: read.revision }, maxChars);
|
|
@@ -522,7 +666,8 @@ export default function terminalPlugin(ctx: Context): void {
|
|
|
522
666
|
entry.readRevision = inc.cursor.revision;
|
|
523
667
|
entry.readLen = inc.cursor.len;
|
|
524
668
|
entry.readTail = inc.cursor.tail;
|
|
525
|
-
entry.
|
|
669
|
+
entry.readTextLen = inc.cursor.textLen;
|
|
670
|
+
entry.readTextHash = inc.cursor.textHash;
|
|
526
671
|
touchTerminal(entry);
|
|
527
672
|
}
|
|
528
673
|
if (inc.mode === 'none') {
|