@deathbeam/pi-delegate 0.0.10 → 0.0.12

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.
Files changed (3) hide show
  1. package/format.ts +3 -16
  2. package/index.ts +153 -38
  3. package/package.json +1 -1
package/format.ts CHANGED
@@ -41,7 +41,6 @@ const WIDGET_MAX_JOBS = 8;
41
41
  export const COLLAPSED_OUTPUT_LINES = 10;
42
42
  export const MAX_OUTPUT_BYTES = 50 * 1024;
43
43
  const EXPANDED_PAD = " ";
44
- const TASK_LABEL = "Task: ";
45
44
 
46
45
  /** Terminal statuses have static icons; running jobs use statusIcon's clock-driven frame. */
47
46
  export function statusIcon(status: JobStatus, now = Date.now()): string {
@@ -110,21 +109,9 @@ export function toolCallDetail(toolName: string, args: unknown): string {
110
109
  }
111
110
  }
112
111
 
113
- /** Align multi-line task details under the Task label. */
114
- export function launchDetails(info: { task?: string; model?: string; tools: string[] }): string[] {
115
- const lines = [
116
- `${EXPANDED_PAD}Model: ${info.model ?? "default"}`,
117
- `${EXPANDED_PAD}Tools: ${formatTools(info.tools)}`,
118
- ];
119
- const task = (info.task ?? "").trim();
120
- if (task) {
121
- lines.push(
122
- ...task
123
- .split("\n")
124
- .map((line, index) => `${EXPANDED_PAD}${index ? " ".repeat(TASK_LABEL.length) : TASK_LABEL}${line}`),
125
- );
126
- }
127
- return lines;
112
+ /** Expanded launch metadata; the call renderer shows the task. */
113
+ export function launchDetails(info: { model?: string; tools: string[] }): string[] {
114
+ return [`${EXPANDED_PAD}Model: ${info.model ?? "default"}`, `${EXPANDED_PAD}Tools: ${formatTools(info.tools)}`];
128
115
  }
129
116
 
130
117
  /** Close dangling Markdown fences so collapsed previews render correctly. */
package/index.ts CHANGED
@@ -4,7 +4,7 @@ import { existsSync, readdirSync, readFileSync } from "node:fs";
4
4
  import { homedir } from "node:os";
5
5
  import { join, resolve } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
- import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
7
+ import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
8
8
  import {
9
9
  CONFIG_DIR_NAME,
10
10
  getAgentDir,
@@ -13,10 +13,13 @@ import {
13
13
  parseFrontmatter,
14
14
  } from "@earendil-works/pi-coding-agent";
15
15
  import {
16
+ type Component,
16
17
  Container,
17
18
  HStack,
18
19
  Markdown,
20
+ Spacer,
19
21
  Text,
22
+ TruncatedText,
20
23
  matchesKey,
21
24
  truncateToWidth,
22
25
  wrapTextWithAnsi,
@@ -96,6 +99,7 @@ const DELEGATION_TOOLS = new Set(["delegate", "delegate_list", "delegate_steer",
96
99
  const MODEL_TIERS = new Set(["cheap", "balanced", "strong"]);
97
100
  const WIDGET_KEY = "delegate";
98
101
  const RESULT_MESSAGE = "delegate-result";
102
+ const TASK_PREVIEW_LINES = 5;
99
103
 
100
104
  function expandPath(value: string, cwd: string): string {
101
105
  return resolve(cwd, value.replace(/^~(?=\/|$)/, homedir()));
@@ -182,6 +186,60 @@ function contextWindowFor(ctx: ExtensionContext, model: string | undefined): num
182
186
  return ctx.modelRegistry.find(model.slice(0, separator), model.slice(separator + 1))?.contextWindow;
183
187
  }
184
188
 
189
+ function argText(value: unknown): string {
190
+ return typeof value === "string" ? value : "";
191
+ }
192
+
193
+ function jobId(value: unknown): string {
194
+ return argText(value)
195
+ .trim()
196
+ .replace(/^job\s+/i, "");
197
+ }
198
+
199
+ function resultText(result: { content: readonly { type: string; text?: string }[] }): string {
200
+ return result.content.flatMap((part) => (part.type === "text" ? [part.text ?? ""] : [])).join("\n");
201
+ }
202
+
203
+ function resultFallback(body: string, theme: Theme, isError: boolean): Text {
204
+ return new Text(`\n${theme.fg(isError ? "error" : "toolOutput", body || "(no output)")}`, 0, 0);
205
+ }
206
+
207
+ /** Shared tool layout: an optional identity header, then a width-aware payload preview. */
208
+ function toolLayout(toolName: string, identity: string, payload: string, theme: Theme, expanded: boolean): Component {
209
+ const container = new Container();
210
+ if (toolName)
211
+ container.addChild(
212
+ new TruncatedText(`${theme.fg("toolTitle", theme.bold(toolName))}${identity ? ` ${identity}` : ""}`),
213
+ );
214
+ if (!payload.trim()) return container;
215
+ const body = new Text(
216
+ payload
217
+ .split("\n")
218
+ .map((line) => theme.fg("toolOutput", line))
219
+ .join("\n"),
220
+ 0,
221
+ 0,
222
+ );
223
+ if (toolName) container.addChild(new Spacer(1));
224
+ container.addChild({
225
+ render: (width) => {
226
+ // Wrapping turns one long line into many, so the cap counts rendered rows, not source lines.
227
+ const lines = body.render(width);
228
+ if (expanded || lines.length <= COLLAPSED_OUTPUT_LINES) return lines;
229
+ return [
230
+ ...lines.slice(0, COLLAPSED_OUTPUT_LINES),
231
+ truncateToWidth(
232
+ theme.fg("muted", `… ${lines.length - COLLAPSED_OUTPUT_LINES} more lines, `) +
233
+ keyHint("app.tools.expand", "to expand"),
234
+ width,
235
+ ),
236
+ ];
237
+ },
238
+ invalidate: () => body.invalidate(),
239
+ });
240
+ return container;
241
+ }
242
+
185
243
  export default function (pi: ExtensionAPI) {
186
244
  const running = new Map<string, DelegateJob>();
187
245
  const recent: InspectJob[] = [];
@@ -202,7 +260,6 @@ export default function (pi: ExtensionAPI) {
202
260
  viewing?.();
203
261
  };
204
262
 
205
- // Status words are gone; only a failure detail is worth a log line.
206
263
  const remember = (job: DelegateJob, status: JobStatus, detail?: string) => {
207
264
  job.status = status;
208
265
  if (detail) addActivity(job, { kind: "status", text: detail });
@@ -210,6 +267,21 @@ export default function (pi: ExtensionAPI) {
210
267
  recent.unshift({ ...snapshot, endedAt: Date.now() });
211
268
  };
212
269
 
270
+ const jobSnapshot = (job: DelegateJob) => ({
271
+ id: job.id,
272
+ agent: job.agent,
273
+ description: job.description,
274
+ contextTokens: job.contextTokens,
275
+ contextWindow: job.contextWindow,
276
+ startedAt: job.startedAt,
277
+ });
278
+
279
+ const jobTarget = (rawId: unknown, theme: Theme): string => {
280
+ const id = jobId(rawId);
281
+ const job = running.get(id) ?? recent.find((item) => item.id === id);
282
+ return job ? jobIdentity(theme, job) : theme.fg("muted", id || "…");
283
+ };
284
+
213
285
  const refreshWidget = (ctx: ExtensionContext) => {
214
286
  if (!ctx.hasUI) return;
215
287
  viewing?.();
@@ -338,8 +410,16 @@ export default function (pi: ExtensionAPI) {
338
410
  const jobs = () => [...running.values(), ...recent];
339
411
  const bodyHeight = () => Math.max(0, tui.terminal.rows - 3);
340
412
  // The list pane already draws a border, and the muted model line sets the task apart.
341
- const taskLines = (job: InspectJob, width: number) =>
342
- wrapTextWithAnsi(job.task.trim(), Math.max(1, width)).map((line) => theme.fg("text", line));
413
+ const taskLines = (job: InspectJob, width: number) => {
414
+ const lines = wrapTextWithAnsi(job.task.trim(), Math.max(1, width)).map((line) =>
415
+ theme.fg("text", line),
416
+ );
417
+ if (lines.length <= TASK_PREVIEW_LINES) return lines;
418
+ return [
419
+ ...lines.slice(0, TASK_PREVIEW_LINES),
420
+ theme.fg("muted", `… ${lines.length - TASK_PREVIEW_LINES} more lines`),
421
+ ];
422
+ };
343
423
  const toolsLines = (job: InspectJob, width: number) =>
344
424
  wrapTextWithAnsi(formatTools(job.tools), Math.max(1, width)).map((line) =>
345
425
  theme.fg("dim", line),
@@ -644,31 +724,45 @@ export default function (pi: ExtensionAPI) {
644
724
  },
645
725
 
646
726
  renderCall(args, theme, context) {
647
- const summary = args.description?.trim() || args.task?.split("\n")[0]?.trim() || "";
648
- const hint = `${theme.fg("muted", "(")}${keyHint("app.tools.expand", context.expanded ? "to collapse" : "to expand")}${theme.fg("muted", ")")}`;
649
- return new Text(
650
- `${theme.fg("toolTitle", theme.bold("delegate "))}${theme.fg("accent", summary)} ${hint}`,
651
- 0,
652
- 0,
727
+ const agent = argText(args?.agent).trim();
728
+ const description = argText(args?.description).trim();
729
+ const identity = [
730
+ agent ? theme.fg("toolTitle", theme.bold(agent)) : "",
731
+ description ? theme.fg("accent", description) : "",
732
+ ]
733
+ .filter(Boolean)
734
+ .join(" ");
735
+ return toolLayout(
736
+ "delegate",
737
+ identity || theme.fg("muted", "…"),
738
+ argText(args?.task),
739
+ theme,
740
+ context.expanded,
653
741
  );
654
742
  },
655
743
 
656
744
  renderResult(result, { expanded }, theme, context) {
657
745
  const details = result.details as DelegateDetails | undefined;
658
- const body = result.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n");
659
- if (!details?.agent) return new Text(body || "(no output)", 0, 0);
660
-
661
- const icon = statusText(theme, context.isError ? "failed" : "done");
746
+ const body = resultText(result);
747
+ if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
662
748
  const status = details.background ? "started in background" : "completed";
663
749
  const container = new Container();
664
750
  container.addChild(
665
751
  new Text(
666
- `${icon} ${jobIdentity(theme, details)} ${theme.fg("muted", details.description)} ${theme.fg("dim", status)}`,
752
+ `\n${statusText(theme, "done")} ${jobIdentity(theme, details)} ${theme.fg("dim", status)}`,
667
753
  0,
668
754
  0,
669
755
  ),
670
756
  );
671
- if (expanded) container.addChild(new Text(theme.fg("dim", launchDetails(details).join("\n")), 0, 0));
757
+ // The call body already carries the task; only the launch metadata is new here.
758
+ if (expanded)
759
+ container.addChild(
760
+ new Text(
761
+ theme.fg("dim", launchDetails({ model: details.model, tools: details.tools }).join("\n")),
762
+ 0,
763
+ 0,
764
+ ),
765
+ );
672
766
  // Background results arrive as their own message; headless runs still show the output here.
673
767
  if (!details.background && body) {
674
768
  const { shown, hidden } = outputPreview(body, expanded ? Infinity : COLLAPSED_OUTPUT_LINES);
@@ -699,7 +793,7 @@ export default function (pi: ExtensionAPI) {
699
793
  message: Type.String({ description: "The guidance to deliver to the running child." }),
700
794
  }),
701
795
  async execute(_toolCallId, params) {
702
- const id = params.id.trim().replace(/^job\s+/i, "");
796
+ const id = jobId(params.id);
703
797
  const job = running.get(id);
704
798
  if (!job?.steer) throw new Error(`No running delegate job "${id}".`);
705
799
  await job.steer(params.message);
@@ -722,30 +816,24 @@ export default function (pi: ExtensionAPI) {
722
816
  },
723
817
 
724
818
  renderCall(args, theme, context) {
725
- const message = args.message?.split("\n")[0]?.trim() ?? "";
726
- const hint = `${theme.fg("muted", "(")}${keyHint("app.tools.expand", context.expanded ? "to collapse" : "to expand")}${theme.fg("muted", ")")}`;
727
- return new Text(
728
- `${theme.fg("toolTitle", theme.bold("delegate_steer "))}${theme.fg("accent", message)} ${hint}`,
729
- 0,
730
- 0,
819
+ return toolLayout(
820
+ "delegate_steer",
821
+ jobTarget(args?.id, theme),
822
+ argText(args?.message),
823
+ theme,
824
+ context.expanded,
731
825
  );
732
826
  },
733
827
 
734
- renderResult(result, { expanded }, theme, context) {
828
+ renderResult(result, _options, theme, context) {
735
829
  const details = result.details as SteerDetails | undefined;
736
- const body = result.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n");
737
- if (!details?.agent) return new Text(body || "(no output)", 0, 0);
738
- const icon = statusText(theme, context.isError ? "failed" : "done");
739
- const container = new Container();
740
- container.addChild(
741
- new Text(
742
- `${icon} ${jobIdentity(theme, details)} ${theme.fg("muted", details.description)} ${theme.fg("muted", usageStats(details, details.elapsedMs))}`,
743
- 0,
744
- 0,
745
- ),
830
+ const body = resultText(result);
831
+ if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
832
+ return new Text(
833
+ `\n${statusText(theme, "done")} ${jobIdentity(theme, details)} ${theme.fg("muted", details.description)} ${theme.fg("muted", usageStats(details, details.elapsedMs))}`,
834
+ 0,
835
+ 0,
746
836
  );
747
- if (expanded) container.addChild(new Text(theme.fg("dim", details.message), 0, 0));
748
- return container;
749
837
  },
750
838
  });
751
839
 
@@ -759,7 +847,7 @@ export default function (pi: ExtensionAPI) {
759
847
  id: Type.String({ description: "Job id from delegate or delegate_list." }),
760
848
  }),
761
849
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
762
- const id = params.id.trim().replace(/^job\s+/i, "");
850
+ const id = jobId(params.id);
763
851
  const job = running.get(id);
764
852
  if (!job) throw new Error(`No running delegate job "${id}".`);
765
853
  running.delete(id);
@@ -774,6 +862,21 @@ export default function (pi: ExtensionAPI) {
774
862
  details: { id: job.id, agent: job.agent },
775
863
  };
776
864
  },
865
+
866
+ renderCall(args, theme, context) {
867
+ return toolLayout("delegate_cancel", jobTarget(args?.id, theme), "", theme, context.expanded);
868
+ },
869
+
870
+ renderResult(result, _options, theme, context) {
871
+ const details = result.details as { id: string; agent: string } | undefined;
872
+ const body = resultText(result);
873
+ if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
874
+ return new Text(
875
+ `\n${statusText(theme, "cancelled")} ${jobIdentity(theme, details)} ${theme.fg("muted", "cancellation requested")}`,
876
+ 0,
877
+ 0,
878
+ );
879
+ },
777
880
  });
778
881
 
779
882
  pi.registerTool({
@@ -795,8 +898,20 @@ export default function (pi: ExtensionAPI) {
795
898
  );
796
899
  return {
797
900
  content: [{ type: "text", text: `${jobs.length} running:\n${lines.join("\n")}` }],
798
- details: undefined,
901
+ details: { jobs: jobs.map(jobSnapshot) },
799
902
  };
800
903
  },
904
+ renderResult(result, _options, theme, context) {
905
+ const jobs = (result.details as { jobs?: ReturnType<typeof jobSnapshot>[] } | undefined)?.jobs;
906
+ if (!jobs?.length || context.isError) return resultFallback(resultText(result), theme, context.isError);
907
+ const now = Date.now();
908
+ return new Text(
909
+ `\n${jobs
910
+ .map((job) => `${jobIdentity(theme, job)} ${theme.fg("muted", jobLine(job, now - job.startedAt))}`)
911
+ .join("\n")}`,
912
+ 0,
913
+ 0,
914
+ );
915
+ },
801
916
  });
802
917
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deathbeam/pi-delegate",
3
- "version": "0.0.10",
3
+ "version": "0.0.12",
4
4
  "description": "Run focused Pi subagents as background tasks",
5
5
  "type": "module",
6
6
  "license": "MIT",