@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/render.ts
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TUI rendering in the facelift / tool-frame look:
|
|
3
|
+
*
|
|
4
|
+
* ╭── Agent Explore Find auth code · sonnet-5-5 @low ─────────
|
|
5
|
+
* │ ╰ Find where the session cookie is validated…
|
|
6
|
+
* │ read src/auth/session.ts
|
|
7
|
+
* ╰── ◌ running · 12s · 45k · 5 tool calls──────────────
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { Theme } from "@earendil-works/pi-coding-agent";
|
|
11
|
+
import { Text } from "@earendil-works/pi-tui";
|
|
12
|
+
import {
|
|
13
|
+
type FrameStatus,
|
|
14
|
+
frameResult,
|
|
15
|
+
frameResultWithBottomLabel,
|
|
16
|
+
frameTop,
|
|
17
|
+
getDefaultFrameWidth,
|
|
18
|
+
} from "@wierdbytes/pi-common/tool-frame";
|
|
19
|
+
import { duration, elapsed, tokens } from "./format.ts";
|
|
20
|
+
import type { AgentSnapshot, AgentStatus } from "./manager.ts";
|
|
21
|
+
|
|
22
|
+
const PAD = { paddingX: 1 };
|
|
23
|
+
const COLLAPSED_LINES = 8;
|
|
24
|
+
|
|
25
|
+
export interface AgentToolDetails {
|
|
26
|
+
agent?: AgentSnapshot;
|
|
27
|
+
/** steer_subagent: how the message went in. */
|
|
28
|
+
mode?: "steer" | "follow-up";
|
|
29
|
+
error?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const frameStatusOf = (s: AgentStatus): FrameStatus =>
|
|
33
|
+
s === "completed" ? "success" : s === "failed" || s === "stopped" ? "error" : "pending";
|
|
34
|
+
|
|
35
|
+
const ICON: Record<AgentStatus, string> = {
|
|
36
|
+
running: "◌",
|
|
37
|
+
blocked: "◆",
|
|
38
|
+
completed: "✓",
|
|
39
|
+
failed: "✗",
|
|
40
|
+
stopped: "■",
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const COLOR: Record<AgentStatus, "warning" | "success" | "error" | "muted"> = {
|
|
44
|
+
running: "warning",
|
|
45
|
+
blocked: "warning",
|
|
46
|
+
completed: "success",
|
|
47
|
+
failed: "error",
|
|
48
|
+
stopped: "muted",
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
const shortModel = (m: string | undefined): string | undefined => (m ? (m.split("/").pop() ?? m) : undefined);
|
|
52
|
+
|
|
53
|
+
export function modelChip(model: string | undefined, thinking: string | undefined): string | undefined {
|
|
54
|
+
const m = shortModel(model);
|
|
55
|
+
if (!m && !thinking) return undefined;
|
|
56
|
+
return `${m ?? "inherit"}${thinking ? ` @${thinking}` : ""}`;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function firstLine(s: string | undefined, max = 200): string {
|
|
60
|
+
return (s ?? "").trim().split("\n")[0]!.slice(0, max);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function frameStatusFromCtx(ctx: unknown): FrameStatus {
|
|
64
|
+
const c = (ctx ?? {}) as { isError?: boolean; isPartial?: boolean };
|
|
65
|
+
return c.isError ? "error" : c.isPartial ? "pending" : "success";
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The body + bottom label for one agent. */
|
|
69
|
+
export function agentBody(
|
|
70
|
+
s: AgentSnapshot,
|
|
71
|
+
theme: Theme,
|
|
72
|
+
expanded: boolean,
|
|
73
|
+
now = Date.now(),
|
|
74
|
+
): { body: string; bottom: string; status: FrameStatus } {
|
|
75
|
+
const lines: string[] = [];
|
|
76
|
+
const act = s.activity;
|
|
77
|
+
if (s.status === "running" || s.status === "blocked") {
|
|
78
|
+
if (s.status === "blocked") lines.push(theme.fg("warning", `needs a person${s.hcMessage ? `: ${s.hcMessage}` : ""} — open it in herdr`));
|
|
79
|
+
if (act?.tool) lines.push(theme.fg("dim", `${act.tool}${act.detail ? ` ${act.detail}` : ""}`));
|
|
80
|
+
} else {
|
|
81
|
+
const text = (s.result ?? "").trim();
|
|
82
|
+
if (s.status === "failed" && s.error) lines.push(theme.fg("error", s.error.split("\n").slice(0, expanded ? 40 : 3).join("\n")));
|
|
83
|
+
if (text) {
|
|
84
|
+
const all = text.split("\n");
|
|
85
|
+
const shown = expanded ? all : all.slice(0, COLLAPSED_LINES);
|
|
86
|
+
lines.push(...shown.map((l) => theme.fg("toolOutput", l)));
|
|
87
|
+
if (!expanded && all.length > shown.length) lines.push(theme.fg("dim", `… ${all.length - shown.length} more lines`));
|
|
88
|
+
} else if (s.status === "completed") lines.push(theme.fg("dim", "(no final message)"));
|
|
89
|
+
else if (s.status === "stopped") lines.push(theme.fg("muted", "stopped"));
|
|
90
|
+
}
|
|
91
|
+
const bottomParts = [
|
|
92
|
+
theme.fg(COLOR[s.status], `${ICON[s.status]} ${s.status}`),
|
|
93
|
+
theme.fg("dim", duration(elapsed(s, now))),
|
|
94
|
+
];
|
|
95
|
+
if (act?.context) bottomParts.push(theme.fg("dim", tokens(act.context.tokens)));
|
|
96
|
+
if (act?.tools) bottomParts.push(theme.fg("dim", `${act.tools} tool call${act.tools === 1 ? "" : "s"}`));
|
|
97
|
+
return { body: lines.join("\n"), bottom: bottomParts.join(theme.fg("dim", " · ")), status: frameStatusOf(s.status) };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// ─────────────────────────────────────────────────────────────── Agent ──
|
|
101
|
+
|
|
102
|
+
export interface AgentArgs {
|
|
103
|
+
prompt?: string;
|
|
104
|
+
description?: string;
|
|
105
|
+
subagent_type?: string;
|
|
106
|
+
model?: string;
|
|
107
|
+
thinking?: string;
|
|
108
|
+
run_in_background?: boolean;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function renderAgentCall(args: AgentArgs, theme: Theme, ctx: unknown): Text {
|
|
112
|
+
let title = theme.fg("toolTitle", theme.bold("Agent "));
|
|
113
|
+
title += theme.fg("accent", args.subagent_type || "general-purpose");
|
|
114
|
+
if (args.description) title += ` ${args.description}`;
|
|
115
|
+
const chip = modelChip(args.model, args.thinking);
|
|
116
|
+
if (chip) title += theme.fg("dim", ` · ${chip}`);
|
|
117
|
+
if (args.run_in_background) title += theme.fg("dim", " · background");
|
|
118
|
+
const prompt = firstLine(args.prompt);
|
|
119
|
+
if (prompt) title += `\n${theme.fg("dim", prompt)}`;
|
|
120
|
+
return new Text(frameTop(title, frameStatusFromCtx(ctx), theme, getDefaultFrameWidth()), 0, 0);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function renderAgentResult(
|
|
124
|
+
result: { details?: AgentToolDetails; content?: Array<{ type: string; text?: string }> },
|
|
125
|
+
options: { expanded: boolean; isPartial: boolean },
|
|
126
|
+
theme: Theme,
|
|
127
|
+
): Text {
|
|
128
|
+
const width = getDefaultFrameWidth();
|
|
129
|
+
const d = result.details;
|
|
130
|
+
if (d?.agent) {
|
|
131
|
+
const { body, bottom, status } = agentBody(d.agent, theme, options.expanded);
|
|
132
|
+
if (d.agent.background && d.agent.status === "running" && !options.isPartial) {
|
|
133
|
+
return new Text(
|
|
134
|
+
frameResultWithBottomLabel(
|
|
135
|
+
theme.fg("dim", "started in the background — you'll be told when it finishes"),
|
|
136
|
+
bottom,
|
|
137
|
+
"success",
|
|
138
|
+
theme,
|
|
139
|
+
width,
|
|
140
|
+
PAD,
|
|
141
|
+
),
|
|
142
|
+
0,
|
|
143
|
+
0,
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
return new Text(frameResultWithBottomLabel(body, bottom, status, theme, width, PAD), 0, 0);
|
|
147
|
+
}
|
|
148
|
+
const text = d?.error ?? result.content?.find((c) => c.type === "text")?.text ?? "";
|
|
149
|
+
if (options.isPartial) {
|
|
150
|
+
return new Text(frameResult(theme.fg("warning", "starting…"), "pending", theme, width, PAD), 0, 0);
|
|
151
|
+
}
|
|
152
|
+
return new Text(frameResultWithBottomLabel(theme.fg("error", text), theme.fg("error", "✗ error"), "error", theme, width, PAD), 0, 0);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// ──────────────────────────────────────────────── get / steer / stop ──
|
|
156
|
+
|
|
157
|
+
export function renderRefCall(tool: string, args: { agent_id?: string; wait?: boolean; message?: string }, theme: Theme, ctx: unknown): Text {
|
|
158
|
+
let title = theme.fg("toolTitle", theme.bold(`${tool} `));
|
|
159
|
+
title += theme.fg("accent", args.agent_id ?? "");
|
|
160
|
+
if (args.wait) title += theme.fg("dim", " · wait");
|
|
161
|
+
const msg = firstLine(args.message);
|
|
162
|
+
if (msg) title += `\n${theme.fg("dim", msg)}`;
|
|
163
|
+
return new Text(frameTop(title, frameStatusFromCtx(ctx), theme, getDefaultFrameWidth()), 0, 0);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export function renderRefResult(
|
|
167
|
+
result: { details?: AgentToolDetails; content?: Array<{ type: string; text?: string }> },
|
|
168
|
+
options: { expanded: boolean; isPartial: boolean },
|
|
169
|
+
theme: Theme,
|
|
170
|
+
): Text {
|
|
171
|
+
const width = getDefaultFrameWidth();
|
|
172
|
+
const d = result.details;
|
|
173
|
+
if (d?.mode && d.agent) {
|
|
174
|
+
const line = d.mode === "steer" ? "→ delivered as a steer while it works" : "→ follow-up sent; it's working again";
|
|
175
|
+
return new Text(frameResult(theme.fg("muted", line), "success", theme, width, PAD), 0, 0);
|
|
176
|
+
}
|
|
177
|
+
if (d?.agent) return renderAgentResult(result, options, theme);
|
|
178
|
+
const text = d?.error ?? result.content?.find((c) => c.type === "text")?.text ?? "";
|
|
179
|
+
return new Text(frameResultWithBottomLabel(theme.fg("error", text), theme.fg("error", "✗ error"), "error", theme, width, PAD), 0, 0);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// ───────────────────────────────────────────────────── notification ──
|
|
183
|
+
|
|
184
|
+
export interface NotificationDetails {
|
|
185
|
+
agents: AgentSnapshot[];
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export function renderNotification(details: NotificationDetails | undefined, expanded: boolean, theme: Theme): Text {
|
|
189
|
+
const agents = details?.agents ?? [];
|
|
190
|
+
const width = getDefaultFrameWidth();
|
|
191
|
+
const blocks = agents.map((s) => {
|
|
192
|
+
const { body, bottom, status } = agentBody(s, theme, expanded);
|
|
193
|
+
let title = theme.fg("toolTitle", theme.bold("Agent "));
|
|
194
|
+
title += theme.fg("accent", s.type);
|
|
195
|
+
title += ` ${s.description}`;
|
|
196
|
+
const chip = modelChip(s.model, s.thinking);
|
|
197
|
+
if (chip) title += theme.fg("dim", ` · ${chip}`);
|
|
198
|
+
return `${frameTop(title, status, theme, width)}\n${frameResultWithBottomLabel(body, bottom, status, theme, width, PAD)}`;
|
|
199
|
+
});
|
|
200
|
+
return new Text(blocks.join("\n"), 0, 0);
|
|
201
|
+
}
|
package/agents/rpc.ts
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `pi.events` RPC for other extensions. Request on `agents:rpc:<method>`
|
|
3
|
+
* with a `requestId`; the reply comes on `agents:rpc:<method>:reply:<requestId>`
|
|
4
|
+
* as `{ success: true, data }` or `{ success: false, error }`.
|
|
5
|
+
*
|
|
6
|
+
* Lifecycle broadcasts: `agents:<status>` (`spawned`, `running`, `blocked`,
|
|
7
|
+
* `completed`, `failed`, `stopped`) with the agent's snapshot.
|
|
8
|
+
*
|
|
9
|
+
* `client.ts` wraps this; the protocol is described in README.md.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { AgentManager, AgentSnapshot, AgentStatus } from "./manager.ts";
|
|
13
|
+
import { isFinal, snapshot } from "./manager.ts";
|
|
14
|
+
import type { SpawnInput } from "./prepare.ts";
|
|
15
|
+
|
|
16
|
+
export const RPC_VERSION = 1;
|
|
17
|
+
export const RPC_PREFIX = "agents:rpc:";
|
|
18
|
+
export const replyChannel = (method: string, requestId: string) => `${RPC_PREFIX}${method}:reply:${requestId}`;
|
|
19
|
+
|
|
20
|
+
export type RpcReply<T> = { success: true; data: T } | { success: false; error: string };
|
|
21
|
+
|
|
22
|
+
export interface EventBus {
|
|
23
|
+
on(channel: string, handler: (data: unknown) => void): () => void;
|
|
24
|
+
emit(channel: string, data: unknown): void;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface RpcMethods {
|
|
28
|
+
ping: { params: Record<string, never>; result: { version: number; available: boolean } };
|
|
29
|
+
spawn: { params: SpawnInput; result: AgentSnapshot };
|
|
30
|
+
get: { params: { id: string }; result: AgentSnapshot };
|
|
31
|
+
wait: { params: { id: string; timeoutMs?: number }; result: AgentSnapshot };
|
|
32
|
+
steer: { params: { id: string; message: string }; result: AgentSnapshot & { mode: "steer" | "follow-up" } };
|
|
33
|
+
stop: { params: { id: string }; result: AgentSnapshot };
|
|
34
|
+
list: { params: Record<string, never>; result: AgentSnapshot[] };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface RpcDeps {
|
|
38
|
+
events: EventBus;
|
|
39
|
+
manager: AgentManager;
|
|
40
|
+
unavailable(): string | undefined;
|
|
41
|
+
/** Resolves the spawn input against the live session, or throws. */
|
|
42
|
+
spawn(input: SpawnInput): Promise<AgentSnapshot>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function registerRpc(deps: RpcDeps): () => void {
|
|
46
|
+
const { events, manager } = deps;
|
|
47
|
+
const offs: Array<() => void> = [];
|
|
48
|
+
|
|
49
|
+
const handle = <M extends keyof RpcMethods>(
|
|
50
|
+
method: M,
|
|
51
|
+
fn: (params: RpcMethods[M]["params"]) => Promise<RpcMethods[M]["result"]> | RpcMethods[M]["result"],
|
|
52
|
+
) => {
|
|
53
|
+
offs.push(
|
|
54
|
+
events.on(`${RPC_PREFIX}${method}`, (raw) => {
|
|
55
|
+
const req = (raw ?? {}) as { requestId?: unknown } & Record<string, unknown>;
|
|
56
|
+
if (typeof req.requestId !== "string") return;
|
|
57
|
+
const reply = replyChannel(method, req.requestId);
|
|
58
|
+
Promise.resolve()
|
|
59
|
+
.then(() => {
|
|
60
|
+
const why = method === "ping" ? undefined : deps.unavailable();
|
|
61
|
+
if (why) throw new Error(why);
|
|
62
|
+
return fn(req as unknown as RpcMethods[M]["params"]);
|
|
63
|
+
})
|
|
64
|
+
.then(
|
|
65
|
+
(data) => events.emit(reply, { success: true, data } satisfies RpcReply<unknown>),
|
|
66
|
+
(e) => events.emit(reply, { success: false, error: e instanceof Error ? e.message : String(e) } satisfies RpcReply<unknown>),
|
|
67
|
+
);
|
|
68
|
+
}),
|
|
69
|
+
);
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const find = (id: unknown) => {
|
|
73
|
+
const rec = typeof id === "string" ? manager.find(id) : undefined;
|
|
74
|
+
if (!rec) throw new Error(`No sub-agent "${String(id)}"`);
|
|
75
|
+
return rec;
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
handle("ping", () => ({ version: RPC_VERSION, available: deps.unavailable() === undefined }));
|
|
79
|
+
handle("spawn", (p) => deps.spawn({ ...p, background: true, notify: p.notify ?? false }));
|
|
80
|
+
handle("get", (p) => snapshot(find(p.id)));
|
|
81
|
+
handle("wait", async (p) => {
|
|
82
|
+
const rec = find(p.id);
|
|
83
|
+
await manager.wait(rec, { timeoutMs: p.timeoutMs });
|
|
84
|
+
if (isFinal(rec.status)) rec.consumed = true;
|
|
85
|
+
return snapshot(rec);
|
|
86
|
+
});
|
|
87
|
+
handle("steer", async (p) => {
|
|
88
|
+
const rec = find(p.id);
|
|
89
|
+
const { mode } = await manager.steer(rec, p.message);
|
|
90
|
+
return { ...snapshot(rec), mode };
|
|
91
|
+
});
|
|
92
|
+
handle("stop", async (p) => {
|
|
93
|
+
const rec = find(p.id);
|
|
94
|
+
await manager.stop(rec);
|
|
95
|
+
return snapshot(rec);
|
|
96
|
+
});
|
|
97
|
+
handle("list", () => manager.list().map(snapshot));
|
|
98
|
+
|
|
99
|
+
offs.push(
|
|
100
|
+
manager.onChange((rec, previous) => {
|
|
101
|
+
if (previous === rec.status) return;
|
|
102
|
+
const name: AgentStatus | "spawned" = previous === undefined ? "spawned" : rec.status;
|
|
103
|
+
events.emit(`agents:${name}`, snapshot(rec));
|
|
104
|
+
}),
|
|
105
|
+
);
|
|
106
|
+
|
|
107
|
+
return () => {
|
|
108
|
+
for (const off of offs.splice(0)) off();
|
|
109
|
+
};
|
|
110
|
+
}
|
package/agents/runs.ts
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The files a parent and its sub-agents share, one pair per run:
|
|
3
|
+
*
|
|
4
|
+
* - `<runId>.meta.json` — written by the parent before the child starts:
|
|
5
|
+
* what the child is for and the instructions its type adds.
|
|
6
|
+
* - `<runId>.json` — written by the child: how many runs settled, the last
|
|
7
|
+
* assistant message, live activity.
|
|
8
|
+
*
|
|
9
|
+
* Writes are atomic (tmp + rename) so a reader never sees half a file.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
13
|
+
import { join } from "node:path";
|
|
14
|
+
|
|
15
|
+
export interface RunMeta {
|
|
16
|
+
v: 1;
|
|
17
|
+
runId: string;
|
|
18
|
+
description: string;
|
|
19
|
+
type: string;
|
|
20
|
+
/** Instructions the agent type adds to the child's system prompt. */
|
|
21
|
+
typePrompt: string;
|
|
22
|
+
/** The parent's terminal address. */
|
|
23
|
+
parent: string;
|
|
24
|
+
parentPid: number;
|
|
25
|
+
depth: number;
|
|
26
|
+
cwd: string;
|
|
27
|
+
model?: string;
|
|
28
|
+
thinking?: string;
|
|
29
|
+
createdAt: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export type LastStatus = "done" | "error" | "aborted";
|
|
33
|
+
|
|
34
|
+
export interface ChildActivity {
|
|
35
|
+
/** Tool calls started so far, across runs. */
|
|
36
|
+
tools: number;
|
|
37
|
+
/** Assistant turns ended so far, across runs. */
|
|
38
|
+
turns: number;
|
|
39
|
+
/** The latest tool call. */
|
|
40
|
+
tool?: string;
|
|
41
|
+
detail?: string;
|
|
42
|
+
/** Context window in use: tokens on the branch and the model's window. */
|
|
43
|
+
context?: { tokens: number; window: number };
|
|
44
|
+
at: number;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface ChildState {
|
|
48
|
+
v: 1;
|
|
49
|
+
runId: string;
|
|
50
|
+
pid: number;
|
|
51
|
+
sessionId?: string;
|
|
52
|
+
sessionFile?: string;
|
|
53
|
+
/** Runs settled so far; the parent finishes a record when this moves past its baseline. */
|
|
54
|
+
seq: number;
|
|
55
|
+
running: boolean;
|
|
56
|
+
last?: { status: LastStatus; text: string; error?: string; at: number };
|
|
57
|
+
activity?: ChildActivity;
|
|
58
|
+
updatedAt: number;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export const metaPath = (dir: string, runId: string): string => join(dir, `${runId}.meta.json`);
|
|
62
|
+
export const statePath = (dir: string, runId: string): string => join(dir, `${runId}.json`);
|
|
63
|
+
|
|
64
|
+
/** `<runId>.json` → runId; meta files and temp files → undefined. */
|
|
65
|
+
export function runIdOfStateFile(file: string): string | undefined {
|
|
66
|
+
if (!file.endsWith(".json") || file.endsWith(".meta.json")) return undefined;
|
|
67
|
+
return file.slice(0, -".json".length);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function newRunId(now = Date.now()): string {
|
|
71
|
+
return `${now.toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function writeJsonAtomic(path: string, value: unknown): void {
|
|
75
|
+
const tmp = `${path}.${process.pid}.${Math.random().toString(36).slice(2, 8)}.tmp`;
|
|
76
|
+
writeFileSync(tmp, JSON.stringify(value), "utf8");
|
|
77
|
+
renameSync(tmp, path);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function readJson<T>(path: string): T | undefined {
|
|
81
|
+
try {
|
|
82
|
+
return JSON.parse(readFileSync(path, "utf8")) as T;
|
|
83
|
+
} catch {
|
|
84
|
+
return undefined;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function ensureDir(dir: string): void {
|
|
89
|
+
mkdirSync(dir, { recursive: true });
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export const readMeta = (dir: string, runId: string): RunMeta | undefined => readJson<RunMeta>(metaPath(dir, runId));
|
|
93
|
+
export const readState = (dir: string, runId: string): ChildState | undefined =>
|
|
94
|
+
readJson<ChildState>(statePath(dir, runId));
|
|
95
|
+
|
|
96
|
+
export function writeMeta(dir: string, meta: RunMeta): void {
|
|
97
|
+
ensureDir(dir);
|
|
98
|
+
writeJsonAtomic(metaPath(dir, meta.runId), meta);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function writeState(dir: string, state: ChildState): void {
|
|
102
|
+
ensureDir(dir);
|
|
103
|
+
writeJsonAtomic(statePath(dir, state.runId), state);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Drops run files older than `maxAgeMs`. Never throws. */
|
|
107
|
+
export function pruneRuns(dir: string, maxAgeMs = 7 * 24 * 3600_000, now = Date.now()): void {
|
|
108
|
+
let files: string[];
|
|
109
|
+
try {
|
|
110
|
+
files = readdirSync(dir);
|
|
111
|
+
} catch {
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
for (const f of files) {
|
|
115
|
+
const p = join(dir, f);
|
|
116
|
+
try {
|
|
117
|
+
if (now - statSync(p).mtimeMs > maxAgeMs) unlinkSync(p);
|
|
118
|
+
} catch {
|
|
119
|
+
// Gone already, or not ours to delete.
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `agents` key of `~/.pi/agent/@wierdbytes/pi-wierdr/settings.json`
|
|
3
|
+
* (`../settings.ts`). Every key is optional; a missing or broken file means
|
|
4
|
+
* the defaults.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { legacySettingsPath, packageDir, readJson, settingsPath } from "../settings.ts";
|
|
9
|
+
|
|
10
|
+
export interface AgentsSettings {
|
|
11
|
+
/** How to start pi in a sub-agent's terminal. */
|
|
12
|
+
command: string[];
|
|
13
|
+
/** Extra pi arguments for every sub-agent, e.g. `["--no-voice", "--no-peon"]`. */
|
|
14
|
+
extraArgs: string[];
|
|
15
|
+
/** How deep sub-agents may nest: 1 = only the top pi starts sub-agents. */
|
|
16
|
+
maxDepth: number;
|
|
17
|
+
/** Give sub-agents this pi's environment (API keys, PATH), minus terminal identity. */
|
|
18
|
+
inheritEnv: boolean;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export const DEFAULT_SETTINGS: AgentsSettings = {
|
|
22
|
+
command: ["pi"],
|
|
23
|
+
extraArgs: [],
|
|
24
|
+
maxDepth: 1,
|
|
25
|
+
inheritEnv: true,
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export const runsDir = (): string => join(packageDir(), "runs");
|
|
29
|
+
|
|
30
|
+
const strings = (v: unknown): string[] | undefined =>
|
|
31
|
+
Array.isArray(v) && v.every((x) => typeof x === "string") ? (v as string[]) : undefined;
|
|
32
|
+
|
|
33
|
+
export function parseSettings(raw: unknown): AgentsSettings {
|
|
34
|
+
const o = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>;
|
|
35
|
+
const command = strings(o.command);
|
|
36
|
+
return {
|
|
37
|
+
command: command && command.length > 0 ? command : DEFAULT_SETTINGS.command,
|
|
38
|
+
extraArgs: strings(o.extraArgs) ?? DEFAULT_SETTINGS.extraArgs,
|
|
39
|
+
maxDepth:
|
|
40
|
+
typeof o.maxDepth === "number" && Number.isFinite(o.maxDepth) && o.maxDepth >= 0
|
|
41
|
+
? Math.floor(o.maxDepth)
|
|
42
|
+
: DEFAULT_SETTINGS.maxDepth,
|
|
43
|
+
inheritEnv: typeof o.inheritEnv === "boolean" ? o.inheritEnv : DEFAULT_SETTINGS.inheritEnv,
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** pi-wierdr's file (its `agents` key), or pi-agents' while that one doesn't exist (the same keys at the top). */
|
|
48
|
+
export function loadSettings(path = settingsPath(), legacy = legacySettingsPath("pi-agents")): AgentsSettings {
|
|
49
|
+
const raw = readJson(path);
|
|
50
|
+
if (raw === undefined) return parseSettings(readJson(legacy));
|
|
51
|
+
return parseSettings((raw as { agents?: unknown } | null)?.agents);
|
|
52
|
+
}
|