pi-better-background-tasks 0.13.1 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +67 -0
- package/package.json +3 -1
- package/src/adapter-contract.ts +16 -2
- package/src/batch.ts +108 -0
- package/src/delivery-observer.ts +42 -0
- package/src/goal-provider.ts +72 -5
- package/src/index.ts +39 -0
- package/src/navigator-provider.ts +175 -6
- package/src/observed-waits.ts +3677 -0
- package/src/runtime.ts +10 -0
- package/src/sandbox.ts +276 -2
- package/src/shared-execution-policy.ts +2 -0
- package/src/shared-operation-coordinator/index.ts +113 -0
- package/src/shared-operation-coordinator/src/errors.ts +75 -0
- package/src/shared-operation-coordinator/src/operations.ts +376 -0
- package/src/shared-operation-coordinator/src/outbox.ts +431 -0
- package/src/shared-operation-coordinator/src/rows.ts +439 -0
- package/src/shared-operation-coordinator/src/schema.ts +244 -0
- package/src/shared-operation-coordinator/src/sqlite.ts +239 -0
- package/src/shared-operation-coordinator/src/store.ts +397 -0
- package/src/shared-operation-coordinator/src/types.ts +648 -0
- package/src/shared-operation-coordinator/src/validate.ts +239 -0
- package/src/shared-operation-coordinator/src/waits.ts +1378 -0
- package/src/supervisor/README.md +111 -0
- package/src/supervisor/emit-runner.mjs +101 -0
- package/src/supervisor/generated/conditions.mjs +96 -0
- package/src/supervisor/generated/identity.mjs +95 -0
- package/src/supervisor/generated/process-identity.mjs +43 -0
- package/src/supervisor/generated/process.mjs +514 -0
- package/src/supervisor/generated/runner.mjs +872 -0
- package/src/supervisor/generated/store.mjs +605 -0
- package/src/supervisor/generated/types.mjs +50 -0
- package/src/supervisor/identity.ts +99 -0
- package/src/supervisor/index.ts +37 -0
- package/src/supervisor/invocation.ts +44 -0
- package/src/supervisor/runner.ts +982 -0
- package/src/supervisor/store.ts +649 -0
- package/src/supervisor/supervisor.ts +730 -0
- package/src/supervisor/types.ts +384 -0
- package/src/tools.ts +396 -9
- package/src/types.ts +8 -0
package/src/runtime.ts
CHANGED
|
@@ -169,6 +169,14 @@ export interface TaskIntentParams {
|
|
|
169
169
|
|
|
170
170
|
export interface SpawnTaskParams extends CommandSpec, TaskIntentParams {
|
|
171
171
|
name?: string;
|
|
172
|
+
/**
|
|
173
|
+
* Batch identity assigned by the batch launcher, never declared by a caller.
|
|
174
|
+
* Absent for a single spawn; carried into the persisted metadata so batch
|
|
175
|
+
* membership survives a reload instead of living only in the launch result.
|
|
176
|
+
*/
|
|
177
|
+
batchId?: string;
|
|
178
|
+
/** Batch label from the same launch, when the operator gave one. */
|
|
179
|
+
batchName?: string;
|
|
172
180
|
callback?: boolean;
|
|
173
181
|
timeout_seconds?: number;
|
|
174
182
|
max_log_bytes?: number;
|
|
@@ -346,6 +354,8 @@ export function spawnTask(
|
|
|
346
354
|
const meta = withCommandPolicy({
|
|
347
355
|
id,
|
|
348
356
|
name: params.name,
|
|
357
|
+
batchId: params.batchId,
|
|
358
|
+
batchName: params.batchName,
|
|
349
359
|
kind: "process",
|
|
350
360
|
status: "running",
|
|
351
361
|
startedAt: now,
|
package/src/sandbox.ts
CHANGED
|
@@ -27,11 +27,11 @@
|
|
|
27
27
|
|
|
28
28
|
import { accessSync, constants, mkdirSync, realpathSync, statSync } from "node:fs";
|
|
29
29
|
import { homedir } from "node:os";
|
|
30
|
-
import { delimiter, dirname, resolve } from "node:path";
|
|
30
|
+
import { delimiter, dirname, isAbsolute, resolve } from "node:path";
|
|
31
31
|
|
|
32
32
|
import { commandExecution } from "./process.js";
|
|
33
33
|
import { baseDir } from "./registry.js";
|
|
34
|
-
import { compileWritePolicy, describeSandboxSupport, directApplicationTarget, maybeBuildSandboxCommand, type SandboxSeams } from "./shared-sandbox-core.js";
|
|
34
|
+
import { canonicalizePath, compileWritePolicy, describeSandboxSupport, directApplicationTarget, maybeBuildSandboxCommand, type SandboxSeams } from "./shared-sandbox-core.js";
|
|
35
35
|
|
|
36
36
|
type SandboxPermissions = {
|
|
37
37
|
/** `write` = read, create and overwrite in place; `read-write` = Write & delete. */
|
|
@@ -455,6 +455,280 @@ export function planFor(policy: ForegroundSandboxPolicy | undefined): Foreground
|
|
|
455
455
|
...(permissions ? { permissions } : {}) };
|
|
456
456
|
}
|
|
457
457
|
|
|
458
|
+
/**
|
|
459
|
+
* The parent-captured task authority a worker conversation launches background
|
|
460
|
+
* tasks under.
|
|
461
|
+
*
|
|
462
|
+
* This is a structural subset of the Subagents task policy and is declared here
|
|
463
|
+
* on purpose: `pi-better-background-tasks` must keep working when the Subagents
|
|
464
|
+
* package is absent, so it never imports that package. The parent supplies the
|
|
465
|
+
* object from the policy it captured at worker launch; it is never built from
|
|
466
|
+
* model tool arguments, so a child cannot widen its own authority by asking for
|
|
467
|
+
* a different profile. The object is treated as immutable; the resolved plan is
|
|
468
|
+
* a copy that later changes to the source cannot alter.
|
|
469
|
+
*
|
|
470
|
+
* A present `root` means the worker was confined. An unconfined worker (the
|
|
471
|
+
* `sandbox:false` opt-out) has no captured task authority and passes `undefined`
|
|
472
|
+
* (or `null`). A `PermissionProfile`-shaped source may also express that with
|
|
473
|
+
* `permissions.enabled === false`.
|
|
474
|
+
*
|
|
475
|
+
* Supported intersection contract:
|
|
476
|
+
*
|
|
477
|
+
* - No worker authority: the current Background tasks profile applies unchanged.
|
|
478
|
+
* - Worker confined, Background tasks off: the worker's confinement and settings
|
|
479
|
+
* are preserved exactly.
|
|
480
|
+
* - Both confined, same canonical root: project/outside/credential levels take
|
|
481
|
+
* the weaker side, commands/network/shell are ANDed, the command cap is the
|
|
482
|
+
* smaller one, and deny paths are unioned.
|
|
483
|
+
* - Both confined with different canonical roots, or either confined side
|
|
484
|
+
* publishing no permission levels to intersect, refuses the launch. Dropping
|
|
485
|
+
* one side's file or command rules would be a weaker profile than either
|
|
486
|
+
* owner approved.
|
|
487
|
+
*/
|
|
488
|
+
export interface WorkerSandboxPolicy {
|
|
489
|
+
/** Canonical project directory the parent confined the worker to. */
|
|
490
|
+
readonly root: string;
|
|
491
|
+
readonly permissions?: WorkerSandboxPermissions;
|
|
492
|
+
/** Concrete paths that stay non-writable inside `root`. */
|
|
493
|
+
readonly denyWrite?: readonly string[];
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/** The capability levels and command switches a worker was launched with. */
|
|
497
|
+
export interface WorkerSandboxPermissions {
|
|
498
|
+
readonly projectFiles: "off" | "read" | "write" | "read-write";
|
|
499
|
+
readonly outsideProject: "off" | "read" | "write" | "read-write";
|
|
500
|
+
readonly storedCredentials: "off" | "read" | "read-write";
|
|
501
|
+
readonly commands: boolean;
|
|
502
|
+
readonly network: boolean;
|
|
503
|
+
readonly shell?: boolean;
|
|
504
|
+
readonly commandTimeoutSeconds?: number | null;
|
|
505
|
+
/** Present only on a `PermissionProfile`-shaped source; false = not confined. */
|
|
506
|
+
readonly enabled?: boolean;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/** Thrown when a parent-supplied worker policy is malformed; nothing was launched. */
|
|
510
|
+
export class InvalidWorkerSandboxPolicyError extends Error {
|
|
511
|
+
constructor(detail: string) {
|
|
512
|
+
super(`Invalid worker sandbox policy: ${detail}`);
|
|
513
|
+
this.name = "InvalidWorkerSandboxPolicyError";
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
const FILE_ACCESS_RANK = Object.freeze({ off: 0, read: 1, write: 2, "read-write": 3 } as const);
|
|
518
|
+
const CREDENTIAL_ACCESS_RANK = Object.freeze({ off: 0, read: 1, "read-write": 2 } as const);
|
|
519
|
+
|
|
520
|
+
type WorkerAuthority =
|
|
521
|
+
| { readonly confined: false }
|
|
522
|
+
| { readonly confined: true; readonly root: string; readonly denyWrite: readonly string[]; readonly permissions?: SandboxPermissions };
|
|
523
|
+
|
|
524
|
+
/**
|
|
525
|
+
* Validate and normalize the parent-captured authority before anything else
|
|
526
|
+
* happens. Levels are checked as a whole profile so a typo cannot narrow itself
|
|
527
|
+
* silently, and a relative root or deny entry is refused rather than resolved
|
|
528
|
+
* against Pi's own cwd.
|
|
529
|
+
*/
|
|
530
|
+
function readWorkerAuthority(value: WorkerSandboxPolicy | null | undefined): WorkerAuthority {
|
|
531
|
+
if (value === null || value === undefined) return { confined: false };
|
|
532
|
+
if (typeof value !== "object" || Array.isArray(value)) {
|
|
533
|
+
throw new InvalidWorkerSandboxPolicyError("the parent-captured policy must be an object.");
|
|
534
|
+
}
|
|
535
|
+
const raw = value as unknown as Record<string, unknown>;
|
|
536
|
+
if (typeof raw.root !== "string" || raw.root.length === 0 || !isAbsolute(raw.root)) {
|
|
537
|
+
throw new InvalidWorkerSandboxPolicyError("root must be an absolute path.");
|
|
538
|
+
}
|
|
539
|
+
const root = canonicalizePath(raw.root);
|
|
540
|
+
if (root === dirname(root) || root === canonicalizePath(homedir())) {
|
|
541
|
+
throw new InvalidWorkerSandboxPolicyError("root must be a project directory, not the filesystem or home root.");
|
|
542
|
+
}
|
|
543
|
+
const denyWrite = raw.denyWrite;
|
|
544
|
+
if (denyWrite !== undefined && (!Array.isArray(denyWrite) ||
|
|
545
|
+
!denyWrite.every((entry) => typeof entry === "string" && isAbsolute(entry)))) {
|
|
546
|
+
throw new InvalidWorkerSandboxPolicyError("denyWrite must be a list of absolute paths.");
|
|
547
|
+
}
|
|
548
|
+
const deny = Object.freeze([...new Set((denyWrite as string[] | undefined) ?? [])]);
|
|
549
|
+
|
|
550
|
+
if (raw.permissions === undefined) {
|
|
551
|
+
return { confined: true, root, denyWrite: deny };
|
|
552
|
+
}
|
|
553
|
+
const source = raw.permissions;
|
|
554
|
+
if (!source || typeof source !== "object" || Array.isArray(source)) {
|
|
555
|
+
throw new InvalidWorkerSandboxPolicyError("permissions must be an object.");
|
|
556
|
+
}
|
|
557
|
+
const p = source as Record<string, unknown>;
|
|
558
|
+
if (p.enabled !== undefined && typeof p.enabled !== "boolean") {
|
|
559
|
+
throw new InvalidWorkerSandboxPolicyError("permissions.enabled must be a boolean.");
|
|
560
|
+
}
|
|
561
|
+
// A PermissionProfile that is not enabled grants no task authority at all.
|
|
562
|
+
if (p.enabled === false) return { confined: false };
|
|
563
|
+
if (typeof p.projectFiles !== "string" || !Object.hasOwn(FILE_ACCESS_RANK, p.projectFiles)) {
|
|
564
|
+
throw new InvalidWorkerSandboxPolicyError("permissions.projectFiles must be off, read, write or read-write.");
|
|
565
|
+
}
|
|
566
|
+
if (typeof p.outsideProject !== "string" || !Object.hasOwn(FILE_ACCESS_RANK, p.outsideProject)) {
|
|
567
|
+
throw new InvalidWorkerSandboxPolicyError("permissions.outsideProject must be off, read, write or read-write.");
|
|
568
|
+
}
|
|
569
|
+
if (typeof p.storedCredentials !== "string" || !Object.hasOwn(CREDENTIAL_ACCESS_RANK, p.storedCredentials)) {
|
|
570
|
+
throw new InvalidWorkerSandboxPolicyError("permissions.storedCredentials must be off, read or read-write.");
|
|
571
|
+
}
|
|
572
|
+
if (typeof p.commands !== "boolean") {
|
|
573
|
+
throw new InvalidWorkerSandboxPolicyError("permissions.commands must be a boolean.");
|
|
574
|
+
}
|
|
575
|
+
if (typeof p.network !== "boolean") {
|
|
576
|
+
throw new InvalidWorkerSandboxPolicyError("permissions.network must be a boolean.");
|
|
577
|
+
}
|
|
578
|
+
if (p.shell !== undefined && typeof p.shell !== "boolean") {
|
|
579
|
+
throw new InvalidWorkerSandboxPolicyError("permissions.shell must be a boolean.");
|
|
580
|
+
}
|
|
581
|
+
if (p.commandTimeoutSeconds !== undefined && p.commandTimeoutSeconds !== null && !isCommandTimeoutSeconds(p.commandTimeoutSeconds)) {
|
|
582
|
+
throw new InvalidWorkerSandboxPolicyError(`permissions.commandTimeoutSeconds must be null or a positive, finite number of seconds up to ${MAX_COMMAND_TIMEOUT_SECONDS}.`);
|
|
583
|
+
}
|
|
584
|
+
const permissions: SandboxPermissions = {
|
|
585
|
+
projectFiles: p.projectFiles as SandboxPermissions["projectFiles"],
|
|
586
|
+
outsideProject: p.outsideProject as SandboxPermissions["outsideProject"],
|
|
587
|
+
storedCredentials: p.storedCredentials as SandboxPermissions["storedCredentials"],
|
|
588
|
+
commands: p.commands,
|
|
589
|
+
network: p.network,
|
|
590
|
+
...(p.shell === undefined ? {} : { shell: p.shell }),
|
|
591
|
+
...(p.commandTimeoutSeconds === undefined ? {} : { commandTimeoutSeconds: p.commandTimeoutSeconds as number | null }),
|
|
592
|
+
};
|
|
593
|
+
return { confined: true, root, denyWrite: deny, permissions: Object.freeze(permissions) };
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/** The weaker of two file-access levels; deletion is never broader than writes. */
|
|
597
|
+
function weakerFileAccess(
|
|
598
|
+
a: SandboxPermissions["projectFiles"],
|
|
599
|
+
b: SandboxPermissions["projectFiles"],
|
|
600
|
+
): SandboxPermissions["projectFiles"] {
|
|
601
|
+
return FILE_ACCESS_RANK[a] <= FILE_ACCESS_RANK[b] ? a : b;
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
function weakerCredentialAccess(
|
|
605
|
+
a: SandboxPermissions["storedCredentials"],
|
|
606
|
+
b: SandboxPermissions["storedCredentials"],
|
|
607
|
+
): SandboxPermissions["storedCredentials"] {
|
|
608
|
+
return CREDENTIAL_ACCESS_RANK[a] <= CREDENTIAL_ACCESS_RANK[b] ? a : b;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/** Intersect two already-validated capability profiles. */
|
|
612
|
+
function intersectPermissions(background: SandboxPermissions, worker: SandboxPermissions): SandboxPermissions {
|
|
613
|
+
const backgroundCap = isCommandTimeoutSeconds(background.commandTimeoutSeconds) ? background.commandTimeoutSeconds : undefined;
|
|
614
|
+
const workerCap = isCommandTimeoutSeconds(worker.commandTimeoutSeconds) ? worker.commandTimeoutSeconds : undefined;
|
|
615
|
+
const cap = backgroundCap === undefined ? workerCap
|
|
616
|
+
: workerCap === undefined ? backgroundCap : Math.min(backgroundCap, workerCap);
|
|
617
|
+
const shellGiven = background.shell !== undefined || worker.shell !== undefined;
|
|
618
|
+
const capGiven = background.commandTimeoutSeconds !== undefined || worker.commandTimeoutSeconds !== undefined;
|
|
619
|
+
return Object.freeze({
|
|
620
|
+
projectFiles: weakerFileAccess(background.projectFiles, worker.projectFiles),
|
|
621
|
+
outsideProject: weakerFileAccess(background.outsideProject, worker.outsideProject),
|
|
622
|
+
storedCredentials: weakerCredentialAccess(background.storedCredentials, worker.storedCredentials),
|
|
623
|
+
commands: background.commands && worker.commands,
|
|
624
|
+
network: background.network && worker.network,
|
|
625
|
+
...(shellGiven ? { shell: background.shell !== false && worker.shell !== false } : {}),
|
|
626
|
+
...(capGiven ? { commandTimeoutSeconds: cap ?? null } : {}),
|
|
627
|
+
});
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/**
|
|
631
|
+
* The policy snapshot stored behind a worker-authored plan, so provenance and
|
|
632
|
+
* {@link backgroundExecutionLimits} read the effective authority rather than
|
|
633
|
+
* the parent's published profile.
|
|
634
|
+
*/
|
|
635
|
+
function workerPlanPolicy(
|
|
636
|
+
plan: { readonly writableRoot: string; readonly denyWrite: readonly string[]; readonly permissions?: SandboxPermissions },
|
|
637
|
+
reason: string,
|
|
638
|
+
): ForegroundSandboxPolicy {
|
|
639
|
+
return Object.freeze({
|
|
640
|
+
state: "enabled",
|
|
641
|
+
writableRoot: plan.writableRoot,
|
|
642
|
+
denyWrite: Object.freeze([...plan.denyWrite]),
|
|
643
|
+
reason,
|
|
644
|
+
...(plan.permissions ? { permissions: Object.freeze({ ...plan.permissions, enabled: true }) } : {}),
|
|
645
|
+
policySource: "background",
|
|
646
|
+
});
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/**
|
|
650
|
+
* Resolve how a worker-launched local background task must be confined.
|
|
651
|
+
*
|
|
652
|
+
* The effective authority is always the worker's captured task authority and
|
|
653
|
+
* the current Background tasks profile, never the parent session's sibling Main
|
|
654
|
+
* profile. When the publisher sends a Background column this reads that column;
|
|
655
|
+
* a legacy publisher with one profile keeps its historical meaning, which is
|
|
656
|
+
* already what Background tasks enforce.
|
|
657
|
+
*
|
|
658
|
+
* Validation runs before any task state exists. A malformed policy, an invalid
|
|
659
|
+
* command cap or level, a disabled worker command capability, differing
|
|
660
|
+
* canonical roots, or an unsupported intersection refuses the launch instead of
|
|
661
|
+
* dropping a rule. The returned plan is an immutable snapshot: it is captured
|
|
662
|
+
* through {@link capturePlan} so later command checks and
|
|
663
|
+
* {@link backgroundExecutionLimits} keep the authority this launch started with.
|
|
664
|
+
*/
|
|
665
|
+
export function resolveWorkerSandboxPlan(
|
|
666
|
+
pi: unknown,
|
|
667
|
+
workerPolicy?: WorkerSandboxPolicy | null,
|
|
668
|
+
operation?: unknown,
|
|
669
|
+
tool = "bg_task_spawn",
|
|
670
|
+
): ForegroundSandboxPlan {
|
|
671
|
+
const background = currentForegroundSandboxPolicy(pi);
|
|
672
|
+
let worker: WorkerAuthority;
|
|
673
|
+
try {
|
|
674
|
+
worker = readWorkerAuthority(workerPolicy);
|
|
675
|
+
} catch (error) {
|
|
676
|
+
backgroundDiagnostics(background)?.observe({ tool, operation, resource: "sandbox-backend", basis: "policy-refusal", outcome: "denied" });
|
|
677
|
+
throw error;
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
// No captured authority: the current Background tasks profile is the whole
|
|
681
|
+
// answer, exactly as it is for a parent-launched task.
|
|
682
|
+
if (!worker.confined) return capturePlan(planFor(background), background);
|
|
683
|
+
|
|
684
|
+
// Commands Off is the worker's master switch, independent of Background being
|
|
685
|
+
// on or off. It is checked before any plan is built.
|
|
686
|
+
if (worker.permissions && !worker.permissions.commands) {
|
|
687
|
+
const snapshot = { writableRoot: worker.root, denyWrite: worker.denyWrite, permissions: worker.permissions };
|
|
688
|
+
const policy = workerPlanPolicy(snapshot, "The worker task authority disables commands.");
|
|
689
|
+
backgroundDiagnostics(background)?.observe({ tool, operation, resource: "command-execution", basis: "policy-refusal", outcome: "denied" });
|
|
690
|
+
throw new ForegroundSandboxBlockedError(policy,
|
|
691
|
+
"The worker task authority disables commands. Change the Subagents permissions before launching background tasks.");
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
const backgroundOff = !background || background.state === "inactive" || background.state === "disabled";
|
|
695
|
+
if (backgroundOff) {
|
|
696
|
+
// Preserve the worker's own confinement even though no Background profile is
|
|
697
|
+
// enforcing anything. Its settings are copied, never linked to the source.
|
|
698
|
+
const plan = {
|
|
699
|
+
confined: true as const,
|
|
700
|
+
writableRoot: worker.root,
|
|
701
|
+
denyWrite: Object.freeze([...worker.denyWrite]),
|
|
702
|
+
...(worker.permissions ? { permissions: worker.permissions } : {}),
|
|
703
|
+
};
|
|
704
|
+
return capturePlan(plan, workerPlanPolicy(plan, "Worker task authority applies; the Background tasks profile is off."));
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
try {
|
|
708
|
+
const base = planFor(background);
|
|
709
|
+
if (!base.confined) throw new Error("Worker sandbox resolution expected a confined Background tasks plan.");
|
|
710
|
+
const backgroundRoot = canonicalizePath(base.writableRoot);
|
|
711
|
+
if (backgroundRoot !== worker.root) {
|
|
712
|
+
throw new ForegroundSandboxBlockedError(background,
|
|
713
|
+
`Cannot intersect the Background tasks root ${JSON.stringify(backgroundRoot)} with the worker root ${JSON.stringify(worker.root)}: they confine different directories, so a correct intersection cannot be constructed. Refusing rather than dropping either side's rules.`);
|
|
714
|
+
}
|
|
715
|
+
if (!base.permissions || !worker.permissions) {
|
|
716
|
+
throw new ForegroundSandboxBlockedError(background,
|
|
717
|
+
`Cannot intersect the Background tasks profile with the worker task authority because ${base.permissions ? "the worker" : "the Background tasks profile"} publishes no permission levels (file access, commands, network). Refusing rather than dropping the other side's controls; update the sandbox packages or set permissions in /sandbox.`);
|
|
718
|
+
}
|
|
719
|
+
const permissions = intersectPermissions(base.permissions, worker.permissions);
|
|
720
|
+
const denyWrite = Object.freeze([...new Set([...base.denyWrite, ...worker.denyWrite])]);
|
|
721
|
+
const plan = { confined: true as const, writableRoot: backgroundRoot, denyWrite, permissions };
|
|
722
|
+
return capturePlan(plan, workerPlanPolicy(plan,
|
|
723
|
+
"Worker task authority intersected with the Background tasks profile (weaker levels, ANDed switches, smallest cap, deny paths unioned)."));
|
|
724
|
+
} catch (error) {
|
|
725
|
+
if (error instanceof ForegroundSandboxBlockedError) {
|
|
726
|
+
backgroundDiagnostics(background)?.observe({ tool, operation, resource: "sandbox-backend", basis: "policy-refusal", outcome: "denied" });
|
|
727
|
+
}
|
|
728
|
+
throw error;
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
|
|
458
732
|
/**
|
|
459
733
|
* The application, shell, and time switches captured with one launch plan.
|
|
460
734
|
*
|
|
@@ -7,6 +7,8 @@ const EXECUTION_POLICY = [
|
|
|
7
7
|
"Serialize only for a concrete dependency, conflicting writes or ownership, resource or concurrency limit, documented rollout gate, or explicit availability requirement. Record the reason in the plan or explain it to the user. Do not invent a canary or host-by-host availability requirement.",
|
|
8
8
|
"If concurrency raises an unresolved material operational trade-off (for example, draining all hosts could leave no available runners), ask the user once before the affected operations. Continue independent preparation meanwhile. Existing authorization, safety checks, workflow prerequisites, and human-approved rollout constraints remain binding; urgency does not waive them.",
|
|
9
9
|
"Choose the execution mechanism after deciding what can run together: foreground tools for small, tightly coupled, or interactive work; subagents for bounded independent reasoning or implementation when the active delegation mode permits; background tasks for independent long-running commands or waits. Manual delegation forbids proactive subagents, not concurrent foreground tools or background commands. Use available batch or parallel tool interfaces where appropriate and inspect every launch receipt for failures or skipped work.",
|
|
10
|
+
"Established command-only jobs and external waits belong to background operations, including in coordinator mode. Use bg_task_spawn for a long command and bg_task_watch for a repeated check; use watch_delivery for supported merge delivery so a stateful domain watcher observes the queue. A subagent assignment must require reasoning or implementation beyond launching and waiting. Workers retain their assigned validation: use supervised background tools and wait_for_operations to park, then resume the same conversation to interpret and acknowledge the terminal result. A linked external wait must have a registered observer and an execution owner. Continue independent work while it runs; a task launch or a completed parked attempt is not completion of the assignment.",
|
|
11
|
+
"If a worker hands back a command, the coordinator launches it through background tools with the supplied cwd and inspects its terminal result before claiming verification. Workers may run focused implementation checks; moving a command to a worker does not make it a background task.",
|
|
10
12
|
"A unit waiting or failing does not block other ready independent units unless the evidence shows a shared blocker. Preserve each unit's guards and rollback boundary. Before completing verification, the plan, or the goal, inspect and integrate every relevant terminal result or failure; launch is not completion.",
|
|
11
13
|
].join("\n");
|
|
12
14
|
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// Generated from packages/operation-coordinator/index.ts. Do not edit directly.
|
|
2
|
+
/**
|
|
3
|
+
* Durable operation coordinator.
|
|
4
|
+
*
|
|
5
|
+
* A small, reusable library that records what a harness is waiting for and who
|
|
6
|
+
* owns the result. It provides no provider transport, no process launch, no tool
|
|
7
|
+
* execution and no model call: Background Tasks, Subagents and the parent
|
|
8
|
+
* harness share these records instead of duplicating a journal.
|
|
9
|
+
*
|
|
10
|
+
* The contracts here implement the accepted invariant in
|
|
11
|
+
* `docs/adr/0020-observed-waits-retain-an-owner.md` and the record shapes in
|
|
12
|
+
* `docs/plans/observed-waits-design.md`.
|
|
13
|
+
*
|
|
14
|
+
* ```ts
|
|
15
|
+
* import { openStore } from "operation-coordinator";
|
|
16
|
+
*
|
|
17
|
+
* const store = openStore({ path: join(agentDir, "operation-coordinator.sqlite") });
|
|
18
|
+
* store.registerOperation({ operationId, taskId, launchToken, owner, observer });
|
|
19
|
+
* // later, from the supervisor:
|
|
20
|
+
* store.recordTerminalOutcome({ operationId, eventId, outcome: "succeeded", owner, evidence });
|
|
21
|
+
* // the owner interprets the evidence it read, then consumes the wait:
|
|
22
|
+
* store.recordEvidenceRead({ waitId, generation, owner, operationId, terminalRevision: 1 });
|
|
23
|
+
* store.acknowledgeResult({ waitId, generation, owner, disposition: "continue", note, terminalRevisions });
|
|
24
|
+
* ```
|
|
25
|
+
*
|
|
26
|
+
* Rules the store enforces by itself:
|
|
27
|
+
*
|
|
28
|
+
* - an owner, task id and launch token are immutable once registered;
|
|
29
|
+
* - one durable operation per background task, and one pending wait generation
|
|
30
|
+
* per owner identity;
|
|
31
|
+
* - a parked worker reaches `waiting`/`ready` only with checkpoint and writer
|
|
32
|
+
* exit proof, and a dependency that settled earlier is never missed;
|
|
33
|
+
* - duplicate terminal events and replayed reconciliation produce one terminal
|
|
34
|
+
* revision and one delivery per wait generation;
|
|
35
|
+
* - resume attempt ids and launch tokens are persisted before spawn, and one
|
|
36
|
+
* generation has one active claim;
|
|
37
|
+
* - cancellation increments a fencing epoch and invalidates the pending claim;
|
|
38
|
+
* - an acknowledgement requires a recorded read of the exact evidence revision by
|
|
39
|
+
* the owner, and only then are evidence pins released;
|
|
40
|
+
* - no credential, token value or environment value is stored; obvious secret
|
|
41
|
+
* material in a note or reference is refused.
|
|
42
|
+
*
|
|
43
|
+
* `node:sqlite` (Node 24+) is required. There is no in-memory fallback: an
|
|
44
|
+
* unavailable or unreadable database disables the feature instead of pretending
|
|
45
|
+
* to be durable.
|
|
46
|
+
*/
|
|
47
|
+
export { SCHEMA_VERSION, TERMINAL_WAIT_PHASES } from "./src/types.ts";
|
|
48
|
+
export type {
|
|
49
|
+
AcknowledgeDisposition,
|
|
50
|
+
AcknowledgeResultInput,
|
|
51
|
+
AcknowledgeResultOutput,
|
|
52
|
+
CancelWaitInput,
|
|
53
|
+
CancelWaitResult,
|
|
54
|
+
ClaimOutboxInput,
|
|
55
|
+
ClaimResumeInput,
|
|
56
|
+
EvidenceKind,
|
|
57
|
+
EvidencePinRecord,
|
|
58
|
+
EvidenceReadRecord,
|
|
59
|
+
EvidenceRefInput,
|
|
60
|
+
HoldFailedResumeInput,
|
|
61
|
+
HoldFailedResumeResult,
|
|
62
|
+
ObserverHealth,
|
|
63
|
+
ObserverIdentity,
|
|
64
|
+
OperationEvidenceRecord,
|
|
65
|
+
OperationFilter,
|
|
66
|
+
OperationPhase,
|
|
67
|
+
OperationRecord,
|
|
68
|
+
OutboxDispatchClaim,
|
|
69
|
+
OutboxDispatchInput,
|
|
70
|
+
OutboxEventRecord,
|
|
71
|
+
OutboxFilter,
|
|
72
|
+
OutboxState,
|
|
73
|
+
OwnerIdentity,
|
|
74
|
+
OwnerKind,
|
|
75
|
+
PublishResumeAttemptInput,
|
|
76
|
+
PublishResumeAttemptResult,
|
|
77
|
+
RecordEvidencePinInput,
|
|
78
|
+
RecordEvidencePinResult,
|
|
79
|
+
RecordEvidenceReadInput,
|
|
80
|
+
RecordEvidenceReadResult,
|
|
81
|
+
RecordSupervisionInput,
|
|
82
|
+
RecordTerminalOutcomeInput,
|
|
83
|
+
RecordTerminalOutcomeResult,
|
|
84
|
+
RegisterOperationInput,
|
|
85
|
+
RegisterOperationResult,
|
|
86
|
+
RegisterWaitInput,
|
|
87
|
+
RegisterWaitResult,
|
|
88
|
+
ReleaseOutboxInput,
|
|
89
|
+
ReleaseResumeClaimInput,
|
|
90
|
+
ReleaseResumeClaimResult,
|
|
91
|
+
ResumeClaimFilter,
|
|
92
|
+
ResumeClaimRecord,
|
|
93
|
+
ResumeClaimResult,
|
|
94
|
+
ResumeClaimState,
|
|
95
|
+
ResumeLeaseIdentity,
|
|
96
|
+
StoreOptions,
|
|
97
|
+
SupervisionIdentity,
|
|
98
|
+
TerminalOutcome,
|
|
99
|
+
TransitionWaitPhaseInput,
|
|
100
|
+
TransitionWaitPhaseResult,
|
|
101
|
+
WaitAcknowledgement,
|
|
102
|
+
WaitDependencyInput,
|
|
103
|
+
WaitDependencyRecord,
|
|
104
|
+
WaitFilter,
|
|
105
|
+
WaitParkIntent,
|
|
106
|
+
WaitPhase,
|
|
107
|
+
WaitRecord,
|
|
108
|
+
WaitRef,
|
|
109
|
+
} from "./src/types.ts";
|
|
110
|
+
export { StoreError, isStoreError } from "./src/errors.ts";
|
|
111
|
+
export type { StoreErrorCode } from "./src/errors.ts";
|
|
112
|
+
export { openStore, ownerDiff } from "./src/store.ts";
|
|
113
|
+
export type { Store } from "./src/store.ts";
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// Generated from packages/operation-coordinator/src/errors.ts. Do not edit directly.
|
|
2
|
+
/**
|
|
3
|
+
* Refusals from the durable operation coordinator.
|
|
4
|
+
*
|
|
5
|
+
* Every refusal is a typed `code` so a transport can turn it into a specific
|
|
6
|
+
* model-facing reason instead of a generic failure. A refusal never leaves a
|
|
7
|
+
* partial record: all writes run inside one immediate transaction.
|
|
8
|
+
*/
|
|
9
|
+
export type StoreErrorCode =
|
|
10
|
+
/** The database was written by another schema version. Records are left untouched. */
|
|
11
|
+
| "schema-version"
|
|
12
|
+
/** This runtime has no `node:sqlite`, so durability cannot be promised. */
|
|
13
|
+
| "sqlite-unavailable"
|
|
14
|
+
/** Another process holds the write lock for longer than the configured budget. */
|
|
15
|
+
| "store-busy"
|
|
16
|
+
/** A stored row could not be parsed back into its record shape. */
|
|
17
|
+
| "store-corruption"
|
|
18
|
+
/** Caller input is malformed, out of bounds, or looks like credential material. */
|
|
19
|
+
| "validation"
|
|
20
|
+
/** The operation id is not registered in this store. */
|
|
21
|
+
| "unknown-operation"
|
|
22
|
+
/** An operation already exists with different immutable launch identity. */
|
|
23
|
+
| "operation-conflict"
|
|
24
|
+
/** The background task id belongs to a different owner. */
|
|
25
|
+
| "task-ownership"
|
|
26
|
+
/** The caller is not the recorded owner of the record it wants to change. */
|
|
27
|
+
| "foreign-owner"
|
|
28
|
+
/** A different terminal event is already recorded for this operation. */
|
|
29
|
+
| "terminal-conflict"
|
|
30
|
+
/** The owner already has a pending wait generation. */
|
|
31
|
+
| "pending-wait-generation"
|
|
32
|
+
/** The wait id / generation is not registered in this store. */
|
|
33
|
+
| "unknown-wait"
|
|
34
|
+
/** The requested wait phase transition is not allowed from the current phase. */
|
|
35
|
+
| "wait-phase"
|
|
36
|
+
/** The caller's view of the current phase is out of date (out-of-order call). */
|
|
37
|
+
| "stale-phase"
|
|
38
|
+
/** The caller addressed a generation that is not the current one. */
|
|
39
|
+
| "stale-generation"
|
|
40
|
+
/** The caller's cancellation epoch is out of date; the wait changed underneath. */
|
|
41
|
+
| "stale-cancel-epoch"
|
|
42
|
+
/** Not every dependency has a terminal outcome yet. */
|
|
43
|
+
| "dependencies-unsettled"
|
|
44
|
+
/** A parked wait tried to reach waiting/ready without checkpoint and writer proof. */
|
|
45
|
+
| "checkpoint-proof"
|
|
46
|
+
/** A published resume cannot be held without proven writer exit and a free lease. */
|
|
47
|
+
| "resume-proof"
|
|
48
|
+
/** Another resume claim is already active for this wait generation. */
|
|
49
|
+
| "concurrent-claim"
|
|
50
|
+
/** The resume claim is not in a state that allows the requested step. */
|
|
51
|
+
| "claim-state"
|
|
52
|
+
/** The attempt id is already published by another resume claim. */
|
|
53
|
+
| "attempt-conflict"
|
|
54
|
+
/** The owner must record reading the exact terminal evidence before acknowledging. */
|
|
55
|
+
| "evidence-read-required"
|
|
56
|
+
/** The acknowledged evidence revision is not the dependency's terminal revision. */
|
|
57
|
+
| "stale-evidence"
|
|
58
|
+
/** The outbox event is not in a state that allows the requested step. */
|
|
59
|
+
| "outbox-state"
|
|
60
|
+
/** The store has been closed. */
|
|
61
|
+
| "closed";
|
|
62
|
+
|
|
63
|
+
export class StoreError extends Error {
|
|
64
|
+
readonly code: StoreErrorCode;
|
|
65
|
+
|
|
66
|
+
constructor(code: StoreErrorCode, message: string) {
|
|
67
|
+
super(message);
|
|
68
|
+
this.name = "StoreError";
|
|
69
|
+
this.code = code;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function isStoreError(error: unknown): error is StoreError {
|
|
74
|
+
return error instanceof StoreError;
|
|
75
|
+
}
|