@maheidem/pi-delegate 0.6.4 → 0.7.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/application.ts CHANGED
@@ -173,6 +173,33 @@ export class DelegateApplicationImpl implements DelegateApplication {
173
173
  }
174
174
  }
175
175
 
176
+ /**
177
+ * R22: the configured default execution mode for delegations without
178
+ * an explicit override (absent `background` parameter / no flag).
179
+ */
180
+ defaultExecution(): "background" | "foreground" {
181
+ return this.liveConfig.defaultExecution;
182
+ }
183
+
184
+ /**
185
+ * R22: toggle the default execution mode (dashboard Advanced screen).
186
+ * Persists through the same saveConfig path as patchConfig; unlike
187
+ * patchConfig it is NOT numeric. Returns an error string or null.
188
+ */
189
+ patchDefaultExecution(value: "background" | "foreground"): string | null {
190
+ if (value !== "background" && value !== "foreground") {
191
+ return `Unknown execution mode '${value}'.`;
192
+ }
193
+ try {
194
+ const { config } = normalizeConfig({ ...(this.liveConfig as unknown as Record<string, unknown>), defaultExecution: value });
195
+ saveConfig(this.ports.agentDir, config);
196
+ this.liveConfig = config;
197
+ return null;
198
+ } catch (error) {
199
+ return `Save failed: ${(error as Error).message}`;
200
+ }
201
+ }
202
+
176
203
  // ── Mode ───────────────────────────────────────────────────────────────
177
204
 
178
205
  isStrict(): boolean {
@@ -217,7 +244,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
217
244
  }
218
245
 
219
246
  /** Advanced knobs for the dashboard's Configure-advanced screen (§ S7). */
220
- panelConfig(): Pick<DelegateConfigV1, "queueLimit" | "killGraceMs" | "handoffGraceMs" | "handoffEnforceTimeoutMs" | "stuckToolTimeoutMs" | "maxTaskBytes" | "maxResultBytes" | "updateThrottleMs" | "defaultRole" | "maxRuns" | "maxRunAgeDays"> {
247
+ panelConfig(): Pick<DelegateConfigV1, "queueLimit" | "killGraceMs" | "handoffGraceMs" | "handoffEnforceTimeoutMs" | "stuckToolTimeoutMs" | "maxTaskBytes" | "maxResultBytes" | "updateThrottleMs" | "defaultRole" | "defaultExecution" | "maxRuns" | "maxRunAgeDays"> {
221
248
  const c = this.liveConfig;
222
249
  return {
223
250
  queueLimit: c.queueLimit,
@@ -229,6 +256,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
229
256
  maxResultBytes: c.maxResultBytes,
230
257
  updateThrottleMs: c.updateThrottleMs,
231
258
  defaultRole: c.defaultRole,
259
+ defaultExecution: c.defaultExecution,
232
260
  maxRuns: c.maxRuns,
233
261
  maxRunAgeDays: c.maxRunAgeDays,
234
262
  };
@@ -344,7 +372,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
344
372
  } catch {
345
373
  // cleanup failure is warning-only
346
374
  }
347
- return outcomeToRunResult(outcome, opened.metadata, role.name, model, request.thinkingLevel, { timeoutInfo, modelNote });
375
+ return outcomeToRunResult(outcome, opened.metadata, role.name, model, request.thinkingLevel, { timeoutInfo, modelNote, ...(request.description ? { description: request.description } : {}) });
348
376
  } catch (error) {
349
377
  this.activeRun = null;
350
378
  return errorResult(opened.metadata.runId, role.name, "E_CHILD_EXIT", `Delegation failed unexpectedly: ${(error as Error).message}`);
@@ -908,7 +936,7 @@ function outcomeToRunResult(
908
936
  role: RoleName,
909
937
  model: string,
910
938
  thinkingLevel?: string,
911
- provenance?: { timeoutInfo?: string; modelNote?: string },
939
+ provenance?: { timeoutInfo?: string; modelNote?: string; description?: string },
912
940
  ): DelegateRunResult {
913
941
  const ok = outcome.state === "succeeded";
914
942
  const details: DelegateDetails = {
@@ -928,6 +956,8 @@ function outcomeToRunResult(
928
956
  outputTruncated: outcome.outputTruncated,
929
957
  ...(outcome.partialHandoff ? { partialHandoff: outcome.partialHandoff } : {}),
930
958
  ...(provenance?.timeoutInfo ? { timeoutInfo: provenance.timeoutInfo } : {}),
959
+ // R22: foreground results return the validated description inline.
960
+ ...(provenance?.description ? { description: provenance.description } : {}),
931
961
  transcriptPath: outcome.transcriptPath,
932
962
  stderrPath: outcome.stderrPath,
933
963
  displayItems: outcome.displayItems,
package/commands.ts CHANGED
@@ -19,11 +19,12 @@ 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
+ | { kind: "bg"; role: RoleName; task: string; timeoutMs?: number; execution?: "background" | "foreground" }
23
+ | { kind: "fg"; role: RoleName; task: string; timeoutMs?: number; execution?: "background" | "foreground" }
23
24
  | { kind: "inspect"; runId?: string }
24
- | { kind: "resume"; runId?: string; task: string; timeoutMs?: number }
25
+ | { kind: "resume"; runId?: string; task: string; timeoutMs?: number; execution?: "background" | "foreground" }
25
26
  | { kind: "peek"; runId?: string }
26
- | { kind: "run"; role: RoleName; task: string; explicit: boolean; timeoutMs?: number }
27
+ | { kind: "run"; role: RoleName; task: string; explicit: boolean; timeoutMs?: number; execution?: "background" | "foreground" }
27
28
  | { kind: "invalid"; token: string; usage: string };
28
29
 
29
30
  export const DELEGATE_USAGE = [
@@ -38,9 +39,10 @@ export const DELEGATE_USAGE = [
38
39
  "/delegate peek [run-id] live/final feed of a run's child activity",
39
40
  "/delegate inspect [run-id] show run metadata (defaults to latest)",
40
41
  "/delegate run <general|research> <task...> run with an explicit role",
42
+ "/delegate fg [general|research] <task...> run in the FOREGROUND (blocks until done)",
41
43
  "/delegate research <task...> research-role shorthand",
42
44
  "/delegate <task...> general-role shorthand",
43
- "flags (run/research/<task>): --timeout <90s|10m|2h|1d|ms>",
45
+ "flags (run/research/<task>): --timeout <90s|10m|2h|1d|ms> --background --foreground (mutually exclusive)",
44
46
  "timeout priority: per-invocation > project .pi/delegate/config.json > user ~/.pi/agent/delegate/config.json",
45
47
  "/delegate help this help",
46
48
  ].join("\n");
@@ -55,6 +57,7 @@ export const RESERVED_FIRST_TOKENS = new Set([
55
57
  "cancel",
56
58
  "answer",
57
59
  "bg",
60
+ "fg",
58
61
  "inspect",
59
62
  "resume",
60
63
  "peek",
@@ -75,9 +78,9 @@ export function parseDelegateCommand(input: string, options: ParseOptions = {}):
75
78
  if (!RESERVED_FIRST_TOKENS.has(first)) {
76
79
  // General-role shorthand. `research` is reserved, so a general task
77
80
  // that starts with that word must use `run general ...`.
78
- const { task, timeoutMs } = extractFlags(trimmed);
81
+ const { task, timeoutMs, execution } = extractFlags(trimmed);
79
82
  if (!task) return invalid(first);
80
- return { kind: "run", role: "general", task, explicit: false, timeoutMs };
83
+ return { kind: "run", role: "general", task, explicit: false, timeoutMs, ...(execution ? { execution } : {}) };
81
84
  }
82
85
 
83
86
  switch (first) {
@@ -117,47 +120,65 @@ export function parseDelegateCommand(input: string, options: ParseOptions = {}):
117
120
  case "resume": {
118
121
  const rest = trimmed.slice("resume".length).trim();
119
122
  if (!rest) return invalid("resume");
120
- const { task, timeoutMs } = extractFlags(rest);
123
+ const { task, timeoutMs, execution } = extractFlags(rest);
121
124
  const runId = task.split(/\s+/)[0] ?? "";
122
125
  const body = task.slice(runId.length).trim();
123
126
  if (!runId || !body) return invalid("resume");
124
- return { kind: "resume", runId, task: body, timeoutMs };
127
+ return { kind: "resume", runId, task: body, timeoutMs, ...(execution ? { execution } : {}) };
125
128
  }
126
129
  case "bg": {
127
130
  // R20: user-facing background launch — /delegate bg [general|research] <task>
128
131
  const rest = trimmed.slice("bg".length).trim();
129
132
  if (!rest) return invalid("bg");
130
- const { task, timeoutMs } = extractFlags(rest);
133
+ const { task, timeoutMs, execution } = extractFlags(rest);
131
134
  if (!task) return invalid("bg");
132
135
  const parts = task.split(/\s+/);
133
136
  const roleToken = parts[0]!;
134
137
  if (roleToken === "general" || roleToken === "research") {
135
138
  const body = parts.slice(1).join(" ").trim();
136
139
  if (!body) return invalid("bg");
137
- return { kind: "bg", role: roleToken, task: body, timeoutMs };
140
+ return { kind: "bg", role: roleToken, task: body, timeoutMs, ...(execution ? { execution } : {}) };
138
141
  }
139
- return { kind: "bg", role: "general", task, timeoutMs };
142
+ return { kind: "bg", role: "general", task, timeoutMs, ...(execution ? { execution } : {}) };
143
+ }
144
+ case "fg": {
145
+ // R22: explicit foreground shorthand — mirrors `bg` (role prefix
146
+ // optional, defaults to general), but means FOREGROUND.
147
+ const rest = trimmed.slice("fg".length).trim();
148
+ if (!rest) return invalid("fg");
149
+ const { task, timeoutMs, execution } = extractFlags(rest);
150
+ if (!task) return invalid("fg");
151
+ const parts = task.split(/\s+/);
152
+ const roleToken = parts[0]!;
153
+ if (roleToken === "general" || roleToken === "research") {
154
+ const body = parts.slice(1).join(" ").trim();
155
+ if (!body) return invalid("fg");
156
+ return { kind: "fg", role: roleToken, task: body, timeoutMs, ...(execution ? { execution } : {}) };
157
+ }
158
+ return { kind: "fg", role: "general", task, timeoutMs, ...(execution ? { execution } : {}) };
140
159
  }
141
160
  case "run": {
142
161
  const rest = trimmed.slice("run".length).trim();
143
162
  if (!rest) return invalid("run");
144
- const { task, timeoutMs } = extractFlags(rest);
163
+ const { task, timeoutMs, execution } = extractFlags(rest);
145
164
  const parts = task.split(/\s+/);
146
165
  const roleToken = parts[0]!;
147
166
  if (roleToken === "general" || roleToken === "research") {
148
167
  const body = parts.slice(1).join(" ").trim();
149
- if (!body) return invalid("run");
150
- return { kind: "run", role: roleToken, task: body, explicit: true, timeoutMs };
168
+ if (!body) return invalid("run");
169
+ return { kind: "run", role: roleToken, task: body, explicit: true, timeoutMs, ...(execution ? { execution } : {}) };
151
170
  }
152
- // `run <task...>` — role defaults to general.
153
- return { kind: "run", role: "general", task, explicit: true, timeoutMs };
171
+ // `run <task...>` — role defaults to general. A flag error (e.g.
172
+ // --background + --foreground) also lands here with an empty task.
173
+ if (!task) return invalid("run");
174
+ return { kind: "run", role: "general", task, explicit: true, timeoutMs, ...(execution ? { execution } : {}) };
154
175
  }
155
176
  case "research": {
156
177
  const rest = trimmed.slice("research".length).trim();
157
178
  if (!rest) return invalid("research");
158
- const { task, timeoutMs } = extractFlags(rest);
179
+ const { task, timeoutMs, execution } = extractFlags(rest);
159
180
  if (!task) return invalid("research");
160
- return { kind: "run", role: "research", task, explicit: true, timeoutMs };
181
+ return { kind: "run", role: "research", task, explicit: true, timeoutMs, ...(execution ? { execution } : {}) };
161
182
  }
162
183
  }
163
184
  return invalid(first);
@@ -171,7 +192,7 @@ function invalid(token: string): DelegateIntent {
171
192
  export function delegateCompletions(prefix: string, recentRunIds: string[] = []): string[] {
172
193
  const words = (prefix ?? "").trimStart();
173
194
  const tokens = words.split(/\s+/);
174
- const base: string[] = ["on", "off", "status", "paths", "doctor", "help", "cancel ", "answer ", "bg ", "inspect ", "resume ", "peek ", "run ", "research "];
195
+ const base: string[] = ["on", "off", "status", "paths", "doctor", "help", "cancel ", "answer ", "bg ", "fg ", "inspect ", "resume ", "peek ", "run ", "research "];
175
196
 
176
197
  const matches: string[] = [];
177
198
  if (tokens.length <= 1) {
@@ -192,7 +213,7 @@ export function delegateCompletions(prefix: string, recentRunIds: string[] = [])
192
213
  }
193
214
  }
194
215
  // De-duplicate, keep order, cap for the TUI (all primary verbs fit).
195
- return [...new Set(matches)].slice(0, 14);
216
+ return [...new Set(matches)].slice(0, 15);
196
217
  }
197
218
 
198
219
  /**
@@ -200,10 +221,13 @@ export function delegateCompletions(prefix: string, recentRunIds: string[] = [])
200
221
  * Unknown flags are kept in the task text; a malformed duration yields a
201
222
  * stable error message.
202
223
  */
203
- export function extractFlags(input: string): { task: string; timeoutMs?: number; error?: string } {
224
+ export function extractFlags(input: string): { task: string; timeoutMs?: number; execution?: "background" | "foreground"; error?: string } {
204
225
  const tokens = input.split(/\s+/).filter(Boolean);
205
226
  const kept: string[] = [];
206
227
  let timeoutMs: number | undefined;
228
+ let execution: "background" | "foreground" | undefined;
229
+ let bg = 0;
230
+ let fg = 0;
207
231
  for (let i = 0; i < tokens.length; i++) {
208
232
  const t = tokens[i]!;
209
233
  if (t === "--timeout") {
@@ -219,9 +243,22 @@ export function extractFlags(input: string): { task: string; timeoutMs?: number;
219
243
  }
220
244
  continue;
221
245
  }
246
+ if (t === "--background") {
247
+ bg += 1;
248
+ execution = "background";
249
+ continue;
250
+ }
251
+ if (t === "--foreground") {
252
+ fg += 1;
253
+ execution = "foreground";
254
+ continue;
255
+ }
222
256
  kept.push(t);
223
257
  }
224
- return { task: kept.join(" "), timeoutMs };
258
+ if (bg > 0 && fg > 0) {
259
+ return { task: "", error: "--background and --foreground are mutually exclusive" };
260
+ }
261
+ return { task: kept.join(" "), timeoutMs, ...(execution ? { execution } : {}) };
225
262
  }
226
263
 
227
264
  /**
package/config.ts CHANGED
@@ -27,6 +27,8 @@ export interface DelegateConfigV1 {
27
27
  maxRuns: number;
28
28
  maxRunAgeDays: number;
29
29
  updateThrottleMs: number;
30
+ /** R22: default execution mode for delegations without an explicit override. */
31
+ defaultExecution: "background" | "foreground";
30
32
  /** R9: concurrent background children (default 3, clamp 1–8). */
31
33
  maxBackgroundRuns: number;
32
34
  /** R17/R18: ask_parent channel (background children). */
@@ -52,6 +54,7 @@ export const DEFAULT_DELEGATE_CONFIG: DelegateConfigV1 = {
52
54
  maxRuns: 50,
53
55
  maxRunAgeDays: 30,
54
56
  updateThrottleMs: 100,
57
+ defaultExecution: "background",
55
58
  maxBackgroundRuns: 3,
56
59
  askParent: {
57
60
  enabled: true,
@@ -142,6 +145,13 @@ function applyKnownField(config: DelegateConfigV1, key: string, value: unknown):
142
145
  return;
143
146
  }
144
147
  // R17: nested askParent block — merge field-by-field with clamps.
148
+ if (key === "defaultExecution") {
149
+ // R22: accept exactly the two enum words; anything else keeps the default.
150
+ if (value === "background" || value === "foreground") {
151
+ config.defaultExecution = value;
152
+ }
153
+ return;
154
+ }
145
155
  if (key === "askParent") {
146
156
  if (!value || typeof value !== "object" || Array.isArray(value)) return;
147
157
  const raw = value as Record<string, unknown>;
package/index.ts CHANGED
@@ -361,7 +361,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
361
361
  const secs = Math.round(d.durationMs / 1000);
362
362
  const head =
363
363
  `[delegate v${delegateVersion()} · ${d.runId} · ${d.role} · ${stateLabel} in ${secs}s` +
364
- `${d.model ? ` · ${d.model}` : ""}${d.timeoutInfo ? ` · ${d.timeoutInfo}` : ""}]`;
364
+ `${d.model ? ` · ${d.model}` : ""}${d.timeoutInfo ? ` · ${d.timeoutInfo}` : ""}${d.description ? ` · ${d.description}` : ""}]`;
365
365
  if (!res.ok) {
366
366
  const parts = [head];
367
367
  const err = res.error ? `${res.error.code}: ${res.error.message}` : "unknown failure";
@@ -429,15 +429,13 @@ export default function delegateExtension(pi: ExtensionAPI) {
429
429
  })),
430
430
  background: Type.Optional(Type.Boolean({
431
431
  description:
432
- "Run this delegation in the background: the call returns a runId immediately and the terminal report " +
433
- "arrives later as a message. Use it for long builds, test matrices, or research that should not block " +
434
- "this turn. Requires 'description'. Poll with the delegate_status pattern or wait for the report message.",
435
- })),
436
- description: Type.Optional(Type.String({
437
- description:
438
- "Required with background=true: a 3-to-6-word purpose summary for the user, e.g. 'Run full test matrix'. " +
439
- "Describes the work, not the mechanism. Single line.",
432
+ "Execution mode override: absent = follow the configured default (background unless changed in Advanced config); " +
433
+ "true = background, false = foreground.",
440
434
  })),
435
+ description: Type.String({ minLength: 1, description:
436
+ "A 3-to-6-word purpose summary for the user, e.g. 'Run full test matrix'. Required for EVERY delegation " +
437
+ "(background and foreground). Describes the work, not the mechanism. Single line.",
438
+ }),
441
439
  });
442
440
 
443
441
  pi.registerTool({
@@ -446,14 +444,17 @@ export default function delegateExtension(pi: ExtensionAPI) {
446
444
  description:
447
445
  "Delegate a self-contained subtask to an isolated child Pi session with a bounded final handoff. " +
448
446
  "Roles: general (implementation, write-capable) and research (read-only web research via Firecrawl, optionally supplemented by Reddit). " +
449
- "The child does not see parent history; include all objective, relevant paths, constraints, and acceptance criteria in the task.",
447
+ "The child does not see parent history; include all objective, relevant paths, constraints, and acceptance criteria in the task. " +
448
+ "Background is the default execution mode; use background: false only when the very next step depends on the result.",
450
449
  promptSnippet: "Delegate a bounded subtask (implementation or research) to an isolated child session",
451
450
  promptGuidelines: [
452
451
  "Use delegate autonomously when a bounded subtask would consume substantial parent context, benefits from a specialist tool ceiling, or needs independent verification.",
453
452
  "Pass the objective, relevant paths, constraints, and acceptance criteria in the delegate task text; the child cannot see parent history.",
454
453
  "Do not use delegate for trivial one-step work, or when most of the parent history would have to be copied into the task.",
455
454
  "Parallel delegate calls are fine: they queue and run back-to-back (one child at a time) — every call gets a real result; do not re-issue on 'queue full', wait for the in-flight results instead.",
456
- "Use background=true (with a 3–6-word description) for long builds, test matrices, or research that should not block this turn: the call returns a runId immediately and the terminal report arrives later as a message. Check progress with delegate_status; do not wait inline.",
455
+ "Background is the DEFAULT execution mode (an absent background parameter follows the configured default, normally background): the call returns a runId immediately and the terminal report arrives later as a message. Check progress with delegate_status; do not wait inline.",
456
+ "Use foreground (background: false) ONLY when the very next step depends on the delegation's result; the call then blocks this turn until the child finishes.",
457
+ "A 3–6-word description is REQUIRED for every delegation, foreground included.",
457
458
  "Treat background terminal reports as internal work events: acknowledge them to the user with at most one line; do not re-narrate the handoff unless material.",
458
459
  "On E_BACKGROUND_FULL, do not re-issue the task: check delegate_status and wait for terminal reports to free slots.",
459
460
  "Steer live background runs with delegate_send (course corrections apply at the child's next model call); reserve resumeFrom for finished runs.",
@@ -480,16 +481,21 @@ export default function delegateExtension(pi: ExtensionAPI) {
480
481
  const modelExtra = typeof params.model === "string" && params.model.trim() ? params.model.trim() : undefined;
481
482
  const resumeExtra = typeof params.resumeFrom === "string" && params.resumeFrom.trim() ? params.resumeFrom.trim() : undefined;
482
483
 
484
+ // R22: description is required for EVERY delegation (both modes) —
485
+ // validate before any side effect.
486
+ const desc = validateBackgroundDescription(params.description);
487
+ if (!desc.ok) {
488
+ return {
489
+ content: [{ type: "text" as const, text: `description invalid: ${desc.error}` }],
490
+ details: {} satisfies Record<string, unknown>,
491
+ isError: true,
492
+ };
493
+ }
494
+ // R22: absent background parameter follows the configured default.
495
+ const effectiveBackground = params.background === undefined ? app.defaultExecution() === "background" : params.background;
496
+
483
497
  // R8: background path — validate, slot-check, spawn, return runId.
484
- if (params.background === true) {
485
- const desc = validateBackgroundDescription(params.description);
486
- if (!desc.ok) {
487
- return {
488
- content: [{ type: "text" as const, text: `description invalid: ${desc.error}` }],
489
- details: {} satisfies Record<string, unknown>,
490
- isError: true,
491
- };
492
- }
498
+ if (effectiveBackground) {
493
499
  const slot = background.slotError();
494
500
  if (slot) {
495
501
  return {
@@ -530,6 +536,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
530
536
  const request = buildRequest(params.task, params.role ?? config.defaultRole, "tool", ctx, timeoutMs, {
531
537
  model: modelExtra,
532
538
  resumeFrom: resumeExtra,
539
+ description: desc.value,
533
540
  });
534
541
  refreshDoctor(ctx);
535
542
  const hooks = {
@@ -894,7 +901,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
894
901
  }
895
902
  };
896
903
 
897
- const runCommandForeground = async (task: string, role: "general" | "research", ctx: ExtensionCommandContext, timeoutMs?: number, extras?: { resumeFrom?: string }): Promise<void> => {
904
+ const runCommandForeground = async (task: string, role: "general" | "research", ctx: ExtensionCommandContext, timeoutMs?: number, extras?: { resumeFrom?: string; description?: string }): Promise<void> => {
898
905
  const request = buildRequest(task, role, "command", ctx, timeoutMs, extras);
899
906
  refreshDoctor(ctx);
900
907
  let lastText = `[delegate] starting ${role} run…`;
@@ -1009,7 +1016,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
1009
1016
  // R20: user-facing background launch — /delegate bg and the dashboard
1010
1017
  // action spawn a background run (description derived from the task's
1011
1018
  // first line) and return immediately; the report arrives later.
1012
- const runCommandBackground = async (task: string, role: "general" | "research", ctx: ExtensionCommandContext, timeoutMs?: number): Promise<void> => {
1019
+ const runCommandBackground = async (task: string, role: "general" | "research", ctx: ExtensionCommandContext, timeoutMs?: number, extras?: { resumeFrom?: string }): Promise<void> => {
1013
1020
  const desc = deriveBackgroundDescription(task);
1014
1021
  if (!desc.ok) {
1015
1022
  say(ctx, `[delegate] ${desc.error}`, "error");
@@ -1023,6 +1030,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
1023
1030
  const request = buildRequest(task, role, "command", ctx, timeoutMs, {
1024
1031
  background: true,
1025
1032
  description: desc.value,
1033
+ ...(extras?.resumeFrom ? { resumeFrom: extras.resumeFrom } : {}),
1026
1034
  });
1027
1035
  refreshDoctor(ctx);
1028
1036
  const attempt = app.runBackground(request, {
@@ -1036,6 +1044,21 @@ export default function delegateExtension(pi: ExtensionAPI) {
1036
1044
  say(ctx, formatBackgroundStartedText(attempt.handle.runId, attempt.handle.role, attempt.handle.description));
1037
1045
  };
1038
1046
 
1047
+ // R22: a foreground launch from the user surface (slash/panel) also needs
1048
+ // a description — derive it from the task's first line exactly like the
1049
+ // background path (R20) and pass it to the foreground run.
1050
+ const launchForeground = async (task: string, role: "general" | "research", ctx: ExtensionCommandContext, timeoutMs?: number, extras?: { resumeFrom?: string }): Promise<void> => {
1051
+ const desc = deriveBackgroundDescription(task);
1052
+ if (!desc.ok) {
1053
+ say(ctx, `[delegate] ${desc.error}`, "error");
1054
+ return;
1055
+ }
1056
+ await runCommandForeground(task, role, ctx, timeoutMs, {
1057
+ ...(extras?.resumeFrom ? { resumeFrom: extras.resumeFrom } : {}),
1058
+ description: desc.value,
1059
+ });
1060
+ };
1061
+
1039
1062
  const statusText = (ctx: ExtensionContext): string => {
1040
1063
  const s = app.getStatus(pi.getActiveTools(), ctx.cwd ?? process.cwd());
1041
1064
  const lines = ["[delegate]", `version: v${delegateVersion()} (loaded at session start; /reload picks up newer installs)`, `mode: ${s.modeEnabled ? "strict" : "normal"}`];
@@ -1079,7 +1102,9 @@ export default function delegateExtension(pi: ExtensionAPI) {
1079
1102
  "/delegate run general <task> run a delegation with a role",
1080
1103
  "/delegate research <task> research role",
1081
1104
  "/delegate bg [role] <task> run it in the background (report arrives later)",
1105
+ "/delegate fg [role] <task> run it in the foreground (blocks until done)",
1082
1106
  "/delegate <task> general-role shorthand",
1107
+ "flags (run/research/<task>): --timeout <90s|10m|2h|1d> --background --foreground",
1083
1108
  "/delegate cancel [run-id] cancel the active run",
1084
1109
  "/delegate answer <run-id> <text> answer a blocked background child's question",
1085
1110
  "/delegate resume <run-id> <task> resume a prior run's child session",
@@ -1195,11 +1220,19 @@ export default function delegateExtension(pi: ExtensionAPI) {
1195
1220
  say(ctx, `[delegate] invalid role '${intent.role}'. Use general or research.`, "error");
1196
1221
  return;
1197
1222
  }
1198
- await runCommandForeground(intent.task, intent.role, ctx, intent.timeoutMs);
1223
+ // R22: run follows the configured default unless a flag overrides.
1224
+ if ((intent.execution ?? app.defaultExecution()) === "foreground") {
1225
+ await launchForeground(intent.task, intent.role, ctx, intent.timeoutMs);
1226
+ } else {
1227
+ await runCommandBackground(intent.task, intent.role, ctx, intent.timeoutMs);
1228
+ }
1199
1229
  return;
1200
1230
  case "bg":
1201
1231
  await runCommandBackground(intent.task, isRoleName(intent.role) ? intent.role : "general", ctx, intent.timeoutMs);
1202
1232
  return;
1233
+ case "fg":
1234
+ await launchForeground(intent.task, isRoleName(intent.role) ? intent.role : "general", ctx, intent.timeoutMs);
1235
+ return;
1203
1236
  case "peek": {
1204
1237
  const id = intent.runId?.trim() || app.mostRecentRunId();
1205
1238
  if (!id) {
@@ -1216,7 +1249,12 @@ export default function delegateExtension(pi: ExtensionAPI) {
1216
1249
  say(ctx, `[delegate] usage: /delegate resume <run-id> <continuation task...>`, "error");
1217
1250
  return;
1218
1251
  }
1219
- await runCommandForeground(intent.task, "general", ctx, intent.timeoutMs, { resumeFrom: runId });
1252
+ // R22: resume follows the configured default unless a flag overrides.
1253
+ if ((intent.execution ?? app.defaultExecution()) === "foreground") {
1254
+ await launchForeground(intent.task, "general", ctx, intent.timeoutMs, { resumeFrom: runId });
1255
+ } else {
1256
+ await runCommandBackground(intent.task, "general", ctx, intent.timeoutMs, { resumeFrom: runId });
1257
+ }
1220
1258
  return;
1221
1259
  }
1222
1260
  case "invalid":
@@ -1308,6 +1346,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
1308
1346
  { key: "cfg:user:maxResultBytes", label: "Max result bytes", value: String(c.maxResultBytes), rawValue: String(c.maxResultBytes), kind: "input" },
1309
1347
  { key: "cfg:user:updateThrottleMs", label: "Update throttle", value: formatDuration(c.updateThrottleMs), rawValue: String(c.updateThrottleMs), kind: "input", inputHint: "live update cadence" },
1310
1348
  { key: "info:defaultRole", label: "Default role", value: c.defaultRole, kind: "info" },
1349
+ { key: "exec-default-toggle", label: "Execution default", value: c.defaultExecution, kind: "action" },
1311
1350
  { key: "info:retention", label: "Retention", value: `${c.maxRuns} runs · ${c.maxRunAgeDays}d`, kind: "info" },
1312
1351
  ];
1313
1352
  };
@@ -1328,7 +1367,16 @@ export default function delegateExtension(pi: ExtensionAPI) {
1328
1367
  if (!m) return `Unknown setting '${key}'.`;
1329
1368
  return app.patchConfig(m[1]!, raw);
1330
1369
  },
1331
- activate: (): PanelActionResult => ({ kind: "close", action: "advanced-done" }),
1370
+ activate: (key): PanelActionResult => {
1371
+ // R22: the execution-default toggle cycles background ⇄ foreground
1372
+ // in place (action row, no editor input).
1373
+ if (key === "exec-default-toggle") {
1374
+ const next = app.panelConfig().defaultExecution === "background" ? "foreground" : "background";
1375
+ const err = app.patchDefaultExecution(next);
1376
+ return err ? { kind: "error", message: err } : { kind: "updated", message: `Execution default: ${next}` };
1377
+ }
1378
+ return { kind: "close", action: "advanced-done" };
1379
+ },
1332
1380
  requestRender: () => tui.requestRender(),
1333
1381
  done,
1334
1382
  }),
@@ -1415,7 +1463,6 @@ export default function delegateExtension(pi: ExtensionAPI) {
1415
1463
  rows: [
1416
1464
  { key: "run-general", label: "Run general task…", value: "", kind: "action" },
1417
1465
  { key: "run-research", label: "Run research task…", value: "", kind: "action" },
1418
- { key: "run-background", label: "Run background task…", value: "", kind: "action" },
1419
1466
  { key: "peek", label: "Peek live / final detail", value: "", kind: "action", disabled: !active && !last },
1420
1467
  { key: "cancel", label: "Cancel active run", value: "", kind: "action", disabled: !active },
1421
1468
  { key: "resume", label: "Resume last run…", value: "", kind: "action", disabled: !last },
@@ -1504,14 +1551,12 @@ export default function delegateExtension(pi: ExtensionAPI) {
1504
1551
  const role = action === "run-research" ? ("research" as const) : ("general" as const);
1505
1552
  const task = await ctx.ui.editor(`Delegated task (${role})`, "");
1506
1553
  if (!task || !task.trim()) continue;
1507
- await runCommandForeground(task, role, ctx);
1508
- continue;
1509
- }
1510
- // R20: user-facing background launch — spawn, return immediately.
1511
- if (action === "run-background") {
1512
- const task = await ctx.ui.editor("Background task (returns immediately)", "");
1513
- if (!task || !task.trim()) continue;
1514
- await runCommandBackground(task.trim(), "general", ctx);
1554
+ // R22: role-based actions honor the effective (default) mode.
1555
+ if (app.defaultExecution() === "foreground") {
1556
+ await launchForeground(task, role, ctx);
1557
+ } else {
1558
+ await runCommandBackground(task, role, ctx);
1559
+ }
1515
1560
  continue;
1516
1561
  }
1517
1562
  if (action === "peek") {
@@ -1544,7 +1589,12 @@ export default function delegateExtension(pi: ExtensionAPI) {
1544
1589
  }
1545
1590
  const task = await ctx.ui.editor(`Resume ${target.runId.slice(-12)} (${target.role})`, "");
1546
1591
  if (!task || !task.trim()) continue;
1547
- await runCommandForeground(task, target.role === "research" ? "research" : "general", ctx, undefined, { resumeFrom: target.runId });
1592
+ const role = target.role === "research" ? ("research" as const) : ("general" as const);
1593
+ if (app.defaultExecution() === "foreground") {
1594
+ await launchForeground(task, role, ctx, undefined, { resumeFrom: target.runId });
1595
+ } else {
1596
+ await runCommandBackground(task, role, ctx, undefined, { resumeFrom: target.runId });
1597
+ }
1548
1598
  continue;
1549
1599
  }
1550
1600
  if (action === "strict-toggle") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maheidem/pi-delegate",
3
- "version": "0.6.4",
3
+ "version": "0.7.0",
4
4
  "type": "module",
5
5
  "description": "Foreground isolated delegation and strict coordinator mode for the Pi coding agent.",
6
6
  "license": "MIT",
package/types.ts CHANGED
@@ -149,6 +149,9 @@ export interface DelegateDetails {
149
149
  sessionPath?: string;
150
150
  /** R7: resolved timeout provenance, e.g. "hard 45m (per-run) · idle 22m30s". */
151
151
  timeoutInfo?: string;
152
+ /** R22: validated 3–6-word purpose summary (required for every delegation;
153
+ * returned inline in the foreground result header). */
154
+ description?: string;
152
155
  transcriptPath: string;
153
156
  stderrPath: string;
154
157
  displayItems: DelegateDisplayItem[];