@wierdbytes/pi-wierdr 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/LICENSE +21 -0
- package/README.md +224 -2
- package/agents/agent-types.ts +154 -0
- package/agents/child.ts +224 -0
- package/agents/client.ts +76 -0
- package/agents/format.ts +76 -0
- package/agents/hc.ts +209 -0
- package/agents/index.ts +182 -0
- package/agents/launch.ts +117 -0
- package/agents/manager.ts +545 -0
- package/agents/models.ts +71 -0
- package/agents/prepare.ts +86 -0
- package/agents/render.ts +201 -0
- package/agents/rpc.ts +110 -0
- package/agents/runs.ts +122 -0
- package/agents/settings.ts +52 -0
- package/agents/tools.ts +217 -0
- package/herdr/bash-tool.ts +100 -0
- package/herdr/bash.ts +427 -0
- package/herdr/cache.ts +144 -0
- package/herdr/hc.ts +126 -0
- package/herdr/index.ts +187 -0
- package/herdr/limits-publisher.ts +118 -0
- package/herdr/limits.ts +458 -0
- package/herdr/meta.ts +111 -0
- package/herdr/publisher.ts +99 -0
- package/herdr/settings.ts +25 -0
- package/herdr/subagents.ts +72 -0
- package/index.ts +23 -0
- package/package.json +68 -4
- package/settings.ts +35 -0
package/agents/client.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A typed client for pi-wierdr's sub-agent `pi.events` RPC, for other extensions:
|
|
3
|
+
*
|
|
4
|
+
* ```ts
|
|
5
|
+
* import { agentsClient } from "@wierdbytes/pi-wierdr/client";
|
|
6
|
+
*
|
|
7
|
+
* const agents = agentsClient(pi.events);
|
|
8
|
+
* const a = await agents.spawn({ description: "Review diff", prompt: "…", model: "sonnet", thinking: "low" });
|
|
9
|
+
* const done = await agents.wait(a.id);
|
|
10
|
+
* console.log(done.status, done.result);
|
|
11
|
+
* ```
|
|
12
|
+
*
|
|
13
|
+
* Importing this file does not load the extension; pi-wierdr itself must be
|
|
14
|
+
* installed. `ping()` tells whether it is there and can start agents.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import type { AgentSnapshot } from "./manager.ts";
|
|
18
|
+
import type { SpawnInput } from "./prepare.ts";
|
|
19
|
+
import { type EventBus, type RpcMethods, type RpcReply, replyChannel, RPC_PREFIX } from "./rpc.ts";
|
|
20
|
+
|
|
21
|
+
export type { AgentSnapshot, SpawnInput, EventBus };
|
|
22
|
+
|
|
23
|
+
export interface AgentsClient {
|
|
24
|
+
ping(timeoutMs?: number): Promise<RpcMethods["ping"]["result"]>;
|
|
25
|
+
/** Always background; the parent model is not notified unless `notify: true`. */
|
|
26
|
+
spawn(input: Omit<SpawnInput, "background">): Promise<AgentSnapshot>;
|
|
27
|
+
get(id: string): Promise<AgentSnapshot>;
|
|
28
|
+
/** Until it finishes or needs a person. */
|
|
29
|
+
wait(id: string, timeoutMs?: number): Promise<AgentSnapshot>;
|
|
30
|
+
steer(id: string, message: string): Promise<AgentSnapshot & { mode: "steer" | "follow-up" }>;
|
|
31
|
+
stop(id: string): Promise<AgentSnapshot>;
|
|
32
|
+
list(): Promise<AgentSnapshot[]>;
|
|
33
|
+
/** `agents:spawned|running|blocked|completed|failed|stopped`. */
|
|
34
|
+
on(event: "spawned" | AgentSnapshot["status"], handler: (agent: AgentSnapshot) => void): () => void;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
let counter = 0;
|
|
38
|
+
|
|
39
|
+
export function agentsClient(events: EventBus, defaultTimeoutMs = 30_000): AgentsClient {
|
|
40
|
+
const request = <M extends keyof RpcMethods>(
|
|
41
|
+
method: M,
|
|
42
|
+
params: RpcMethods[M]["params"],
|
|
43
|
+
timeoutMs: number | undefined = defaultTimeoutMs,
|
|
44
|
+
): Promise<RpcMethods[M]["result"]> => {
|
|
45
|
+
const requestId = `${Date.now().toString(36)}-${(counter++).toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
|
|
46
|
+
return new Promise((resolve, reject) => {
|
|
47
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
48
|
+
const off = events.on(replyChannel(method, requestId), (raw) => {
|
|
49
|
+
off();
|
|
50
|
+
if (timer) clearTimeout(timer);
|
|
51
|
+
const reply = raw as RpcReply<RpcMethods[M]["result"]>;
|
|
52
|
+
if (reply?.success) resolve(reply.data);
|
|
53
|
+
else reject(new Error(reply?.error ?? "pi-wierdr: bad reply"));
|
|
54
|
+
});
|
|
55
|
+
if (timeoutMs !== undefined && timeoutMs > 0) {
|
|
56
|
+
timer = setTimeout(() => {
|
|
57
|
+
off();
|
|
58
|
+
reject(new Error(`pi-wierdr: ${method} got no reply (is @wierdbytes/pi-wierdr installed?)`));
|
|
59
|
+
}, timeoutMs);
|
|
60
|
+
}
|
|
61
|
+
events.emit(`${RPC_PREFIX}${method}`, { ...params, requestId });
|
|
62
|
+
});
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
return {
|
|
66
|
+
ping: (timeoutMs = 1000) => request("ping", {}, timeoutMs),
|
|
67
|
+
spawn: (input) => request("spawn", input as SpawnInput, 60_000),
|
|
68
|
+
get: (id) => request("get", { id }),
|
|
69
|
+
// The RPC itself waits; give it room beyond the agent's own timeout.
|
|
70
|
+
wait: (id, timeoutMs) => request("wait", { id, timeoutMs }, timeoutMs ? timeoutMs + 5000 : 0),
|
|
71
|
+
steer: (id, message) => request("steer", { id, message }, 120_000),
|
|
72
|
+
stop: (id) => request("stop", { id }),
|
|
73
|
+
list: () => request("list", {}),
|
|
74
|
+
on: (event, handler) => events.on(`agents:${event}`, (d) => handler(d as AgentSnapshot)),
|
|
75
|
+
};
|
|
76
|
+
}
|
package/agents/format.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/** What the parent's model reads about a sub-agent. Plain text, no ANSI. */
|
|
2
|
+
|
|
3
|
+
import type { AgentSnapshot } from "./manager.ts";
|
|
4
|
+
|
|
5
|
+
export function duration(ms: number): string {
|
|
6
|
+
const s = Math.max(0, Math.round(ms / 1000));
|
|
7
|
+
if (s < 60) return `${s}s`;
|
|
8
|
+
const m = Math.floor(s / 60);
|
|
9
|
+
if (m < 60) return `${m}m${s % 60 ? `${String(s % 60).padStart(2, "0")}s` : ""}`;
|
|
10
|
+
const h = Math.floor(m / 60);
|
|
11
|
+
return `${h}h${m % 60 ? `${String(m % 60).padStart(2, "0")}m` : ""}`;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** `950`, `4.2k`, `45k`, `1.2M` */
|
|
15
|
+
export function tokens(n: number): string {
|
|
16
|
+
if (n < 1000) return `${n}`;
|
|
17
|
+
if (n < 10_000) return `${(n / 1000).toFixed(1)}k`;
|
|
18
|
+
if (n < 1_000_000) return `${Math.round(n / 1000)}k`;
|
|
19
|
+
if (n < 10_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
|
|
20
|
+
return `${Math.round(n / 1_000_000)}M`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const elapsed = (s: AgentSnapshot, now = Date.now()): number => (s.endedAt ?? now) - s.startedAt;
|
|
24
|
+
|
|
25
|
+
export function activityText(s: AgentSnapshot): string | undefined {
|
|
26
|
+
const a = s.activity;
|
|
27
|
+
if (!a || a.tools === 0) return undefined;
|
|
28
|
+
const last = a.tool ? `, last: ${a.tool}${a.detail ? ` ${a.detail}` : ""}` : "";
|
|
29
|
+
return `${a.tools} tool call${a.tools === 1 ? "" : "s"}${last}`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** `Agent "Find auth code" [find-auth-code · t8c]` */
|
|
33
|
+
export const label = (s: AgentSnapshot): string => `Agent "${s.description}" [${s.id} · ${s.address}]`;
|
|
34
|
+
|
|
35
|
+
export function statusLine(s: AgentSnapshot, now = Date.now()): string {
|
|
36
|
+
const took = duration(elapsed(s, now));
|
|
37
|
+
const act = activityText(s);
|
|
38
|
+
switch (s.status) {
|
|
39
|
+
case "running":
|
|
40
|
+
return `${label(s)} is still working (${took}${act ? `, ${act}` : ""}).`;
|
|
41
|
+
case "blocked":
|
|
42
|
+
return `${label(s)} is blocked waiting for a person${s.hcMessage ? ` (${s.hcMessage})` : ""}. It is in herdr under this agent; ask the user to answer it there.`;
|
|
43
|
+
case "completed":
|
|
44
|
+
return `${label(s)} completed in ${took}${s.activity?.tools ? ` (${s.activity.tools} tool calls)` : ""}${s.error === "interrupted" ? ", interrupted by a person" : ""}.`;
|
|
45
|
+
case "failed":
|
|
46
|
+
return `${label(s)} failed after ${took}: ${s.error ?? "unknown error"}`;
|
|
47
|
+
case "stopped":
|
|
48
|
+
return `${label(s)} was stopped after ${took}.`;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const NEXT_STEPS =
|
|
53
|
+
"It stays open, idle, in herdr: steer_subagent sends it a follow-up, stop_subagent closes it.";
|
|
54
|
+
|
|
55
|
+
export function forModel(s: AgentSnapshot, now = Date.now()): string {
|
|
56
|
+
const parts = [statusLine(s, now)];
|
|
57
|
+
if (s.status === "completed" || s.status === "failed" || s.status === "stopped") {
|
|
58
|
+
if (s.result) parts.push("", s.result);
|
|
59
|
+
else if (s.status === "completed") parts.push("", "(no final message)");
|
|
60
|
+
if (s.status !== "stopped" && s.live) parts.push("", NEXT_STEPS);
|
|
61
|
+
}
|
|
62
|
+
return parts.join("\n");
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function startedText(s: AgentSnapshot): string {
|
|
66
|
+
return [
|
|
67
|
+
`Started ${label(s)} in the background${s.model ? ` on ${s.model}${s.thinking ? ` @${s.thinking}` : ""}` : ""}.`,
|
|
68
|
+
`You'll get its result as a message when it finishes; get_subagent_result with wait: true blocks for it, steer_subagent sends it more instructions.`,
|
|
69
|
+
].join("\n");
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function notificationText(list: readonly AgentSnapshot[], now = Date.now()): string {
|
|
73
|
+
return list
|
|
74
|
+
.map((s) => `<subagent id="${s.id}" terminal="${s.address}" status="${s.status}">\n${forModel(s, now)}\n</subagent>`)
|
|
75
|
+
.join("\n\n");
|
|
76
|
+
}
|
package/agents/hc.ts
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A small herdr-core client: JSON-RPC over the socket herdr-core hands every
|
|
3
|
+
* terminal (`HC_TERMINAL_SOCKET`). One connection per request, plus a
|
|
4
|
+
* long-lived `events.subscribe` stream that reconnects on its own.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import net from "node:net";
|
|
8
|
+
|
|
9
|
+
export interface HcEndpoint {
|
|
10
|
+
/** herdr-core's socket path. */
|
|
11
|
+
socket: string;
|
|
12
|
+
/** The terminal this pi runs in (`t12`): the parent of every sub-agent it starts. */
|
|
13
|
+
terminal: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** The terminal pi runs in, when herdr-core started it. */
|
|
17
|
+
export function endpointFromEnv(env: NodeJS.ProcessEnv = process.env): HcEndpoint | undefined {
|
|
18
|
+
const socket = env.HC_TERMINAL_SOCKET;
|
|
19
|
+
const terminal = env.HC_TERMINAL_ID;
|
|
20
|
+
if (!socket || !terminal) return undefined;
|
|
21
|
+
return { socket, terminal };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export class HcError extends Error {
|
|
25
|
+
constructor(
|
|
26
|
+
message: string,
|
|
27
|
+
readonly kind?: string,
|
|
28
|
+
readonly hint?: string,
|
|
29
|
+
) {
|
|
30
|
+
super(message);
|
|
31
|
+
this.name = "HcError";
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const endpointPath = (socket: string): string =>
|
|
36
|
+
process.platform === "win32" ? `\\\\.\\pipe\\${socket}` : socket;
|
|
37
|
+
|
|
38
|
+
let nextId = 1;
|
|
39
|
+
|
|
40
|
+
export interface CallOptions {
|
|
41
|
+
timeoutMs?: number;
|
|
42
|
+
signal?: AbortSignal;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** One request, one connection. Rejects with HcError on an RPC error, a timeout or a dead socket. */
|
|
46
|
+
export function hcCall<T = unknown>(
|
|
47
|
+
socket: string,
|
|
48
|
+
method: string,
|
|
49
|
+
params: Record<string, unknown>,
|
|
50
|
+
{ timeoutMs = 15_000, signal }: CallOptions = {},
|
|
51
|
+
): Promise<T> {
|
|
52
|
+
const id = nextId++;
|
|
53
|
+
return new Promise<T>((resolve, reject) => {
|
|
54
|
+
if (signal?.aborted) {
|
|
55
|
+
reject(new HcError("aborted", "aborted"));
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
let done = false;
|
|
59
|
+
let buffer = "";
|
|
60
|
+
const conn = net.createConnection(endpointPath(socket));
|
|
61
|
+
const finish = (err: Error | undefined, value?: T) => {
|
|
62
|
+
if (done) return;
|
|
63
|
+
done = true;
|
|
64
|
+
clearTimeout(timer);
|
|
65
|
+
signal?.removeEventListener("abort", onAbort);
|
|
66
|
+
conn.destroy();
|
|
67
|
+
if (err) reject(err);
|
|
68
|
+
else resolve(value as T);
|
|
69
|
+
};
|
|
70
|
+
const onAbort = () => finish(new HcError("aborted", "aborted"));
|
|
71
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
72
|
+
const timer = setTimeout(() => finish(new HcError(`herdr-core: ${method} timed out`, "timeout")), timeoutMs);
|
|
73
|
+
timer.unref?.();
|
|
74
|
+
conn.on("error", (e) => finish(new HcError(`herdr-core unreachable: ${e.message}`, "unreachable")));
|
|
75
|
+
conn.on("end", () => finish(new HcError(`herdr-core closed the connection during ${method}`, "closed")));
|
|
76
|
+
conn.on("connect", () => conn.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`));
|
|
77
|
+
conn.on("data", (chunk) => {
|
|
78
|
+
buffer += chunk.toString("utf8");
|
|
79
|
+
let newline: number;
|
|
80
|
+
while ((newline = buffer.indexOf("\n")) !== -1) {
|
|
81
|
+
const line = buffer.slice(0, newline);
|
|
82
|
+
buffer = buffer.slice(newline + 1);
|
|
83
|
+
let reply: any;
|
|
84
|
+
try {
|
|
85
|
+
reply = JSON.parse(line);
|
|
86
|
+
} catch {
|
|
87
|
+
finish(new HcError("herdr-core sent invalid JSON", "parse"));
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
if (reply?.id !== id) continue;
|
|
91
|
+
if (reply.error) {
|
|
92
|
+
const data = reply.error.data ?? {};
|
|
93
|
+
finish(new HcError(String(reply.error.message ?? "herdr-core error"), data.kind, data.hint));
|
|
94
|
+
} else finish(undefined, reply.result as T);
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** A terminal as herdr-core describes it (the fields this package reads). */
|
|
102
|
+
export interface HcTerminal {
|
|
103
|
+
address: string;
|
|
104
|
+
name?: string | null;
|
|
105
|
+
parent?: string | null;
|
|
106
|
+
state: "live" | "finished" | string;
|
|
107
|
+
status?: { app?: string; state: string; msg?: string; kind?: string | null } | null;
|
|
108
|
+
turn?: number;
|
|
109
|
+
labels?: Record<string, string>;
|
|
110
|
+
exit_code?: number | null;
|
|
111
|
+
reason?: string | null;
|
|
112
|
+
cwd?: string;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export interface HcEvent {
|
|
116
|
+
type: string;
|
|
117
|
+
terminal: string;
|
|
118
|
+
seq?: number;
|
|
119
|
+
data: any;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export interface SubscriptionHandlers {
|
|
123
|
+
/** The matching terminals at (re)connect time. */
|
|
124
|
+
snapshot(terminals: HcTerminal[]): void;
|
|
125
|
+
event(event: HcEvent): void;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* `events.subscribe` that stays open: reconnects with backoff after the core
|
|
130
|
+
* restarts or the socket drops, delivering a fresh snapshot each time.
|
|
131
|
+
*/
|
|
132
|
+
export class HcSubscription {
|
|
133
|
+
private conn: net.Socket | undefined;
|
|
134
|
+
private stopped = false;
|
|
135
|
+
private retry: ReturnType<typeof setTimeout> | undefined;
|
|
136
|
+
private backoff = 500;
|
|
137
|
+
/** True between a snapshot and the next disconnect. */
|
|
138
|
+
connected = false;
|
|
139
|
+
|
|
140
|
+
constructor(
|
|
141
|
+
private readonly socket: string,
|
|
142
|
+
private readonly params: Record<string, unknown>,
|
|
143
|
+
private readonly handlers: SubscriptionHandlers,
|
|
144
|
+
) {}
|
|
145
|
+
|
|
146
|
+
start(): void {
|
|
147
|
+
if (this.conn || this.stopped) return;
|
|
148
|
+
const id = nextId++;
|
|
149
|
+
let buffer = "";
|
|
150
|
+
const conn = net.createConnection(endpointPath(this.socket));
|
|
151
|
+
this.conn = conn;
|
|
152
|
+
conn.on("connect", () =>
|
|
153
|
+
conn.write(`${JSON.stringify({ jsonrpc: "2.0", id, method: "events.subscribe", params: this.params })}\n`),
|
|
154
|
+
);
|
|
155
|
+
conn.on("data", (chunk) => {
|
|
156
|
+
buffer += chunk.toString("utf8");
|
|
157
|
+
let newline: number;
|
|
158
|
+
while ((newline = buffer.indexOf("\n")) !== -1) {
|
|
159
|
+
const line = buffer.slice(0, newline);
|
|
160
|
+
buffer = buffer.slice(newline + 1);
|
|
161
|
+
let msg: any;
|
|
162
|
+
try {
|
|
163
|
+
msg = JSON.parse(line);
|
|
164
|
+
} catch {
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
try {
|
|
168
|
+
if (msg.id === id && msg.result) {
|
|
169
|
+
this.connected = true;
|
|
170
|
+
this.backoff = 500;
|
|
171
|
+
this.handlers.snapshot((msg.result.terminals ?? []) as HcTerminal[]);
|
|
172
|
+
} else if (msg.method === "event" && msg.params) {
|
|
173
|
+
this.handlers.event(msg.params as HcEvent);
|
|
174
|
+
} else if (msg.method === "missed" && msg.params) {
|
|
175
|
+
// Fell behind: the core follows with a fresh snapshot.
|
|
176
|
+
if (Array.isArray(msg.params.terminals)) this.handlers.snapshot(msg.params.terminals);
|
|
177
|
+
}
|
|
178
|
+
} catch {
|
|
179
|
+
// A handler bug must not kill the stream.
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
});
|
|
183
|
+
const drop = () => {
|
|
184
|
+
if (this.conn !== conn) return;
|
|
185
|
+
this.conn = undefined;
|
|
186
|
+
this.connected = false;
|
|
187
|
+
conn.destroy();
|
|
188
|
+
if (this.stopped) return;
|
|
189
|
+
this.retry = setTimeout(() => {
|
|
190
|
+
this.retry = undefined;
|
|
191
|
+
this.start();
|
|
192
|
+
}, this.backoff);
|
|
193
|
+
this.retry.unref?.();
|
|
194
|
+
this.backoff = Math.min(this.backoff * 2, 10_000);
|
|
195
|
+
};
|
|
196
|
+
conn.on("error", drop);
|
|
197
|
+
conn.on("close", drop);
|
|
198
|
+
conn.unref?.();
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
stop(): void {
|
|
202
|
+
this.stopped = true;
|
|
203
|
+
if (this.retry) clearTimeout(this.retry);
|
|
204
|
+
this.retry = undefined;
|
|
205
|
+
this.conn?.destroy();
|
|
206
|
+
this.conn = undefined;
|
|
207
|
+
this.connected = false;
|
|
208
|
+
}
|
|
209
|
+
}
|
package/agents/index.ts
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pi-wierdr's sub-agents (formerly @wierdbytes/pi-agents) — sub-agents as
|
|
3
|
+
* their own pi in herdr-core terminals, started as children of this pi's
|
|
4
|
+
* terminal so herdr nests them under it. Wiring only:
|
|
5
|
+
*
|
|
6
|
+
* - `child.ts` — this pi *is* a sub-agent: report results through the run file
|
|
7
|
+
* - `manager.ts` — start / follow / steer / stop children
|
|
8
|
+
* - `tools.ts` — Agent, get_subagent_result, steer_subagent, stop_subagent
|
|
9
|
+
* - `rpc.ts` — the same over pi.events for other extensions
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
13
|
+
import { loadAgentTypes } from "./agent-types.ts";
|
|
14
|
+
import { childFromEnv, setupChild, takeChildEnv } from "./child.ts";
|
|
15
|
+
import { notificationText } from "./format.ts";
|
|
16
|
+
import { endpointFromEnv } from "./hc.ts";
|
|
17
|
+
import { AgentManager, type AgentRecord, isFinal, snapshot } from "./manager.ts";
|
|
18
|
+
import { type PrepareContext, prepareSpawn } from "./prepare.ts";
|
|
19
|
+
import { type NotificationDetails, renderNotification } from "./render.ts";
|
|
20
|
+
import { registerRpc } from "./rpc.ts";
|
|
21
|
+
import { pruneRuns } from "./runs.ts";
|
|
22
|
+
import { loadSettings, runsDir } from "./settings.ts";
|
|
23
|
+
import { registerTools } from "./tools.ts";
|
|
24
|
+
|
|
25
|
+
/** Kept from pi-agents: sessions saved before still render their notifications. */
|
|
26
|
+
export const NOTIFICATION_TYPE = "pi-agents:notification";
|
|
27
|
+
|
|
28
|
+
export default function piAgents(pi: ExtensionAPI) {
|
|
29
|
+
// Taken out of process.env: only this pi is the sub-agent, not what it starts.
|
|
30
|
+
const child = childFromEnv(takeChildEnv());
|
|
31
|
+
if (child) setupChild(pi, child);
|
|
32
|
+
|
|
33
|
+
const settings = loadSettings();
|
|
34
|
+
const depth = child?.depth ?? 0;
|
|
35
|
+
// Sub-agents don't start more sub-agents unless maxDepth allows it.
|
|
36
|
+
if (depth >= settings.maxDepth) return;
|
|
37
|
+
|
|
38
|
+
const endpoint = endpointFromEnv();
|
|
39
|
+
const unavailable = endpoint
|
|
40
|
+
? undefined
|
|
41
|
+
: "pi-wierdr starts sub-agents as herdr-core terminals, but this pi isn't running in one (HC_TERMINAL_ID / HC_TERMINAL_SOCKET unset). Start pi from herdr.";
|
|
42
|
+
const dir = runsDir();
|
|
43
|
+
const manager = new AgentManager({
|
|
44
|
+
endpoint: endpoint ?? { socket: "", terminal: "" },
|
|
45
|
+
runsDir: dir,
|
|
46
|
+
settings,
|
|
47
|
+
depth,
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
let ctx: ExtensionContext | undefined;
|
|
51
|
+
|
|
52
|
+
const prepareContext = (c: ExtensionContext): PrepareContext => {
|
|
53
|
+
let trusted: boolean | undefined;
|
|
54
|
+
try {
|
|
55
|
+
trusted = c.isProjectTrusted();
|
|
56
|
+
} catch {
|
|
57
|
+
trusted = undefined;
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
cwd: c.cwd,
|
|
61
|
+
types: loadAgentTypes(c.cwd, trusted === true),
|
|
62
|
+
available: c.modelRegistry.getAvailable(),
|
|
63
|
+
scoped: (c.scopedModels ?? []).map((s) => s.model),
|
|
64
|
+
currentModel: c.model,
|
|
65
|
+
currentThinking: c.thinkingLevel ?? pi.getThinkingLevel?.(),
|
|
66
|
+
projectTrusted: trusted,
|
|
67
|
+
};
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const tools = { pi, manager, unavailable, prepareContext };
|
|
71
|
+
// Outside herdr-core there's nowhere to start sub-agents: offer no tools
|
|
72
|
+
// the model would only fail with (the RPC still answers ping).
|
|
73
|
+
if (!unavailable) registerTools(tools, loadAgentTypes(process.cwd(), false).values());
|
|
74
|
+
|
|
75
|
+
registerRpc({
|
|
76
|
+
events: pi.events,
|
|
77
|
+
manager,
|
|
78
|
+
unavailable: () => unavailable ?? (ctx ? undefined : "pi-wierdr: no session yet"),
|
|
79
|
+
spawn: async (input) => {
|
|
80
|
+
if (!ctx) throw new Error("pi-wierdr: no session yet");
|
|
81
|
+
return snapshot(await manager.spawn(prepareSpawn(input, prepareContext(ctx))));
|
|
82
|
+
},
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
// ─────────────────────────────────────────── completion notifications ──
|
|
86
|
+
|
|
87
|
+
const pending = new Set<AgentRecord>();
|
|
88
|
+
let flushTimer: ReturnType<typeof setTimeout> | undefined;
|
|
89
|
+
const deliverable = (r: AgentRecord) =>
|
|
90
|
+
r.notify && !r.consumed && ((isFinal(r.status) && r.status !== "stopped") || r.status === "blocked");
|
|
91
|
+
|
|
92
|
+
const flush = () => {
|
|
93
|
+
flushTimer = undefined;
|
|
94
|
+
// While this pi works, hold the news: the model may still collect the
|
|
95
|
+
// result itself (get_subagent_result), and a queued message can't be taken back.
|
|
96
|
+
let idle = true;
|
|
97
|
+
try {
|
|
98
|
+
idle = ctx?.isIdle() ?? true;
|
|
99
|
+
} catch {
|
|
100
|
+
idle = true;
|
|
101
|
+
}
|
|
102
|
+
if (!idle) return;
|
|
103
|
+
const list = [...pending].filter(deliverable);
|
|
104
|
+
pending.clear();
|
|
105
|
+
if (list.length === 0) return;
|
|
106
|
+
const finished = list.filter((r) => isFinal(r.status));
|
|
107
|
+
for (const r of finished) r.consumed = true;
|
|
108
|
+
const agents = list.map(snapshot);
|
|
109
|
+
pi.sendMessage<NotificationDetails>(
|
|
110
|
+
{ customType: NOTIFICATION_TYPE, content: notificationText(agents), display: true, details: { agents } },
|
|
111
|
+
// A finished result is news to act on; "needs a person" is only for the record.
|
|
112
|
+
{ deliverAs: "followUp", triggerTurn: finished.length > 0 },
|
|
113
|
+
);
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
const scheduleFlush = () => {
|
|
117
|
+
if (flushTimer || pending.size === 0) return;
|
|
118
|
+
flushTimer = setTimeout(flush, 300);
|
|
119
|
+
flushTimer.unref?.();
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
manager.onChange((rec, previous) => {
|
|
123
|
+
if (previous === rec.status || !deliverable(rec)) return;
|
|
124
|
+
pending.add(rec);
|
|
125
|
+
// Agents finishing together arrive as one message.
|
|
126
|
+
scheduleFlush();
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
pi.on("agent_settled", async (_event, next) => {
|
|
130
|
+
ctx = next ?? ctx;
|
|
131
|
+
scheduleFlush();
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
pi.registerMessageRenderer<NotificationDetails>(NOTIFICATION_TYPE, (message, { expanded }, theme) =>
|
|
135
|
+
renderNotification(message.details, expanded, theme),
|
|
136
|
+
);
|
|
137
|
+
|
|
138
|
+
// ─────────────────────────────────────────────────────────── /agents ──
|
|
139
|
+
|
|
140
|
+
pi.registerCommand("agents", {
|
|
141
|
+
description: "Sub-agents of this pi: peek at one in herdr, or stop it",
|
|
142
|
+
handler: async (_args, c) => {
|
|
143
|
+
const list = manager.list();
|
|
144
|
+
if (list.length === 0) {
|
|
145
|
+
c.ui.notify("No sub-agents in this pi yet.", "info");
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
const options = list.map((r) => `${r.id} · ${r.address} · ${r.status}${r.live ? "" : " (closed)"} — ${r.description}`);
|
|
149
|
+
const picked = await c.ui.select("Sub-agents", options);
|
|
150
|
+
const rec = picked ? list[options.indexOf(picked)] : undefined;
|
|
151
|
+
if (!rec) return;
|
|
152
|
+
const actions = rec.live ? ["Peek in herdr", "Stop and close"] : ["Peek in herdr"];
|
|
153
|
+
const action = await c.ui.select(`${rec.id} (${rec.address})`, actions);
|
|
154
|
+
if (action === "Peek in herdr") {
|
|
155
|
+
const r = await pi.exec("herdr-app", ["do", "terminal.peek", "--terminal", rec.address]).catch(() => undefined);
|
|
156
|
+
if (!r || r.code !== 0) c.ui.notify(`Couldn't open ${rec.address} in herdr${r?.stderr ? `: ${r.stderr.trim()}` : ""}`, "warning");
|
|
157
|
+
} else if (action === "Stop and close") {
|
|
158
|
+
await manager.stop(rec).catch((e) => c.ui.notify(String(e instanceof Error ? e.message : e), "error"));
|
|
159
|
+
}
|
|
160
|
+
},
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
// ─────────────────────────────────────────────────────────── session ──
|
|
164
|
+
|
|
165
|
+
pi.on("session_start", async (_event, next) => {
|
|
166
|
+
ctx = next;
|
|
167
|
+
if (unavailable) return;
|
|
168
|
+
// Agent types can come from the project: refresh the tool description.
|
|
169
|
+
registerTools(tools, prepareContext(next).types.values());
|
|
170
|
+
manager.start();
|
|
171
|
+
pruneRuns(dir);
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
pi.on("session_shutdown", async (event) => {
|
|
175
|
+
ctx = undefined;
|
|
176
|
+
if (event.reason !== "quit") return;
|
|
177
|
+
// herdr-core ends children with their terminal, but the terminal is the
|
|
178
|
+
// shell pi runs in: end them with pi instead.
|
|
179
|
+
await manager.stopAll();
|
|
180
|
+
manager.dispose();
|
|
181
|
+
});
|
|
182
|
+
}
|
package/agents/launch.ts
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How a sub-agent's terminal starts: its hc name, pi's argv and the
|
|
3
|
+
* environment. Pure functions, so the details stay testable.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { AgentsSettings } from "./settings.ts";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* What every key of {@link ENV} starts with. Named before pi-agents became
|
|
10
|
+
* pi-wierdr, and kept: pi-web and pi-voice drop these from the `pi -p` they start.
|
|
11
|
+
*/
|
|
12
|
+
export const ENV_PREFIX = "PI_AGENTS_";
|
|
13
|
+
|
|
14
|
+
/** Env keys the child reads. */
|
|
15
|
+
export const ENV = {
|
|
16
|
+
RUN: "PI_AGENTS_RUN",
|
|
17
|
+
DIR: "PI_AGENTS_DIR",
|
|
18
|
+
DEPTH: "PI_AGENTS_DEPTH",
|
|
19
|
+
TRUST: "PI_AGENTS_TRUST",
|
|
20
|
+
} as const;
|
|
21
|
+
|
|
22
|
+
const CYRILLIC: Record<string, string> = {
|
|
23
|
+
а: "a", б: "b", в: "v", г: "g", д: "d", е: "e", ё: "e", ж: "zh", з: "z", и: "i", й: "y",
|
|
24
|
+
к: "k", л: "l", м: "m", н: "n", о: "o", п: "p", р: "r", с: "s", т: "t", у: "u", ф: "f",
|
|
25
|
+
х: "h", ц: "ts", ч: "ch", ш: "sh", щ: "sch", ъ: "", ы: "y", ь: "", э: "e", ю: "yu", я: "ya",
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* hc names are 1-32 of `a-z 0-9 - _`. Cyrillic is transliterated so a
|
|
30
|
+
* Russian description still gives a readable name; `max` leaves room for a
|
|
31
|
+
* `-2` suffix on collisions.
|
|
32
|
+
*/
|
|
33
|
+
export function slugName(description: string, max = 28): string {
|
|
34
|
+
const s = description
|
|
35
|
+
.toLowerCase()
|
|
36
|
+
.split("")
|
|
37
|
+
.map((ch) => CYRILLIC[ch] ?? ch)
|
|
38
|
+
.join("")
|
|
39
|
+
.normalize("NFKD")
|
|
40
|
+
.replace(/[\u0300-\u036f]/g, "")
|
|
41
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
42
|
+
.replace(/^-+|-+$/g, "");
|
|
43
|
+
const cut = s.slice(0, max).replace(/-+$/, "");
|
|
44
|
+
return cut || "agent";
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** `name`, `name-2`, `name-3`, … within 32 characters. */
|
|
48
|
+
export function nameCandidate(base: string, attempt: number): string {
|
|
49
|
+
if (attempt <= 1) return base.slice(0, 32);
|
|
50
|
+
const suffix = `-${attempt}`;
|
|
51
|
+
return `${base.slice(0, 32 - suffix.length).replace(/-+$/, "")}${suffix}`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface ChildArgs {
|
|
55
|
+
model?: string;
|
|
56
|
+
thinking?: string;
|
|
57
|
+
tools?: string[];
|
|
58
|
+
excludeTools?: string[];
|
|
59
|
+
sessionName: string;
|
|
60
|
+
prompt: string;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Options first, then `--` and the task: pi's extension flags may take a
|
|
65
|
+
* value, so a stray flag before the task could swallow it.
|
|
66
|
+
*/
|
|
67
|
+
export function buildArgv(settings: Pick<AgentsSettings, "command" | "extraArgs">, a: ChildArgs): string[] {
|
|
68
|
+
const argv = [...settings.command];
|
|
69
|
+
if (a.model) argv.push("--model", a.model);
|
|
70
|
+
if (a.thinking) argv.push("--thinking", a.thinking);
|
|
71
|
+
if (a.tools?.length) argv.push("--tools", a.tools.join(","));
|
|
72
|
+
if (a.excludeTools?.length) argv.push("--exclude-tools", a.excludeTools.join(","));
|
|
73
|
+
argv.push("--name", a.sessionName);
|
|
74
|
+
argv.push(...settings.extraArgs);
|
|
75
|
+
// A task starting with "@" would be read as a file to attach.
|
|
76
|
+
const prompt = a.prompt.startsWith("@") ? `Task:\n${a.prompt}` : a.prompt;
|
|
77
|
+
argv.push("--", prompt);
|
|
78
|
+
return argv;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Keys that describe the parent's own terminal or session, never the child's. */
|
|
82
|
+
const DROP_EXACT = new Set([
|
|
83
|
+
"TERM",
|
|
84
|
+
"TERM_PROGRAM",
|
|
85
|
+
"TERM_PROGRAM_VERSION",
|
|
86
|
+
"COLORTERM",
|
|
87
|
+
"SHLVL",
|
|
88
|
+
"PWD",
|
|
89
|
+
"OLDPWD",
|
|
90
|
+
"_",
|
|
91
|
+
"WINDOWID",
|
|
92
|
+
"TTY",
|
|
93
|
+
"AI_AGENT",
|
|
94
|
+
"PI_CODING_AGENT",
|
|
95
|
+
"PI_MODEL",
|
|
96
|
+
"PI_PROVIDER",
|
|
97
|
+
"PI_REASONING_LEVEL",
|
|
98
|
+
"PI_SESSION_FILE",
|
|
99
|
+
"PI_SESSION_ID",
|
|
100
|
+
"STARSHIP_SESSION_KEY",
|
|
101
|
+
"LaunchInstanceID",
|
|
102
|
+
]);
|
|
103
|
+
const DROP_PREFIX = ["HC_", "HERDR_", ENV_PREFIX, "GHOSTTY_", "KITTY_", "ITERM_", "TMUX", "VSCODE_", "LC_TERMINAL", "WEZTERM_", "ZELLIJ"];
|
|
104
|
+
|
|
105
|
+
/** The parent's environment minus terminal identity, for a child that should run like its parent. */
|
|
106
|
+
export function inheritedEnv(env: NodeJS.ProcessEnv): Record<string, string> {
|
|
107
|
+
const out: Record<string, string> = {};
|
|
108
|
+
for (const [k, v] of Object.entries(env)) {
|
|
109
|
+
if (v === undefined) continue;
|
|
110
|
+
if (DROP_EXACT.has(k)) continue;
|
|
111
|
+
if (DROP_PREFIX.some((p) => k.startsWith(p))) continue;
|
|
112
|
+
// Shell functions exported by bash, and zsh/fzf leftovers that aren't real names.
|
|
113
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(k)) continue;
|
|
114
|
+
out[k] = v;
|
|
115
|
+
}
|
|
116
|
+
return out;
|
|
117
|
+
}
|