@oyasmi/pipiclaw 0.9.0-beta.7 → 0.9.0-beta.9
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/dist/agent/channel-runner.d.ts +1 -0
- package/dist/agent/channel-runner.js +21 -2
- package/dist/agent/index.d.ts +1 -1
- package/dist/agent/index.js +1 -1
- package/dist/agent/job-manager.d.ts +3 -3
- package/dist/agent/job-manager.js +0 -1
- package/dist/agent/runner-factory.d.ts +16 -4
- package/dist/agent/runner-factory.js +9 -23
- package/dist/agent/types.d.ts +9 -1
- package/dist/agent/types.js +3 -16
- package/dist/memory/review-log.js +0 -0
- package/dist/memory/scheduler.d.ts +1 -0
- package/dist/memory/scheduler.js +64 -6
- package/dist/playbooks/agent-delegation.md +2 -2
- package/dist/runtime/bootstrap.d.ts +10 -2
- package/dist/runtime/bootstrap.js +83 -55
- package/dist/runtime/channel-event.d.ts +41 -0
- package/dist/runtime/channel-event.js +1 -0
- package/dist/runtime/delivery.d.ts +3 -2
- package/dist/runtime/dingtalk.d.ts +9 -31
- package/dist/runtime/durable-dispatch.d.ts +4 -2
- package/dist/runtime/durable-dispatch.js +36 -25
- package/dist/runtime/events.d.ts +3 -2
- package/dist/runtime/events.js +2 -3
- package/dist/runtime/subagent-commands.js +48 -10
- package/dist/runtime/task-commands.js +2 -2
- package/dist/runtime/task-driver.d.ts +7 -7
- package/dist/runtime/task-driver.js +1 -4
- package/dist/runtime/task-migration.js +1 -1
- package/dist/runtime/task-wake.d.ts +4 -4
- package/dist/settings.d.ts +0 -106
- package/dist/settings.js +0 -224
- package/dist/shared/host-process.d.ts +25 -9
- package/dist/shared/host-process.js +59 -10
- package/dist/shared/types.d.ts +1 -0
- package/dist/shared/types.js +10 -1
- package/dist/subagents/discovery.d.ts +24 -0
- package/dist/subagents/discovery.js +103 -17
- package/dist/subagents/external/claude-code.js +10 -3
- package/dist/subagents/external/codex-cli.js +9 -3
- package/dist/subagents/external/exec.js +1 -0
- package/dist/subagents/external/harness.d.ts +22 -0
- package/dist/subagents/external/harness.js +22 -4
- package/dist/subagents/external/run.d.ts +23 -3
- package/dist/subagents/external/run.js +112 -131
- package/dist/subagents/external/settlement.d.ts +50 -0
- package/dist/subagents/external/settlement.js +123 -0
- package/dist/subagents/format.d.ts +4 -0
- package/dist/subagents/format.js +7 -0
- package/dist/subagents/runs.d.ts +73 -16
- package/dist/subagents/runs.js +197 -120
- package/dist/subagents/tool.d.ts +38 -6
- package/dist/subagents/tool.js +93 -61
- package/dist/subagents/verification-outcome.d.ts +26 -0
- package/dist/subagents/verification-outcome.js +16 -0
- package/dist/subagents/workspace-lease.d.ts +10 -1
- package/dist/subagents/workspace-lease.js +15 -2
- package/dist/tasks/ledger.js +1 -1
- package/dist/{shared → tasks}/task-schedule.js +1 -1
- package/dist/tools/bash.js +1 -1
- package/dist/tools/event-manage.js +1 -4
- package/dist/tools/grep.js +2 -3
- package/dist/tools/index.js +6 -0
- package/dist/tools/job.js +5 -5
- package/dist/tools/memory-manage.js +3 -6
- package/dist/tools/session-search.js +0 -1
- package/dist/tools/skill-manage.js +3 -3
- package/dist/tools/subagent-manage.d.ts +20 -6
- package/dist/tools/subagent-manage.js +88 -18
- package/dist/tools/task-manage/shared.js +2 -2
- package/dist/tools/task-manage.js +1 -4
- package/dist/tools/web-fetch.js +0 -1
- package/dist/tui/app.js +4 -4
- package/package.json +1 -1
- /package/dist/{shared → tasks}/task-events.d.ts +0 -0
- /package/dist/{shared → tasks}/task-events.js +0 -0
- /package/dist/{shared → tasks}/task-schedule.d.ts +0 -0
package/dist/subagents/runs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { mkdir, readdir, readFile, unlink } from "node:fs/promises";
|
|
1
|
+
import { mkdir, readdir, readFile, stat, 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";
|
|
@@ -7,9 +7,9 @@ import { RecoverableToolError } from "../shared/recoverable-error.js";
|
|
|
7
7
|
import { createSerialQueue } from "../shared/serial-queue.js";
|
|
8
8
|
import { errorMessage } from "../shared/text-utils.js";
|
|
9
9
|
import { isRecord } from "../shared/type-guards.js";
|
|
10
|
+
import { createEmptyUsageTotals } from "../shared/types.js";
|
|
10
11
|
import { beginWakeClaim, finishWakeClaim } from "../shared/wake-claim.js";
|
|
11
|
-
import {
|
|
12
|
-
import { getExternalHarness } from "./external/registry.js";
|
|
12
|
+
import { finalizeExternalRun } from "./external/settlement.js";
|
|
13
13
|
import { acquireWorkspaceLease, formatWorkspaceLeaseConflict, releaseWorkspaceLease } from "./workspace-lease.js";
|
|
14
14
|
/**
|
|
15
15
|
* Longest a dispatching tool call waits for its run to settle before returning a "still running"
|
|
@@ -51,6 +51,19 @@ function normalizeRunIdQuery(query) {
|
|
|
51
51
|
const hostAdmissionQueue = createSerialQueue();
|
|
52
52
|
/** Bytes of the reply text carried inline in the completion wake, matching job-manager's tail budget. */
|
|
53
53
|
const WAKE_OUTPUT_TAIL_CHARS = 2_000;
|
|
54
|
+
/** Settled runs and every runtime-managed artifact are retained together for one week. GC runs
|
|
55
|
+
* daily, so an item can remain for up to one additional sweep interval after this age. */
|
|
56
|
+
const RUN_RETENTION_MS = 7 * 24 * 60 * 60_000;
|
|
57
|
+
const RUN_ARTIFACT_FILENAMES = ["prompt.txt", "system-prompt.txt", "events.jsonl", "stderr.log", "output.md"];
|
|
58
|
+
async function unlinkIfPresent(path) {
|
|
59
|
+
try {
|
|
60
|
+
await unlink(path);
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
if (error.code !== "ENOENT")
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
54
67
|
function isTerminal(status) {
|
|
55
68
|
return status !== "running";
|
|
56
69
|
}
|
|
@@ -93,6 +106,9 @@ export class SubAgentRunManager {
|
|
|
93
106
|
/** External launch intents exist before a safe live child handle does. A cancel in that window
|
|
94
107
|
* is remembered here and consumed before spawn, rather than spawning a process nothing can cancel. */
|
|
95
108
|
this.externalLaunches = new Map();
|
|
109
|
+
/** One-shot deadline checks for external processes adopted during restore. Unlike a child this
|
|
110
|
+
* daemon spawned itself, an adopted process cannot emit a `close` event to this process. */
|
|
111
|
+
this.externalRecoveryTimers = new Map();
|
|
96
112
|
this.queue = createSerialQueue();
|
|
97
113
|
}
|
|
98
114
|
recordPath(runId) {
|
|
@@ -131,12 +147,16 @@ export class SubAgentRunManager {
|
|
|
131
147
|
}
|
|
132
148
|
}
|
|
133
149
|
async forget(record) {
|
|
150
|
+
// Delete artifacts before the durable record. If a real filesystem error occurs, retaining
|
|
151
|
+
// the record keeps the run eligible for a later daily retry instead of orphaning its files.
|
|
152
|
+
await Promise.all(RUN_ARTIFACT_FILENAMES.map((name) => unlinkIfPresent(join(record.artifactDir, name))));
|
|
153
|
+
const path = this.recordPath(record.runId);
|
|
154
|
+
if (path)
|
|
155
|
+
await unlinkIfPresent(path);
|
|
134
156
|
this.runs.delete(record.runId);
|
|
135
157
|
this.cancelHandles.delete(record.runId);
|
|
136
158
|
this.externalLaunches.delete(record.runId);
|
|
137
|
-
|
|
138
|
-
if (path)
|
|
139
|
-
await unlink(path).catch(() => undefined);
|
|
159
|
+
this.clearExternalRecoveryTimer(record.runId);
|
|
140
160
|
}
|
|
141
161
|
get(runId) {
|
|
142
162
|
return this.runs.get(runId);
|
|
@@ -206,7 +226,7 @@ export class SubAgentRunManager {
|
|
|
206
226
|
...input,
|
|
207
227
|
status: "running",
|
|
208
228
|
startedAt: Date.now(),
|
|
209
|
-
usage:
|
|
229
|
+
usage: createEmptyUsageTotals(),
|
|
210
230
|
usageKnown: true,
|
|
211
231
|
costKnown: true,
|
|
212
232
|
};
|
|
@@ -258,6 +278,14 @@ export class SubAgentRunManager {
|
|
|
258
278
|
// at settle(), means a run that crashes before any output is still resumable.
|
|
259
279
|
if (info.sessionId)
|
|
260
280
|
record.sessionId = info.sessionId;
|
|
281
|
+
record.verifySubjectBefore = info.verifySubjectBefore;
|
|
282
|
+
record.maxWallTimeSec = info.maxWallTimeSec;
|
|
283
|
+
record.processStartedAt = info.processStartedAt;
|
|
284
|
+
record.channelDir = info.channelDir;
|
|
285
|
+
record.invocationWarnings = info.invocationWarnings;
|
|
286
|
+
record.roleFingerprint = info.roleFingerprint;
|
|
287
|
+
record.parserVersion = info.parserVersion;
|
|
288
|
+
record.cliVersion = info.cliVersion;
|
|
261
289
|
await this.persist(record, true);
|
|
262
290
|
}
|
|
263
291
|
/** Reserve a task wake exactly once. A replay of the same durable dispatch may resume an
|
|
@@ -340,6 +368,7 @@ export class SubAgentRunManager {
|
|
|
340
368
|
record.turns = input.turns;
|
|
341
369
|
record.toolCalls = input.toolCalls;
|
|
342
370
|
record.durationMs = input.durationMs;
|
|
371
|
+
record.durationEstimated = input.durationEstimated;
|
|
343
372
|
record.verificationVerdict = input.verificationVerdict;
|
|
344
373
|
record.verificationStrength = input.verificationStrength;
|
|
345
374
|
if (input.sessionId)
|
|
@@ -354,10 +383,11 @@ export class SubAgentRunManager {
|
|
|
354
383
|
throw error;
|
|
355
384
|
}
|
|
356
385
|
const outputSaved = await this.writeOutputFile(record, input.outputText);
|
|
357
|
-
releaseWorkspaceLease(record.leaseKey);
|
|
386
|
+
releaseWorkspaceLease(record.leaseKey, record.runId);
|
|
358
387
|
record.leaseKey = undefined; // Terminal records never display as "lease held" (P1-4).
|
|
359
388
|
this.cancelHandles.delete(runId);
|
|
360
389
|
this.externalLaunches.delete(runId);
|
|
390
|
+
this.clearExternalRecoveryTimer(runId);
|
|
361
391
|
await this.persist(record);
|
|
362
392
|
if (!record.usageRecorded) {
|
|
363
393
|
record.usageRecorded = true;
|
|
@@ -440,7 +470,7 @@ export class SubAgentRunManager {
|
|
|
440
470
|
user: "SUBAGENT",
|
|
441
471
|
userName: "SUBAGENT",
|
|
442
472
|
text: `[SUBAGENT:${record.runId}] Delegation "${record.label}" -> ${record.agent} (${harnessLabel}) finished: ` +
|
|
443
|
-
`${record.status} (${formatDuration(record.durationMs ?? 0)}).${belongsTo}${verdictLine}\n` +
|
|
473
|
+
`${record.status} (${record.durationEstimated ? "≈" : ""}${formatDuration(record.durationMs ?? 0)}).${belongsTo}${verdictLine}\n` +
|
|
444
474
|
`Result:\n${tail || "(no output)"}\n` +
|
|
445
475
|
// A run that produced no text has no output.md; pointing at it would send the model
|
|
446
476
|
// after a file that does not exist. The artifact dir still holds the run's evidence
|
|
@@ -450,7 +480,6 @@ export class SubAgentRunManager {
|
|
|
450
480
|
: `No text output was produced. Run artifacts: ${record.artifactDir}\n`) +
|
|
451
481
|
"Continue whatever was waiting on this delegation. If it needs no follow-up, respond with exactly [SILENT].",
|
|
452
482
|
ts: String(Date.now()),
|
|
453
|
-
conversationId: "",
|
|
454
483
|
conversationType: record.channelId.startsWith("group_") ? "2" : "1",
|
|
455
484
|
dispatchId: `subagent:${record.channelId}:${record.runId}:done`,
|
|
456
485
|
...(record.taskId
|
|
@@ -476,7 +505,8 @@ export class SubAgentRunManager {
|
|
|
476
505
|
}
|
|
477
506
|
/** Explicit cancel (`subagent_manage op=cancel`, spec 040 D6). Does not wake — it is the model's own decision. */
|
|
478
507
|
async cancel(runId) {
|
|
479
|
-
|
|
508
|
+
let adoptedRecord;
|
|
509
|
+
const status = await this.queue.run(runId, async () => {
|
|
480
510
|
const record = this.runs.get(runId);
|
|
481
511
|
if (!record)
|
|
482
512
|
return "not_found";
|
|
@@ -486,9 +516,8 @@ export class SubAgentRunManager {
|
|
|
486
516
|
this.cancelHandles.delete(runId);
|
|
487
517
|
if (cancelHandle) {
|
|
488
518
|
// External: mark the reason before the handle kills the process, so whichever code
|
|
489
|
-
// path settles this run
|
|
490
|
-
// process
|
|
491
|
-
// whatever the process happened to print before it died (P1-1). This also covers
|
|
519
|
+
// path settles this run reports "cancelled" instead of guessing from whatever the
|
|
520
|
+
// process happened to print before it died (P1-1). This also covers
|
|
492
521
|
// the pre-spawn placeholder handle `claimExternalLaunch` installs: a cancel that
|
|
493
522
|
// lands in that narrow window durably marks the intent even though the placeholder
|
|
494
523
|
// itself does nothing else.
|
|
@@ -505,11 +534,12 @@ export class SubAgentRunManager {
|
|
|
505
534
|
}
|
|
506
535
|
else if (record.runtime === "external" && record.pid) {
|
|
507
536
|
// Adopted from a previous daemon (spec 040, D10.3): no live in-process watcher, but
|
|
508
|
-
// the run is genuinely still running and
|
|
509
|
-
//
|
|
537
|
+
// the run is genuinely still running. Kill and reconcile it directly rather than
|
|
538
|
+
// waiting for its one-shot deadline check.
|
|
510
539
|
record.terminationReason = "cancelled";
|
|
511
540
|
await this.persist(record).catch(() => undefined);
|
|
512
541
|
await killProcessGroup(record.pid).catch(() => undefined);
|
|
542
|
+
adoptedRecord = record;
|
|
513
543
|
}
|
|
514
544
|
else {
|
|
515
545
|
// Truly unreachable (e.g. an internal run this process did not launch): mark it lost
|
|
@@ -518,13 +548,20 @@ export class SubAgentRunManager {
|
|
|
518
548
|
record.finishedAt = Date.now();
|
|
519
549
|
record.settledAt = record.finishedAt;
|
|
520
550
|
record.wakeEnqueued = true;
|
|
521
|
-
releaseWorkspaceLease(record.leaseKey);
|
|
551
|
+
releaseWorkspaceLease(record.leaseKey, record.runId);
|
|
522
552
|
record.leaseKey = undefined;
|
|
523
553
|
await this.persist(record);
|
|
524
554
|
return record.status;
|
|
525
555
|
}
|
|
526
|
-
return "running"; //
|
|
556
|
+
return "running"; // A live handle or the adopted-run reconciliation below drives settlement.
|
|
527
557
|
});
|
|
558
|
+
if (!adoptedRecord)
|
|
559
|
+
return status;
|
|
560
|
+
this.clearExternalRecoveryTimer(runId);
|
|
561
|
+
await this.reconcileExternalRun(adoptedRecord).catch((error) => {
|
|
562
|
+
log.logWarning(`Failed to reconcile cancelled adopted run ${runId}`, errorMessage(error));
|
|
563
|
+
});
|
|
564
|
+
return this.runs.get(runId)?.status ?? status;
|
|
528
565
|
}
|
|
529
566
|
/**
|
|
530
567
|
* Rebuild in-memory state after a restart. Internal runs cannot survive a restart by
|
|
@@ -586,13 +623,31 @@ export class SubAgentRunManager {
|
|
|
586
623
|
channelId: record.channelId,
|
|
587
624
|
workingDirectory: record.workingDirectory,
|
|
588
625
|
});
|
|
589
|
-
if (
|
|
626
|
+
if (rebuilt.ok) {
|
|
627
|
+
// Spec 042 D5: persist what was *actually* acquired, not just trust the old
|
|
628
|
+
// value — a symlink swap or a checkout replaced at the same path can make the
|
|
629
|
+
// realpath drift between restarts.
|
|
630
|
+
record.leaseKey = rebuilt.leaseKey;
|
|
631
|
+
await this.persist(record).catch((error) => {
|
|
632
|
+
log.logWarning(`Failed to persist rebuilt lease for run ${record.runId}`, errorMessage(error));
|
|
633
|
+
});
|
|
634
|
+
}
|
|
635
|
+
else {
|
|
590
636
|
log.logWarning(`Could not rebuild workspace lease for adopted run ${record.runId}`, formatWorkspaceLeaseConflict(rebuilt.heldBy));
|
|
637
|
+
// This run does not actually hold a lease anymore — record that honestly
|
|
638
|
+
// (spec 042 D5) so a later settle() cannot delete a different holder's lease
|
|
639
|
+
// for the same key, and so displays stop claiming this run still holds it.
|
|
640
|
+
record.leaseKey = undefined;
|
|
641
|
+
await this.persist(record).catch((error) => {
|
|
642
|
+
log.logWarning(`Failed to persist cleared lease for run ${record.runId}`, errorMessage(error));
|
|
643
|
+
});
|
|
591
644
|
}
|
|
592
645
|
}
|
|
593
|
-
await this.
|
|
646
|
+
await this.reconcileExternalRunAtDeadline(record, Date.now()).catch((error) => {
|
|
594
647
|
log.logWarning(`Failed to reconcile external run ${record?.runId}`, errorMessage(error));
|
|
595
648
|
});
|
|
649
|
+
if (record.status === "running")
|
|
650
|
+
this.scheduleExternalRecovery(record);
|
|
596
651
|
}
|
|
597
652
|
if (isTerminal(record.status) && record.settledAt) {
|
|
598
653
|
// A settled-but-unwoken record means the wake was lost between settlement and
|
|
@@ -605,7 +660,6 @@ export class SubAgentRunManager {
|
|
|
605
660
|
log.logWarning(`Failed to re-announce sub-agent run ${record?.runId}`, errorMessage(error));
|
|
606
661
|
});
|
|
607
662
|
}
|
|
608
|
-
await this.collectGarbageIfExpired(record);
|
|
609
663
|
}
|
|
610
664
|
}
|
|
611
665
|
return restored;
|
|
@@ -632,9 +686,10 @@ export class SubAgentRunManager {
|
|
|
632
686
|
* ever started, so it is judged `lost` the same as an internal run (D1).
|
|
633
687
|
* - `pid` alive under the same identity: genuinely still running. Left alone.
|
|
634
688
|
* - `pid` gone (or reused by an unrelated process): the process finished, died, or was killed
|
|
635
|
-
* while the daemon was down.
|
|
636
|
-
*
|
|
637
|
-
*
|
|
689
|
+
* while the daemon was down. `finalizeExternalRun` (spec 042 D1) parses whatever the process
|
|
690
|
+
* actually wrote before applying `terminationReason` — the same sequence the live post-exit
|
|
691
|
+
* path uses, so a reconciled run never loses usage, output, session id, or its verify verdict
|
|
692
|
+
* just because the daemon happened to be down when the run finished.
|
|
638
693
|
*/
|
|
639
694
|
async reconcileExternalRun(record) {
|
|
640
695
|
if (!record.pid) {
|
|
@@ -647,6 +702,7 @@ export class SubAgentRunManager {
|
|
|
647
702
|
turns: record.turns ?? 0,
|
|
648
703
|
toolCalls: record.toolCalls ?? 0,
|
|
649
704
|
durationMs: Date.now() - record.startedAt,
|
|
705
|
+
durationEstimated: true,
|
|
650
706
|
outputText: "",
|
|
651
707
|
}, { announce: true });
|
|
652
708
|
return;
|
|
@@ -654,100 +710,112 @@ export class SubAgentRunManager {
|
|
|
654
710
|
if (isProcessAlive(record.pid) && (await this.isSameProcess(record))) {
|
|
655
711
|
return; // Still genuinely running; nothing to reconcile yet.
|
|
656
712
|
}
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
await this.settle(record.runId, {
|
|
660
|
-
status: "cancelled",
|
|
661
|
-
failureReason: "Cancelled by request.",
|
|
662
|
-
usage: record.usage,
|
|
663
|
-
usageKnown: record.usageKnown,
|
|
664
|
-
costKnown: record.costKnown,
|
|
665
|
-
turns: record.turns ?? 0,
|
|
666
|
-
toolCalls: record.toolCalls ?? 0,
|
|
667
|
-
durationMs,
|
|
668
|
-
outputText: "",
|
|
669
|
-
}, { announce: false });
|
|
670
|
-
return;
|
|
671
|
-
}
|
|
672
|
-
if (record.terminationReason === "timeout") {
|
|
673
|
-
const budgetSec = record.deadlineAt ? Math.round((record.deadlineAt - record.startedAt) / 1000) : undefined;
|
|
713
|
+
if (!record.harness) {
|
|
714
|
+
// Defensive only: external runs always get a harness at register() time (spec 040 D1).
|
|
674
715
|
await this.settle(record.runId, {
|
|
675
716
|
status: "failed",
|
|
676
|
-
failureReason:
|
|
717
|
+
failureReason: "Run has no recorded harness; cannot judge it.",
|
|
677
718
|
usage: record.usage,
|
|
678
719
|
usageKnown: record.usageKnown,
|
|
679
720
|
costKnown: record.costKnown,
|
|
680
721
|
turns: record.turns ?? 0,
|
|
681
722
|
toolCalls: record.toolCalls ?? 0,
|
|
682
|
-
durationMs,
|
|
723
|
+
durationMs: Date.now() - record.startedAt,
|
|
724
|
+
durationEstimated: true,
|
|
683
725
|
outputText: "",
|
|
684
726
|
}, { announce: true });
|
|
685
727
|
return;
|
|
686
728
|
}
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
const
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
await
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
729
|
+
// Duration can only be estimated post-restart: the artifact file's own mtime is the closest
|
|
730
|
+
// proxy for "when the process last wrote something" (D1); wall clock from the last known
|
|
731
|
+
// process start is the fallback when the file is missing (e.g. already GC'd).
|
|
732
|
+
const processStartedAt = record.processStartedAt ?? record.startedAt;
|
|
733
|
+
let durationMs = Date.now() - processStartedAt;
|
|
734
|
+
try {
|
|
735
|
+
const eventsStat = await stat(join(record.artifactDir, "events.jsonl"));
|
|
736
|
+
durationMs = eventsStat.mtimeMs - processStartedAt;
|
|
737
|
+
}
|
|
738
|
+
catch {
|
|
739
|
+
// No events file (or already GC'd) — fall back to the wall-clock estimate above.
|
|
740
|
+
}
|
|
741
|
+
const maxWallTimeSec = record.maxWallTimeSec ??
|
|
742
|
+
(record.deadlineAt ? Math.round((record.deadlineAt - record.startedAt) / 1000) : undefined);
|
|
743
|
+
await finalizeExternalRun({
|
|
744
|
+
runId: record.runId,
|
|
745
|
+
channelId: record.channelId,
|
|
746
|
+
channelDir: record.channelDir,
|
|
747
|
+
harnessId: record.harness,
|
|
748
|
+
purpose: record.purpose,
|
|
749
|
+
taskId: record.taskId,
|
|
750
|
+
workingDirectory: record.workingDirectory,
|
|
751
|
+
artifactDir: record.artifactDir,
|
|
752
|
+
exitCode: undefined,
|
|
753
|
+
durationMs: Math.max(0, durationMs),
|
|
754
|
+
durationEstimated: true,
|
|
755
|
+
terminationReason: record.terminationReason,
|
|
756
|
+
maxWallTimeSec,
|
|
757
|
+
verifySubjectBefore: record.verifySubjectBefore,
|
|
758
|
+
}, (settleInput, options) => this.settle(record.runId, settleInput, options), { announce: record.terminationReason !== "cancelled" });
|
|
759
|
+
}
|
|
760
|
+
/** Reconcile an adopted process once at restore and once at its persisted deadline. Probing
|
|
761
|
+
* liveness before assigning a timeout lets a process that finished just before the deadline be
|
|
762
|
+
* settled from its artifacts as a normal completion. */
|
|
763
|
+
async reconcileExternalRunAtDeadline(record, now = Date.now()) {
|
|
764
|
+
if (record.pid &&
|
|
765
|
+
record.deadlineAt &&
|
|
766
|
+
now >= record.deadlineAt &&
|
|
767
|
+
record.terminationReason !== "timeout" &&
|
|
768
|
+
isProcessAlive(record.pid) &&
|
|
769
|
+
(await this.isSameProcess(record))) {
|
|
770
|
+
await this.markTerminationReason(record.runId, "timeout");
|
|
771
|
+
await killProcessGroup(record.pid).catch(() => undefined);
|
|
772
|
+
}
|
|
773
|
+
await this.reconcileExternalRun(record);
|
|
774
|
+
}
|
|
775
|
+
clearExternalRecoveryTimer(runId) {
|
|
776
|
+
const timer = this.externalRecoveryTimers.get(runId);
|
|
777
|
+
if (!timer)
|
|
778
|
+
return;
|
|
779
|
+
clearTimeout(timer);
|
|
780
|
+
this.externalRecoveryTimers.delete(runId);
|
|
781
|
+
}
|
|
782
|
+
scheduleExternalRecovery(record) {
|
|
783
|
+
if (!record.deadlineAt)
|
|
784
|
+
return;
|
|
785
|
+
this.clearExternalRecoveryTimer(record.runId);
|
|
786
|
+
const timer = setTimeout(() => {
|
|
787
|
+
this.externalRecoveryTimers.delete(record.runId);
|
|
788
|
+
const current = this.runs.get(record.runId);
|
|
789
|
+
if (!current || current.status !== "running")
|
|
790
|
+
return;
|
|
791
|
+
void this.reconcileExternalRunAtDeadline(current).catch((error) => {
|
|
792
|
+
log.logWarning(`Failed to reconcile adopted external run ${current.runId}`, errorMessage(error));
|
|
793
|
+
});
|
|
794
|
+
}, Math.max(0, record.deadlineAt - Date.now()));
|
|
795
|
+
timer.unref?.();
|
|
796
|
+
this.externalRecoveryTimers.set(record.runId, timer);
|
|
713
797
|
}
|
|
714
798
|
/**
|
|
715
|
-
*
|
|
716
|
-
*
|
|
717
|
-
*
|
|
718
|
-
* settling it. `reconcileExternalRun` no-ops on a genuinely still-running, still-watched run,
|
|
719
|
-
* so sweeping one this process itself launched is harmless, not just adopted ones.
|
|
799
|
+
* Daily retention GC. A settled run and all runtime-managed artifacts are deleted together once
|
|
800
|
+
* they are at least seven days old. Other files deliberately created by the delegated task are
|
|
801
|
+
* not recursively removed from the artifact directory.
|
|
720
802
|
*/
|
|
721
|
-
async
|
|
803
|
+
async collectGarbageIfExpired(record, now = Date.now()) {
|
|
804
|
+
if (!record.settledAt)
|
|
805
|
+
return;
|
|
806
|
+
if (now - record.settledAt >= RUN_RETENTION_MS) {
|
|
807
|
+
await this.forget(record);
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
async collectGarbage(now = Date.now()) {
|
|
722
811
|
for (const record of Array.from(this.runs.values())) {
|
|
723
|
-
if (record.status
|
|
812
|
+
if (!isTerminal(record.status))
|
|
724
813
|
continue;
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
await killProcessGroup(record.pid).catch(() => undefined);
|
|
728
|
-
}
|
|
729
|
-
await this.reconcileExternalRun(record).catch((error) => {
|
|
730
|
-
log.logWarning(`Failed to sweep external run ${record.runId}`, errorMessage(error));
|
|
814
|
+
await this.collectGarbageIfExpired(record, now).catch((error) => {
|
|
815
|
+
log.logWarning(`Failed to garbage-collect sub-agent run ${record.runId}`, errorMessage(error));
|
|
731
816
|
});
|
|
732
817
|
}
|
|
733
818
|
}
|
|
734
|
-
/** Drop a settled record once its retention window has passed, mirroring job-manager's GC. */
|
|
735
|
-
async collectGarbageIfExpired(record, now = Date.now()) {
|
|
736
|
-
const RETENTION_MS = 24 * 60 * 60_000;
|
|
737
|
-
if (record.settledAt && now - record.settledAt >= RETENTION_MS) {
|
|
738
|
-
await this.forget(record);
|
|
739
|
-
}
|
|
740
|
-
}
|
|
741
|
-
}
|
|
742
|
-
function emptyUsage() {
|
|
743
|
-
return {
|
|
744
|
-
input: 0,
|
|
745
|
-
output: 0,
|
|
746
|
-
cacheRead: 0,
|
|
747
|
-
cacheWrite: 0,
|
|
748
|
-
total: 0,
|
|
749
|
-
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
750
|
-
};
|
|
751
819
|
}
|
|
752
820
|
const managers = new Map();
|
|
753
821
|
/** Host-wide running count for the D10.2 admission check, summed across every known channel. */
|
|
@@ -759,35 +827,42 @@ function totalRunningSubAgentRuns() {
|
|
|
759
827
|
return total;
|
|
760
828
|
}
|
|
761
829
|
let runtimeConfig = {};
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
830
|
+
const GARBAGE_COLLECTION_INTERVAL_MS = 24 * 60 * 60_000;
|
|
831
|
+
let garbageCollectionTimer;
|
|
832
|
+
let collectingGarbage = false;
|
|
833
|
+
async function collectGarbageAllChannels() {
|
|
834
|
+
if (collectingGarbage)
|
|
835
|
+
return;
|
|
836
|
+
collectingGarbage = true;
|
|
837
|
+
try {
|
|
838
|
+
for (const manager of managers.values()) {
|
|
839
|
+
await manager
|
|
840
|
+
.collectGarbage()
|
|
841
|
+
.catch((error) => log.logWarning("Sub-agent garbage collection failed", errorMessage(error)));
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
finally {
|
|
845
|
+
collectingGarbage = false;
|
|
772
846
|
}
|
|
773
847
|
}
|
|
774
|
-
function
|
|
775
|
-
if (
|
|
776
|
-
clearInterval(
|
|
777
|
-
|
|
778
|
-
|
|
848
|
+
function startSubAgentGarbageCollector() {
|
|
849
|
+
if (garbageCollectionTimer)
|
|
850
|
+
clearInterval(garbageCollectionTimer);
|
|
851
|
+
garbageCollectionTimer = setInterval(() => void collectGarbageAllChannels(), GARBAGE_COLLECTION_INTERVAL_MS);
|
|
852
|
+
garbageCollectionTimer.unref?.();
|
|
779
853
|
}
|
|
780
|
-
/**
|
|
781
|
-
export function
|
|
782
|
-
if (
|
|
783
|
-
clearInterval(
|
|
784
|
-
|
|
854
|
+
/** Stop the host-wide daily garbage collector during shutdown or test teardown. */
|
|
855
|
+
export function stopSubAgentGarbageCollector() {
|
|
856
|
+
if (garbageCollectionTimer) {
|
|
857
|
+
clearInterval(garbageCollectionTimer);
|
|
858
|
+
garbageCollectionTimer = undefined;
|
|
785
859
|
}
|
|
786
860
|
}
|
|
787
861
|
/** Give runs their persistence root, wake delivery, ledger, and archive. Called once from bootstrap. */
|
|
788
862
|
export function configureSubAgentRuntime(config) {
|
|
789
863
|
runtimeConfig = config;
|
|
790
|
-
|
|
864
|
+
stopSubAgentGarbageCollector();
|
|
865
|
+
startSubAgentGarbageCollector();
|
|
791
866
|
}
|
|
792
867
|
export function getSubAgentRunManager(channelId) {
|
|
793
868
|
let manager = managers.get(channelId);
|
|
@@ -825,6 +900,8 @@ export async function restoreAllSubAgentRuns() {
|
|
|
825
900
|
for (const channelId of channelIds) {
|
|
826
901
|
restored += await getSubAgentRunManager(channelId).restore();
|
|
827
902
|
}
|
|
903
|
+
// Reclaim stale runs once as a host-wide startup batch; subsequent batches run daily.
|
|
904
|
+
await collectGarbageAllChannels();
|
|
828
905
|
if (restored > 0) {
|
|
829
906
|
log.logInfo(`Restored ${restored} sub-agent run record(s)`);
|
|
830
907
|
}
|
package/dist/subagents/tool.d.ts
CHANGED
|
@@ -5,9 +5,9 @@ import type { Executor } from "../executor.js";
|
|
|
5
5
|
import type { MemoryCandidateStore } from "../memory/candidates.js";
|
|
6
6
|
import type { SecurityConfig } from "../security/types.js";
|
|
7
7
|
import type { PipiclawMemoryRecallSettings } from "../settings.js";
|
|
8
|
-
import type
|
|
8
|
+
import { type UsageTotals } from "../shared/types.js";
|
|
9
9
|
import type { PipiclawWebToolsConfig } from "../tools/config.js";
|
|
10
|
-
import { type ResolvedSubAgentConfig, type SubAgentDiscoveryResult } from "./discovery.js";
|
|
10
|
+
import { type ResolvedSubAgentConfig, type SubAgentConfig, type SubAgentDiscoveryResult } from "./discovery.js";
|
|
11
11
|
import { getSubAgentRunManager } from "./runs.js";
|
|
12
12
|
declare const subagentSchema: Type.TObject<{
|
|
13
13
|
label: Type.TString;
|
|
@@ -26,8 +26,11 @@ declare const subagentSchema: Type.TObject<{
|
|
|
26
26
|
returns: Type.TOptional<Type.TUnion<[Type.TLiteral<"text">, Type.TLiteral<"artifact">]>>;
|
|
27
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
|
-
|
|
30
|
-
|
|
29
|
+
/**
|
|
30
|
+
* Fields the `subagent` tool itself constructs. `kind` is not among them: `withToolDetails`
|
|
31
|
+
* stamps it from the registration name when the tool set is built (see `tools/tool-details.ts`).
|
|
32
|
+
*/
|
|
33
|
+
export interface SubAgentToolFields {
|
|
31
34
|
agent: string;
|
|
32
35
|
source: "predefined" | "inline";
|
|
33
36
|
model: string;
|
|
@@ -55,6 +58,10 @@ export interface SubAgentToolDetails {
|
|
|
55
58
|
*/
|
|
56
59
|
dispatched?: boolean;
|
|
57
60
|
}
|
|
61
|
+
/** The shape consumers read post-wrap, once `withToolDetails` has stamped `kind`. */
|
|
62
|
+
export type SubAgentToolDetails = SubAgentToolFields & {
|
|
63
|
+
kind: "subagent";
|
|
64
|
+
};
|
|
58
65
|
export interface SubAgentToolOptions {
|
|
59
66
|
executor: Executor;
|
|
60
67
|
/** Host checkout used as the sub-agent's cwd. Defaults to process.cwd(). */
|
|
@@ -107,7 +114,9 @@ interface SubAgentWorker {
|
|
|
107
114
|
* only caps what gets echoed into the parent's context.
|
|
108
115
|
*/
|
|
109
116
|
export declare const MAX_SUBAGENT_RESULT_UNITS = 1200;
|
|
110
|
-
|
|
117
|
+
/** Exported for `subagent_manage op=follow_up` (spec 042 D7), which constructs one of these for
|
|
118
|
+
* its own new run rather than a hand-rolled envelope. */
|
|
119
|
+
export interface SubAgentRunContext {
|
|
111
120
|
runId: string;
|
|
112
121
|
purpose: "work" | "verify";
|
|
113
122
|
taskId?: string;
|
|
@@ -122,5 +131,28 @@ interface SubAgentRunContext {
|
|
|
122
131
|
declare function buildSubagentTools(executor: Executor, bashTimeoutSec: number, options: SubAgentToolOptions, runContext: SubAgentRunContext): AgentTool<any>[];
|
|
123
132
|
/** Shared by both runtimes' task envelopes and `subagent_manage`'s verify follow-up (spec 040, D9). */
|
|
124
133
|
export declare function buildVerificationProtocol(taskPath: string): string;
|
|
125
|
-
|
|
134
|
+
/**
|
|
135
|
+
* D9 verify admission — a role that admits it writes cannot also be the checker, `exec` has no
|
|
136
|
+
* protocol terminal to prove it even ran to completion, and a target with an active write lease
|
|
137
|
+
* is refused up front (cheaper than explaining afterward why the attestation would be worthless).
|
|
138
|
+
* Spec 042 D7: exported so `subagent_manage op=follow_up` runs the exact same checks the initial
|
|
139
|
+
* dispatch does — before this function existed, follow_up on a role that had since been hot-edited
|
|
140
|
+
* to `mutates: write` would silently take the write lease and dispatch instead of refusing.
|
|
141
|
+
*/
|
|
142
|
+
export declare function assertVerifyAdmissible(config: Pick<ResolvedSubAgentConfig, "name" | "mutates" | "runtime" | "harness">, purpose: "work" | "verify", workingDirectory: string): void;
|
|
143
|
+
/**
|
|
144
|
+
* Exported for `subagent_manage op=follow_up` (spec 042 D7), which builds a follow-up run's task
|
|
145
|
+
* envelope the same way the initial dispatch does rather than a hand-rolled approximation.
|
|
146
|
+
* `config` is deliberately narrowed to `{ name }` — the only field this function reads — so a
|
|
147
|
+
* caller with a raw (unresolved) `SubAgentConfig` from discovery does not need to fabricate a
|
|
148
|
+
* `model`/`modelRef`/`thinkingLevel` just to satisfy a wider type it never touches.
|
|
149
|
+
*/
|
|
150
|
+
export declare function buildSubAgentTask(task: string, config: Pick<SubAgentConfig, "name">, runtimeContext: SubAgentToolOptions["runtimeContext"], contextBlocks: string[], runContext: SubAgentRunContext, returns: "text" | "artifact"): string;
|
|
151
|
+
/** Exported for `subagent_manage op=follow_up` (spec 042 D7) — same reason as `buildSubAgentTask`. */
|
|
152
|
+
/** The slice of `SubAgentToolOptions` `buildContextualBlocks` actually reads — narrowed (spec 042
|
|
153
|
+
* D7) so `subagent_manage op=follow_up` only needs to wire these six fields, not the full tool
|
|
154
|
+
* option surface (executor, discovery, web config, etc. that a context-block build never touches). */
|
|
155
|
+
export type ContextualBlocksOptions = Pick<SubAgentToolOptions, "channelDir" | "getMemoryRecallSettings" | "runtimeContext" | "workspaceDir" | "resolveApiKey" | "memoryCandidateStore">;
|
|
156
|
+
export declare function buildContextualBlocks(task: string, config: Pick<SubAgentConfig, "contextMode" | "paths" | "memory" | "description">, options: ContextualBlocksOptions, currentModel: Model<Api>): Promise<string[]>;
|
|
157
|
+
export declare function createSubAgentTool(options: SubAgentToolOptions): AgentTool<typeof subagentSchema, SubAgentToolFields>;
|
|
126
158
|
export {};
|