@maheidem/pi-delegate 0.6.1 → 0.6.3

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
@@ -28,6 +28,7 @@ is performed by this package.
28
28
  /delegate dashboard (TUI) / status (headless)
29
29
  /delegate run general <task> foreground delegation (impl specialist)
30
30
  /delegate research <task> foreground web research (read-only tools)
31
+ /delegate bg [role] <task> run it in the background (report arrives later)
31
32
  /delegate on enable strict coordinator mode (session,
32
33
  tree-stable; active tool set becomes
33
34
  ['delegate'])
@@ -183,6 +184,16 @@ internal work events.
183
184
  children — receipts finalize interrupted/resumable. Prefer foreground for
184
185
  one-shot headless flows.
185
186
 
187
+ **User-facing launch (v0.6.2, R20).** `/delegate bg [general|research] <task>`
188
+ runs the same background run from the command line with no description to
189
+ write: one is derived from the task's first line (edge punctuation stripped,
190
+ first 3–6 words), validated by the same 3–6-word rule — a first line too
191
+ short to yield 3 words is an instructive error — echoed in the started line,
192
+ and stored on the receipt/ledger like an explicit one. The dashboard's
193
+ **Run background task…** action (task editor) takes the same path. Explicit
194
+ descriptions remain available to the model via `delegate({ background: true,
195
+ description: "…" })`; foreground `/delegate run` is unchanged.
196
+
186
197
  ### Bidirectional channels (v0.6.0, R16–R19)
187
198
 
188
199
  Background children are a team, not batch jobs — three channels, all auditable
package/background.ts CHANGED
@@ -35,6 +35,22 @@ export const BACKGROUND_LEDGER_TYPE = "delegate.background";
35
35
  /** R10: terminal-result custom-message type. */
36
36
  export const BACKGROUND_RESULT_TYPE = "delegate-background-result";
37
37
 
38
+ /**
39
+ * R20: derive a valid 3–6-word description from the task's first line when
40
+ * the user launches via `/delegate bg` (which takes no description). Takes
41
+ * the first line, strips edge punctuation, and uses its first words.
42
+ */
43
+ export function deriveBackgroundDescription(task: string): { ok: true; value: string } | { ok: false; error: string } {
44
+ const firstLine = task.split("\n")[0]?.trim() ?? "";
45
+ const cleaned = firstLine.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, " ").trim();
46
+ const words = cleaned.split(/\s+/).filter(Boolean).map((w) => w.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, "")).filter(Boolean);
47
+ if (words.length < 3) {
48
+ return { ok: false, error: "could not derive a 3–6-word description from the task's first line; give a longer task or use the delegate tool with an explicit description." };
49
+ }
50
+ const value = words.slice(0, 6).join(" ");
51
+ return validateBackgroundDescription(value);
52
+ }
53
+
38
54
  /** R12: was a terminal result for this run already delivered on the branch? */
39
55
  export function wasResultDelivered(branch: readonly SessionEntryLike[], runId: string): boolean {
40
56
  return branch.some((entry) => {
@@ -134,11 +150,9 @@ export function formatBackgroundResultEnvelope(
134
150
  runText: string,
135
151
  ): string {
136
152
  return (
137
- `[delegate background ${runId} · ${role} · ${description}: ${backgroundStateWord(state)}]\n` +
153
+ `### [delegate background ${runId} · ${role} · ${description}: ${backgroundStateWord(state)}]\n` +
138
154
  "\n" +
139
- "This is the terminal report of a background delegation. The run has finished and\n" +
140
- "cannot receive steering. Treat it as an internal work event: write user-visible\n" +
141
- "text only if material, and do not re-narrate the handoff.\n" +
155
+ "<!-- This is the terminal report of a background delegation. The run has finished and cannot receive steering. Treat it as an internal work event: write user-visible text only if material, and do not re-narrate the handoff. -->\n" +
142
156
  "\n" +
143
157
  runText
144
158
  );
@@ -157,13 +171,9 @@ export function formatBackgroundStartedText(runId: string, role: RoleName, descr
157
171
  /** R17: the question envelope (SPEC §5, byte-exact; wakes the parent). */
158
172
  export function formatChildQuestionEnvelope(runId: string, role: RoleName, description: string, topic: string, question: string): string {
159
173
  return (
160
- `[delegate background ${runId} · ${role} · ${description}: asks]\n` +
174
+ `### [delegate background ${runId} · ${role} · ${description}: asks]\n` +
161
175
  "\n" +
162
- `A delegated child is blocked waiting for your answer (topic: ${topic}). Answer\n` +
163
- `with the delegate_answer tool: delegate_answer({ runId: "${runId}", answer: "…" }).\n` +
164
- "Be terse and directive; the child resumes the moment your answer lands. Do not\n" +
165
- "narrate this exchange to the user unless it is material. If you cannot answer,\n" +
166
- "say so — the child proceeds with its best judgment after the ask budget expires.\n" +
176
+ `<!-- A delegated child is blocked waiting for your answer (topic: ${topic}). Answer with the delegate_answer tool: delegate_answer({ runId: "${runId}", answer: "…" }). Be terse and directive; the child resumes the moment your answer lands. Do not narrate this exchange to the user unless it is material. If you cannot answer, say so — the child proceeds with its best judgment after the ask budget expires. -->\n` +
167
177
  "\n" +
168
178
  question
169
179
  );
@@ -172,10 +182,9 @@ export function formatChildQuestionEnvelope(runId: string, role: RoleName, descr
172
182
  /** R18: the note envelope (SPEC §5, byte-exact; NEVER wakes the parent). */
173
183
  export function formatChildNoteEnvelope(runId: string, role: RoleName, description: string, topic: string, note: string): string {
174
184
  return (
175
- `[delegate background ${runId} · ${role} · ${description}: note]\n` +
185
+ `### [delegate background ${runId} · ${role} · ${description}: note]\n` +
176
186
  "\n" +
177
- `A delegated child filed a non-blocking note (topic: ${topic}). No answer is\n` +
178
- "expected or possible. Treat it as an internal work event.\n" +
187
+ `<!-- A delegated child filed a non-blocking note (topic: ${topic}). No answer is expected or possible. Treat it as an internal work event. -->\n` +
179
188
  "\n" +
180
189
  note
181
190
  );
@@ -744,7 +753,7 @@ export function backgroundResultDisplay(content: string, details: { runId?: stri
744
753
  const state = (details.state ?? "?") as RunTerminalState;
745
754
  const word = backgroundStateWord(state);
746
755
  const glyph = state === "succeeded" ? "✓" : state === "cancelled" ? "⊘" : state.startsWith("timed_out") ? "⏱" : "⚠";
747
- const runId = details.runId ?? "?";
756
+ const runId = (details.runId ?? "?").slice(-12);
748
757
  const desc = details.description ? ` · ${details.description}` : "";
749
758
  const bodyLines = body.split("\n");
750
759
  const head = bodyLines[0] ?? "";
package/commands.ts CHANGED
@@ -19,6 +19,7 @@ export type DelegateIntent =
19
19
  | { kind: "help" }
20
20
  | { kind: "cancel"; runId?: string }
21
21
  | { kind: "answer"; runId: string; text: string }
22
+ | { kind: "bg"; role: RoleName; task: string; timeoutMs?: number }
22
23
  | { kind: "inspect"; runId?: string }
23
24
  | { kind: "resume"; runId?: string; task: string; timeoutMs?: number }
24
25
  | { kind: "peek"; runId?: string }
@@ -53,6 +54,7 @@ export const RESERVED_FIRST_TOKENS = new Set([
53
54
  "help",
54
55
  "cancel",
55
56
  "answer",
57
+ "bg",
56
58
  "inspect",
57
59
  "resume",
58
60
  "peek",
@@ -121,6 +123,21 @@ export function parseDelegateCommand(input: string, options: ParseOptions = {}):
121
123
  if (!runId || !body) return invalid("resume");
122
124
  return { kind: "resume", runId, task: body, timeoutMs };
123
125
  }
126
+ case "bg": {
127
+ // R20: user-facing background launch — /delegate bg [general|research] <task>
128
+ const rest = trimmed.slice("bg".length).trim();
129
+ if (!rest) return invalid("bg");
130
+ const { task, timeoutMs } = extractFlags(rest);
131
+ if (!task) return invalid("bg");
132
+ const parts = task.split(/\s+/);
133
+ const roleToken = parts[0]!;
134
+ if (roleToken === "general" || roleToken === "research") {
135
+ const body = parts.slice(1).join(" ").trim();
136
+ if (!body) return invalid("bg");
137
+ return { kind: "bg", role: roleToken, task: body, timeoutMs };
138
+ }
139
+ return { kind: "bg", role: "general", task, timeoutMs };
140
+ }
124
141
  case "run": {
125
142
  const rest = trimmed.slice("run".length).trim();
126
143
  if (!rest) return invalid("run");
@@ -154,7 +171,7 @@ function invalid(token: string): DelegateIntent {
154
171
  export function delegateCompletions(prefix: string, recentRunIds: string[] = []): string[] {
155
172
  const words = (prefix ?? "").trimStart();
156
173
  const tokens = words.split(/\s+/);
157
- const base: string[] = ["on", "off", "status", "paths", "doctor", "help", "cancel ", "answer ", "inspect ", "resume ", "peek ", "run ", "research "];
174
+ const base: string[] = ["on", "off", "status", "paths", "doctor", "help", "cancel ", "answer ", "bg ", "inspect ", "resume ", "peek ", "run ", "research "];
158
175
 
159
176
  const matches: string[] = [];
160
177
  if (tokens.length <= 1) {
package/index.ts CHANGED
@@ -49,6 +49,7 @@ import {
49
49
  BackgroundManager,
50
50
  BACKGROUND_RESULT_TYPE,
51
51
  backgroundResultDisplay,
52
+ deriveBackgroundDescription,
52
53
  formatBackgroundDetailText,
53
54
  formatBackgroundInventoryText,
54
55
  formatBackgroundStartedText,
@@ -822,7 +823,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
822
823
  : "";
823
824
  const parts = text.split("\n\n");
824
825
  const body = parts.length > 2 ? parts.slice(2).join("\n\n") : text;
825
- return new Text(`? background ${d.runId ?? "?"}${d.description ? ` · ${d.description}` : ""}: asks (${d.topic ?? "?"})\n\n${body}`, 0, 0);
826
+ return new Text(`? background ${(d.runId ?? "?").slice(-12)}${d.description ? ` · ${d.description}` : ""}: asks (${d.topic ?? "?"})\n\n${body}`, 0, 0);
826
827
  });
827
828
 
828
829
  pi.registerMessageRenderer(CHILD_NOTE_TYPE, (message: { content?: string | unknown[]; details?: unknown }) => {
@@ -834,7 +835,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
834
835
  : "";
835
836
  const parts = text.split("\n\n");
836
837
  const body = parts.length > 2 ? parts.slice(2).join("\n\n") : text;
837
- return new Text(`ℹ background ${d.runId ?? "?"}${d.description ? ` · ${d.description}` : ""}: note (${d.topic ?? "?"})\n\n${body}`, 0, 0);
838
+ return new Text(`ℹ background ${(d.runId ?? "?").slice(-12)}${d.description ? ` · ${d.description}` : ""}: note (${d.topic ?? "?"})\n\n${body}`, 0, 0);
838
839
  });
839
840
 
840
841
  // ── Handoff custom message renderer (§6.4) ─────────────────────────────
@@ -992,6 +993,36 @@ export default function delegateExtension(pi: ExtensionAPI) {
992
993
  sendHandoffMessage(r);
993
994
  };
994
995
 
996
+ // R20: user-facing background launch — /delegate bg and the dashboard
997
+ // action spawn a background run (description derived from the task's
998
+ // first line) and return immediately; the report arrives later.
999
+ const runCommandBackground = async (task: string, role: "general" | "research", ctx: ExtensionCommandContext, timeoutMs?: number): Promise<void> => {
1000
+ const desc = deriveBackgroundDescription(task);
1001
+ if (!desc.ok) {
1002
+ say(ctx, `[delegate] ${desc.error}`, "error");
1003
+ return;
1004
+ }
1005
+ const slot = background.slotError();
1006
+ if (slot) {
1007
+ say(ctx, `[delegate] ${slot.code}: ${slot.message}`, "warning");
1008
+ return;
1009
+ }
1010
+ const request = buildRequest(task, role, "command", ctx, timeoutMs, {
1011
+ background: true,
1012
+ description: desc.value,
1013
+ });
1014
+ refreshDoctor(ctx);
1015
+ const attempt = app.runBackground(request, {
1016
+ onAsk: (ask) => background.onAsk(ask),
1017
+ });
1018
+ if ("error" in attempt) {
1019
+ say(ctx, formatRunText(attempt.error), "error");
1020
+ return;
1021
+ }
1022
+ background.register(attempt.handle);
1023
+ say(ctx, formatBackgroundStartedText(attempt.handle.runId, attempt.handle.role, attempt.handle.description));
1024
+ };
1025
+
995
1026
  const statusText = (ctx: ExtensionContext): string => {
996
1027
  const s = app.getStatus(pi.getActiveTools(), ctx.cwd ?? process.cwd());
997
1028
  const lines = ["[delegate]", `version: v${delegateVersion()} (loaded at session start; /reload picks up newer installs)`, `mode: ${s.modeEnabled ? "strict" : "normal"}`];
@@ -1034,6 +1065,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
1034
1065
  "/delegate status stable status text",
1035
1066
  "/delegate run general <task> run a delegation with a role",
1036
1067
  "/delegate research <task> research role",
1068
+ "/delegate bg [role] <task> run it in the background (report arrives later)",
1037
1069
  "/delegate <task> general-role shorthand",
1038
1070
  "/delegate cancel [run-id] cancel the active run",
1039
1071
  "/delegate answer <run-id> <text> answer a blocked background child's question",
@@ -1152,6 +1184,9 @@ export default function delegateExtension(pi: ExtensionAPI) {
1152
1184
  }
1153
1185
  await runCommandForeground(intent.task, intent.role, ctx, intent.timeoutMs);
1154
1186
  return;
1187
+ case "bg":
1188
+ await runCommandBackground(intent.task, isRoleName(intent.role) ? intent.role : "general", ctx, intent.timeoutMs);
1189
+ return;
1155
1190
  case "peek": {
1156
1191
  const id = intent.runId?.trim() || app.mostRecentRunId();
1157
1192
  if (!id) {
@@ -1367,6 +1402,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
1367
1402
  rows: [
1368
1403
  { key: "run-general", label: "Run general task…", value: "", kind: "action" },
1369
1404
  { key: "run-research", label: "Run research task…", value: "", kind: "action" },
1405
+ { key: "run-background", label: "Run background task…", value: "", kind: "action" },
1370
1406
  { key: "peek", label: "Peek live / final detail", value: "", kind: "action", disabled: !active && !last },
1371
1407
  { key: "cancel", label: "Cancel active run", value: "", kind: "action", disabled: !active },
1372
1408
  { key: "resume", label: "Resume last run…", value: "", kind: "action", disabled: !last },
@@ -1458,6 +1494,13 @@ export default function delegateExtension(pi: ExtensionAPI) {
1458
1494
  await runCommandForeground(task, role, ctx);
1459
1495
  continue;
1460
1496
  }
1497
+ // R20: user-facing background launch — spawn, return immediately.
1498
+ if (action === "run-background") {
1499
+ const task = await ctx.ui.editor("Background task (returns immediately)", "");
1500
+ if (!task || !task.trim()) continue;
1501
+ await runCommandBackground(task.trim(), "general", ctx);
1502
+ continue;
1503
+ }
1461
1504
  if (action === "peek") {
1462
1505
  await openPeek(ctx);
1463
1506
  continue;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maheidem/pi-delegate",
3
- "version": "0.6.1",
3
+ "version": "0.6.3",
4
4
  "type": "module",
5
5
  "description": "Foreground isolated delegation and strict coordinator mode for the Pi coding agent.",
6
6
  "license": "MIT",