@maheidem/pi-delegate 0.2.1 → 0.2.2

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
@@ -118,6 +118,17 @@ Consequences worth internalizing:
118
118
  than blamed on the provider, and the stderr tail is no longer presented as
119
119
  the cause.
120
120
 
121
+ ### Concurrent calls queue (fan-out just works)
122
+
123
+ Models naturally issue several `delegate` calls in one turn. Pi executes
124
+ them truly in parallel; delegate runs **one child at a time** and places
125
+ concurrent calls in a bounded FIFO queue (`queueLimit`, default 3): a 4-way
126
+ fan-out becomes 4 back-to-back children and 4 real results — no error
127
+ storm. Aborting a still-queued call removes it (resolved as `cancelled`,
128
+ never spawned). Beyond the limit the call fails fast with an instructive
129
+ `E_DELEGATE_BUSY` ("wait for the in-flight results, then re-issue").
130
+ `/delegate status` shows the queue depth.
131
+
121
132
  ### Watching a child work: the live feed and `/delegate peek`
122
133
 
123
134
  - **Foreground `/delegate run` (TUI)** opens a live feed panel: identity
package/application.ts CHANGED
@@ -64,6 +64,18 @@ interface ActiveRunReservation {
64
64
  startedAt: string;
65
65
  }
66
66
 
67
+ /**
68
+ * A concurrent delegate call waiting for the single child slot. Pi executes
69
+ * parallel tool calls truly in parallel and models routinely fan out — the
70
+ * queue serializes those calls on the one-child policy instead of failing
71
+ * them: a 4-way fan-out becomes 4 back-to-back children and 4 real results.
72
+ */
73
+ interface QueuedRun {
74
+ request: DelegateRequest;
75
+ hooks: RunHooks;
76
+ resolve: (result: RunAttemptResult) => void;
77
+ }
78
+
67
79
  function errorResult(
68
80
  runId: string,
69
81
  role: RoleName,
@@ -98,6 +110,7 @@ function errorResult(
98
110
 
99
111
  export class DelegateApplicationImpl implements DelegateApplication {
100
112
  private activeRun: ActiveRunReservation | null = null;
113
+ private runQueue: QueuedRun[] = [];
101
114
  private readonly modeRuntime: ModeRuntime;
102
115
  private readonly ports: DelegateApplicationPorts;
103
116
  private liveConfig: DelegateConfigV1;
@@ -183,24 +196,57 @@ export class DelegateApplicationImpl implements DelegateApplication {
183
196
  }
184
197
 
185
198
  /**
186
- * Canonical run entry point shared by tool and command. Reservation is
187
- * synchronous before the first await (POL-005).
199
+ * Canonical entry point shared by tool and command. ONE child executes at
200
+ * a time (POL-005): concurrent calls queue (bounded by `queueLimit`) and
201
+ * run back-to-back — models fan out, and the queue turns that into
202
+ * serialized results instead of an error storm.
188
203
  */
189
204
  async run(request: DelegateRequest, hooks: RunHooks = {}): Promise<RunAttemptResult> {
190
- // 1. Synchronous reservation BEFORE any await.
191
205
  if (this.activeRun) {
192
- return {
193
- ok: false,
194
- busy: true,
195
- runId: this.activeRun.id,
196
- role: this.activeRun.role,
197
- message: `Delegation is busy with run ${this.activeRun.id} (${this.activeRun.role}).`,
198
- error: {
199
- code: "E_DELEGATE_BUSY",
200
- message: `Active run ${this.activeRun.id} (${this.activeRun.role}). Inspect, cancel, or wait.`,
201
- },
202
- };
206
+ if (this.runQueue.length >= this.liveConfig.queueLimit) {
207
+ return {
208
+ ok: false,
209
+ busy: true,
210
+ runId: this.activeRun.id,
211
+ role: this.activeRun.role,
212
+ message: `Delegation queue is full (${this.runQueue.length} waiting) while run ${this.activeRun.id} (${this.activeRun.role}) executes.`,
213
+ error: {
214
+ code: "E_DELEGATE_BUSY",
215
+ message: `Queue full (${this.runQueue.length} waiting; limit ${this.liveConfig.queueLimit}); active run ${this.activeRun.id} (${this.activeRun.role}). Wait for the in-flight results, then re-issue.`,
216
+ },
217
+ };
218
+ }
219
+ return await new Promise<RunAttemptResult>((resolve) => {
220
+ const entry: QueuedRun = { request, hooks, resolve };
221
+ // Aborting a STILL-QUEUED call removes it (the runner wires
222
+ // the signal only once spawned); once started, the runner
223
+ // owns cancellation through the same signal.
224
+ const onAbort = () => {
225
+ const idx = this.runQueue.indexOf(entry);
226
+ if (idx >= 0) {
227
+ this.runQueue.splice(idx, 1);
228
+ resolve(
229
+ errorResult("", request.role, "E_CANCELLED", "aborted before start (queued call cancelled)", {
230
+ state: "cancelled",
231
+ }),
232
+ );
233
+ }
234
+ };
235
+ if (hooks.abortSignal) {
236
+ if (hooks.abortSignal.aborted) {
237
+ onAbort();
238
+ return;
239
+ }
240
+ hooks.abortSignal.addEventListener("abort", onAbort, { once: true });
241
+ }
242
+ this.runQueue.push(entry);
243
+ });
203
244
  }
245
+ return await this.startRun(request, hooks);
246
+ }
247
+
248
+ /** Execute one run in the free slot (reservation stays synchronous). */
249
+ private async startRun(request: DelegateRequest, hooks: RunHooks = {}): Promise<RunAttemptResult> {
204
250
 
205
251
  const agentDir = this.ports.agentDir;
206
252
  // Config cascade: project .pi/delegate/config.json overlays the
@@ -346,9 +392,29 @@ export class DelegateApplicationImpl implements DelegateApplication {
346
392
  } catch (error) {
347
393
  this.activeRun = null;
348
394
  return errorResult(opened.metadata.runId, role.name, "E_CHILD_EXIT", `Delegation failed unexpectedly: ${(error as Error).message}`);
395
+ } finally {
396
+ this.startNextQueuedRun();
349
397
  }
350
398
  }
351
399
 
400
+ /** Queued-call introspection for status views. */
401
+ queuedRunCount(): number {
402
+ return this.runQueue.length;
403
+ }
404
+
405
+ queueLimit(): number {
406
+ return this.liveConfig.queueLimit;
407
+ }
408
+
409
+ /** Pop the next queued run (if any) into the free slot, fire-and-forget. */
410
+ private startNextQueuedRun(): void {
411
+ const next = this.runQueue.shift();
412
+ if (!next) return;
413
+ void this.startRun(next.request, next.hooks).then(next.resolve, (error: unknown) => {
414
+ next.resolve(errorResult("", next.request.role, "E_CHILD_EXIT", `Delegation failed unexpectedly: ${(error as Error).message}`));
415
+ });
416
+ }
417
+
352
418
  /** Cancel the active run (default) or an exact run ID. */
353
419
  async cancel(runId?: string): Promise<CancelResult> {
354
420
  const active = this.activeRun;
package/config.ts CHANGED
@@ -20,6 +20,8 @@ export interface DelegateConfigV1 {
20
20
  handoffGraceMs: number;
21
21
  /** Bounded wait for the mandatory-handoff enforcement answer (default 60 s). */
22
22
  handoffEnforceTimeoutMs: number;
23
+ /** Concurrent calls beyond the active child wait in this FIFO queue. */
24
+ queueLimit: number;
23
25
  /** R1: watchdog budget while a tool call is in flight (default: hard). */
24
26
  stuckToolTimeoutMs?: number;
25
27
  maxRuns: number;
@@ -37,6 +39,7 @@ export const DEFAULT_DELEGATE_CONFIG: DelegateConfigV1 = {
37
39
  killGraceMs: 5_000,
38
40
  handoffGraceMs: 90_000,
39
41
  handoffEnforceTimeoutMs: 60_000,
42
+ queueLimit: 3,
40
43
  stuckToolTimeoutMs: undefined,
41
44
  maxRuns: 50,
42
45
  maxRunAgeDays: 30,
@@ -51,6 +54,7 @@ const MIN_VALUES: Partial<Record<keyof DelegateConfigV1, number>> = {
51
54
  killGraceMs: 100,
52
55
  handoffGraceMs: 1_000,
53
56
  handoffEnforceTimeoutMs: 1_000,
57
+ queueLimit: 0,
54
58
  stuckToolTimeoutMs: 1_000,
55
59
  maxRuns: 1,
56
60
  maxRunAgeDays: 1,
@@ -65,6 +69,7 @@ const MAX_VALUES: Partial<Record<keyof DelegateConfigV1, number>> = {
65
69
  killGraceMs: 60_000,
66
70
  handoffGraceMs: 600_000,
67
71
  handoffEnforceTimeoutMs: 600_000,
72
+ queueLimit: 20,
68
73
  stuckToolTimeoutMs: 604_800_000,
69
74
  maxRuns: 10_000,
70
75
  maxRunAgeDays: 3650,
package/index.ts CHANGED
@@ -303,6 +303,16 @@ export default function delegateExtension(pi: ExtensionAPI) {
303
303
  if (!res.ok) {
304
304
  const parts = [head];
305
305
  const err = res.error ? `${res.error.code}: ${res.error.message}` : "unknown failure";
306
+ if (d.state === "cancelled") {
307
+ // A cancellation is user intent, not a failure — neutral line,
308
+ // plus the resume path when a durable session exists.
309
+ parts.push(`cancelled — ${res.error?.message ?? "aborted"}; no handoff.`);
310
+ if (d.sessionPath) parts.push(`resume: re-issue with resumeFrom: ${d.runId} to continue in the same child context.`);
311
+ if (res.details.partialHandoff) parts.push("", "partial handoff (captured at kill):", res.details.partialHandoff);
312
+ if (res.modelNote) parts.push(`note: ${res.modelNote}`);
313
+ parts.push(`transcript: ${d.transcriptPath}`);
314
+ return parts.join("\n");
315
+ }
306
316
  parts.push(`error: ${err}`);
307
317
  // R2: the killed child's own account of its partial work.
308
318
  if (res.details.partialHandoff) {
@@ -369,6 +379,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
369
379
  "Use delegate autonomously when a bounded subtask would consume substantial parent context, benefits from a specialist tool ceiling, or needs independent verification.",
370
380
  "Pass the objective, relevant paths, constraints, and acceptance criteria in the delegate task text; the child cannot see parent history.",
371
381
  "Do not use delegate for trivial one-step work, or when most of the parent history would have to be copied into the task.",
382
+ "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.",
372
383
  "A timed-out run leaves a partialHandoff, a git checkpoint and a resumable child session: pass resumeFrom: <runId> to continue in the same context instead of re-explaining, and inspect the receipt's gitDelta before repairing anything.",
373
384
  "Pin model: 'provider/model-id' when the child must not silently follow the parent's current model (e.g. after a mid-session model fallback).",
374
385
  "For long validation/benchmark subtasks set timeout to at least 2x the longest expected single tool call.",
@@ -602,6 +613,8 @@ export default function delegateExtension(pi: ExtensionAPI) {
602
613
  const lines = ["[delegate]", `version: v${delegateVersion()} (loaded at session start; /reload picks up newer installs)`, `mode: ${s.modeEnabled ? "strict" : "normal"}`];
603
614
  lines.push(`parent tools: ${s.modeEnabled ? "delegate only" : "normal active set"}`);
604
615
  lines.push(`active run: ${s.activeRun ? `${s.activeRun.runId} (${s.activeRun.role})` : "none"}`);
616
+ const queued = app.queuedRunCount();
617
+ lines.push(`queue: ${queued} waiting (concurrent calls serialize; limit ${app.queueLimit()})`);
605
618
  if (s.lastRun) {
606
619
  const dur = s.lastRun.durationMs != null ? `${Math.round(s.lastRun.durationMs / 1000)}s` : "";
607
620
  lines.push(`last run: ${s.lastRun.runId} ${s.lastRun.role} ${s.lastRun.state} ${dur}`.trimEnd());
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maheidem/pi-delegate",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "type": "module",
5
5
  "description": "Foreground isolated delegation and strict coordinator mode for the Pi coding agent.",
6
6
  "license": "MIT",