pi-better-server 0.7.1 → 0.7.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/package.json +1 -1
- package/src/runtime/background-tools.ts +2 -1
- package/src/runtime/domain/background/registry.mjs +3 -0
- package/src/runtime/domain/background/shared-operation-coordinator/src/task-lifetime.mjs +6 -0
- package/src/runtime/domain/background/terminal-publication.mjs +5 -2
- package/src/runtime/domain/background-service/managed-authority.domain.mjs +13 -0
- package/src/runtime/domain/background-service/managed-authority.ts +16 -0
- package/src/runtime/domain/background-service/managed-client.domain.mjs +2 -2
- package/src/runtime/domain/background-service/managed-client.ts +2 -2
- package/src/runtime/domain/background-service/observed-waits.domain.mjs +8 -4
- package/src/runtime/domain/background-service/observed-waits.ts +8 -4
- package/src/runtime/domain/background-service/registry.domain.mjs +3 -0
- package/src/runtime/domain/background-service/registry.ts +2 -0
- package/src/runtime/domain/background-service/runtime.domain.mjs +3 -2
- package/src/runtime/domain/background-service/runtime.ts +3 -2
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/expiry.domain.mjs +44 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/expiry.ts +44 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +8 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +8 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +3 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +5 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/task-lifetime.domain.mjs +7 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/task-lifetime.ts +7 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/waits.domain.mjs +22 -13
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/waits.ts +40 -32
- package/src/runtime/domain/background-service/shared-sandbox-diagnostics.domain.mjs +12 -19
- package/src/runtime/domain/background-service/shared-sandbox-diagnostics.ts +12 -16
- package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
- package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +12 -7
- package/src/runtime/domain/background-service/supervisor/generated/task-lifetime.mjs +9 -0
- package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +12 -7
- package/src/runtime/domain/background-service/supervisor/runner.ts +12 -7
- package/src/runtime/domain/background-service/supervisor/types.ts +1 -1
- package/src/runtime/domain/background-service/tools.domain.mjs +3 -2
- package/src/runtime/domain/background-service/tools.ts +3 -2
- package/src/runtime/domain/coordinator/src/expiry.mjs +43 -0
- package/src/runtime/domain/coordinator/src/schema.mjs +8 -1
- package/src/runtime/domain/coordinator/src/store.mjs +3 -0
- package/src/runtime/domain/coordinator/src/task-lifetime.mjs +6 -0
- package/src/runtime/domain/coordinator/src/waits.mjs +22 -13
- package/src/runtime/domain/sandbox-policy/shared-sandbox-diagnostics.domain.mjs +12 -19
- package/src/runtime/domain/sandbox-policy/shared-sandbox-diagnostics.ts +12 -16
- package/src/runtime/domain/subagents/README.md +2 -2
- package/src/runtime/domain/subagents/cleanup.domain.mjs +5 -2
- package/src/runtime/domain/subagents/cleanup.ts +4 -1
- package/src/runtime/domain/subagents/index.domain.mjs +41 -27
- package/src/runtime/domain/subagents/index.ts +39 -25
- package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +28 -2
- package/src/runtime/domain/subagents/managed-launch-host.ts +26 -2
- package/src/runtime/domain/subagents/managed-launch-port.ts +2 -0
- package/src/runtime/domain/subagents/package.json +1 -1
- package/src/runtime/domain/subagents/registry-cleanup-worker.mjs +24 -0
- package/src/runtime/domain/subagents/registry.domain.mjs +33 -7
- package/src/runtime/domain/subagents/registry.ts +18 -4
- package/src/runtime/domain/subagents/settings-page.domain.mjs +10 -10
- package/src/runtime/domain/subagents/settings-page.ts +10 -10
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/expiry.domain.mjs +44 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/expiry.ts +44 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +8 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +8 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +3 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +5 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/task-lifetime.domain.mjs +7 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/task-lifetime.ts +7 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/waits.domain.mjs +22 -13
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/waits.ts +40 -32
- package/src/runtime/domain/subagents/shared-sandbox-diagnostics.domain.mjs +12 -19
- package/src/runtime/domain/subagents/shared-sandbox-diagnostics.ts +12 -16
- package/src/runtime/domain/subagents/stop.domain.mjs +7 -5
- package/src/runtime/domain/subagents/stop.ts +7 -5
- package/src/runtime/domain/subagents/timing.domain.mjs +7 -3
- package/src/runtime/domain/subagents/timing.ts +11 -4
- package/src/runtime/domain/subagents/workspace-files.domain.mjs +6 -6
- package/src/runtime/domain/subagents/workspace-files.ts +6 -6
- package/src/runtime/task-expiry.ts +52 -0
- package/src/server.ts +4 -0
- package/src/version.ts +1 -1
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
* the cancellation epoch it observed. Cancellation invalidates the active resume
|
|
15
15
|
* claim, and a claim whose epoch no longer matches can never publish an attempt.
|
|
16
16
|
*/
|
|
17
|
+
import { taskDeadline } from "./task-lifetime.mjs";
|
|
17
18
|
import { randomUUID } from "node:crypto";
|
|
18
19
|
import { StoreError } from "./errors.mjs";
|
|
19
20
|
import { acknowledgeGenerationOutbox, enqueueReadyGeneration, releaseGenerationPins, voidGenerationOutbox, } from "./outbox.mjs";
|
|
@@ -369,21 +370,25 @@ export function cancelWait(ctx, input) {
|
|
|
369
370
|
throw new StoreError("wait-phase", `Wait ${waitId} generation ${generation} is already ${wait.phase}; cancellation is recorded once and cannot be repeated or replaced.`);
|
|
370
371
|
}
|
|
371
372
|
assertExpectedEpoch(wait, expectedCancelEpoch);
|
|
372
|
-
|
|
373
|
-
run(ctx, "UPDATE waits SET phase = 'cancelled', phase_reason = ?, cancel_epoch = cancel_epoch + 1, updated_at = ? WHERE wait_id = ? AND generation = ?", reason, at, waitId, generation);
|
|
374
|
-
const activeClaimRows = getRows(ctx, "SELECT claim_id FROM resume_claims WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')", waitId, generation);
|
|
375
|
-
const invalidatedClaimIds = activeClaimRows.map((row) => columnText(row, "claim_id"));
|
|
376
|
-
run(ctx, `UPDATE resume_claims SET state = 'invalidated', invalidated_at = ?, reason = ?
|
|
377
|
-
WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')`, at, reason, waitId, generation);
|
|
378
|
-
const voidedOutboxIds = voidGenerationOutbox(ctx, waitId, generation, reason, at);
|
|
379
|
-
releaseGenerationPins(ctx, waitId, generation, "wait-cancelled", at);
|
|
380
|
-
return {
|
|
381
|
-
wait: requireWait(ctx, waitId, generation),
|
|
382
|
-
invalidatedClaimIds,
|
|
383
|
-
voidedOutboxIds,
|
|
384
|
-
};
|
|
373
|
+
return cancelGeneration(ctx, waitId, generation, reason);
|
|
385
374
|
});
|
|
386
375
|
}
|
|
376
|
+
/** Caller holds the write transaction and has selected a nonterminal generation. */
|
|
377
|
+
export function cancelGeneration(ctx, waitId, generation, reason) {
|
|
378
|
+
const at = ctx.now();
|
|
379
|
+
run(ctx, "UPDATE waits SET phase = 'cancelled', phase_reason = ?, cancel_epoch = cancel_epoch + 1, updated_at = ? WHERE wait_id = ? AND generation = ?", reason, at, waitId, generation);
|
|
380
|
+
const activeClaimRows = getRows(ctx, "SELECT claim_id FROM resume_claims WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')", waitId, generation);
|
|
381
|
+
const invalidatedClaimIds = activeClaimRows.map((row) => columnText(row, "claim_id"));
|
|
382
|
+
run(ctx, `UPDATE resume_claims SET state = 'invalidated', invalidated_at = ?, reason = ?
|
|
383
|
+
WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')`, at, reason, waitId, generation);
|
|
384
|
+
const voidedOutboxIds = voidGenerationOutbox(ctx, waitId, generation, reason, at);
|
|
385
|
+
releaseGenerationPins(ctx, waitId, generation, "wait-cancelled", at);
|
|
386
|
+
return {
|
|
387
|
+
wait: requireWait(ctx, waitId, generation),
|
|
388
|
+
invalidatedClaimIds,
|
|
389
|
+
voidedOutboxIds,
|
|
390
|
+
};
|
|
391
|
+
}
|
|
387
392
|
// ---- resume claims ------------------------------------------------------
|
|
388
393
|
export function claimResume(ctx, input) {
|
|
389
394
|
const waitId = requireId("waitId", input.waitId);
|
|
@@ -394,6 +399,8 @@ export function claimResume(ctx, input) {
|
|
|
394
399
|
return ctx.transaction(() => {
|
|
395
400
|
assertCurrentGeneration(ctx, waitId, generation);
|
|
396
401
|
const wait = requireWait(ctx, waitId, generation);
|
|
402
|
+
if (ctx.now() >= taskDeadline(wait.createdAt))
|
|
403
|
+
throw new StoreError("wait-phase", "The 24-hour wait lifetime has expired.");
|
|
397
404
|
const active = getRows(ctx, "SELECT claim_id FROM resume_claims WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')", waitId, generation)[0];
|
|
398
405
|
if (active) {
|
|
399
406
|
throw new StoreError("concurrent-claim", `Wait ${waitId} generation ${generation} already has an active resume claim (${columnText(active, "claim_id")}). One conversation admits one writer; release or invalidate that claim instead of claiming again.`);
|
|
@@ -438,6 +445,8 @@ export function publishResumeAttempt(ctx, input) {
|
|
|
438
445
|
return ctx.transaction(() => {
|
|
439
446
|
assertCurrentGeneration(ctx, waitId, generation);
|
|
440
447
|
const wait = requireWait(ctx, waitId, generation);
|
|
448
|
+
if (ctx.now() >= taskDeadline(wait.createdAt))
|
|
449
|
+
throw new StoreError("wait-phase", "The 24-hour wait lifetime has expired.");
|
|
441
450
|
const claim = requireClaim(ctx, claimId);
|
|
442
451
|
if (claim.waitId !== waitId || claim.generation !== generation) {
|
|
443
452
|
throw new StoreError("claim-state", `Resume claim ${claimId} belongs to ${claim.waitId} generation ${claim.generation}, not ${waitId} generation ${generation}.`);
|
|
@@ -273,7 +273,7 @@ function sameOperation(a, b) {
|
|
|
273
273
|
function load(dir, key) {
|
|
274
274
|
const path = join(dir, "events.jsonl");
|
|
275
275
|
if (!stat(path))
|
|
276
|
-
return { records: [], losses: emptyLosses() };
|
|
276
|
+
return { records: [], losses: emptyLosses(), needsRepair: false };
|
|
277
277
|
chmodSync(path, 0o600);
|
|
278
278
|
const raw = readSafe(path, MAX_BYTES);
|
|
279
279
|
const lines = raw.split("\n");
|
|
@@ -304,7 +304,8 @@ function load(dir, key) {
|
|
|
304
304
|
catch {
|
|
305
305
|
losses.malformed++;
|
|
306
306
|
}
|
|
307
|
-
|
|
307
|
+
const headerMatches = header && header.count === lines.length && header.digest === digest(key, "journal", lines.join("\n"));
|
|
308
|
+
if (header && !headerMatches)
|
|
308
309
|
losses.tampered++;
|
|
309
310
|
const records = [];
|
|
310
311
|
const seen = new Set();
|
|
@@ -340,7 +341,7 @@ function load(dir, key) {
|
|
|
340
341
|
seen.add(record.fingerprint);
|
|
341
342
|
records.push(record);
|
|
342
343
|
}
|
|
343
|
-
return { records, losses };
|
|
344
|
+
return { records, losses, needsRepair: !headerMatches || records.length !== lines.length };
|
|
344
345
|
}
|
|
345
346
|
function encode(journal, key) {
|
|
346
347
|
const lines = journal.records.map(record => JSON.stringify({ ...record, mac: digest(key, "event", JSON.stringify(record)) }));
|
|
@@ -460,31 +461,22 @@ export class SandboxDiagnostics {
|
|
|
460
461
|
return;
|
|
461
462
|
if (input.outcome === "succeeded" && !stat(join(dir, "events.jsonl")))
|
|
462
463
|
return;
|
|
463
|
-
locked(dir, () => {
|
|
464
|
+
const repaired = locked(dir, () => {
|
|
464
465
|
const key = installationKey(dir, input.outcome === "denied");
|
|
465
466
|
const journal = load(dir, key);
|
|
466
|
-
const before = JSON.stringify(journal.losses);
|
|
467
467
|
const pruned = retain(journal, key, now);
|
|
468
468
|
const fingerprint = imported ? digest(key, "relay-event-identity", identity([imported.runIdentity, imported.value.idFingerprint])) :
|
|
469
469
|
digest(key, "event-identity", randomBytes(32).toString("hex"));
|
|
470
470
|
// Signed record identities survive parent reloads and full log rescans.
|
|
471
|
-
|
|
472
|
-
if (pruned || journal.losses.malformed || journal.losses.tampered)
|
|
473
|
-
atomic(join(dir, "events.jsonl"), encode(journal, key));
|
|
474
|
-
if (issues(journal.losses).length)
|
|
475
|
-
this.report(new Error("Diagnostics collection has gaps."));
|
|
476
|
-
return;
|
|
477
|
-
}
|
|
471
|
+
const duplicate = imported && journal.records.some(r => r.fingerprint === fingerprint);
|
|
478
472
|
const operationFingerprint = digest(key, "operation", operation);
|
|
479
473
|
const recovered = new Set(journal.records.flatMap(r => r.recoveryOf ? [r.recoveryOf] : []));
|
|
480
474
|
const prior = [...journal.records].reverse().find(r => r.outcome === "denied" && r.context === this.options.context &&
|
|
481
475
|
r.tool === tool && r.operationFingerprint === operationFingerprint && r.timestamp <= now);
|
|
482
|
-
if (input.outcome === "succeeded" && (!prior || recovered.has(prior.fingerprint))) {
|
|
483
|
-
if (pruned ||
|
|
476
|
+
if (duplicate || (input.outcome === "succeeded" && (!prior || recovered.has(prior.fingerprint)))) {
|
|
477
|
+
if (pruned || journal.needsRepair)
|
|
484
478
|
atomic(join(dir, "events.jsonl"), encode(journal, key));
|
|
485
|
-
|
|
486
|
-
this.report(new Error("Diagnostics collection has gaps."));
|
|
487
|
-
return;
|
|
479
|
+
return journal.needsRepair;
|
|
488
480
|
}
|
|
489
481
|
const backend = imported?.value.backend ?? this.options.backend();
|
|
490
482
|
const version = imported?.value.version ?? this.options.version;
|
|
@@ -505,9 +497,10 @@ export class SandboxDiagnostics {
|
|
|
505
497
|
journal.records.push(record);
|
|
506
498
|
retain(journal, key, now);
|
|
507
499
|
atomic(join(dir, "events.jsonl"), encode(journal, key));
|
|
508
|
-
|
|
509
|
-
this.report(new Error("Diagnostics collection has gaps."));
|
|
500
|
+
return journal.needsRepair;
|
|
510
501
|
});
|
|
502
|
+
if (repaired)
|
|
503
|
+
this.report(new Error("Diagnostics collection has gaps."));
|
|
511
504
|
}
|
|
512
505
|
catch (error) {
|
|
513
506
|
this.report(this.options.relay || imported ? new Error("Diagnostics collection has gaps.") : error);
|
|
@@ -249,9 +249,9 @@ function sameOperation(a: DiagnosticRecord, b: DiagnosticRecord): boolean {
|
|
|
249
249
|
return a.context === b.context && a.tool === b.tool && a.operationFingerprint === b.operationFingerprint;
|
|
250
250
|
}
|
|
251
251
|
interface Journal { records: DiagnosticRecord[]; losses: DiagnosticLosses }
|
|
252
|
-
function load(dir: string, key: Buffer): Journal {
|
|
252
|
+
function load(dir: string, key: Buffer): Journal & { needsRepair: boolean } {
|
|
253
253
|
const path = join(dir, "events.jsonl");
|
|
254
|
-
if (!stat(path)) return { records: [], losses: emptyLosses() };
|
|
254
|
+
if (!stat(path)) return { records: [], losses: emptyLosses(), needsRepair: false };
|
|
255
255
|
chmodSync(path, 0o600);
|
|
256
256
|
const raw = readSafe(path, MAX_BYTES);
|
|
257
257
|
const lines = raw.split("\n");
|
|
@@ -273,7 +273,8 @@ function load(dir: string, key: Buffer): Journal {
|
|
|
273
273
|
} else losses.tampered++;
|
|
274
274
|
} else losses.malformed++;
|
|
275
275
|
} catch { losses.malformed++; }
|
|
276
|
-
|
|
276
|
+
const headerMatches = header && header.count === lines.length && header.digest === digest(key, "journal", lines.join("\n"));
|
|
277
|
+
if (header && !headerMatches) losses.tampered++;
|
|
277
278
|
const records: DiagnosticRecord[] = [];
|
|
278
279
|
const seen = new Set<string>();
|
|
279
280
|
const denied = new Map<string, DiagnosticRecord>();
|
|
@@ -293,7 +294,7 @@ function load(dir: string, key: Buffer): Journal {
|
|
|
293
294
|
seen.add(record.fingerprint);
|
|
294
295
|
records.push(record);
|
|
295
296
|
}
|
|
296
|
-
return { records, losses };
|
|
297
|
+
return { records, losses, needsRepair: !headerMatches || records.length !== lines.length };
|
|
297
298
|
}
|
|
298
299
|
function encode(journal: Journal, key: Buffer): string {
|
|
299
300
|
const lines = journal.records.map(record => JSON.stringify({ ...record, mac: digest(key, "event", JSON.stringify(record)) }));
|
|
@@ -385,27 +386,21 @@ export class SandboxDiagnostics {
|
|
|
385
386
|
const dir = directory(this.options, input.outcome === "denied");
|
|
386
387
|
if (!dir) return;
|
|
387
388
|
if (input.outcome === "succeeded" && !stat(join(dir, "events.jsonl"))) return;
|
|
388
|
-
locked(dir, () => {
|
|
389
|
+
const repaired = locked(dir, () => {
|
|
389
390
|
const key = installationKey(dir, input.outcome === "denied");
|
|
390
391
|
const journal = load(dir, key);
|
|
391
|
-
const before = JSON.stringify(journal.losses);
|
|
392
392
|
const pruned = retain(journal, key, now);
|
|
393
393
|
const fingerprint = imported ? digest(key, "relay-event-identity", identity([imported.runIdentity, imported.value.idFingerprint])) :
|
|
394
394
|
digest(key, "event-identity", randomBytes(32).toString("hex"));
|
|
395
395
|
// Signed record identities survive parent reloads and full log rescans.
|
|
396
|
-
|
|
397
|
-
if (pruned || journal.losses.malformed || journal.losses.tampered) atomic(join(dir, "events.jsonl"), encode(journal, key));
|
|
398
|
-
if (issues(journal.losses).length) this.report(new Error("Diagnostics collection has gaps."));
|
|
399
|
-
return;
|
|
400
|
-
}
|
|
396
|
+
const duplicate = imported && journal.records.some(r => r.fingerprint === fingerprint);
|
|
401
397
|
const operationFingerprint = digest(key, "operation", operation);
|
|
402
398
|
const recovered = new Set(journal.records.flatMap(r => r.recoveryOf ? [r.recoveryOf] : []));
|
|
403
399
|
const prior = [...journal.records].reverse().find(r => r.outcome === "denied" && r.context === this.options.context &&
|
|
404
400
|
r.tool === tool && r.operationFingerprint === operationFingerprint && r.timestamp <= now);
|
|
405
|
-
if (input.outcome === "succeeded" && (!prior || recovered.has(prior.fingerprint))) {
|
|
406
|
-
if (pruned ||
|
|
407
|
-
|
|
408
|
-
return;
|
|
401
|
+
if (duplicate || (input.outcome === "succeeded" && (!prior || recovered.has(prior.fingerprint)))) {
|
|
402
|
+
if (pruned || journal.needsRepair) atomic(join(dir, "events.jsonl"), encode(journal, key));
|
|
403
|
+
return journal.needsRepair;
|
|
409
404
|
}
|
|
410
405
|
const backend = imported?.value.backend ?? this.options.backend();
|
|
411
406
|
const version = imported?.value.version ?? this.options.version;
|
|
@@ -425,8 +420,9 @@ export class SandboxDiagnostics {
|
|
|
425
420
|
journal.records.push(record);
|
|
426
421
|
retain(journal, key, now);
|
|
427
422
|
atomic(join(dir, "events.jsonl"), encode(journal, key));
|
|
428
|
-
|
|
423
|
+
return journal.needsRepair;
|
|
429
424
|
});
|
|
425
|
+
if (repaired) this.report(new Error("Diagnostics collection has gaps."));
|
|
430
426
|
} catch (error) { this.report(this.options.relay || imported ? new Error("Diagnostics collection has gaps.") : error); }
|
|
431
427
|
}
|
|
432
428
|
}
|
|
@@ -32,7 +32,7 @@ The API is `runtime-client/src/runtime/client.mjs`, exporting `ensureRuntime`.
|
|
|
32
32
|
- Durable logs, result retrieval, and [failure observations](docs/failure-observations.md) independent of lifecycle status. A live child handles its own tool errors; the parent is woken only for actionable incidents, and children can classify handled failures with `failure_disposition`.
|
|
33
33
|
- Live background-work navigator for active runs.
|
|
34
34
|
- Git writers start in separate Clones by default. **Git workspace** in `/subagents settings` also offers Worktree. Results carry the working directory or a recoverable copy, including incomplete work. [Workspace recovery](docs/usage.md#git-workspaces)
|
|
35
|
-
- Harness-owned run timing: every run gets independent factual alerts for a tool call left open (5 min) and for no progress (10 min), plus a 60-minute hard timeout. Choose a duration or **
|
|
35
|
+
- Harness-owned run timing: every run gets independent factual alerts for a tool call left open (5 min) and for no progress (10 min), plus a 60-minute hard timeout. Choose a duration or **24 hours** under **Run timeout** in `/subagents settings`. Soft deadlines remain opt-in. Configure per spawn with `deadline_minutes`, `grace_minutes`, `max_minutes`, `tool_wait_minutes`, `stuck_minutes`, globally in `config.json` / `PI_SUBAGENT_*_MINUTES`, or in `/subagents settings`. See [usage notes](docs/usage.md#run-timing-deadline-ceiling-tool-wait-stuck).
|
|
36
36
|
|
|
37
37
|
Every single or batch launch automatically joins one shared supervision watcher in the
|
|
38
38
|
foreground Pi process. The last active run's exit or stop tears it down; a later
|
|
@@ -97,7 +97,7 @@ Linux confinement requires a usable `bubblewrap` backend and Pi SDK 0.82.1 or ne
|
|
|
97
97
|
The user config sets `delegationMode` to `manual`, `adaptive` (default), or
|
|
98
98
|
`coordinator`. `/subagents settings` (or `/subagents`) opens a settings page
|
|
99
99
|
for delegation mode, the concurrent-subagent cap (default 6), and Git workspace
|
|
100
|
-
(Clone or Worktree). Run timeout supports a duration or **
|
|
100
|
+
(Clone or Worktree). Run timeout supports a duration or **24 hours**. The
|
|
101
101
|
tool-wait alert (default 5 minutes) and no-progress alert (default 10 minutes)
|
|
102
102
|
have separate intervals. Enter `0` to turn an alert off. Skill exposure cycles between Discover automatically and No skill
|
|
103
103
|
catalog. The Selected skills row opens the same searchable checkbox picker used
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Generated fixed launch domain from packages/pi-better-subagents/cleanup.ts. Do not edit directly.
|
|
2
2
|
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync, } from "node:fs";
|
|
3
3
|
import { join, relative, sep } from "node:path";
|
|
4
|
-
import { ABANDONED_LAUNCH_GRACE_MS, abandonedLaunchRecord, baseDir, listMetas, observeArchivePublication, ownedByThisParent, orphanedTaskRuntimeProvenance, processStartToken, purgeAbandonedLaunch, readMeta, removeMetaArtifacts, removeRunDirectory, removeTaskRuntimeProvenance, runDir, listPendingParkedRuns, } from "./registry.domain.mjs";
|
|
4
|
+
import { ABANDONED_LAUNCH_GRACE_MS, abandonedLaunchRecord, baseDir, launchAttemptInProgress, listMetas, observeArchivePublication, ownedByThisParent, orphanedTaskRuntimeProvenance, processStartToken, purgeAbandonedLaunch, readMeta, removeMetaArtifacts, removeRunDirectory, removeTaskRuntimeProvenance, runDir, listPendingParkedRuns, } from "./registry.domain.mjs";
|
|
5
5
|
import { ConversationBusyError, ConversationLockUnavailableError, conversationLeaseDir, readConversationLease, readRetention, retainedRunIds, retainedSessionIds, withConversationMutation, } from "./continuation.domain.mjs";
|
|
6
6
|
import { processExists } from "./spawn.domain.mjs";
|
|
7
7
|
import { archiveCompletedAttempt, archivePublicationPending, listArchivedAttempts } from "./session-store.domain.mjs";
|
|
@@ -108,6 +108,9 @@ function safeStatMtime(path) {
|
|
|
108
108
|
/** A metadata-less run directory, with its provenance record (#325). */
|
|
109
109
|
function removeRun(id, errors) {
|
|
110
110
|
try {
|
|
111
|
+
// A concurrent launch publishes its claim before metadata and drops it after publication.
|
|
112
|
+
if (launchAttemptInProgress(id) || readMeta(id))
|
|
113
|
+
return false;
|
|
111
114
|
removeRunDirectory(id);
|
|
112
115
|
return true;
|
|
113
116
|
}
|
|
@@ -777,7 +780,7 @@ export function enforceRegistrySizeCapOnce(options = {}) {
|
|
|
777
780
|
// the shortfall it reports stay honest.
|
|
778
781
|
const keptBytes = plan.keptBytes + retainedBytes;
|
|
779
782
|
try {
|
|
780
|
-
writeCleanupState({ ...state, lastSizeSweepAt: now });
|
|
783
|
+
writeCleanupState({ ...state, lastSizeSweepAt: options.now ?? Date.now() });
|
|
781
784
|
}
|
|
782
785
|
catch (err) {
|
|
783
786
|
errors.push(`${cleanupStatePath()}: ${err instanceof Error ? err.message : String(err)}`);
|
|
@@ -11,6 +11,7 @@ import { join, relative, sep } from "node:path";
|
|
|
11
11
|
import { ABANDONED_LAUNCH_GRACE_MS,
|
|
12
12
|
abandonedLaunchRecord,
|
|
13
13
|
baseDir,
|
|
14
|
+
launchAttemptInProgress,
|
|
14
15
|
listMetas,
|
|
15
16
|
observeArchivePublication,
|
|
16
17
|
ownedByThisParent,
|
|
@@ -236,6 +237,8 @@ function safeStatMtime(path: string): number | undefined {
|
|
|
236
237
|
/** A metadata-less run directory, with its provenance record (#325). */
|
|
237
238
|
function removeRun(id: string, errors: string[]): boolean {
|
|
238
239
|
try {
|
|
240
|
+
// A concurrent launch publishes its claim before metadata and drops it after publication.
|
|
241
|
+
if (launchAttemptInProgress(id) || readMeta(id)) return false;
|
|
239
242
|
removeRunDirectory(id);
|
|
240
243
|
return true;
|
|
241
244
|
} catch (err) {
|
|
@@ -977,7 +980,7 @@ export function enforceRegistrySizeCapOnce(options: SizeCapOptions = {}): SizeCa
|
|
|
977
980
|
const keptBytes = plan.keptBytes + retainedBytes;
|
|
978
981
|
|
|
979
982
|
try {
|
|
980
|
-
writeCleanupState({ ...state, lastSizeSweepAt: now });
|
|
983
|
+
writeCleanupState({ ...state, lastSizeSweepAt: options.now ?? Date.now() });
|
|
981
984
|
} catch (err) {
|
|
982
985
|
errors.push(`${cleanupStatePath()}: ${err instanceof Error ? err.message : String(err)}`);
|
|
983
986
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
// Generated fixed launch domain from packages/pi-better-subagents/index.ts. Do not edit directly.
|
|
2
|
+
import { taskDeadline } from "./shared-operation-coordinator/src/task-lifetime.domain.mjs";
|
|
2
3
|
import { shouldRestoreWorkObservation } from "./shared-work-client.mjs";
|
|
3
4
|
import { appendTimingWake, removeTimingReceipt, receiptTimingWake, timingWakeReceipt } from "./timing-notifications.domain.mjs";
|
|
4
5
|
import { captureLaunchContext } from "./launch-context.domain.mjs";
|
|
@@ -44,7 +45,7 @@ import { ORDINARY_TOOL_PROVIDERS, activeChildProviders, ordinaryChildConfig, add
|
|
|
44
45
|
import { createSubagentSettingsPage } from "./settings-page.domain.mjs";
|
|
45
46
|
import { deliverSubagentPrompt, effectiveSubagentSettings, subagentSettingsTool } from "./effective-settings.domain.mjs";
|
|
46
47
|
import { STEER_FILE_ENV, readSteerReceipt } from "./child-steer.domain.mjs";
|
|
47
|
-
import { continuationTimingParams, decideTiming, describeTiming, DEFAULT_TIMING_MINUTES, emptyProgress, foldProgress, formatTimingLimits, isTimingMinutes, isProgressRelevantLine, resolveRunTiming, steerText, stuckAlertText, TIMING_ENV, timingParameterSchemas, toolWaitAlertText, validatedTimingMinutes, } from "./timing.domain.mjs";
|
|
48
|
+
import { continuationTimingParams, configuredMaxMinutes, decideTiming, describeTiming, DEFAULT_TIMING_MINUTES, emptyProgress, foldProgress, formatTimingLimits, isTimingMinutes, isProgressRelevantLine, resolveRunTiming, steerText, stuckAlertText, TIMING_ENV, timingParameterSchemas, toolWaitAlertText, validatedTimingMinutes, } from "./timing.domain.mjs";
|
|
48
49
|
import { readAppendedLines } from "./log-cursor.domain.mjs";
|
|
49
50
|
import { DELEGATION_MODES, DELEGATION_MODE_REQUEST, isDelegationMode, normalizeDelegationMode } from "./delegation.domain.mjs";
|
|
50
51
|
import { resolveExtensions, extensionArgs } from "./extensions.domain.mjs";
|
|
@@ -1156,7 +1157,12 @@ function stopForTiming(pi, id, reason, now) {
|
|
|
1156
1157
|
*/
|
|
1157
1158
|
function enforceTiming(pi, meta, now) {
|
|
1158
1159
|
const timing = meta.timing;
|
|
1159
|
-
if (!timing
|
|
1160
|
+
if (!timing)
|
|
1161
|
+
return false;
|
|
1162
|
+
if ((meta.status === "running" || meta.status === "orphaned") && now >= (timing.lifetimeAt ?? taskDeadline(meta.startedAt))) {
|
|
1163
|
+
return stopForTiming(pi, meta.id, "ceiling", now);
|
|
1164
|
+
}
|
|
1165
|
+
if (timing.stopReason)
|
|
1160
1166
|
return false;
|
|
1161
1167
|
// The ceiling also bounds an orphaned run (child gone, its process group still alive).
|
|
1162
1168
|
if (meta.status === "orphaned") {
|
|
@@ -1656,10 +1662,7 @@ function navigatorCloseRun(id) {
|
|
|
1656
1662
|
if (outcome.action === "dismissed" || outcome.action === "stopped-and-dismissed")
|
|
1657
1663
|
pendingNavigatorDismissals.add(id);
|
|
1658
1664
|
// A closed row is off the hot path: release its caches and retained events.
|
|
1659
|
-
|
|
1660
|
-
healthLogCache.delete(id);
|
|
1661
|
-
resetChildEventLogCursor(id);
|
|
1662
|
-
resetParseRunCursor(id);
|
|
1665
|
+
forgetRunCaches(id);
|
|
1663
1666
|
syncHealthTicker();
|
|
1664
1667
|
// Close stops (or log-finalizes) the run, which is a terminal transition:
|
|
1665
1668
|
// queue its one completion callback so no terminal state is silent (#624).
|
|
@@ -2038,6 +2041,12 @@ function resolvePiBinary() {
|
|
|
2038
2041
|
}
|
|
2039
2042
|
return cachedPi;
|
|
2040
2043
|
}
|
|
2044
|
+
function forgetRunCaches(id) {
|
|
2045
|
+
spendCache.delete(id);
|
|
2046
|
+
healthLogCache.delete(id);
|
|
2047
|
+
resetChildEventLogCursor(id);
|
|
2048
|
+
resetParseRunCursor(id);
|
|
2049
|
+
}
|
|
2041
2050
|
function prepareLaunchWorkspace(options, isolated) {
|
|
2042
2051
|
const built = import.meta.url.endsWith(".domain.mjs");
|
|
2043
2052
|
const entry = new URL("./workspace-prepare-worker.mjs", import.meta.url);
|
|
@@ -2488,13 +2497,13 @@ export default function (pi, managed) {
|
|
|
2488
2497
|
const defaults = resolveRunTiming({ settings: cfg, env: process.env, startedAt: 0 });
|
|
2489
2498
|
const minutes = (ms) => ms === undefined ? 0 : ms / 60_000;
|
|
2490
2499
|
return {
|
|
2491
|
-
maxMinutes:
|
|
2500
|
+
maxMinutes: configuredMaxMinutes(sessionTimeout, timingSettingsFor(cfg), process.env),
|
|
2492
2501
|
toolWaitMinutes: minutes(effective.toolWaitMs),
|
|
2493
2502
|
stuckMinutes: minutes(effective.stuckMs),
|
|
2494
2503
|
timeoutSource: timeoutSource(),
|
|
2495
2504
|
toolWaitSource: sourceFor("toolWaitMinutes"),
|
|
2496
2505
|
stuckSource: sourceFor("stuckMinutes"),
|
|
2497
|
-
defaultMaxMinutes:
|
|
2506
|
+
defaultMaxMinutes: configuredMaxMinutes({}, cfg, process.env),
|
|
2498
2507
|
defaultToolWaitMinutes: minutes(defaults.toolWaitMs),
|
|
2499
2508
|
defaultStuckMinutes: minutes(defaults.stuckMs),
|
|
2500
2509
|
};
|
|
@@ -2949,20 +2958,17 @@ export default function (pi, managed) {
|
|
|
2949
2958
|
model = parsed.model;
|
|
2950
2959
|
thinking = parsed.thinking;
|
|
2951
2960
|
}
|
|
2952
|
-
//
|
|
2953
|
-
|
|
2954
|
-
|
|
2955
|
-
|
|
2956
|
-
|
|
2957
|
-
|
|
2958
|
-
|
|
2959
|
-
|
|
2960
|
-
|
|
2961
|
-
|
|
2962
|
-
|
|
2963
|
-
healthLogCache.delete(id);
|
|
2964
|
-
resetChildEventLogCursor(id);
|
|
2965
|
-
resetParseRunCursor(id);
|
|
2961
|
+
// Continuations revalidate and lease their saved history. Only fresh launches request maintenance.
|
|
2962
|
+
if (!resume) {
|
|
2963
|
+
if (managed) {
|
|
2964
|
+
const { cleanupTerminalRunRetentionMs, cleanupSessionRetentionMs, maxRegistryBytes } = cfg;
|
|
2965
|
+
managed.scheduleRegistryCleanup({ cleanupTerminalRunRetentionMs, cleanupSessionRetentionMs, maxRegistryBytes }, forgetRunCaches);
|
|
2966
|
+
}
|
|
2967
|
+
else {
|
|
2968
|
+
runDailyCleanupOnce({ config: cfg });
|
|
2969
|
+
for (const removed of enforceRegistrySizeCapOnce({ config: cfg }).removed)
|
|
2970
|
+
forgetRunCaches(removed);
|
|
2971
|
+
}
|
|
2966
2972
|
}
|
|
2967
2973
|
const callbackOrigin = internal?.parkOwner
|
|
2968
2974
|
? { cwd: internal.parkOwner.workspace, sessionId: internal.parkOwner.sessionId }
|
|
@@ -3505,6 +3511,11 @@ export default function (pi, managed) {
|
|
|
3505
3511
|
trustedExtensions: resume?.recipe.trustedExtensions ?? taskTools?.trusted.map(({ name, package: owner, loadPath }) => ({ name, package: owner, loadPath })),
|
|
3506
3512
|
});
|
|
3507
3513
|
const startedAt = Date.now();
|
|
3514
|
+
const timing = resolveRunTiming({ params: launchTimingParams(p), settings: timingSettingsFor(cfg), env: process.env, startedAt });
|
|
3515
|
+
if (internal?.resumeWait && resume) {
|
|
3516
|
+
timing.lifetimeAt = resume.prior.timing?.lifetimeAt ?? taskDeadline(resume.prior.startedAt);
|
|
3517
|
+
timing.ceilingAt = Math.min(timing.lifetimeAt, resume.prior.timing?.ceilingAt ?? Infinity, timing.ceilingAt);
|
|
3518
|
+
}
|
|
3508
3519
|
const meta = {
|
|
3509
3520
|
assignment,
|
|
3510
3521
|
outcomeSupport: { version: 1, available: Boolean(assignment), ...(!assignment ? { reason: "Legacy host has no verified parent session/transcript; durable assignment delivery is unavailable." } : {}) },
|
|
@@ -3554,9 +3565,12 @@ export default function (pi, managed) {
|
|
|
3554
3565
|
tools: bridgePlan.tools,
|
|
3555
3566
|
},
|
|
3556
3567
|
} : {}),
|
|
3557
|
-
timing
|
|
3568
|
+
timing,
|
|
3558
3569
|
};
|
|
3559
3570
|
const dispatchGuard = await internal?.beforeSpawn?.({ runId: id, permissionPlan });
|
|
3571
|
+
if (internal?.resumeWait && Date.now() >= timing.ceilingAt) {
|
|
3572
|
+
throw new PreSpawnResumeError("The parked task reached its execution time limit before dispatch.");
|
|
3573
|
+
}
|
|
3560
3574
|
if (isolated)
|
|
3561
3575
|
markWorkspaceWriter(isolated, id);
|
|
3562
3576
|
const managedEnv = managed?.beforeSpawn({ id, sessionId, lease: lease.token, leasePath: lease.path,
|
|
@@ -3723,7 +3737,7 @@ export default function (pi, managed) {
|
|
|
3723
3737
|
if (!prior)
|
|
3724
3738
|
throw new PreSpawnResumeError(`Cannot resume ${input.park.runId}: its run record is gone.`);
|
|
3725
3739
|
const now = Date.now();
|
|
3726
|
-
if (prior.timing?.deadlineAt !== undefined && now >= prior.timing.deadlineAt) {
|
|
3740
|
+
if (now >= taskDeadline(prior.startedAt, prior.timing?.ceilingAt) || (prior.timing?.deadlineAt !== undefined && now >= prior.timing.deadlineAt)) {
|
|
3727
3741
|
throw new PreSpawnResumeError(`Cannot resume ${input.park.runId}: its assignment deadline passed while it was parked. The wait is held for the owner.`);
|
|
3728
3742
|
}
|
|
3729
3743
|
let plan;
|
|
@@ -3925,7 +3939,7 @@ export default function (pi, managed) {
|
|
|
3925
3939
|
"The tools param is both the tool allowlist AND what determines which extensions load in the child (e.g. tools='read,bash,web_fetch' loads only the web-tools package). Ask for the tools the task needs and nothing more; clean:true gives a built-ins-only child. When the task already names its SKILL.md by path, pass skills with those absolute paths (or [] for none) so the child does not advertise the whole skills catalog. Without an agent or role, pick a model with the model param (e.g. 'xai/grok-4.5@high'); providerless model patterns are resolved by Pi, while provider/model is deterministic and loads mapped provider extensions.",
|
|
3926
3940
|
...CATALOG_GUIDELINES,
|
|
3927
3941
|
"Subagent sandboxing defaults to off. Human settings in /sandbox control file, credential-file, command, and network permissions; sandbox:false cannot override an enabled human profile. Set sandbox:true to request kernel confinement, including without published settings. Set callback:false to finish quietly — then read the result on demand via subagent_result.",
|
|
3928
|
-
"Every launch automatically joins one shared harness-owned watcher, including batch launches; it stops when the last active run ends. Do not start a separate heartbeat or background watcher for subagents. A tool call still open for tool_wait_minutes (default 5) or no progress for stuck_minutes (default 10) sends one factual alert; these alerts never stop, cancel, or restart the run. Hard timeouts default to 60 minutes; max_minutes overrides that default (0
|
|
3942
|
+
"Every launch automatically joins one shared harness-owned watcher, including batch launches; it stops when the last active run ends. Do not start a separate heartbeat or background watcher for subagents. A tool call still open for tool_wait_minutes (default 5) or no progress for stuck_minutes (default 10) sends one factual alert; these alerts never stop, cancel, or restart the run. Hard timeouts default to 60 minutes; max_minutes overrides that default up to 24 hours (0 selects the maximum). Soft deadlines remain opt-in for work with a real wall-clock bound: deadline_minutes steers the child to wrap up and later stops it after grace_minutes, while max_minutes stops it without grace. Do not set elapsed-time limits merely because a task may take a while; use them only when the work needs a real wall-clock bound.",
|
|
3929
3943
|
"Git writers receive separate checkouts by default. /subagents settings selects Clone or Worktree. isolation:false selects the live checkout. A sandboxed Worktree can return its files or explicitly continue in a verified Clone with recover_in_clone:true.",
|
|
3930
3944
|
"Saved conversations persist automatically. To continue a completed or stopped worker in its own history, call subagent_spawn with session_id (the native session id reported for the saved conversation) and the new feedback as prompt. Omit session_id for a brand-new conversation.",
|
|
3931
3945
|
"On a continuation, pass prompt, session_id, and only optional model, thinking, callback, or timing overrides. Launch-only options (name, agent, role, alias, tools, exclude_tools, skills, clean, sandbox, sandbox_dir, cwd, git_clone_workspace, approve, allow_nested) keep the saved recipe; repeat them only with the same value, otherwise the launch is refused.",
|
|
@@ -4461,7 +4475,7 @@ export default function (pi, managed) {
|
|
|
4461
4475
|
: skills.mode === "none" ? "no skills" : `${skills.paths.length} selected skills`;
|
|
4462
4476
|
const timing = timingState();
|
|
4463
4477
|
ctx.ui.notify(`Delegation mode: ${activeDelegationMode()}. Concurrent subagents: ${activeConcurrencyCap()}. ` +
|
|
4464
|
-
`Run timeout: ${timing.maxMinutes ? timing.maxMinutes + " minutes" : "
|
|
4478
|
+
`Run timeout: ${timing.maxMinutes ? timing.maxMinutes + " minutes" : "24 hours"}. Tool-wait alert: ${timing.toolWaitMinutes} min. ` +
|
|
4465
4479
|
`No-progress alert: ${timing.stuckMinutes} min. Skills: ${skillChoice}. ` +
|
|
4466
4480
|
`Use /subagents mode <mode>, cap <number>, tool-wait <minutes>, stuck <minutes>, or settings; /subagents save persists them.`, "info");
|
|
4467
4481
|
}
|
|
@@ -4553,7 +4567,7 @@ export default function (pi, managed) {
|
|
|
4553
4567
|
: skills.mode === "none" ? "no skills" : `${skills.paths.length} selected skills`;
|
|
4554
4568
|
const timing = timingState();
|
|
4555
4569
|
if (ctx.hasUI && !(await ctx.ui.confirm("Save subagent defaults?", `Future sessions will start in ${activeDelegationMode()} with a cap of ${activeConcurrencyCap()}, ` +
|
|
4556
|
-
`run timeout ${timing.maxMinutes ? timing.maxMinutes + " minutes" : "
|
|
4570
|
+
`run timeout ${timing.maxMinutes ? timing.maxMinutes + " minutes" : "24 hours"}, tool-wait alert ${timing.toolWaitMinutes} min, ` +
|
|
4557
4571
|
`no-progress alert ${timing.stuckMinutes} min, and ${skillChoice}.`))) {
|
|
4558
4572
|
ctx.ui.notify("Subagent defaults unchanged.", "info");
|
|
4559
4573
|
return;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { taskDeadline } from "./shared-operation-coordinator/src/task-lifetime.ts";
|
|
1
2
|
import { shouldRestoreWorkObservation } from "./shared-work-client.mjs";
|
|
2
3
|
import { appendTimingWake, removeTimingReceipt, receiptTimingWake, timingWakeReceipt } from "./timing-notifications.ts";
|
|
3
4
|
import { captureLaunchContext } from "./launch-context.ts";
|
|
@@ -58,6 +59,7 @@ import { deliverSubagentPrompt, effectiveSubagentSettings, formatSubagentSetting
|
|
|
58
59
|
import { STEER_FILE_ENV, readSteerReceipt } from "./child-steer.ts";
|
|
59
60
|
import {
|
|
60
61
|
continuationTimingParams,
|
|
62
|
+
configuredMaxMinutes,
|
|
61
63
|
decideTiming,
|
|
62
64
|
describeTiming,
|
|
63
65
|
DEFAULT_TIMING_MINUTES,
|
|
@@ -1246,7 +1248,11 @@ function stopForTiming(pi: ExtensionAPI | undefined, id: string, reason: TimingS
|
|
|
1246
1248
|
*/
|
|
1247
1249
|
function enforceTiming(pi: ExtensionAPI | undefined, meta: RunMeta, now: number): boolean {
|
|
1248
1250
|
const timing = meta.timing;
|
|
1249
|
-
if (!timing
|
|
1251
|
+
if (!timing) return false;
|
|
1252
|
+
if ((meta.status === "running" || meta.status === "orphaned") && now >= (timing.lifetimeAt ?? taskDeadline(meta.startedAt))) {
|
|
1253
|
+
return stopForTiming(pi, meta.id, "ceiling", now);
|
|
1254
|
+
}
|
|
1255
|
+
if (timing.stopReason) return false;
|
|
1250
1256
|
// The ceiling also bounds an orphaned run (child gone, its process group still alive).
|
|
1251
1257
|
if (meta.status === "orphaned") {
|
|
1252
1258
|
return timing.ceilingAt !== undefined && now >= timing.ceilingAt ? stopForTiming(pi, meta.id, "ceiling", now) : false;
|
|
@@ -1711,10 +1717,7 @@ function navigatorCloseRun(id: string) {
|
|
|
1711
1717
|
});
|
|
1712
1718
|
if (outcome.action === "dismissed" || outcome.action === "stopped-and-dismissed") pendingNavigatorDismissals.add(id);
|
|
1713
1719
|
// A closed row is off the hot path: release its caches and retained events.
|
|
1714
|
-
|
|
1715
|
-
healthLogCache.delete(id);
|
|
1716
|
-
resetChildEventLogCursor(id);
|
|
1717
|
-
resetParseRunCursor(id);
|
|
1720
|
+
forgetRunCaches(id);
|
|
1718
1721
|
syncHealthTicker();
|
|
1719
1722
|
// Close stops (or log-finalizes) the run, which is a terminal transition:
|
|
1720
1723
|
// queue its one completion callback so no terminal state is silent (#624).
|
|
@@ -2071,6 +2074,13 @@ function resolvePiBinary(): string {
|
|
|
2071
2074
|
return cachedPi;
|
|
2072
2075
|
}
|
|
2073
2076
|
|
|
2077
|
+
function forgetRunCaches(id: string): void {
|
|
2078
|
+
spendCache.delete(id);
|
|
2079
|
+
healthLogCache.delete(id);
|
|
2080
|
+
resetChildEventLogCursor(id);
|
|
2081
|
+
resetParseRunCursor(id);
|
|
2082
|
+
}
|
|
2083
|
+
|
|
2074
2084
|
function prepareLaunchWorkspace(options: SubagentWorkspaceOptions, isolated?: IsolatedWorkspace): Promise<SubagentWorkspace> {
|
|
2075
2085
|
const built = import.meta.url.endsWith(".domain.mjs");
|
|
2076
2086
|
const entry = new URL("./workspace-prepare-worker.mjs", import.meta.url);
|
|
@@ -2536,13 +2546,13 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
2536
2546
|
const defaults = resolveRunTiming({ settings: cfg, env: process.env, startedAt: 0 });
|
|
2537
2547
|
const minutes = (ms: number | undefined): number => ms === undefined ? 0 : ms / 60_000;
|
|
2538
2548
|
return {
|
|
2539
|
-
maxMinutes:
|
|
2549
|
+
maxMinutes: configuredMaxMinutes(sessionTimeout, timingSettingsFor(cfg), process.env),
|
|
2540
2550
|
toolWaitMinutes: minutes(effective.toolWaitMs),
|
|
2541
2551
|
stuckMinutes: minutes(effective.stuckMs),
|
|
2542
2552
|
timeoutSource: timeoutSource(),
|
|
2543
2553
|
toolWaitSource: sourceFor("toolWaitMinutes"),
|
|
2544
2554
|
stuckSource: sourceFor("stuckMinutes"),
|
|
2545
|
-
defaultMaxMinutes:
|
|
2555
|
+
defaultMaxMinutes: configuredMaxMinutes({}, cfg, process.env),
|
|
2546
2556
|
defaultToolWaitMinutes: minutes(defaults.toolWaitMs),
|
|
2547
2557
|
defaultStuckMinutes: minutes(defaults.stuckMs),
|
|
2548
2558
|
};
|
|
@@ -3021,19 +3031,15 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3021
3031
|
model = parsed.model;
|
|
3022
3032
|
thinking = parsed.thinking;
|
|
3023
3033
|
}
|
|
3024
|
-
//
|
|
3025
|
-
|
|
3026
|
-
|
|
3027
|
-
|
|
3028
|
-
|
|
3029
|
-
|
|
3030
|
-
|
|
3031
|
-
|
|
3032
|
-
|
|
3033
|
-
spendCache.delete(id);
|
|
3034
|
-
healthLogCache.delete(id);
|
|
3035
|
-
resetChildEventLogCursor(id);
|
|
3036
|
-
resetParseRunCursor(id);
|
|
3034
|
+
// Continuations revalidate and lease their saved history. Only fresh launches request maintenance.
|
|
3035
|
+
if (!resume) {
|
|
3036
|
+
if (managed) {
|
|
3037
|
+
const { cleanupTerminalRunRetentionMs, cleanupSessionRetentionMs, maxRegistryBytes } = cfg;
|
|
3038
|
+
managed.scheduleRegistryCleanup({ cleanupTerminalRunRetentionMs, cleanupSessionRetentionMs, maxRegistryBytes }, forgetRunCaches);
|
|
3039
|
+
} else {
|
|
3040
|
+
runDailyCleanupOnce({ config: cfg });
|
|
3041
|
+
for (const removed of enforceRegistrySizeCapOnce({ config: cfg }).removed) forgetRunCaches(removed);
|
|
3042
|
+
}
|
|
3037
3043
|
}
|
|
3038
3044
|
const callbackOrigin = internal?.parkOwner
|
|
3039
3045
|
? { cwd: internal.parkOwner.workspace, sessionId: internal.parkOwner.sessionId }
|
|
@@ -3576,6 +3582,11 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3576
3582
|
trustedExtensions: resume?.recipe.trustedExtensions ?? taskTools?.trusted.map(({ name, package: owner, loadPath }) => ({ name, package: owner, loadPath })),
|
|
3577
3583
|
});
|
|
3578
3584
|
const startedAt = Date.now();
|
|
3585
|
+
const timing = resolveRunTiming({ params: launchTimingParams(p), settings: timingSettingsFor(cfg), env: process.env, startedAt });
|
|
3586
|
+
if (internal?.resumeWait && resume) {
|
|
3587
|
+
timing.lifetimeAt = resume.prior.timing?.lifetimeAt ?? taskDeadline(resume.prior.startedAt);
|
|
3588
|
+
timing.ceilingAt = Math.min(timing.lifetimeAt, resume.prior.timing?.ceilingAt ?? Infinity, timing.ceilingAt!);
|
|
3589
|
+
}
|
|
3579
3590
|
const meta: RunMeta = {
|
|
3580
3591
|
assignment,
|
|
3581
3592
|
outcomeSupport: { version: 1, available: Boolean(assignment), ...(!assignment ? { reason: "Legacy host has no verified parent session/transcript; durable assignment delivery is unavailable." } : {}) },
|
|
@@ -3625,9 +3636,12 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3625
3636
|
tools: bridgePlan.tools,
|
|
3626
3637
|
},
|
|
3627
3638
|
} : {}),
|
|
3628
|
-
timing
|
|
3639
|
+
timing,
|
|
3629
3640
|
};
|
|
3630
3641
|
const dispatchGuard = await internal?.beforeSpawn?.({ runId: id, permissionPlan });
|
|
3642
|
+
if (internal?.resumeWait && Date.now() >= timing.ceilingAt!) {
|
|
3643
|
+
throw new PreSpawnResumeError("The parked task reached its execution time limit before dispatch.");
|
|
3644
|
+
}
|
|
3631
3645
|
if (isolated) markWorkspaceWriter(isolated,id);
|
|
3632
3646
|
const managedEnv = managed?.beforeSpawn({ id, sessionId, lease: lease!.token, leasePath: lease!.path,
|
|
3633
3647
|
preflightPath, policyPath: taskRuntime?.policyPath, permissions: permissionPlan, recipe, recoveryMeta: meta });
|
|
@@ -3784,7 +3798,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3784
3798
|
const prior = readMeta(input.park.runId);
|
|
3785
3799
|
if (!prior) throw new PreSpawnResumeError(`Cannot resume ${input.park.runId}: its run record is gone.`);
|
|
3786
3800
|
const now = Date.now();
|
|
3787
|
-
if (prior.timing?.deadlineAt !== undefined && now >= prior.timing.deadlineAt) {
|
|
3801
|
+
if (now >= taskDeadline(prior.startedAt, prior.timing?.ceilingAt) || (prior.timing?.deadlineAt !== undefined && now >= prior.timing.deadlineAt)) {
|
|
3788
3802
|
throw new PreSpawnResumeError(
|
|
3789
3803
|
`Cannot resume ${input.park.runId}: its assignment deadline passed while it was parked. The wait is held for the owner.`,
|
|
3790
3804
|
);
|
|
@@ -3998,7 +4012,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3998
4012
|
"The tools param is both the tool allowlist AND what determines which extensions load in the child (e.g. tools='read,bash,web_fetch' loads only the web-tools package). Ask for the tools the task needs and nothing more; clean:true gives a built-ins-only child. When the task already names its SKILL.md by path, pass skills with those absolute paths (or [] for none) so the child does not advertise the whole skills catalog. Without an agent or role, pick a model with the model param (e.g. 'xai/grok-4.5@high'); providerless model patterns are resolved by Pi, while provider/model is deterministic and loads mapped provider extensions.",
|
|
3999
4013
|
...CATALOG_GUIDELINES,
|
|
4000
4014
|
"Subagent sandboxing defaults to off. Human settings in /sandbox control file, credential-file, command, and network permissions; sandbox:false cannot override an enabled human profile. Set sandbox:true to request kernel confinement, including without published settings. Set callback:false to finish quietly — then read the result on demand via subagent_result.",
|
|
4001
|
-
"Every launch automatically joins one shared harness-owned watcher, including batch launches; it stops when the last active run ends. Do not start a separate heartbeat or background watcher for subagents. A tool call still open for tool_wait_minutes (default 5) or no progress for stuck_minutes (default 10) sends one factual alert; these alerts never stop, cancel, or restart the run. Hard timeouts default to 60 minutes; max_minutes overrides that default (0
|
|
4015
|
+
"Every launch automatically joins one shared harness-owned watcher, including batch launches; it stops when the last active run ends. Do not start a separate heartbeat or background watcher for subagents. A tool call still open for tool_wait_minutes (default 5) or no progress for stuck_minutes (default 10) sends one factual alert; these alerts never stop, cancel, or restart the run. Hard timeouts default to 60 minutes; max_minutes overrides that default up to 24 hours (0 selects the maximum). Soft deadlines remain opt-in for work with a real wall-clock bound: deadline_minutes steers the child to wrap up and later stops it after grace_minutes, while max_minutes stops it without grace. Do not set elapsed-time limits merely because a task may take a while; use them only when the work needs a real wall-clock bound.",
|
|
4002
4016
|
"Git writers receive separate checkouts by default. /subagents settings selects Clone or Worktree. isolation:false selects the live checkout. A sandboxed Worktree can return its files or explicitly continue in a verified Clone with recover_in_clone:true.",
|
|
4003
4017
|
"Saved conversations persist automatically. To continue a completed or stopped worker in its own history, call subagent_spawn with session_id (the native session id reported for the saved conversation) and the new feedback as prompt. Omit session_id for a brand-new conversation.",
|
|
4004
4018
|
"On a continuation, pass prompt, session_id, and only optional model, thinking, callback, or timing overrides. Launch-only options (name, agent, role, alias, tools, exclude_tools, skills, clean, sandbox, sandbox_dir, cwd, git_clone_workspace, approve, allow_nested) keep the saved recipe; repeat them only with the same value, otherwise the launch is refused.",
|
|
@@ -4552,7 +4566,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
4552
4566
|
: skills.mode === "none" ? "no skills" : `${skills.paths.length} selected skills`;
|
|
4553
4567
|
const timing = timingState();
|
|
4554
4568
|
ctx.ui.notify(`Delegation mode: ${activeDelegationMode()}. Concurrent subagents: ${activeConcurrencyCap()}. ` +
|
|
4555
|
-
`Run timeout: ${timing.maxMinutes ? timing.maxMinutes + " minutes" : "
|
|
4569
|
+
`Run timeout: ${timing.maxMinutes ? timing.maxMinutes + " minutes" : "24 hours"}. Tool-wait alert: ${timing.toolWaitMinutes} min. ` +
|
|
4556
4570
|
`No-progress alert: ${timing.stuckMinutes} min. Skills: ${skillChoice}. ` +
|
|
4557
4571
|
`Use /subagents mode <mode>, cap <number>, tool-wait <minutes>, stuck <minutes>, or settings; /subagents save persists them.`, "info");
|
|
4558
4572
|
}
|
|
@@ -4638,7 +4652,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
4638
4652
|
const timing = timingState();
|
|
4639
4653
|
if (ctx.hasUI && !(await ctx.ui.confirm("Save subagent defaults?",
|
|
4640
4654
|
`Future sessions will start in ${activeDelegationMode()} with a cap of ${activeConcurrencyCap()}, ` +
|
|
4641
|
-
`run timeout ${timing.maxMinutes ? timing.maxMinutes + " minutes" : "
|
|
4655
|
+
`run timeout ${timing.maxMinutes ? timing.maxMinutes + " minutes" : "24 hours"}, tool-wait alert ${timing.toolWaitMinutes} min, ` +
|
|
4642
4656
|
`no-progress alert ${timing.stuckMinutes} min, and ${skillChoice}.`))) {
|
|
4643
4657
|
ctx.ui.notify("Subagent defaults unchanged.", "info");
|
|
4644
4658
|
return;
|