@oyasmi/pipiclaw 0.9.0-beta.4 → 0.9.0-beta.6
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 +146 -177
- package/dist/playbooks/agent-delegation.md +9 -8
- package/dist/playbooks/background-jobs.md +1 -1
- package/dist/playbooks/catalog.d.ts +2 -2
- package/dist/playbooks/catalog.js +20 -9
- package/dist/playbooks/event-scheduling.md +1 -1
- package/dist/playbooks/memory-and-learning.md +1 -1
- package/dist/playbooks/outbound-media.md +5 -5
- package/dist/playbooks/runtime-orientation.md +1 -1
- package/dist/playbooks/task-driving.md +1 -1
- package/dist/playbooks/task-planning.md +1 -1
- package/dist/runtime/bootstrap.d.ts +2 -2
- package/dist/runtime/bootstrap.js +8 -4
- package/dist/runtime/delivery.js +6 -5
- package/dist/shared/host-process.d.ts +5 -5
- package/dist/shared/host-process.js +19 -0
- package/dist/subagents/discovery.d.ts +8 -0
- package/dist/subagents/discovery.js +32 -9
- package/dist/subagents/external/claude-code.js +1 -3
- package/dist/subagents/external/codex-cli.js +1 -7
- package/dist/subagents/external/exec.js +7 -2
- package/dist/subagents/external/harness.d.ts +0 -3
- package/dist/subagents/external/run.d.ts +5 -0
- package/dist/subagents/external/run.js +67 -31
- package/dist/subagents/runs.d.ts +40 -9
- package/dist/subagents/runs.js +187 -21
- package/dist/subagents/tool.d.ts +3 -1
- package/dist/subagents/tool.js +33 -14
- package/dist/tools/subagent-manage.js +18 -1
- package/examples/sub-agents/README.md +10 -2
- package/examples/sub-agents/documenter.md +0 -2
- package/examples/sub-agents/git-committer.md +30 -38
- package/examples/sub-agents/reviewer.md +0 -2
- package/examples/sub-agents/scout.md +0 -2
- package/examples/sub-agents/verifier.md +0 -2
- package/examples/sub-agents/worker.md +0 -2
- package/package.json +1 -1
package/dist/subagents/runs.js
CHANGED
|
@@ -2,21 +2,22 @@ import { mkdir, readdir, readFile, unlink } from "node:fs/promises";
|
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import * as log from "../log.js";
|
|
4
4
|
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
5
|
-
import { isProcessAlive } from "../shared/host-process.js";
|
|
5
|
+
import { isProcessAlive, killProcessGroup, readProcessStartTime } from "../shared/host-process.js";
|
|
6
|
+
import { RecoverableToolError } from "../shared/recoverable-error.js";
|
|
6
7
|
import { createSerialQueue } from "../shared/serial-queue.js";
|
|
7
8
|
import { errorMessage } from "../shared/text-utils.js";
|
|
8
9
|
import { isRecord } from "../shared/type-guards.js";
|
|
9
10
|
import { classifyExternalOutcome } from "./external/harness.js";
|
|
10
11
|
import { getExternalHarness } from "./external/registry.js";
|
|
11
|
-
import { releaseWorkspaceLease } from "./workspace-lease.js";
|
|
12
|
+
import { acquireWorkspaceLease, formatWorkspaceLeaseConflict, releaseWorkspaceLease } from "./workspace-lease.js";
|
|
12
13
|
/**
|
|
13
14
|
* Longest a dispatching tool call waits for its run to settle before returning a "still running"
|
|
14
15
|
* placeholder instead of the result (D2). A code constant, not a settings key, per CLAUDE.md's
|
|
15
16
|
* rule for numeric thresholds.
|
|
16
17
|
*/
|
|
17
18
|
export const SYNC_GRACE_MS = 120_000;
|
|
18
|
-
/** D10.2: per-channel cap on concurrently running delegation runs
|
|
19
|
-
export const MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL =
|
|
19
|
+
/** D10.2: per-channel cap on concurrently running delegation runs. */
|
|
20
|
+
export const MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL = 6;
|
|
20
21
|
/** D10.2: host-wide cap across every channel. Bounds unbounded process/worker growth only —
|
|
21
22
|
* not the full cross-subsystem (task/job/sidecar) admission scheme the design doc leaves open. */
|
|
22
23
|
export const MAX_RUNNING_SUBAGENT_RUNS_PER_HOST = 20;
|
|
@@ -190,15 +191,15 @@ export class SubAgentRunManager {
|
|
|
190
191
|
// runaway model, not a global cross-subsystem admission scheme — see the design doc's
|
|
191
192
|
// non-goals). Checked before anything is persisted, so a rejected run costs nothing.
|
|
192
193
|
if (this.runningCount() >= MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL) {
|
|
193
|
-
throw new
|
|
194
|
+
throw new RecoverableToolError(`Too many delegation runs already running on this channel (>= ${MAX_RUNNING_SUBAGENT_RUNS_PER_CHANNEL}). ` +
|
|
194
195
|
"Wait for one to finish, or cancel one with subagent_manage first.");
|
|
195
196
|
}
|
|
196
197
|
if (totalRunningSubAgentRuns() >= MAX_RUNNING_SUBAGENT_RUNS_PER_HOST) {
|
|
197
|
-
throw new
|
|
198
|
+
throw new RecoverableToolError(`Too many delegation runs already running host-wide (>= ${MAX_RUNNING_SUBAGENT_RUNS_PER_HOST}). ` +
|
|
198
199
|
"Wait for one to finish before dispatching another.");
|
|
199
200
|
}
|
|
200
201
|
if (this.runs.has(input.runId)) {
|
|
201
|
-
throw new
|
|
202
|
+
throw new RecoverableToolError(`Run id "${input.runId}" is already registered on this channel.`);
|
|
202
203
|
}
|
|
203
204
|
const record = {
|
|
204
205
|
...input,
|
|
@@ -249,8 +250,9 @@ export class SubAgentRunManager {
|
|
|
249
250
|
if (!record)
|
|
250
251
|
return;
|
|
251
252
|
record.pid = info.pid;
|
|
252
|
-
record.
|
|
253
|
+
record.pidStartedAt = info.pidStartedAt;
|
|
253
254
|
record.argv = info.argv;
|
|
255
|
+
record.deadlineAt = info.deadlineAt;
|
|
254
256
|
// claude-code pre-assigns its session id before running (D4); persisting it here, not just
|
|
255
257
|
// at settle(), means a run that crashes before any output is still resumable.
|
|
256
258
|
if (info.sessionId)
|
|
@@ -301,6 +303,20 @@ export class SubAgentRunManager {
|
|
|
301
303
|
registerCancelHandle(runId, cancel) {
|
|
302
304
|
this.cancelHandles.set(runId, cancel);
|
|
303
305
|
}
|
|
306
|
+
/** Record why a still-running external run is about to be killed, before the signal is sent
|
|
307
|
+
* (P1-1) — see the `terminationReason` field doc. A no-op once the run is no longer running.
|
|
308
|
+
* Called by both the live in-process watcher (`external/run.ts`) and `sweep()` below. */
|
|
309
|
+
async markTerminationReason(runId, reason) {
|
|
310
|
+
await this.queue.run(runId, async () => {
|
|
311
|
+
const record = this.runs.get(runId);
|
|
312
|
+
if (!record || record.status !== "running")
|
|
313
|
+
return;
|
|
314
|
+
record.terminationReason = reason;
|
|
315
|
+
await this.persist(record).catch((error) => {
|
|
316
|
+
log.logWarning(`Failed to persist termination reason for run ${runId}`, errorMessage(error));
|
|
317
|
+
});
|
|
318
|
+
});
|
|
319
|
+
}
|
|
304
320
|
clearCancelHandle(runId) {
|
|
305
321
|
this.cancelHandles.delete(runId);
|
|
306
322
|
}
|
|
@@ -315,6 +331,10 @@ export class SubAgentRunManager {
|
|
|
315
331
|
const record = this.runs.get(runId);
|
|
316
332
|
if (!record || record.settledAt)
|
|
317
333
|
return; // Idempotent: already settled, never replay.
|
|
334
|
+
// The terminal fields are persisted, required, before any side effect runs (P0-2): a
|
|
335
|
+
// failed persist here rolls the record back to `running` so a restart replays settlement
|
|
336
|
+
// from scratch instead of applying side effects the disk never recorded.
|
|
337
|
+
const snapshot = { ...record };
|
|
318
338
|
record.status = input.status;
|
|
319
339
|
record.failureReason = input.failureReason;
|
|
320
340
|
record.usage = input.usage;
|
|
@@ -329,11 +349,19 @@ export class SubAgentRunManager {
|
|
|
329
349
|
record.sessionId = input.sessionId;
|
|
330
350
|
record.finishedAt = Date.now();
|
|
331
351
|
record.settledAt = record.finishedAt;
|
|
352
|
+
try {
|
|
353
|
+
await this.persist(record, true);
|
|
354
|
+
}
|
|
355
|
+
catch (error) {
|
|
356
|
+
Object.assign(record, snapshot);
|
|
357
|
+
throw error;
|
|
358
|
+
}
|
|
332
359
|
const outputSaved = await this.writeOutputFile(record, input.outputText);
|
|
333
360
|
releaseWorkspaceLease(record.leaseKey);
|
|
334
|
-
|
|
361
|
+
record.leaseKey = undefined; // Terminal records never display as "lease held" (P1-4).
|
|
335
362
|
this.cancelHandles.delete(runId);
|
|
336
363
|
this.externalLaunches.delete(runId);
|
|
364
|
+
await this.persist(record);
|
|
337
365
|
if (!record.usageRecorded) {
|
|
338
366
|
record.usageRecorded = true;
|
|
339
367
|
this.options.ledger?.record({
|
|
@@ -353,7 +381,10 @@ export class SubAgentRunManager {
|
|
|
353
381
|
usageKnown: input.usageKnown,
|
|
354
382
|
costKnown: input.costKnown,
|
|
355
383
|
});
|
|
356
|
-
|
|
384
|
+
// Archive is an observability write, not a settlement fact — a full queue must not
|
|
385
|
+
// swallow the completion wake below (P0-2).
|
|
386
|
+
await this.options.store
|
|
387
|
+
?.logSubAgentRun(record.channelId, {
|
|
357
388
|
date: new Date().toISOString(),
|
|
358
389
|
toolCallId: record.runId,
|
|
359
390
|
label: record.label,
|
|
@@ -375,6 +406,9 @@ export class SubAgentRunManager {
|
|
|
375
406
|
status: record.status,
|
|
376
407
|
taskId: record.taskId,
|
|
377
408
|
artifactDir: record.artifactDir,
|
|
409
|
+
})
|
|
410
|
+
.catch((error) => {
|
|
411
|
+
log.logWarning(`Failed to archive sub-agent run ${record.runId}`, errorMessage(error));
|
|
378
412
|
});
|
|
379
413
|
await this.persist(record);
|
|
380
414
|
}
|
|
@@ -454,6 +488,17 @@ export class SubAgentRunManager {
|
|
|
454
488
|
const cancelHandle = this.cancelHandles.get(runId);
|
|
455
489
|
this.cancelHandles.delete(runId);
|
|
456
490
|
if (cancelHandle) {
|
|
491
|
+
// External: mark the reason before the handle kills the process, so whichever code
|
|
492
|
+
// path settles this run (the live watcher below, or the sweeper if that watcher's
|
|
493
|
+
// process disappears mid-kill) reports "cancelled" instead of guessing from
|
|
494
|
+
// whatever the process happened to print before it died (P1-1). This also covers
|
|
495
|
+
// the pre-spawn placeholder handle `claimExternalLaunch` installs: a cancel that
|
|
496
|
+
// lands in that narrow window durably marks the intent even though the placeholder
|
|
497
|
+
// itself does nothing else.
|
|
498
|
+
if (record.runtime === "external") {
|
|
499
|
+
record.terminationReason = "cancelled";
|
|
500
|
+
await this.persist(record).catch(() => undefined);
|
|
501
|
+
}
|
|
457
502
|
cancelHandle();
|
|
458
503
|
}
|
|
459
504
|
else if (record.runtime === "external" && this.externalLaunches.has(runId)) {
|
|
@@ -461,18 +506,27 @@ export class SubAgentRunManager {
|
|
|
461
506
|
// and refuse to spawn instead of starting an uncancellable child.
|
|
462
507
|
this.externalLaunches.get(runId).cancelRequested = true;
|
|
463
508
|
}
|
|
509
|
+
else if (record.runtime === "external" && record.pid) {
|
|
510
|
+
// Adopted from a previous daemon (spec 040, D10.3): no live in-process watcher, but
|
|
511
|
+
// the run is genuinely still running and the sweeper is observing it. Kill it now
|
|
512
|
+
// rather than relabeling a live process "lost" without touching it.
|
|
513
|
+
record.terminationReason = "cancelled";
|
|
514
|
+
await this.persist(record).catch(() => undefined);
|
|
515
|
+
await killProcessGroup(record.pid).catch(() => undefined);
|
|
516
|
+
}
|
|
464
517
|
else {
|
|
465
|
-
//
|
|
466
|
-
//
|
|
518
|
+
// Truly unreachable (e.g. an internal run this process did not launch): mark it lost
|
|
519
|
+
// rather than pretend a cancel we could not perform happened.
|
|
467
520
|
record.status = "lost";
|
|
468
521
|
record.finishedAt = Date.now();
|
|
469
522
|
record.settledAt = record.finishedAt;
|
|
470
523
|
record.wakeEnqueued = true;
|
|
471
524
|
releaseWorkspaceLease(record.leaseKey);
|
|
525
|
+
record.leaseKey = undefined;
|
|
472
526
|
await this.persist(record);
|
|
473
527
|
return record.status;
|
|
474
528
|
}
|
|
475
|
-
return "running"; // The
|
|
529
|
+
return "running"; // The handle, or the sweeper once the process exits, drives the settle() call.
|
|
476
530
|
});
|
|
477
531
|
}
|
|
478
532
|
/**
|
|
@@ -526,27 +580,64 @@ export class SubAgentRunManager {
|
|
|
526
580
|
});
|
|
527
581
|
}
|
|
528
582
|
if (record.runtime === "external" && record.status === "running") {
|
|
583
|
+
// A write run adopted mid-flight must keep excluding other writers the same way it
|
|
584
|
+
// did before the restart (D10.1); the lease itself is a process-local Map, so a
|
|
585
|
+
// fresh process starts with none held until this rebuilds it (P0-1).
|
|
586
|
+
if (record.leaseKey) {
|
|
587
|
+
const rebuilt = acquireWorkspaceLease({
|
|
588
|
+
runId: record.runId,
|
|
589
|
+
channelId: record.channelId,
|
|
590
|
+
workingDirectory: record.workingDirectory,
|
|
591
|
+
});
|
|
592
|
+
if (!rebuilt.ok) {
|
|
593
|
+
log.logWarning(`Could not rebuild workspace lease for adopted run ${record.runId}`, formatWorkspaceLeaseConflict(rebuilt.heldBy));
|
|
594
|
+
}
|
|
595
|
+
}
|
|
529
596
|
await this.reconcileExternalRun(record).catch((error) => {
|
|
530
597
|
log.logWarning(`Failed to reconcile external run ${record?.runId}`, errorMessage(error));
|
|
531
598
|
});
|
|
532
599
|
}
|
|
533
600
|
if (isTerminal(record.status) && record.settledAt) {
|
|
601
|
+
// A settled-but-unwoken record means the wake was lost between settlement and
|
|
602
|
+
// dispatch (e.g. the archive-queue failure this restart may itself be recovering
|
|
603
|
+
// from, P0-2) — durable dispatch is idempotent on dispatchId, so re-announcing is
|
|
604
|
+
// harmless even if the original wake actually made it out.
|
|
605
|
+
if (!record.wakeEnqueued) {
|
|
606
|
+
const outputText = await readFile(join(record.artifactDir, "output.md"), "utf-8").catch(() => "");
|
|
607
|
+
await this.announce(record, outputText, Boolean(outputText.trim())).catch((error) => {
|
|
608
|
+
log.logWarning(`Failed to re-announce sub-agent run ${record?.runId}`, errorMessage(error));
|
|
609
|
+
});
|
|
610
|
+
}
|
|
534
611
|
await this.collectGarbageIfExpired(record);
|
|
535
612
|
}
|
|
536
613
|
}
|
|
537
614
|
return restored;
|
|
538
615
|
}
|
|
616
|
+
/** Whether `record.pid` is still the same process that was launched, when that can be checked
|
|
617
|
+
* at all (D10.3). A missing `pidStartedAt` (an older record, or a `ps` that failed once at
|
|
618
|
+
* launch) means there is nothing to compare against — trust `isProcessAlive` alone rather
|
|
619
|
+
* than manufacture a false negative. */
|
|
620
|
+
async isSameProcess(record) {
|
|
621
|
+
if (!record.pid)
|
|
622
|
+
return false;
|
|
623
|
+
if (!record.pidStartedAt)
|
|
624
|
+
return true;
|
|
625
|
+
const current = await readProcessStartTime(record.pid);
|
|
626
|
+
return current === record.pidStartedAt;
|
|
627
|
+
}
|
|
539
628
|
/**
|
|
540
|
-
* Restart reconciliation for an external run still marked `running` (D10.3)
|
|
629
|
+
* Restart reconciliation for an external run still marked `running` (D10.3), and the terminal
|
|
630
|
+
* judgement `sweep()` uses once an adopted run's process is confirmed gone. Unlike internal
|
|
541
631
|
* runs, a `detached` external process outlives the daemon, so the first move is a liveness
|
|
542
632
|
* probe, not an automatic `lost`:
|
|
543
633
|
*
|
|
544
634
|
* - no `pid` at all: the intent was persisted but spawn was never confirmed — cannot prove it
|
|
545
635
|
* ever started, so it is judged `lost` the same as an internal run (D1).
|
|
546
|
-
* - `pid` alive: genuinely still running. Left alone
|
|
547
|
-
* - `pid` gone
|
|
548
|
-
*
|
|
549
|
-
* the
|
|
636
|
+
* - `pid` alive under the same identity: genuinely still running. Left alone.
|
|
637
|
+
* - `pid` gone (or reused by an unrelated process): the process finished, died, or was killed
|
|
638
|
+
* while the daemon was down. A `terminationReason` set before the kill (P1-1) takes priority
|
|
639
|
+
* over guessing from output; absent that, `events.jsonl` drives the same D4 status table the
|
|
640
|
+
* live post-exit path uses.
|
|
550
641
|
*/
|
|
551
642
|
async reconcileExternalRun(record) {
|
|
552
643
|
if (!record.pid) {
|
|
@@ -563,9 +654,39 @@ export class SubAgentRunManager {
|
|
|
563
654
|
}, { announce: true });
|
|
564
655
|
return;
|
|
565
656
|
}
|
|
566
|
-
if (isProcessAlive(record.pid)) {
|
|
657
|
+
if (isProcessAlive(record.pid) && (await this.isSameProcess(record))) {
|
|
567
658
|
return; // Still genuinely running; nothing to reconcile yet.
|
|
568
659
|
}
|
|
660
|
+
const durationMs = Date.now() - record.startedAt;
|
|
661
|
+
if (record.terminationReason === "cancelled") {
|
|
662
|
+
await this.settle(record.runId, {
|
|
663
|
+
status: "cancelled",
|
|
664
|
+
failureReason: "Cancelled by request.",
|
|
665
|
+
usage: record.usage,
|
|
666
|
+
usageKnown: record.usageKnown,
|
|
667
|
+
costKnown: record.costKnown,
|
|
668
|
+
turns: record.turns ?? 0,
|
|
669
|
+
toolCalls: record.toolCalls ?? 0,
|
|
670
|
+
durationMs,
|
|
671
|
+
outputText: "",
|
|
672
|
+
}, { announce: false });
|
|
673
|
+
return;
|
|
674
|
+
}
|
|
675
|
+
if (record.terminationReason === "timeout") {
|
|
676
|
+
const budgetSec = record.deadlineAt ? Math.round((record.deadlineAt - record.startedAt) / 1000) : undefined;
|
|
677
|
+
await this.settle(record.runId, {
|
|
678
|
+
status: "failed",
|
|
679
|
+
failureReason: `Wall time budget exceeded${budgetSec ? ` (${budgetSec}s)` : ""}`,
|
|
680
|
+
usage: record.usage,
|
|
681
|
+
usageKnown: record.usageKnown,
|
|
682
|
+
costKnown: record.costKnown,
|
|
683
|
+
turns: record.turns ?? 0,
|
|
684
|
+
toolCalls: record.toolCalls ?? 0,
|
|
685
|
+
durationMs,
|
|
686
|
+
outputText: "",
|
|
687
|
+
}, { announce: true });
|
|
688
|
+
return;
|
|
689
|
+
}
|
|
569
690
|
const harness = record.harness ? getExternalHarness(record.harness) : undefined;
|
|
570
691
|
const eventsText = await readFile(join(record.artifactDir, "events.jsonl"), "utf-8").catch(() => "");
|
|
571
692
|
const stderrTail = (await readFile(join(record.artifactDir, "stderr.log"), "utf-8").catch(() => "")).slice(-2_000);
|
|
@@ -575,7 +696,6 @@ export class SubAgentRunManager {
|
|
|
575
696
|
protocolStatus: "unparsable",
|
|
576
697
|
usageKnown: false,
|
|
577
698
|
costKnown: false,
|
|
578
|
-
outputTruncated: false,
|
|
579
699
|
stderrTail,
|
|
580
700
|
};
|
|
581
701
|
const classification = harness
|
|
@@ -589,11 +709,31 @@ export class SubAgentRunManager {
|
|
|
589
709
|
costKnown: outcome.costKnown,
|
|
590
710
|
turns: record.turns ?? 0,
|
|
591
711
|
toolCalls: record.toolCalls ?? 0,
|
|
592
|
-
durationMs
|
|
712
|
+
durationMs,
|
|
593
713
|
outputText: outcome.finalText,
|
|
594
714
|
sessionId: outcome.sessionId,
|
|
595
715
|
}, { announce: true });
|
|
596
716
|
}
|
|
717
|
+
/**
|
|
718
|
+
* Periodic host-wide check for external runs (spec 040, D10.3): kills anything past its
|
|
719
|
+
* deadline, and reconciles anything a `close` event will never fire for — a run adopted from a
|
|
720
|
+
* previous daemon via `restore()`, or (rarely) one whose local watcher already unwound without
|
|
721
|
+
* settling it. `reconcileExternalRun` no-ops on a genuinely still-running, still-watched run,
|
|
722
|
+
* so sweeping one this process itself launched is harmless, not just adopted ones.
|
|
723
|
+
*/
|
|
724
|
+
async sweep(now = Date.now()) {
|
|
725
|
+
for (const record of Array.from(this.runs.values())) {
|
|
726
|
+
if (record.status !== "running" || record.runtime !== "external" || !record.pid)
|
|
727
|
+
continue;
|
|
728
|
+
if (record.deadlineAt && now >= record.deadlineAt && record.terminationReason !== "timeout") {
|
|
729
|
+
await this.markTerminationReason(record.runId, "timeout");
|
|
730
|
+
await killProcessGroup(record.pid).catch(() => undefined);
|
|
731
|
+
}
|
|
732
|
+
await this.reconcileExternalRun(record).catch((error) => {
|
|
733
|
+
log.logWarning(`Failed to sweep external run ${record.runId}`, errorMessage(error));
|
|
734
|
+
});
|
|
735
|
+
}
|
|
736
|
+
}
|
|
597
737
|
/** Drop a settled record once its retention window has passed, mirroring job-manager's GC. */
|
|
598
738
|
async collectGarbageIfExpired(record, now = Date.now()) {
|
|
599
739
|
const RETENTION_MS = 24 * 60 * 60_000;
|
|
@@ -622,9 +762,35 @@ function totalRunningSubAgentRuns() {
|
|
|
622
762
|
return total;
|
|
623
763
|
}
|
|
624
764
|
let runtimeConfig = {};
|
|
765
|
+
/** How often the host-wide sweep checks external runs for an overdue deadline or a process that
|
|
766
|
+
* exited while nobody was watching it (D10.3). A code constant per CLAUDE.md's rule for numeric
|
|
767
|
+
* thresholds — deliberately coarse (budgets are in the 300-1800s range) since it exists to
|
|
768
|
+
* guarantee eventual enforcement across a restart, not to replace the live in-process watcher's
|
|
769
|
+
* prompt one. */
|
|
770
|
+
const SWEEP_INTERVAL_MS = 30_000;
|
|
771
|
+
let sweepTimer;
|
|
772
|
+
async function sweepAllChannels() {
|
|
773
|
+
for (const manager of managers.values()) {
|
|
774
|
+
await manager.sweep().catch((error) => log.logWarning("Sub-agent sweep failed", errorMessage(error)));
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
function startSubAgentSweeper() {
|
|
778
|
+
if (sweepTimer)
|
|
779
|
+
clearInterval(sweepTimer);
|
|
780
|
+
sweepTimer = setInterval(() => void sweepAllChannels(), SWEEP_INTERVAL_MS);
|
|
781
|
+
sweepTimer.unref?.();
|
|
782
|
+
}
|
|
783
|
+
/** Test seam: stop the background sweeper so it doesn't outlive a test's own fake timers or run. */
|
|
784
|
+
export function stopSubAgentSweeper() {
|
|
785
|
+
if (sweepTimer) {
|
|
786
|
+
clearInterval(sweepTimer);
|
|
787
|
+
sweepTimer = undefined;
|
|
788
|
+
}
|
|
789
|
+
}
|
|
625
790
|
/** Give runs their persistence root, wake delivery, ledger, and archive. Called once from bootstrap. */
|
|
626
791
|
export function configureSubAgentRuntime(config) {
|
|
627
792
|
runtimeConfig = config;
|
|
793
|
+
startSubAgentSweeper();
|
|
628
794
|
}
|
|
629
795
|
export function getSubAgentRunManager(channelId) {
|
|
630
796
|
let manager = managers.get(channelId);
|
package/dist/subagents/tool.d.ts
CHANGED
|
@@ -24,7 +24,7 @@ declare const subagentSchema: Type.TObject<{
|
|
|
24
24
|
purpose: Type.TOptional<Type.TUnion<[Type.TLiteral<"work">, Type.TLiteral<"verify">]>>;
|
|
25
25
|
taskId: Type.TOptional<Type.TString>;
|
|
26
26
|
returns: Type.TOptional<Type.TUnion<[Type.TLiteral<"text">, Type.TLiteral<"artifact">]>>;
|
|
27
|
-
thinkingLevel: Type.TOptional<Type.TUnion<[Type.TLiteral<"off">, Type.TLiteral<"minimal">, Type.TLiteral<"low">, Type.TLiteral<"medium">, Type.TLiteral<"high">, Type.TLiteral<"xhigh">]>>;
|
|
27
|
+
thinkingLevel: Type.TOptional<Type.TUnion<[Type.TLiteral<"off">, Type.TLiteral<"minimal">, Type.TLiteral<"low">, Type.TLiteral<"medium">, Type.TLiteral<"high">, Type.TLiteral<"xhigh">, Type.TLiteral<"max">]>>;
|
|
28
28
|
}>;
|
|
29
29
|
export interface SubAgentToolDetails {
|
|
30
30
|
kind: "subagent";
|
|
@@ -120,5 +120,7 @@ interface SubAgentRunContext {
|
|
|
120
120
|
* (rooted at the sub-agent workspace) and their own per-invocation bash timeout.
|
|
121
121
|
*/
|
|
122
122
|
declare function buildSubagentTools(executor: Executor, bashTimeoutSec: number, options: SubAgentToolOptions, runContext: SubAgentRunContext): AgentTool<any>[];
|
|
123
|
+
/** Shared by both runtimes' task envelopes and `subagent_manage`'s verify follow-up (spec 040, D9). */
|
|
124
|
+
export declare function buildVerificationProtocol(taskPath: string): string;
|
|
123
125
|
export declare function createSubAgentTool(options: SubAgentToolOptions): AgentTool<typeof subagentSchema, SubAgentToolDetails>;
|
|
124
126
|
export {};
|
package/dist/subagents/tool.js
CHANGED
|
@@ -13,6 +13,7 @@ import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
|
13
13
|
import { formatLocalTime } from "../shared/local-time.js";
|
|
14
14
|
import { splitH1Sections } from "../shared/markdown-sections.js";
|
|
15
15
|
import { clipTextByPromptUnits, countPromptUnits } from "../shared/prompt-units.js";
|
|
16
|
+
import { RecoverableToolError } from "../shared/recoverable-error.js";
|
|
16
17
|
import { clipText, errorMessage, extractAssistantText, extractLabelFromArgs } from "../shared/text-utils.js";
|
|
17
18
|
import { workspaceSubjectHash } from "../tasks/artifact-subject.js";
|
|
18
19
|
import { readStoredTask } from "../tasks/store.js";
|
|
@@ -58,6 +59,7 @@ const subagentSchema = Type.Object({
|
|
|
58
59
|
Type.Literal("medium"),
|
|
59
60
|
Type.Literal("high"),
|
|
60
61
|
Type.Literal("xhigh"),
|
|
62
|
+
Type.Literal("max"),
|
|
61
63
|
], {
|
|
62
64
|
description: 'Optional reasoning effort for the sub-agent. Defaults to "medium" for purpose=verify, "off" otherwise.',
|
|
63
65
|
})),
|
|
@@ -132,7 +134,7 @@ function resolveRunWorkingDirectory(requested, options) {
|
|
|
132
134
|
return base;
|
|
133
135
|
const target = resolve(base, trimmed);
|
|
134
136
|
if (!existsSync(target) || !statSync(target).isDirectory()) {
|
|
135
|
-
throw new
|
|
137
|
+
throw new RecoverableToolError(`workingDirectory "${requested}" is not an existing directory.`);
|
|
136
138
|
}
|
|
137
139
|
return target;
|
|
138
140
|
}
|
|
@@ -140,11 +142,11 @@ async function prepareRunContext(runId, params, options) {
|
|
|
140
142
|
const purpose = params.purpose ?? "work";
|
|
141
143
|
const taskId = params.taskId?.trim() || undefined;
|
|
142
144
|
if (purpose === "verify" && !taskId)
|
|
143
|
-
throw new
|
|
145
|
+
throw new RecoverableToolError("purpose=verify requires taskId.");
|
|
144
146
|
if (taskId && !TASK_ID_PATTERN.test(taskId))
|
|
145
|
-
throw new
|
|
147
|
+
throw new RecoverableToolError(`Invalid taskId: ${taskId}`);
|
|
146
148
|
if (taskId && !(await readStoredTask(options.channelDir, taskId))) {
|
|
147
|
-
throw new
|
|
149
|
+
throw new RecoverableToolError(`Task ${taskId} does not exist. Create it with task_manage before delegating task-owned work.`);
|
|
148
150
|
}
|
|
149
151
|
const artifactDir = await prepareArtifactDir(options.channelDir, runId);
|
|
150
152
|
const workingDirectory = resolveRunWorkingDirectory(params.workingDirectory, options);
|
|
@@ -278,6 +280,16 @@ function buildSubagentTools(executor, bashTimeoutSec, options, runContext) {
|
|
|
278
280
|
bashDefaultTimeoutSeconds: bashTimeoutSec,
|
|
279
281
|
}, { forSubagent: true }).filter((tool) => runContext.purpose !== "verify" || (tool.name !== "write" && tool.name !== "edit"));
|
|
280
282
|
}
|
|
283
|
+
/** Shared by both runtimes' task envelopes and `subagent_manage`'s verify follow-up (spec 040, D9). */
|
|
284
|
+
export function buildVerificationProtocol(taskPath) {
|
|
285
|
+
return [
|
|
286
|
+
"Verification protocol:",
|
|
287
|
+
`- Independently inspect ${taskPath} and verify every DoD/Verification item against concrete evidence.`,
|
|
288
|
+
"- You are the checker, not the maker. Do not edit files or fix failures; report them.",
|
|
289
|
+
"- Run deterministic checks when available and distinguish observed evidence from assumptions.",
|
|
290
|
+
"- End the response with exactly one final line: VERDICT: PASS or VERDICT: FAIL.",
|
|
291
|
+
].join("\n");
|
|
292
|
+
}
|
|
281
293
|
function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runContext, returns) {
|
|
282
294
|
const taskText = task.trim();
|
|
283
295
|
const lines = [
|
|
@@ -298,7 +310,7 @@ function buildSubAgentTask(task, config, runtimeContext, contextBlocks, runConte
|
|
|
298
310
|
lines.push("", `Task:`, taskText);
|
|
299
311
|
if (runContext.purpose === "verify") {
|
|
300
312
|
const taskPath = join(runtimeContext.workspaceDir, runtimeContext.channelId, "tasks", `${runContext.taskId}.md`);
|
|
301
|
-
lines.push("",
|
|
313
|
+
lines.push("", buildVerificationProtocol(taskPath));
|
|
302
314
|
}
|
|
303
315
|
else if (returns === "artifact") {
|
|
304
316
|
lines.push("", "Output protocol:", `- Write your primary output as a file under the artifact directory above.`, "- End the response with exactly one final line: ARTIFACT: <filename>");
|
|
@@ -440,11 +452,11 @@ export function createSubAgentTool(options) {
|
|
|
440
452
|
const currentModel = options.getCurrentModel();
|
|
441
453
|
const taskLengthError = validateSubAgentTask(params.task);
|
|
442
454
|
if (taskLengthError) {
|
|
443
|
-
throw new
|
|
455
|
+
throw new RecoverableToolError(taskLengthError);
|
|
444
456
|
}
|
|
445
457
|
const invocation = resolveSubAgentConfig(availableModels, currentModel, discovery.agents, params, options.getSubAgentModelReference?.() ?? undefined);
|
|
446
458
|
if (!invocation.config) {
|
|
447
|
-
throw new
|
|
459
|
+
throw new RecoverableToolError(`${invocation.error}\n\nAvailable configured sub-agents:\n${formatSubAgentList(discovery.agents)}`);
|
|
448
460
|
}
|
|
449
461
|
const config = invocation.config;
|
|
450
462
|
const returns = params.returns ?? "text";
|
|
@@ -459,14 +471,14 @@ export function createSubAgentTool(options) {
|
|
|
459
471
|
// A role that admits it writes cannot also be the checker, and `exec` has no protocol
|
|
460
472
|
// terminal to prove it even ran to completion — both are hard "no"s, not advisories.
|
|
461
473
|
if (config.mutates === "write") {
|
|
462
|
-
throw new
|
|
474
|
+
throw new RecoverableToolError(`Sub-agent "${config.name}" declares mutates: write and cannot be used for purpose=verify.`);
|
|
463
475
|
}
|
|
464
476
|
if (config.runtime === "external" && config.harness === "exec") {
|
|
465
|
-
throw new
|
|
477
|
+
throw new RecoverableToolError(`Sub-agent "${config.name}" uses the exec harness, which has no protocol terminal and cannot be used for purpose=verify.`);
|
|
466
478
|
}
|
|
467
479
|
const holder = findWorkspaceLeaseHolder(runContext.workingDirectory);
|
|
468
480
|
if (holder) {
|
|
469
|
-
throw new
|
|
481
|
+
throw new RecoverableToolError(`Cannot verify "${runContext.workingDirectory}": ${formatWorkspaceLeaseConflict(holder)}`);
|
|
470
482
|
}
|
|
471
483
|
}
|
|
472
484
|
// Admission: a write-mutating run takes an exclusive workspace lease before it is even
|
|
@@ -480,7 +492,7 @@ export function createSubAgentTool(options) {
|
|
|
480
492
|
workingDirectory: runContext.workingDirectory,
|
|
481
493
|
});
|
|
482
494
|
if (!lease.ok) {
|
|
483
|
-
throw new
|
|
495
|
+
throw new RecoverableToolError(formatWorkspaceLeaseConflict(lease.heldBy));
|
|
484
496
|
}
|
|
485
497
|
leaseKey = lease.leaseKey;
|
|
486
498
|
}
|
|
@@ -490,6 +502,11 @@ export function createSubAgentTool(options) {
|
|
|
490
502
|
throw new Error(`Sub-agent "${config.name}" has runtime: external but no harness configured.`);
|
|
491
503
|
}
|
|
492
504
|
try {
|
|
505
|
+
// D9/T5: external roles get the same task envelope internal workers do — runtime
|
|
506
|
+
// paths, injected context blocks, and (for purpose=verify) the verification
|
|
507
|
+
// protocol — rather than the raw task text (spec 040 gap closed post-review).
|
|
508
|
+
const contextualBlocks = await buildContextualBlocks(params.task, config, options, currentModel);
|
|
509
|
+
const envelopedTask = buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext, returns);
|
|
493
510
|
await launchExternalRun({
|
|
494
511
|
runId: runContext.runId,
|
|
495
512
|
channelId: options.runtimeContext.channelId,
|
|
@@ -505,7 +522,7 @@ export function createSubAgentTool(options) {
|
|
|
505
522
|
thinkingLevel: config.thinkingLevel,
|
|
506
523
|
maxWallTimeSec: config.maxWallTimeSec,
|
|
507
524
|
systemPrompt: config.systemPrompt,
|
|
508
|
-
task:
|
|
525
|
+
task: envelopedTask,
|
|
509
526
|
workingDirectory: runContext.workingDirectory,
|
|
510
527
|
artifactDir: runContext.artifactDir,
|
|
511
528
|
purpose: runContext.purpose,
|
|
@@ -834,7 +851,9 @@ export function createSubAgentTool(options) {
|
|
|
834
851
|
},
|
|
835
852
|
settleInput: {
|
|
836
853
|
...baseSettleInput,
|
|
837
|
-
|
|
854
|
+
// An explicit cancel is not a failure (P1-1) — the model asked this run to
|
|
855
|
+
// stop, and it did.
|
|
856
|
+
status: externallyCancelled ? "cancelled" : "failed",
|
|
838
857
|
failureReason: effectiveFailureReason,
|
|
839
858
|
outputText: finalText,
|
|
840
859
|
},
|
|
@@ -857,7 +876,7 @@ export function createSubAgentTool(options) {
|
|
|
857
876
|
/** Best-effort settle input for the one fatal path that rejects instead of resolving. */
|
|
858
877
|
function fatalSettleInput(error) {
|
|
859
878
|
return {
|
|
860
|
-
status: "failed",
|
|
879
|
+
status: externallyCancelled ? "cancelled" : "failed",
|
|
861
880
|
failureReason: failureReason || error.message,
|
|
862
881
|
usage,
|
|
863
882
|
usageKnown: true,
|
|
@@ -1,9 +1,11 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
1
2
|
import { Type } from "typebox";
|
|
2
3
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
3
4
|
import { RecoverableToolError } from "../shared/recoverable-error.js";
|
|
4
5
|
import { launchExternalRun } from "../subagents/external/run.js";
|
|
5
6
|
import { elapsedMs, formatCost, formatDuration, harnessLabel } from "../subagents/format.js";
|
|
6
7
|
import { getSubAgentRunManager } from "../subagents/runs.js";
|
|
8
|
+
import { buildVerificationProtocol } from "../subagents/tool.js";
|
|
7
9
|
import { acquireWorkspaceLease, formatWorkspaceLeaseConflict, releaseWorkspaceLease, } from "../subagents/workspace-lease.js";
|
|
8
10
|
const subagentManageSchema = Type.Object({
|
|
9
11
|
label: Type.String({ description: "Brief description of what you're checking (shown to user)" }),
|
|
@@ -94,6 +96,16 @@ export function createSubAgentManageTool(options) {
|
|
|
94
96
|
if (role.unavailable) {
|
|
95
97
|
throw new RecoverableToolError(`Role "${record.agent}" is currently unavailable: ${role.unavailable}`);
|
|
96
98
|
}
|
|
99
|
+
// P1-2: a role hot-edited between the original run and this follow-up must not silently
|
|
100
|
+
// resume under a stale harness (the wrong CLI would parse a command it never wrote), or
|
|
101
|
+
// masquerade a shell role as resumable (there is no flag to carry `resumeSessionId` into
|
|
102
|
+
// `/bin/sh -lc`, so the run would silently start a fresh, unrelated session anyway).
|
|
103
|
+
if (role.harness !== harness) {
|
|
104
|
+
throw new RecoverableToolError(`Role "${record.agent}" now uses harness "${role.harness}", but run "${resolvedRunId}" was started on "${harness}". Delegate a new run instead of resuming across a harness change.`);
|
|
105
|
+
}
|
|
106
|
+
if (role.shell) {
|
|
107
|
+
throw new RecoverableToolError(`Role "${record.agent}" runs its command through a shell, which has no way to carry a resume session id. Delegate a new run instead, carrying forward whatever context it needs.`);
|
|
108
|
+
}
|
|
97
109
|
// A short, human-typeable id (spec 041) — the follow-up gets a fresh identity, not the
|
|
98
110
|
// dispatching tool call's own id.
|
|
99
111
|
const newRunId = manager().mintRunId();
|
|
@@ -109,6 +121,11 @@ export function createSubAgentManageTool(options) {
|
|
|
109
121
|
}
|
|
110
122
|
leaseKey = lease.leaseKey;
|
|
111
123
|
}
|
|
124
|
+
// The initial dispatch envelopes verify runs with the protocol (tool.ts); a follow-up
|
|
125
|
+
// on a verify run must carry the same protocol, not just the bare instruction (D9).
|
|
126
|
+
const envelopedTask = record.purpose === "verify" && record.taskId
|
|
127
|
+
? `${task.trim()}\n\n${buildVerificationProtocol(join(options.workspaceDir ?? "", options.channelId, "tasks", `${record.taskId}.md`))}`
|
|
128
|
+
: task;
|
|
112
129
|
try {
|
|
113
130
|
await launchExternalRun({
|
|
114
131
|
runId: newRunId,
|
|
@@ -125,7 +142,7 @@ export function createSubAgentManageTool(options) {
|
|
|
125
142
|
thinkingLevel: role.thinkingLevel,
|
|
126
143
|
maxWallTimeSec: role.maxWallTimeSec,
|
|
127
144
|
systemPrompt: role.systemPrompt,
|
|
128
|
-
task,
|
|
145
|
+
task: envelopedTask,
|
|
129
146
|
workingDirectory: record.workingDirectory,
|
|
130
147
|
artifactDir: record.artifactDir.replace(/[^/\\]+$/, newRunId),
|
|
131
148
|
purpose: record.purpose,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
#
|
|
1
|
+
# 工作区智能体角色示例
|
|
2
2
|
|
|
3
|
-
这里的文件既是配置示例,也是按生产使用标准维护的推荐模板。Pipiclaw
|
|
3
|
+
这里的文件既是配置示例,也是按生产使用标准维护的推荐模板。Pipiclaw 不会自动加载它们;请只复制实际需要的角色到工作区,并根据账号、sandbox 和团队规则逐项审查。下面的命令适用于源码 checkout:
|
|
4
4
|
|
|
5
5
|
```bash
|
|
6
6
|
# 内置角色(无需额外安装):
|
|
@@ -11,6 +11,14 @@ cp examples/sub-agents/{planner,builder,builder-hard}.md ~/.pipiclaw/workspace/s
|
|
|
11
11
|
cp examples/sub-agents/{reviewer,verifier,scout,worker,documenter}.md ~/.pipiclaw/workspace/sub-agents/ # 需要 codex
|
|
12
12
|
```
|
|
13
13
|
|
|
14
|
+
通过 npm 全局安装时,模板位于包目录:
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
PIPICLAW_PACKAGE_DIR="$(npm root -g)/@oyasmi/pipiclaw"
|
|
18
|
+
cp "$PIPICLAW_PACKAGE_DIR"/examples/sub-agents/{builder,reviewer}.md \
|
|
19
|
+
~/.pipiclaw/workspace/sub-agents/
|
|
20
|
+
```
|
|
21
|
+
|
|
14
22
|
## 内置角色(`runtime: internal`)
|
|
15
23
|
|
|
16
24
|
内置角色在 pipiclaw 进程内运行,使用 pipiclaw 自己的工具集和安全守卫,轻量、便宜、通常在同一回合内同步返回。它们的价值是**低延迟**和**上下文隔离**,不是算力。
|