@deathbeam/pi-delegate 0.0.17 → 0.0.19

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # [@deathbeam/pi-delegate](https://www.npmjs.com/package/@deathbeam/pi-delegate)
2
2
 
3
- Run focused subagents with `delegate`, `delegate_list`, `delegate_steer`, and `delegate_cancel`.
3
+ Run subagents with `delegate`, `delegate_list`, `delegate_steer`, and `delegate_cancel`.
4
4
  Use `/delegate` command to inspect jobs in a full-screen TUI.
5
5
 
6
6
  ## Installation
@@ -20,7 +20,7 @@ Optional `delegate` settings live in `~/.pi/agent/settings.json` or `.pi/setting
20
20
  "delegate": {
21
21
  "agentDirs": ["./.pi/agents"],
22
22
  "models": {
23
- "cheap": "anthropic/claude-haiku-latest",
23
+ "cheap": { "model": "anthropic/claude-haiku-latest", "thinking": "low" },
24
24
  "balanced": "anthropic/claude-sonnet-latest",
25
25
  "strong": "anthropic/claude-opus-latest"
26
26
  }
@@ -29,7 +29,9 @@ Optional `delegate` settings live in `~/.pi/agent/settings.json` or `.pi/setting
29
29
  ```
30
30
 
31
31
  Relative `agentDirs` resolve against the project cwd, later same-name definitions win. Project `models` override global
32
- tiers (`cheap`, `balanced`, `strong`), otherwise the child uses the current session model.
32
+ tiers (`cheap`, `balanced`, `strong`); a tier is a `provider/model` string or a `{ "model": "...", "thinking": "..." }`
33
+ object, otherwise the child uses the current session model and thinking level. Thinking resolves from the agent
34
+ frontmatter first, then the tier entry, then the session level.
33
35
 
34
36
  Agents are Markdown files with frontmatter, the body becomes the child's system prompt:
35
37
 
package/agents.ts ADDED
@@ -0,0 +1,115 @@
1
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
6
+ import { CONFIG_DIR_NAME, getAgentDir, parseFrontmatter } from "@earendil-works/pi-coding-agent";
7
+
8
+ type AgentFile = {
9
+ name: string;
10
+ description: string;
11
+ tools?: string[];
12
+ model?: string;
13
+ thinking?: string;
14
+ prompt: string;
15
+ };
16
+
17
+ type DelegateConfig = {
18
+ agentDirs?: unknown;
19
+ models?: Record<string, unknown>;
20
+ };
21
+
22
+ const DEFAULT_AGENT_DIR = "~/.agents/agents";
23
+ const BUNDLED_AGENT_DIR = fileURLToPath(new URL("./agents", import.meta.url));
24
+ const MODEL_TIERS = new Set(["cheap", "balanced", "strong"]);
25
+
26
+ function expandPath(value: string, cwd: string): string {
27
+ return resolve(cwd, value.replace(/^~(?=\/|$)/, homedir()));
28
+ }
29
+
30
+ function stringList(value: unknown): string[] {
31
+ const values = Array.isArray(value) ? value : typeof value === "string" ? value.split(",") : [];
32
+ return values
33
+ .filter((item): item is string => typeof item === "string")
34
+ .map((item) => item.trim())
35
+ .filter(Boolean);
36
+ }
37
+
38
+ function readConfig(path: string): DelegateConfig {
39
+ try {
40
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
41
+ if (!parsed || typeof parsed !== "object") return {};
42
+ const delegate = (parsed as { delegate?: unknown }).delegate;
43
+ return delegate && typeof delegate === "object" ? (delegate as DelegateConfig) : {};
44
+ } catch {
45
+ return {};
46
+ }
47
+ }
48
+
49
+ export function configFor(cwd: string): DelegateConfig {
50
+ const global = readConfig(join(getAgentDir(), "settings.json"));
51
+ const project = readConfig(join(cwd, CONFIG_DIR_NAME, "settings.json"));
52
+ return {
53
+ agentDirs: [...stringList(global.agentDirs), ...stringList(project.agentDirs)],
54
+ models: { ...(global.models ?? {}), ...(project.models ?? {}) },
55
+ };
56
+ }
57
+
58
+ function loadAgents(dir: string): AgentFile[] {
59
+ if (!existsSync(dir)) return [];
60
+ const agents: AgentFile[] = [];
61
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
62
+ if (!entry.name.endsWith(".md") || (!entry.isFile() && !entry.isSymbolicLink())) continue;
63
+ try {
64
+ const { frontmatter, body } = parseFrontmatter<Record<string, unknown>>(
65
+ readFileSync(join(dir, entry.name), "utf8"),
66
+ );
67
+ if (typeof frontmatter.name !== "string" || typeof frontmatter.description !== "string") continue;
68
+ agents.push({
69
+ name: frontmatter.name,
70
+ description: frontmatter.description,
71
+ tools: stringList(frontmatter.tools),
72
+ model: typeof frontmatter.model === "string" ? frontmatter.model : undefined,
73
+ thinking: typeof frontmatter.thinking === "string" ? frontmatter.thinking : undefined,
74
+ prompt: body.trim(),
75
+ });
76
+ } catch {
77
+ // One malformed agent file should not disable delegation.
78
+ }
79
+ }
80
+ return agents;
81
+ }
82
+
83
+ export function discoverAgents(cwd: string, configuredDirs: unknown): AgentFile[] {
84
+ const dirs = [BUNDLED_AGENT_DIR, DEFAULT_AGENT_DIR, ...stringList(configuredDirs)].map((dir) =>
85
+ expandPath(dir, cwd),
86
+ );
87
+ const agents = new Map<string, AgentFile>();
88
+ for (const dir of [...new Set(dirs)]) {
89
+ for (const agent of loadAgents(dir)) agents.set(agent.name, agent);
90
+ }
91
+ return [...agents.values()];
92
+ }
93
+
94
+ export function resolveModel(
95
+ value: string | undefined,
96
+ models: Record<string, unknown>,
97
+ current: ExtensionContext["model"],
98
+ ): { model?: string; thinking?: string } {
99
+ if (value && !MODEL_TIERS.has(value)) return { model: value };
100
+ const configured = value ? models[value] : undefined;
101
+ const entry =
102
+ configured && typeof configured === "object"
103
+ ? (configured as { model?: unknown; thinking?: unknown })
104
+ : undefined;
105
+ const model = typeof configured === "string" ? configured : typeof entry?.model === "string" ? entry.model : "";
106
+ // Tier thinking only applies when the model itself came from the tier entry.
107
+ if (model) return { model, thinking: typeof entry?.thinking === "string" ? entry.thinking : undefined };
108
+ return { model: current ? `${current.provider}/${current.id}` : undefined };
109
+ }
110
+
111
+ export function contextWindowFor(ctx: ExtensionContext, model: string | undefined): number | undefined {
112
+ const separator = model?.indexOf("/") ?? -1;
113
+ if (!model || separator < 0) return undefined;
114
+ return ctx.modelRegistry.find(model.slice(0, separator), model.slice(separator + 1))?.contextWindow;
115
+ }
package/child.ts CHANGED
@@ -22,7 +22,7 @@ export type ChildUpdate = {
22
22
  contextTokens?: number;
23
23
  activity?: ChildActivity;
24
24
  };
25
- export type ChildUpdateHandler = (update: ChildUpdate) => void;
25
+ type ChildUpdateHandler = (update: ChildUpdate) => void;
26
26
 
27
27
  type ChildRun = {
28
28
  done: Promise<string>;
@@ -35,6 +35,7 @@ export function runChild(
35
35
  task: string,
36
36
  signal: AbortSignal | undefined,
37
37
  onUpdate?: ChildUpdateHandler,
38
+ resume?: boolean,
38
39
  ): ChildRun {
39
40
  let buffer = "";
40
41
  let liveText = "";
@@ -49,9 +50,14 @@ export function runChild(
49
50
  let writeQueue = Promise.resolve();
50
51
  const pending = new Map<
51
52
  string,
52
- { command: string; resolve: () => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout> }
53
+ {
54
+ command: string;
55
+ resolve: (data: any) => void;
56
+ reject: (error: Error) => void;
57
+ timer: ReturnType<typeof setTimeout>;
58
+ }
53
59
  >();
54
- let send!: (command: Record<string, unknown>) => Promise<void>;
60
+ let send!: (command: Record<string, unknown>) => Promise<any>;
55
61
 
56
62
  const done = new Promise<string>((resolveChild, reject) => {
57
63
  const rejectPending = (error: Error) => {
@@ -105,7 +111,7 @@ export function runChild(
105
111
  pending.delete(event.id);
106
112
  clearTimeout(request.timer);
107
113
  if (event.success === true && event.command === request.command) {
108
- request.resolve();
114
+ request.resolve(event.data);
109
115
  return;
110
116
  }
111
117
  const responseError = new Error(
@@ -206,7 +212,7 @@ export function runChild(
206
212
  };
207
213
  send = (command: Record<string, unknown>) => {
208
214
  const id = `delegate_${++requestId}`;
209
- const response = new Promise<void>((resolveResponse, rejectResponse) => {
215
+ const response = new Promise<any>((resolveResponse, rejectResponse) => {
210
216
  const timer = setTimeout(() => {
211
217
  pending.delete(id);
212
218
  rejectResponse(new Error(`Timed out waiting for ${command.type} acknowledgement`));
@@ -259,9 +265,32 @@ export function runChild(
259
265
  finish(null);
260
266
  } else {
261
267
  signal?.addEventListener("abort", abort, { once: true });
262
- void send({ type: "prompt", message: task }).catch((error) => {
263
- if (!settled) fail(error);
264
- });
268
+ const prompt = () => {
269
+ void send({ type: "prompt", message: task }).catch((error) => {
270
+ if (!settled) fail(error);
271
+ });
272
+ };
273
+ if (resume) {
274
+ // An empty transcript means the pinned session was recreated (e.g. a different cwd) and the task is gone; fail rather than prompt into a blank session.
275
+ void send({ type: "get_state" })
276
+ .then((data) => {
277
+ if (!settled && !aborted && !data?.messageCount) {
278
+ fail(
279
+ new Error(
280
+ "Resumed delegate transcript is empty; the pinned session was recreated. Start a fresh delegate instead.",
281
+ ),
282
+ );
283
+ return;
284
+ }
285
+ prompt();
286
+ })
287
+ // A resume we cannot verify must not prompt into an unknown transcript.
288
+ .catch((error) => {
289
+ if (!settled && !aborted) fail(error);
290
+ });
291
+ } else {
292
+ prompt();
293
+ }
265
294
  }
266
295
  });
267
296
 
package/format.ts CHANGED
@@ -1,11 +1,12 @@
1
1
  /** Formatting helpers stay runtime Pi-import-free for the native check; Pi's analogous formatters are private. */
2
2
  import type { Theme } from "@earendil-works/pi-coding-agent";
3
+ import type { JobStatus } from "./store.ts";
3
4
 
4
- export type JobStatus = "running" | "done" | "failed" | "cancelled";
5
- export type UsageInfo = {
5
+ type UsageInfo = {
6
6
  contextTokens?: number;
7
7
  contextWindow?: number;
8
8
  };
9
+
9
10
  export type DelegateReport = {
10
11
  id: string;
11
12
  agent: string;
@@ -19,31 +20,33 @@ export type DelegateReport = {
19
20
  error?: string;
20
21
  };
21
22
 
22
- export const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
23
+ const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
23
24
  export const SPINNER_INTERVAL_MS = 100;
24
- export const STATUS_ICONS = {
25
+ const STATUS_ICONS = {
25
26
  done: "✓",
26
27
  failed: "✗",
27
28
  cancelled: "✗",
29
+ interrupted: "⏸",
28
30
  } as const satisfies Record<Exclude<JobStatus, "running">, string>;
29
31
  export const STATUS_COLORS = {
30
32
  running: "warning",
31
33
  done: "success",
32
34
  failed: "error",
33
35
  cancelled: "muted",
36
+ interrupted: "warning",
34
37
  } as const satisfies Record<JobStatus, string>;
35
38
  /** Pi slices extension widgets at ten lines and appends its own truncation note. */
36
- export const WIDGET_MAX_LINES = 10;
37
- /** Only a few jobs still fit with their tool-call and tool-result lines: 1 tally + 3*3 lines. */
38
- const WIDGET_MAX_DETAIL_JOBS = 3;
39
- /** In bulk, one row per job: 1 tally + 8 rows + 1 "more running" footer. */
40
- const WIDGET_MAX_JOBS = 8;
39
+ const WIDGET_MAX_LINES = 10;
40
+ /** Only a few jobs still fit with their tool-call and tool-result lines: 1 tally + 3 lines per job. */
41
+ const WIDGET_MAX_DETAIL_JOBS = Math.floor((WIDGET_MAX_LINES - 1) / 3);
42
+ /** In bulk, one row per job: 1 tally + N rows + 1 "more running" footer. */
43
+ const WIDGET_MAX_JOBS = WIDGET_MAX_LINES - 2;
41
44
  export const COLLAPSED_OUTPUT_LINES = 10;
42
- export const MAX_OUTPUT_BYTES = 50 * 1024;
45
+ const MAX_OUTPUT_BYTES = 50 * 1024;
43
46
  const EXPANDED_PAD = " ";
44
47
 
45
48
  /** Terminal statuses have static icons; running jobs use statusIcon's clock-driven frame. */
46
- export function statusIcon(status: JobStatus, now = Date.now()): string {
49
+ function statusIcon(status: JobStatus, now = Date.now()): string {
47
50
  return status === "running"
48
51
  ? SPINNER_FRAMES[Math.floor(now / SPINNER_INTERVAL_MS) % SPINNER_FRAMES.length]!
49
52
  : STATUS_ICONS[status];
@@ -61,7 +64,7 @@ export function formatTools(tools: string[]): string {
61
64
  return tools.join(", ") || "none";
62
65
  }
63
66
 
64
- export function formatTokens(count: number): string {
67
+ function formatTokens(count: number): string {
65
68
  if (count < 1000) return String(count);
66
69
  if (count < 10000) return `${(count / 1000).toFixed(1)}k`;
67
70
  if (count < 1000000) return `${Math.round(count / 1000)}k`;
@@ -69,7 +72,7 @@ export function formatTokens(count: number): string {
69
72
  return `${Math.round(count / 1000000)}M`;
70
73
  }
71
74
 
72
- export function formatDuration(ms: number): string {
75
+ function formatDuration(ms: number): string {
73
76
  const seconds = Math.max(0, Math.floor(ms / 1000));
74
77
  if (seconds < 60) return `${seconds}s`;
75
78
  const minutes = Math.floor(seconds / 60);
@@ -149,8 +152,14 @@ export function resultPreview(result: unknown, maxChars = 120): string | undefin
149
152
  return line.length > maxChars ? `${line.slice(0, maxChars - 1)}…` : line;
150
153
  }
151
154
 
155
+ /** Shared so failed reports and thrown errors phrase the resume hint identically. */
156
+ export function resumeHint(id: string): string {
157
+ return `To continue this job, call delegate with resume: ${id}.`;
158
+ }
159
+
152
160
  export function reportText(report: DelegateReport): string {
153
- if (report.error) return `Delegate "${report.agent}" (job ${report.id}) failed: ${report.error}`;
161
+ if (report.error)
162
+ return `Delegate "${report.agent}" (job ${report.id}) failed: ${report.error}\n${resumeHint(report.id)}`;
154
163
  const output = (report.output ?? "").trim();
155
164
  return `Delegate "${report.agent}" (job ${report.id}) finished.${output ? `\n\n${output}` : ""}`;
156
165
  }