pi-better-server 0.7.0 → 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/codex/return.ts +3 -2
- package/src/detach/extension.ts +20 -3
- package/src/event-log.ts +40 -12
- package/src/hosted-session.ts +11 -5
- package/src/remote-client/packages.ts +1 -4
- 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-harness-settings.domain.mjs +2 -3
- package/src/runtime/domain/background-service/shared-harness-settings.ts +2 -5
- 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/shared-ssh-core/index.domain.mjs +1 -1
- package/src/runtime/domain/background-service/shared-ssh-core/index.ts +1 -1
- 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/catalog/catalog-preferences.mjs +1 -3
- 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/package.json +1 -1
- package/src/runtime/domain/sandbox-policy/shared-harness-settings.domain.mjs +2 -3
- package/src/runtime/domain/sandbox-policy/shared-harness-settings.ts +2 -5
- 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/shared-harness-settings.mjs +2 -3
- package/src/runtime/domain/subagents/README.md +2 -2
- package/src/runtime/domain/subagents/catalog-preferences.domain.mjs +1 -3
- package/src/runtime/domain/subagents/catalog-preferences.ts +1 -5
- package/src/runtime/domain/subagents/cleanup.domain.mjs +5 -2
- package/src/runtime/domain/subagents/cleanup.ts +4 -1
- package/src/runtime/domain/subagents/config.ts +1 -1
- package/src/runtime/domain/subagents/extensions.mjs +1 -0
- package/src/runtime/domain/subagents/finalization.domain.mjs +34 -30
- package/src/runtime/domain/subagents/finalization.ts +30 -28
- package/src/runtime/domain/subagents/git-workspace.domain.mjs +51 -6
- package/src/runtime/domain/subagents/git-workspace.ts +48 -6
- package/src/runtime/domain/subagents/index.domain.mjs +99 -54
- package/src/runtime/domain/subagents/index.ts +100 -51
- package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +7 -14
- package/src/runtime/domain/subagents/isolated-workspace.ts +6 -12
- 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 +40 -14
- package/src/runtime/domain/subagents/registry.ts +26 -12
- 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-harness-settings.domain.mjs +2 -3
- package/src/runtime/domain/subagents/shared-harness-settings.ts +2 -5
- 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/domain/subagents/workspace-prepare-worker.mjs +12 -0
- package/src/runtime/task-expiry.ts +52 -0
- package/src/server.ts +4 -0
- package/src/shared-ssh-core/index.ts +1 -1
- package/src/version.ts +1 -1
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
* the cancellation epoch it observed. Cancellation invalidates the active resume
|
|
16
16
|
* claim, and a claim whose epoch no longer matches can never publish an attempt.
|
|
17
17
|
*/
|
|
18
|
+
import { taskDeadline } from "./task-lifetime.domain.mjs";
|
|
18
19
|
import { randomUUID } from "node:crypto";
|
|
19
20
|
import { StoreError } from "./errors.domain.mjs";
|
|
20
21
|
import { acknowledgeGenerationOutbox, enqueueReadyGeneration, releaseGenerationPins, voidGenerationOutbox, } from "./outbox.domain.mjs";
|
|
@@ -370,21 +371,25 @@ export function cancelWait(ctx, input) {
|
|
|
370
371
|
throw new StoreError("wait-phase", `Wait ${waitId} generation ${generation} is already ${wait.phase}; cancellation is recorded once and cannot be repeated or replaced.`);
|
|
371
372
|
}
|
|
372
373
|
assertExpectedEpoch(wait, expectedCancelEpoch);
|
|
373
|
-
|
|
374
|
-
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);
|
|
375
|
-
const activeClaimRows = getRows(ctx, "SELECT claim_id FROM resume_claims WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')", waitId, generation);
|
|
376
|
-
const invalidatedClaimIds = activeClaimRows.map((row) => columnText(row, "claim_id"));
|
|
377
|
-
run(ctx, `UPDATE resume_claims SET state = 'invalidated', invalidated_at = ?, reason = ?
|
|
378
|
-
WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')`, at, reason, waitId, generation);
|
|
379
|
-
const voidedOutboxIds = voidGenerationOutbox(ctx, waitId, generation, reason, at);
|
|
380
|
-
releaseGenerationPins(ctx, waitId, generation, "wait-cancelled", at);
|
|
381
|
-
return {
|
|
382
|
-
wait: requireWait(ctx, waitId, generation),
|
|
383
|
-
invalidatedClaimIds,
|
|
384
|
-
voidedOutboxIds,
|
|
385
|
-
};
|
|
374
|
+
return cancelGeneration(ctx, waitId, generation, reason);
|
|
386
375
|
});
|
|
387
376
|
}
|
|
377
|
+
/** Caller holds the write transaction and has selected a nonterminal generation. */
|
|
378
|
+
export function cancelGeneration(ctx, waitId, generation, reason) {
|
|
379
|
+
const at = ctx.now();
|
|
380
|
+
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);
|
|
381
|
+
const activeClaimRows = getRows(ctx, "SELECT claim_id FROM resume_claims WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')", waitId, generation);
|
|
382
|
+
const invalidatedClaimIds = activeClaimRows.map((row) => columnText(row, "claim_id"));
|
|
383
|
+
run(ctx, `UPDATE resume_claims SET state = 'invalidated', invalidated_at = ?, reason = ?
|
|
384
|
+
WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')`, at, reason, waitId, generation);
|
|
385
|
+
const voidedOutboxIds = voidGenerationOutbox(ctx, waitId, generation, reason, at);
|
|
386
|
+
releaseGenerationPins(ctx, waitId, generation, "wait-cancelled", at);
|
|
387
|
+
return {
|
|
388
|
+
wait: requireWait(ctx, waitId, generation),
|
|
389
|
+
invalidatedClaimIds,
|
|
390
|
+
voidedOutboxIds,
|
|
391
|
+
};
|
|
392
|
+
}
|
|
388
393
|
// ---- resume claims ------------------------------------------------------
|
|
389
394
|
export function claimResume(ctx, input) {
|
|
390
395
|
const waitId = requireId("waitId", input.waitId);
|
|
@@ -395,6 +400,8 @@ export function claimResume(ctx, input) {
|
|
|
395
400
|
return ctx.transaction(() => {
|
|
396
401
|
assertCurrentGeneration(ctx, waitId, generation);
|
|
397
402
|
const wait = requireWait(ctx, waitId, generation);
|
|
403
|
+
if (ctx.now() >= taskDeadline(wait.createdAt))
|
|
404
|
+
throw new StoreError("wait-phase", "The 24-hour wait lifetime has expired.");
|
|
398
405
|
const active = getRows(ctx, "SELECT claim_id FROM resume_claims WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')", waitId, generation)[0];
|
|
399
406
|
if (active) {
|
|
400
407
|
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.`);
|
|
@@ -439,6 +446,8 @@ export function publishResumeAttempt(ctx, input) {
|
|
|
439
446
|
return ctx.transaction(() => {
|
|
440
447
|
assertCurrentGeneration(ctx, waitId, generation);
|
|
441
448
|
const wait = requireWait(ctx, waitId, generation);
|
|
449
|
+
if (ctx.now() >= taskDeadline(wait.createdAt))
|
|
450
|
+
throw new StoreError("wait-phase", "The 24-hour wait lifetime has expired.");
|
|
442
451
|
const claim = requireClaim(ctx, claimId);
|
|
443
452
|
if (claim.waitId !== waitId || claim.generation !== generation) {
|
|
444
453
|
throw new StoreError("claim-state", `Resume claim ${claimId} belongs to ${claim.waitId} generation ${claim.generation}, not ${waitId} generation ${generation}.`);
|
|
@@ -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.ts";
|
|
17
18
|
import { randomUUID } from "node:crypto";
|
|
18
19
|
import { StoreError } from "./errors.ts";
|
|
19
20
|
import {
|
|
@@ -606,41 +607,46 @@ export function cancelWait(ctx: StoreContext, input: CancelWaitInput): CancelWai
|
|
|
606
607
|
);
|
|
607
608
|
}
|
|
608
609
|
assertExpectedEpoch(wait, expectedCancelEpoch);
|
|
609
|
-
|
|
610
|
-
run(
|
|
611
|
-
ctx,
|
|
612
|
-
"UPDATE waits SET phase = 'cancelled', phase_reason = ?, cancel_epoch = cancel_epoch + 1, updated_at = ? WHERE wait_id = ? AND generation = ?",
|
|
613
|
-
reason,
|
|
614
|
-
at,
|
|
615
|
-
waitId,
|
|
616
|
-
generation,
|
|
617
|
-
);
|
|
618
|
-
const activeClaimRows = getRows(
|
|
619
|
-
ctx,
|
|
620
|
-
"SELECT claim_id FROM resume_claims WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')",
|
|
621
|
-
waitId,
|
|
622
|
-
generation,
|
|
623
|
-
);
|
|
624
|
-
const invalidatedClaimIds = activeClaimRows.map((row) => columnText(row, "claim_id"));
|
|
625
|
-
run(
|
|
626
|
-
ctx,
|
|
627
|
-
`UPDATE resume_claims SET state = 'invalidated', invalidated_at = ?, reason = ?
|
|
628
|
-
WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')`,
|
|
629
|
-
at,
|
|
630
|
-
reason,
|
|
631
|
-
waitId,
|
|
632
|
-
generation,
|
|
633
|
-
);
|
|
634
|
-
const voidedOutboxIds = voidGenerationOutbox(ctx, waitId, generation, reason, at);
|
|
635
|
-
releaseGenerationPins(ctx, waitId, generation, "wait-cancelled", at);
|
|
636
|
-
return {
|
|
637
|
-
wait: requireWait(ctx, waitId, generation),
|
|
638
|
-
invalidatedClaimIds,
|
|
639
|
-
voidedOutboxIds,
|
|
640
|
-
};
|
|
610
|
+
return cancelGeneration(ctx, waitId, generation, reason);
|
|
641
611
|
});
|
|
642
612
|
}
|
|
643
613
|
|
|
614
|
+
/** Caller holds the write transaction and has selected a nonterminal generation. */
|
|
615
|
+
export function cancelGeneration(ctx: StoreContext, waitId: string, generation: number, reason: string): CancelWaitResult {
|
|
616
|
+
const at = ctx.now();
|
|
617
|
+
run(
|
|
618
|
+
ctx,
|
|
619
|
+
"UPDATE waits SET phase = 'cancelled', phase_reason = ?, cancel_epoch = cancel_epoch + 1, updated_at = ? WHERE wait_id = ? AND generation = ?",
|
|
620
|
+
reason,
|
|
621
|
+
at,
|
|
622
|
+
waitId,
|
|
623
|
+
generation,
|
|
624
|
+
);
|
|
625
|
+
const activeClaimRows = getRows(
|
|
626
|
+
ctx,
|
|
627
|
+
"SELECT claim_id FROM resume_claims WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')",
|
|
628
|
+
waitId,
|
|
629
|
+
generation,
|
|
630
|
+
);
|
|
631
|
+
const invalidatedClaimIds = activeClaimRows.map((row) => columnText(row, "claim_id"));
|
|
632
|
+
run(
|
|
633
|
+
ctx,
|
|
634
|
+
`UPDATE resume_claims SET state = 'invalidated', invalidated_at = ?, reason = ?
|
|
635
|
+
WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')`,
|
|
636
|
+
at,
|
|
637
|
+
reason,
|
|
638
|
+
waitId,
|
|
639
|
+
generation,
|
|
640
|
+
);
|
|
641
|
+
const voidedOutboxIds = voidGenerationOutbox(ctx, waitId, generation, reason, at);
|
|
642
|
+
releaseGenerationPins(ctx, waitId, generation, "wait-cancelled", at);
|
|
643
|
+
return {
|
|
644
|
+
wait: requireWait(ctx, waitId, generation),
|
|
645
|
+
invalidatedClaimIds,
|
|
646
|
+
voidedOutboxIds,
|
|
647
|
+
};
|
|
648
|
+
}
|
|
649
|
+
|
|
644
650
|
// ---- resume claims ------------------------------------------------------
|
|
645
651
|
|
|
646
652
|
export function claimResume(ctx: StoreContext, input: ClaimResumeInput): ResumeClaimResult {
|
|
@@ -653,6 +659,7 @@ export function claimResume(ctx: StoreContext, input: ClaimResumeInput): ResumeC
|
|
|
653
659
|
return ctx.transaction(() => {
|
|
654
660
|
assertCurrentGeneration(ctx, waitId, generation);
|
|
655
661
|
const wait = requireWait(ctx, waitId, generation);
|
|
662
|
+
if (ctx.now() >= taskDeadline(wait.createdAt)) throw new StoreError("wait-phase", "The 24-hour wait lifetime has expired.");
|
|
656
663
|
const active = getRows(
|
|
657
664
|
ctx,
|
|
658
665
|
"SELECT claim_id FROM resume_claims WHERE wait_id = ? AND generation = ? AND state IN ('claimed', 'published')",
|
|
@@ -735,6 +742,7 @@ export function publishResumeAttempt(
|
|
|
735
742
|
return ctx.transaction(() => {
|
|
736
743
|
assertCurrentGeneration(ctx, waitId, generation);
|
|
737
744
|
const wait = requireWait(ctx, waitId, generation);
|
|
745
|
+
if (ctx.now() >= taskDeadline(wait.createdAt)) throw new StoreError("wait-phase", "The 24-hour wait lifetime has expired.");
|
|
738
746
|
const claim = requireClaim(ctx, claimId);
|
|
739
747
|
if (claim.waitId !== waitId || claim.generation !== generation) {
|
|
740
748
|
throw new StoreError(
|
|
@@ -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
|
}
|
|
@@ -27,6 +27,7 @@
|
|
|
27
27
|
* reparented descendants outside that group are out of contract and are
|
|
28
28
|
* never scanned for.
|
|
29
29
|
*/
|
|
30
|
+
import { taskDeadline } from "./shared-operation-coordinator/src/task-lifetime.domain.mjs";
|
|
30
31
|
import { realProcessProbe } from "./health.domain.mjs";
|
|
31
32
|
import { classifyChildExit } from "./lifecycle.domain.mjs";
|
|
32
33
|
import { parseRunForLifecycle } from "./parse.domain.mjs";
|
|
@@ -74,9 +75,10 @@ function oweTerminalCompletion(meta, now) {
|
|
|
74
75
|
return;
|
|
75
76
|
meta.completionCallbackPendingAt = now;
|
|
76
77
|
}
|
|
77
|
-
function
|
|
78
|
-
meta.
|
|
79
|
-
meta.
|
|
78
|
+
function recordStopped(meta, now) {
|
|
79
|
+
const expired = meta.timing?.stopReason === "ceiling" && now >= (meta.timing.lifetimeAt ?? taskDeadline(meta.startedAt));
|
|
80
|
+
meta.status = expired ? "failed" : "killed";
|
|
81
|
+
meta.lifecycleClassification = expired ? "timed_out" : "killed";
|
|
80
82
|
meta.endedAt = now;
|
|
81
83
|
oweTerminalCompletion(meta, now);
|
|
82
84
|
writeMeta(meta);
|
|
@@ -131,7 +133,7 @@ function cleanupOrphanedRun(meta, probe, now) {
|
|
|
131
133
|
const pgid = relatedProcessGroupId(meta);
|
|
132
134
|
if (pgid !== undefined && probe.groupAlive(pgid)) {
|
|
133
135
|
terminateRelatedWork(meta);
|
|
134
|
-
return
|
|
136
|
+
return recordStopped(meta, now);
|
|
135
137
|
}
|
|
136
138
|
return finalizeOrphanedWithoutProcess(meta, now);
|
|
137
139
|
}
|
|
@@ -175,7 +177,7 @@ export function stopRun(id, deps = {}) {
|
|
|
175
177
|
// Supervised path: same process-group kill + killed write as before.
|
|
176
178
|
// Prefer recorded pgid so running and orphaned share one target rule.
|
|
177
179
|
terminateRelatedWork(meta);
|
|
178
|
-
return
|
|
180
|
+
return recordStopped(meta, now);
|
|
179
181
|
}
|
|
180
182
|
if (status === "orphaned") {
|
|
181
183
|
return cleanupOrphanedRun(meta, probe, now);
|
|
@@ -27,6 +27,7 @@
|
|
|
27
27
|
* never scanned for.
|
|
28
28
|
*/
|
|
29
29
|
|
|
30
|
+
import { taskDeadline } from "./shared-operation-coordinator/src/task-lifetime.ts";
|
|
30
31
|
import { realProcessProbe, type ProcessProbe } from "./health.ts";
|
|
31
32
|
import { classifyChildExit } from "./lifecycle.ts";
|
|
32
33
|
import { parseRunForLifecycle } from "./parse.ts";
|
|
@@ -101,9 +102,10 @@ function oweTerminalCompletion(meta: RunMeta, now: number): void {
|
|
|
101
102
|
meta.completionCallbackPendingAt = now;
|
|
102
103
|
}
|
|
103
104
|
|
|
104
|
-
function
|
|
105
|
-
meta.
|
|
106
|
-
meta.
|
|
105
|
+
function recordStopped(meta: RunMeta, now: number): StopOutcome {
|
|
106
|
+
const expired = meta.timing?.stopReason === "ceiling" && now >= (meta.timing.lifetimeAt ?? taskDeadline(meta.startedAt));
|
|
107
|
+
meta.status = expired ? "failed" : "killed";
|
|
108
|
+
meta.lifecycleClassification = expired ? "timed_out" : "killed";
|
|
107
109
|
meta.endedAt = now;
|
|
108
110
|
oweTerminalCompletion(meta, now);
|
|
109
111
|
writeMeta(meta);
|
|
@@ -162,7 +164,7 @@ function cleanupOrphanedRun(meta: RunMeta, probe: ProcessProbe, now: number): St
|
|
|
162
164
|
const pgid = relatedProcessGroupId(meta);
|
|
163
165
|
if (pgid !== undefined && probe.groupAlive(pgid)) {
|
|
164
166
|
terminateRelatedWork(meta);
|
|
165
|
-
return
|
|
167
|
+
return recordStopped(meta, now);
|
|
166
168
|
}
|
|
167
169
|
return finalizeOrphanedWithoutProcess(meta, now);
|
|
168
170
|
}
|
|
@@ -206,7 +208,7 @@ export function stopRun(id: string, deps: StopDeps = {}): StopOutcome {
|
|
|
206
208
|
// Supervised path: same process-group kill + killed write as before.
|
|
207
209
|
// Prefer recorded pgid so running and orphaned share one target rule.
|
|
208
210
|
terminateRelatedWork(meta);
|
|
209
|
-
return
|
|
211
|
+
return recordStopped(meta, now);
|
|
210
212
|
}
|
|
211
213
|
|
|
212
214
|
if (status === "orphaned") {
|
|
@@ -41,6 +41,7 @@
|
|
|
41
41
|
* not repeat it, and parallel calls alert independently. The wake never stops,
|
|
42
42
|
* cancels, or restarts the run.
|
|
43
43
|
*/
|
|
44
|
+
import { taskDeadline } from "./shared-operation-coordinator/src/task-lifetime.domain.mjs";
|
|
44
45
|
import { createHash } from "node:crypto";
|
|
45
46
|
/** Built-in defaults, in minutes. `0` disables that control. */
|
|
46
47
|
export const DEFAULT_TIMING_MINUTES = Object.freeze({
|
|
@@ -110,6 +111,9 @@ export function assertTimingParams(params, label = "") {
|
|
|
110
111
|
function pick(param, env, setting, fallback, names) {
|
|
111
112
|
return minutes(param, names[0]) ?? minutes(env, names[1]) ?? minutes(setting, names[2]) ?? fallback;
|
|
112
113
|
}
|
|
114
|
+
export function configuredMaxMinutes(params, settings, env) {
|
|
115
|
+
return pick(params.max_minutes, env[TIMING_ENV.max], settings.maxMinutes, DEFAULT_TIMING_MINUTES.max, ["max_minutes", TIMING_ENV.max, "maxMinutes"]);
|
|
116
|
+
}
|
|
113
117
|
/** The durable timing record for a run starting at `startedAt`. */
|
|
114
118
|
export function resolveRunTiming(input) {
|
|
115
119
|
const p = input.params ?? {};
|
|
@@ -117,13 +121,13 @@ export function resolveRunTiming(input) {
|
|
|
117
121
|
const env = input.env ?? {};
|
|
118
122
|
const deadline = pick(p.deadline_minutes, env[TIMING_ENV.deadline], s.deadlineMinutes, DEFAULT_TIMING_MINUTES.deadline, ["deadline_minutes", TIMING_ENV.deadline, "deadlineMinutes"]);
|
|
119
123
|
const grace = pick(p.grace_minutes, env[TIMING_ENV.grace], s.graceMinutes, DEFAULT_TIMING_MINUTES.grace, ["grace_minutes", TIMING_ENV.grace, "graceMinutes"]);
|
|
120
|
-
const max =
|
|
124
|
+
const max = configuredMaxMinutes(p, s, env);
|
|
121
125
|
const toolWait = pick(p.tool_wait_minutes, env[TIMING_ENV.toolWait], s.toolWaitMinutes, DEFAULT_TIMING_MINUTES.toolWait, ["tool_wait_minutes", TIMING_ENV.toolWait, "toolWaitMinutes"]);
|
|
122
126
|
const stuck = pick(p.stuck_minutes, env[TIMING_ENV.stuck], s.stuckMinutes, DEFAULT_TIMING_MINUTES.stuck, ["stuck_minutes", TIMING_ENV.stuck, "stuckMinutes"]);
|
|
123
127
|
return {
|
|
124
128
|
...(deadline > 0 ? { deadlineAt: input.startedAt + Math.round(deadline * MINUTE) } : {}),
|
|
125
129
|
graceMs: Math.round(grace * MINUTE),
|
|
126
|
-
|
|
130
|
+
ceilingAt: taskDeadline(input.startedAt, max > 0 ? input.startedAt + Math.round(max * MINUTE) : undefined),
|
|
127
131
|
...(toolWait > 0 ? { toolWaitMs: Math.round(toolWait * MINUTE) } : {}),
|
|
128
132
|
...(stuck > 0 ? { stuckMs: Math.round(stuck * MINUTE) } : {}),
|
|
129
133
|
};
|
|
@@ -132,7 +136,7 @@ export function resolveRunTiming(input) {
|
|
|
132
136
|
const TIMING_DESCRIPTIONS = {
|
|
133
137
|
deadline_minutes: "Optional soft deadline in minutes (default: none; 0 = none; null or omitted = inherit: in a batch job the shared value, otherwise the default). At the deadline the child is told to stop starting new work, commit what is done, and report, and you get one wake. Grace starts when the message reaches the child (after its current tool call); if it has not finished by then, the harness stops it with reason deadline.",
|
|
134
138
|
grace_minutes: "Minutes after the wrap-up message reaches the child before the run is stopped (default 5; null or omitted = inherit).",
|
|
135
|
-
max_minutes: "Optional hard ceiling in minutes (default: 60; 0
|
|
139
|
+
max_minutes: "Optional hard ceiling in minutes (default: 60; 0 uses the 24-hour maximum; null or omitted = inherit). The run is stopped at once, without grace, with reason ceiling.",
|
|
136
140
|
tool_wait_minutes: "Tool-call wait alert in minutes (default 5; 0 = off; null or omitted = inherit). While a tool call stays open this long you get one factual wake for that call, including a normal long test. Parallel calls alert independently. The alert does not stop or cancel the run.",
|
|
137
141
|
stuck_minutes: "No-progress window in minutes (default 10; 0 = off; null or omitted = inherit). Progress is any successful tool call that is not an exact repeat of an earlier one (same tool, same arguments); edits, writes, commits, and a success after a failure always count. Time inside a running tool call does not count. Wakes you once per stuck spell; never stops the run.",
|
|
138
142
|
};
|
|
@@ -41,6 +41,7 @@
|
|
|
41
41
|
* cancels, or restarts the run.
|
|
42
42
|
*/
|
|
43
43
|
|
|
44
|
+
import { taskDeadline } from "./shared-operation-coordinator/src/task-lifetime.ts";
|
|
44
45
|
import { createHash } from "node:crypto";
|
|
45
46
|
|
|
46
47
|
export type TimingStopReason = "deadline" | "ceiling";
|
|
@@ -72,6 +73,8 @@ export interface RunTiming {
|
|
|
72
73
|
graceMs: number;
|
|
73
74
|
/** Hard ceiling (epoch ms): stopped without grace. Absent = none. */
|
|
74
75
|
ceilingAt?: number;
|
|
76
|
+
/** Original 24-hour deadline carried across automatic resumes. */
|
|
77
|
+
lifetimeAt?: number;
|
|
75
78
|
/** No-progress window. Absent = stuck detection off. */
|
|
76
79
|
stuckMs?: number;
|
|
77
80
|
/** Tool-call wait window. Absent = tool-wait alerts off. */
|
|
@@ -186,6 +189,11 @@ function pick(param: unknown, env: unknown, setting: unknown, fallback: number,
|
|
|
186
189
|
return minutes(param, names[0]) ?? minutes(env, names[1]) ?? minutes(setting, names[2]) ?? fallback;
|
|
187
190
|
}
|
|
188
191
|
|
|
192
|
+
export function configuredMaxMinutes(params: TimingParams, settings: TimingSettings, env: Record<string, string | undefined>): number {
|
|
193
|
+
return pick(params.max_minutes, env[TIMING_ENV.max], settings.maxMinutes, DEFAULT_TIMING_MINUTES.max,
|
|
194
|
+
["max_minutes", TIMING_ENV.max, "maxMinutes"]);
|
|
195
|
+
}
|
|
196
|
+
|
|
189
197
|
/** The durable timing record for a run starting at `startedAt`. */
|
|
190
198
|
export function resolveRunTiming(input: {
|
|
191
199
|
params?: TimingParams;
|
|
@@ -200,8 +208,7 @@ export function resolveRunTiming(input: {
|
|
|
200
208
|
["deadline_minutes", TIMING_ENV.deadline, "deadlineMinutes"]);
|
|
201
209
|
const grace = pick(p.grace_minutes, env[TIMING_ENV.grace], s.graceMinutes, DEFAULT_TIMING_MINUTES.grace,
|
|
202
210
|
["grace_minutes", TIMING_ENV.grace, "graceMinutes"]);
|
|
203
|
-
const max =
|
|
204
|
-
["max_minutes", TIMING_ENV.max, "maxMinutes"]);
|
|
211
|
+
const max = configuredMaxMinutes(p, s, env);
|
|
205
212
|
const toolWait = pick(p.tool_wait_minutes, env[TIMING_ENV.toolWait], s.toolWaitMinutes, DEFAULT_TIMING_MINUTES.toolWait,
|
|
206
213
|
["tool_wait_minutes", TIMING_ENV.toolWait, "toolWaitMinutes"]);
|
|
207
214
|
const stuck = pick(p.stuck_minutes, env[TIMING_ENV.stuck], s.stuckMinutes, DEFAULT_TIMING_MINUTES.stuck,
|
|
@@ -209,7 +216,7 @@ export function resolveRunTiming(input: {
|
|
|
209
216
|
return {
|
|
210
217
|
...(deadline > 0 ? { deadlineAt: input.startedAt + Math.round(deadline * MINUTE) } : {}),
|
|
211
218
|
graceMs: Math.round(grace * MINUTE),
|
|
212
|
-
|
|
219
|
+
ceilingAt: taskDeadline(input.startedAt, max > 0 ? input.startedAt + Math.round(max * MINUTE) : undefined),
|
|
213
220
|
...(toolWait > 0 ? { toolWaitMs: Math.round(toolWait * MINUTE) } : {}),
|
|
214
221
|
...(stuck > 0 ? { stuckMs: Math.round(stuck * MINUTE) } : {}),
|
|
215
222
|
};
|
|
@@ -220,7 +227,7 @@ export function resolveRunTiming(input: {
|
|
|
220
227
|
const TIMING_DESCRIPTIONS = {
|
|
221
228
|
deadline_minutes: "Optional soft deadline in minutes (default: none; 0 = none; null or omitted = inherit: in a batch job the shared value, otherwise the default). At the deadline the child is told to stop starting new work, commit what is done, and report, and you get one wake. Grace starts when the message reaches the child (after its current tool call); if it has not finished by then, the harness stops it with reason deadline.",
|
|
222
229
|
grace_minutes: "Minutes after the wrap-up message reaches the child before the run is stopped (default 5; null or omitted = inherit).",
|
|
223
|
-
max_minutes: "Optional hard ceiling in minutes (default: 60; 0
|
|
230
|
+
max_minutes: "Optional hard ceiling in minutes (default: 60; 0 uses the 24-hour maximum; null or omitted = inherit). The run is stopped at once, without grace, with reason ceiling.",
|
|
224
231
|
tool_wait_minutes: "Tool-call wait alert in minutes (default 5; 0 = off; null or omitted = inherit). While a tool call stays open this long you get one factual wake for that call, including a normal long test. Parallel calls alert independently. The alert does not stop or cancel the run.",
|
|
225
232
|
stuck_minutes: "No-progress window in minutes (default 10; 0 = off; null or omitted = inherit). Progress is any successful tool call that is not an exact repeat of an earlier one (same tool, same arguments); edits, writes, commits, and a success after a failure always count. Time inside a running tool call does not count. Wakes you once per stuck spell; never stops the run.",
|
|
226
233
|
} as const;
|
|
@@ -4,11 +4,10 @@
|
|
|
4
4
|
import { createHash, randomUUID } from "node:crypto";
|
|
5
5
|
import { chmodSync, closeSync, constants, copyFileSync, existsSync, lstatSync, mkdirSync, openSync, readSync, readdirSync, readlinkSync, renameSync, rmSync, symlinkSync, } from "node:fs";
|
|
6
6
|
import { dirname, join } from "node:path";
|
|
7
|
-
function fileHash(path) {
|
|
7
|
+
function fileHash(path, buffer) {
|
|
8
8
|
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
9
9
|
try {
|
|
10
10
|
const hash = createHash("sha256");
|
|
11
|
-
const buffer = Buffer.allocUnsafe(128 * 1024);
|
|
12
11
|
let bytes;
|
|
13
12
|
while ((bytes = readSync(fd, buffer, 0, buffer.length, null)) > 0)
|
|
14
13
|
hash.update(buffer.subarray(0, bytes));
|
|
@@ -23,7 +22,7 @@ function blobPath(store, hash) {
|
|
|
23
22
|
throw new Error("Invalid saved file identity");
|
|
24
23
|
return join(store, hash.slice(0, 2), hash.slice(2));
|
|
25
24
|
}
|
|
26
|
-
function saveFile(path, store, hash) {
|
|
25
|
+
function saveFile(path, store, hash, buffer) {
|
|
27
26
|
const dest = blobPath(store, hash);
|
|
28
27
|
if (existsSync(dest))
|
|
29
28
|
return;
|
|
@@ -32,7 +31,7 @@ function saveFile(path, store, hash) {
|
|
|
32
31
|
try {
|
|
33
32
|
copyFileSync(path, temp, constants.COPYFILE_FICLONE);
|
|
34
33
|
chmodSync(temp, 0o600);
|
|
35
|
-
if (fileHash(temp) !== hash)
|
|
34
|
+
if (fileHash(temp, buffer) !== hash)
|
|
36
35
|
throw new Error("File changed while saving " + path);
|
|
37
36
|
renameSync(temp, dest);
|
|
38
37
|
}
|
|
@@ -45,6 +44,7 @@ export function snapshotTree(root, store, omit = new Set()) {
|
|
|
45
44
|
if (!lstatSync(root).isDirectory())
|
|
46
45
|
throw new Error("Expected a directory at " + root);
|
|
47
46
|
const entries = [];
|
|
47
|
+
const buffer = Buffer.allocUnsafe(128 * 1024);
|
|
48
48
|
function walk(parent) {
|
|
49
49
|
for (const child of readdirSync(join(root, parent)).sort()) {
|
|
50
50
|
const name = join(parent, child);
|
|
@@ -59,9 +59,9 @@ export function snapshotTree(root, store, omit = new Set()) {
|
|
|
59
59
|
entries.push({ name, mode, type: "symlink", target: readlinkSync(path) });
|
|
60
60
|
}
|
|
61
61
|
else if (stat.isFile()) {
|
|
62
|
-
const blob = fileHash(path);
|
|
62
|
+
const blob = fileHash(path, buffer);
|
|
63
63
|
if (store)
|
|
64
|
-
saveFile(path, store, blob);
|
|
64
|
+
saveFile(path, store, blob, buffer);
|
|
65
65
|
entries.push({ name, mode, type: "file", blob });
|
|
66
66
|
}
|
|
67
67
|
else
|
|
@@ -24,11 +24,10 @@ export type SavedEntry =
|
|
|
24
24
|
| { name: string; mode: number; type: "file"; blob: string }
|
|
25
25
|
| { name: string; mode: number; type: "symlink"; target: string };
|
|
26
26
|
|
|
27
|
-
function fileHash(path: string): string {
|
|
27
|
+
function fileHash(path: string, buffer: Buffer): string {
|
|
28
28
|
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
29
29
|
try {
|
|
30
30
|
const hash = createHash("sha256");
|
|
31
|
-
const buffer = Buffer.allocUnsafe(128 * 1024);
|
|
32
31
|
let bytes: number;
|
|
33
32
|
while ((bytes = readSync(fd, buffer, 0, buffer.length, null)) > 0) hash.update(buffer.subarray(0, bytes));
|
|
34
33
|
return hash.digest("hex");
|
|
@@ -42,7 +41,7 @@ function blobPath(store: string, hash: string): string {
|
|
|
42
41
|
return join(store, hash.slice(0, 2), hash.slice(2));
|
|
43
42
|
}
|
|
44
43
|
|
|
45
|
-
function saveFile(path: string, store: string, hash: string): void {
|
|
44
|
+
function saveFile(path: string, store: string, hash: string, buffer: Buffer): void {
|
|
46
45
|
const dest = blobPath(store, hash);
|
|
47
46
|
if (existsSync(dest)) return;
|
|
48
47
|
mkdirSync(dirname(dest), { recursive: true, mode: 0o700 });
|
|
@@ -50,7 +49,7 @@ function saveFile(path: string, store: string, hash: string): void {
|
|
|
50
49
|
try {
|
|
51
50
|
copyFileSync(path, temp, constants.COPYFILE_FICLONE);
|
|
52
51
|
chmodSync(temp, 0o600);
|
|
53
|
-
if (fileHash(temp) !== hash) throw new Error("File changed while saving " + path);
|
|
52
|
+
if (fileHash(temp, buffer) !== hash) throw new Error("File changed while saving " + path);
|
|
54
53
|
renameSync(temp, dest);
|
|
55
54
|
} finally {
|
|
56
55
|
rmSync(temp, { force: true });
|
|
@@ -61,6 +60,7 @@ function saveFile(path: string, store: string, hash: string): void {
|
|
|
61
60
|
export function snapshotTree(root: string, store?: string, omit: ReadonlySet<string> = new Set()): SavedEntry[] {
|
|
62
61
|
if (!lstatSync(root).isDirectory()) throw new Error("Expected a directory at " + root);
|
|
63
62
|
const entries: SavedEntry[] = [];
|
|
63
|
+
const buffer = Buffer.allocUnsafe(128 * 1024);
|
|
64
64
|
function walk(parent: string): void {
|
|
65
65
|
for (const child of readdirSync(join(root, parent)).sort()) {
|
|
66
66
|
const name = join(parent, child);
|
|
@@ -74,8 +74,8 @@ export function snapshotTree(root: string, store?: string, omit: ReadonlySet<str
|
|
|
74
74
|
} else if (stat.isSymbolicLink()) {
|
|
75
75
|
entries.push({ name, mode, type: "symlink", target: readlinkSync(path) });
|
|
76
76
|
} else if (stat.isFile()) {
|
|
77
|
-
const blob = fileHash(path);
|
|
78
|
-
if (store) saveFile(path, store, blob);
|
|
77
|
+
const blob = fileHash(path, buffer);
|
|
78
|
+
if (store) saveFile(path, store, blob, buffer);
|
|
79
79
|
entries.push({ name, mode, type: "file", blob });
|
|
80
80
|
} else throw new Error("Cannot save special file " + path + ". The original is retained.");
|
|
81
81
|
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// Generated fixed launch domain from packages/pi-better-subagents/workspace-prepare-worker.mjs. Do not edit directly.
|
|
2
|
+
import { parentPort, workerData } from "node:worker_threads";
|
|
3
|
+
import { resolveSubagentWorkspace } from "./git-workspace.domain.mjs";
|
|
4
|
+
import { createIsolatedWorkspace } from "./isolated-workspace.domain.mjs";
|
|
5
|
+
const { options, isolated } = workerData;
|
|
6
|
+
if (isolated) {
|
|
7
|
+
const cwd = createIsolatedWorkspace(isolated, true);
|
|
8
|
+
parentPort.postMessage({ cwd, requestedSandboxDir: options.sandboxEnabled ? cwd : undefined });
|
|
9
|
+
}
|
|
10
|
+
else {
|
|
11
|
+
parentPort.postMessage(resolveSubagentWorkspace(options));
|
|
12
|
+
}
|