UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

922 lines • 74.2 kB
import type { AgentTool, ExecutionEnv } from "../internal/harness.js";
import type { ToolEffect } from "./types.js";
import { type BackgroundHardKillOutcome, type BackgroundShellCapability, type BackgroundShellId } from "./background-shell.js";
import type { BoundaryLegsGiven } from "./cross-boundary-taint.js";
import { type WorkflowRunStore } from "./workflow-run-store.js";
import type { WorkflowAgentStopReceipt } from "../orchestration/workflow-types.js";
import type { WorkflowRunStopReceipt } from "../orchestration/workflow-stop.js";
import type { WorkflowJournalStore } from "./workflow-journal-store.js";
import type { CheckpointStore } from "./checkpoint-store.js";
import { type BackgroundAgentRecord, type BackgroundAgentSettledStatus, type BackgroundAgentStore } from "./background-agent-store.js";
import type { TaskNotificationPayload } from "./task-notification.js";
import type { ExtensionRequester } from "./task-event.js";
import { type TaskArtifactSeat } from "./tool-result-store.js";
import { type SemaTaskType, type StopSource, type SemaTaskStatus, type TaskRetrievalStatus, type UnifiedTaskOutput, type UnifiedTaskResult, type SemaTaskHandle, type TaskAccess, type BackgroundAgentTaskHandle, type MonitorTimers, type RegisterMonitorInput, type RegisterWorkflowInput, type RegisterPeerTaskInput, type PeerTaskTaskHandle, canAccessWorkflowRun, clipTaskOutput, MONITOR_BATCH_WINDOW_MS, MONITOR_DEFAULT_TIMEOUT_MS, MONITOR_MAX_TIMEOUT_MS, MONITOR_MAX_BATCHES_PER_MINUTE, type OccupantMount } from "./task-registry-shared.js";
export { SEMA_TASK_TYPES, SEMA_TASK_HANDLE_PREFIXES, PEER_TASK_HANDLE_RE, normalizeAgentName, DURABLE_AGENT_HEARTBEAT_MS, DURABLE_AGENT_HANDLE_RE, BG_AGENT_REAP_STOP_ERROR, engineAgentName, chosenAgentName, PARKED_CLAIM_ROLLBACKS, PARKED_CLAIM_ROLLBACK_FACE } from "./task-registry-shared.js";
export type { ParkedClaimTicket, ParkedClaimRollback, RegisterBackgroundAgentInput, BackgroundUnyieldableReason, BackgroundYieldLane, BackgroundYieldOptions, BackgroundYieldReport } from "./task-registry-shared.js";
import type { RegisterBackgroundAgentInput, ParkedClaimTicket, ParkedClaimRollback, ChildSessionStore, LandedAgentTerminal, BackgroundYieldOptions, BackgroundYieldReport } from "./task-registry-shared.js";
import type { ChildSessionAnchor } from "./task-registry-agent.js";
import { type RunEndCause } from "./member-outcome.js";
import { type DelegationOccupant, type DelegationRowAddress } from "./task-registry-agent.js";
import { type AgentStateSource } from "./agent-state.js";
import type { CheckpointSeat } from "./checkpoint-seat.js";
export type { SemaTaskType, StopSource, SemaTaskStatus, TaskRetrievalStatus, UnifiedTaskOutput, SemaTaskHandle, TaskAccess, MonitorTimers, RegisterMonitorInput, RegisterWorkflowInput, };
export { canAccessWorkflowRun, clipTaskOutput, MONITOR_BATCH_WINDOW_MS, MONITOR_DEFAULT_TIMEOUT_MS, MONITOR_MAX_TIMEOUT_MS, MONITOR_MAX_BATCHES_PER_MINUTE };
export interface TaskKind {
    type: SemaTaskType;
    effect: ToolEffect;
}
export interface RegisterBackgroundBashInput extends TaskAccess {
    shellId: BackgroundShellId;
    env: ExecutionEnv & BackgroundShellCapability;
    description?: string;
    toolUseId?: string;
    id?: string;
    now?: number;
    /** (design/129 discipline): session-resident background bash — `owner` MUST be the
     *  sessionId (a later turn's fresh per-turn owner reaches it via `access.sessionId`). Survives the
     *  run teardown (settle/evict skip + dispose except-list); terminal anchor = `reapSessionBackground`. */
    sessionScoped?: true;
    /** design/116 §7 G2b: when set, the registry WATCHES the process (1s poll, increments spooled with a
     *  rolling bound) and fires ONE completion task-notification at the terminal state — the background-bash
     *  half of CC's LocalShellTask completion notify. Also flips the host poll to re-readable spool reads. */
    onTerminal?: (notification: TaskNotificationPayload) => void;
    /** The task's OUTPUT FILE — the launch receipt advertises it and the watcher
     *  mirrors every polled increment into it (append-only, unbounded — unlike the rolling in-memory
     *  spool), so "Read the output file path" is the model's read of the command's output. Terminal
     *  task-notifications carry the same path (`output_file`). Primarily meaningful with `onTerminal`
     *  (only the watcher mirrors increments live); a watcher-less row still gets ONE final best-effort
     *  append at TaskStop/run-teardown (the tail drain), so the file is written even without a watcher —
     *  there is just no live mirror. Callers create the file (empty) before registering. */
    outputFile?: string;
    /** The LAUNCHING task's retain declaration (`TaskSpec.retainBackgroundProcesses`) — the task lane of
     *  {@link retainsBackgroundProcesses}. Carried onto the row as its `retained` mark at registration
     *  (together with the env lane), so faces that never see the spec — the session reap, the exit-boundary
     *  hard face — answer the same retain question the launch receipt answered. Passing it (true or false)
     *  STATES the lane: a later run teardown does not re-judge the row. Absent = the launcher does not know the
     *  lane; the owning run's teardown supplies it. */
    retainBackgroundProcesses?: boolean;
    /** See {@link BackgroundBashTaskHandle.taskArtifacts}. */
    taskArtifacts?: TaskArtifactSeat;
}
/** One row's receipt from {@link TaskRegistry.killAllBackgroundShellsNow} (closed `outcome` set; `retained`
 *  present when the row was retained, whatever the outcome). */
export interface BackgroundShellHardKillReceipt {
    taskId: string;
    type: "background_bash" | "monitor";
    owner?: string;
    retained?: true;
    outcome: BackgroundHardKillOutcome | "retained_skipped";
}
export interface TaskPollOptions {
    workflowStore?: WorkflowRunStore;
    /** design/151 S1a: the durable agent ledger — a live-registry miss on an `a*` id falls back to it
     *  (terminal snapshot / honest cross-instance "running elsewhere"), behind {@link canAccessAgentRecord}. */
    agentStore?: BackgroundAgentStore;
    filter?: string;
    /** design/116 W3: wait until the task reaches a terminal state (or `timeoutMs`) instead of returning the
     *  instantaneous snapshot. Absent ⇒ the snapshot. */
    block?: boolean;
    /** Max wait for `block` (ms). Default 30s, capped at 600s. */
    timeoutMs?: number;
    /** Abort signal — a blocked wait stops when the caller cancels. */
    signal?: AbortSignal;
    /** The run's checkpoint seat: a PARKED background_agent row's park card is read from it for the
     *  answer's `agentState` ({@link import("./agent-state.js").readAgentState}). Absent ⇒ the card reads
     *  `unreadable`; nothing else changes. */
    checkpointSeat?: CheckpointSeat;
}
export interface TaskStopOptions {
    workflowStore?: WorkflowRunStore;
    /** design/151 S1a: durable-ledger fallback for the stop face (an off-process row reads `not_local` —
     *  workflow-fallback parity — instead of a misleading not-found). */
    agentStore?: BackgroundAgentStore;
    /** Who initiated the stop (defaults to `"parent"`; the model's `TaskStop` tool passes `"manager"`). */
    source?: StopSource;
}
/** A mount names its occupant through {@link OccupantMount}'s reading only (read per call), never as a fixed access member. */
export interface TaskToolOptions extends Omit<TaskAccess, "rootSessionIncarnation">, OccupantMount {
    registry: TaskRegistry;
    workflowStore?: WorkflowRunStore;
    /** design/151 S1a: durable agent ledger — threads into the stopTask fallback read. */
    agentStore?: BackgroundAgentStore;
}
/** One row of {@link TaskRegistry.list} (and {@link TaskRegistry.liveTasks}): the DISPLAY projection of a task
 *  the caller reaches — never the internal handle. One name for the list, the live reading and the walk behind both. */
export interface TaskListRow {
    task_id: string;
    type: SemaTaskType;
    status: SemaTaskStatus;
    /** design/129 lifetime flag, surfaced for observability — on resume-leg deployments the
     *  canonical taskId==sessionId, so task- and session-scoped rows share an owner KEY VALUE and only this
     *  explicit flag tells them apart. Bulk attribution should use {@link TaskRegistry.markStopSourceForOwner}, not a
     *  list()-driven loop (the 500-row cap). */
    sessionScoped: boolean;
    /** Present on a shell-lane row (`background_bash` / `monitor`) that THE retain predicate keeps alive
     *  past the automatic reaps — the "keeps running" half of an exit listing: the controlled-exit reap and
     *  the hard face under `includeRetained: false` leave it running; every other running shell row stops. */
    retained?: true;
    description?: string;
    toolUseId?: string;
    /** The child session a `background_agent` row is anchored to — absent in the startup window before the
     *  bind (right after registration, once the child's session id is fixed), present from the bind until a
     *  successful release of that session (a terminal row keeps it until that release or the terminal GC),
     *  absent on every other task type. Present means "the registry has not released the anchor", not "the
     *  session store still holds the session" — the session store answers that. Only this process's
     *  handles are listed: a row known only to the durable store of another process is not here. */
    sessionId?: string;
    /** The extension that started a `background_agent` row, when one did — its registration name, from the extension's own
     *  `$.agent.spawn` (`ExtensionRequester`); ABSENT on every other row (the model's own spawn, the host's, and every row an earlier
     *  release registered): the one reading, with no word for either. A display and audit fact only. */
    requestedBy?: ExtensionRequester;
    /** Present, `true`, on a `running` workflow row whose run has a leg parked (on any gate) — something is being waited on
     *  while `status` still says `running` (the run-level bit, `runParkedOf`, read off the live run through
     *  `WorkflowHandle.parked`; the row projects it and derives nothing). A parked running row is not idle. ABSENT on every other row — a workflow that is not
     *  waiting, one a TaskStop or its own end has moved past `running`, a handle that does not answer `true` (one that THROWS is
     *  {@link TaskListRow.parkedUnreadable}), and every other task type — never `false`. */
    parked?: true;
    /** Present, `true`, on a `running` workflow row whose handle THREW when asked whether its run is parked (`parked` is absent
     *  then): the row cannot say whether somebody is being waited on, so "not parked" would be a guess — an absent `parked` beside this
     *  member is "unknown", not "no". The handle is a host's to supply (`registerWorkflow`), and one handle that cannot answer costs its
     *  own row this member and no other row, nor the listing, anything. ABSENT on every other row — a handle that answered (`true` or
     *  anything else), a settled workflow, every other task type — never `false`. */
    parkedUnreadable?: true;
    /** The row's completion identity — the handle's own fill-once value ({@link SemaTaskHandle.completionId}), the same one the
     *  completion frame, the inbox / replay record and the host poll carry for this completion, so a host that met the
     *  completion on one of those recognizes the row. Present iff the row's completion minted one: a settled row of every
     *  task type; absent on a `pending` / `running` / `parked` row (a revived background agent drops its earlier cycle's value
     *  until the new cycle settles) and on a settled row whose ending minted none (a workflow whose run never reached its
     *  terminal transition). Never derived, never a placeholder. */
    completionId?: string;
    /** A settled `background_agent` row's refusal record — what the agent did not get done because something refused it: the
     *  `refused` of its ending (`agentOutcomeOf`), the same record its completion frame, fleet terminal, poll and durable listing
     *  summary carry (`BackgroundAgentRowSummary.refused`). Present iff the row's ending carries one; absent on every other row
     *  (running, parked, an ending with no record, every other task type). ABSENT says nothing was stated, never "nothing was
     *  refused". A revived row drops its earlier cycle's record until the new cycle settles. */
    refused?: import("./member-outcome.js").MemberRefusals;
    createdAt: number;
    /** The wall-clock instant of the row's last activity — for display. A clock that steps, or a machine that sleeps, moves it. */
    updatedAt: number;
    /** The same instant on this process's monotonic clock (`performance.now()` milliseconds): how long the row has been silent is
     *  `performance.now() - lastActivityMono`, immune to wall-clock steps and sleep. Only meaningful in the process that listed the row —
     *  never persisted, never compared across processes. */
    lastActivityMono: number;
}
/**
 * RB-49 B-3 (2026-07-25): the row-metadata projection `getAccessibleTask` returns. Was spelled out as a
 * hand-written literal in THREE places (this signature, the internal cast below, and the SendMessage
 * consumer in agents/subagent.ts) with an identical field list — adding a row field meant editing three
 * spots with zero compiler enforcement (the projection-antipattern family).
 * One exported name, three consumers, drift becomes a type error.
 */
export interface AccessibleTaskRow {
    task_id: string;
    type: SemaTaskHandle["type"];
    status: SemaTaskHandle["status"];
    toolUseId?: string;
    sessionScoped?: boolean;
    description?: string;
    name?: string;
    agentType?: string;
    owner?: string;
    scope?: string;
    parentTaskId?: string;
    parentSessionId?: string;
    rootSessionId?: string;
    /** The row's registration instant (the original spawn time for a first-cycle row): the
     *  revive projection needs it so a revive frame's `startedAt` anchors the ROW, not the wake call. */
    createdAt?: number;
}
export declare function abortBackgroundAgentsAtRunEnd(registry: TaskRegistry, access: TaskAccess, opts: {
    skipSessionScoped?: boolean;
}, runEnd: RunEndCause | undefined): number;
/** Watch the running agents {@link ownerSweepTakes} selects for `access` and `opts`; returns `undefined` when none remain, else an unsubscribe and calls `onSettled` once when they settle. */
export declare function onRunEndAgentsSettled(registry: TaskRegistry, access: TaskAccess, opts: {
    skipSessionScoped?: boolean;
}, onSettled: () => void): (() => void) | undefined;
export declare class TaskRegistry {
    private handles;
    /** observers of the design/129 session terminal anchor — `reapSessionBackground`
     *  fires each hook (swallow-guarded) AFTER reaping, so session-anchored side state (the session-scoped
     *  subagent retain ledger) releases on the SAME deployment call. Registered idempotently per consumer. */
    private sessionReapHooks;
    /** design/144 §1.2 (child gate): one-shot quiescence watchers keyed by OWNER — each set fires (and is
     *  removed) when that owner's running background-task count reaches zero. Populated by
     *  {@link onBackgroundQuiescence}; poked from every terminal transition / running-row eviction site.
     *  1.284 C3: callbacks carry a REASON — "quiescent" (the count really reached zero) vs "evicted"
     *  (cap overflow dropped the watcher; the owner's tasks may still be running — the subscriber must
     *  NOT treat this as quiescence). */
    private bgQuiescenceWatchers;
    /** One host-callback isolation scope for this registry's notification seams (session-reap hooks, quiescence fire +
     *  cap-overflow eviction, the terminal-once send every background kind's terminal takes). Same swallow
     *  as the five hand-written try/catches it replaced, now counted per site and readable for diagnostics. */
    private readonly notifier;
    /** The read face for this registry's CONTAINED host-callback failures (site → count).
     *  The registry has no deployment error sink of its own to disclose to (it is process-global,
     *  constructed before any RunnerDeps exists), so readability IS its disclosure grade: a deployment
     *  that suspects a broken observer polls this instead of grepping for silence. Empty on the
     *  healthy path. */
    notifierFailureCounts(): ReadonlyArray<{
        site: string;
        count: number;
    }>;
    /** design/157 B13 一期(#coreView 解法,B13 档「私有成员解法」定稿): the MON+WF lane free functions'
     *  only seam back into the class — exactly the 5 `RegistryCore` members those two lanes' `this.*`
     *  calls actually reached (grep-verified, see task-registry-shared.ts's own doc comment). Declared
     *  AFTER `handles` (its `handles` field below is captured eagerly at construction, so `this.handles`
     *  must already be assigned); the 4 method arrows close over `this` lazily and don't share that
     *  ordering constraint. Two-期 extends this to `DurableAgentCore` (durable-agent 车道, per the B13
     *  「私有成员解法」 note) without touching this shape. */
    private readonly core;
    durableAgentArmed(id: string): boolean;
    durableAgentRowProbe(id: string): (() => Promise<boolean>) | undefined;
    /** The row-side facts the durable rung admits a row on, off this process's copy of its durable record (see
     *  {@link durableAgentRowFactsLane}); read once the row's probe resolved. */
    durableAgentRowFacts(id: string): Pick<BackgroundAgentRecord, "agentType" | "sessionId" | "policyFloor"> | undefined;
    beginDurableClaim(id: string): boolean;
    endDurableClaim(id: string): void;
    /** Delete the durable rows past `policy` (and their transcripts). Deleting a row withdraws any `resumable: true` a frame stated
     *  for it earlier — no frame of this engine says so (the caller is the one that knows the row just went): the caller states
     *  that withdrawal on its own projection of the row. With a deletion bound (`maxAgeMs` / `keep`) the sweep is a deletion batch and
     *  ends with the store's {@link BackgroundAgentStore.settleErasure} (once; a failure throws after the rows and sessions are gone,
     *  and the next sweep settles their bytes). */
    reapDurableAgents(scope: string, deps: {
        store: BackgroundAgentStore;
        /** `listPlaced` (subagent transcript persistence, optional) arms the partition-orphan leg —
         *  see {@link reapDurableAgentsLane}. Pass the deployment's SessionStore directly (the
         *  TtlSessionStore over a placement-capable repo exposes it). */
        sessions?: {
            unpin?(sessionId: string): unknown;
            release(sessionId: string): Promise<void> | void;
            listPlaced?(kind: "subagent", opts?: {
                olderThanMs?: number;
                scope?: string;
            }): Promise<Array<{
                sessionId: string;
                placedAt: number;
            } & ({
                scope: string;
                handle: string;
            } | {
                tupleIncomplete: true;
            })>>;
        };
        mailbox?: {
            drop(scope: string, handle: string): Promise<void>;
        };
    }, policy: {
        now?: number;
        maxAgeMs?: number;
        keep?: number;
        staleRunningMaxAgeMs?: number;
    }): Promise<{
        rowsReaped: number;
        sessionsReleased: number;
        skippedNoSessions: number;
        orphanPlacedReleased: number;
    }>;
    /** The successful release of child session `sessionId` ends row `id`'s anchor on it — handle and durable
     *  record together, and only while the row still names that session (see {@link releaseDurableTranscriptAnchorLane}). */
    releaseDurableTranscriptAnchor(id: string, sessionId: string): void;
    /** Anchor row `id` to its child session `sessionId`, held through `store` — the store the child's run creates or resumes that
     *  session in (see {@link bindBackgroundAgentSessionLane}). */
    bindBackgroundAgentSession(id: string, sessionId: string, store: ChildSessionStore): void;
    registerBackgroundAgent(input: RegisterBackgroundAgentInput): string;
    /**
     * A whole-registry yield covers what enters `running` after it too — a spawn (here, at registration), a parked-resume drive
     * (born parked, running from its consume flip: covered at its leg's report), a retained wake (covered when the wake
     * lands) and a workflow run (at its registration). One rule at the four doors; work the request already reached is left
     * as it is.
     */
    private coverByRegistryYield;
    /**
     * THE yield verb for background work. Hands every running background agent and workflow run the request covers the
     * yield: an agent whose spawner can hold its park parks at its leg's next clean turn boundary (a
     * `resource_limit/preempt` checkpoint, its row `parked`), a workflow run whose park lane is armed has each of its legs
     * do the same and suspends on their parks; one that cannot is listed with why, and stopped only when
     * `opts.stopUnyieldable` says so.
     *
     * `access` absent ⇒ the whole registry, workflow runs included, and the request stays in force for work registered after
     * it (a draining process: call it beside raising your own root legs' `TaskSpec.preemptSignal`, then wait on `drained()`
     * or your drain window). With `access` ⇒ the background agents that access reaches (a workflow run is never its
     * launching leg's to decide) — the engine's own call is a parent leg that durably parked, over the agents it owns
     * (`skipSessionScoped`, `stopUnyieldable: "parent"`). A host that mounted its own registry calls this on that
     * registry; the engine reaches only the run's own. What yielded continues when its owner runs again: a yielded agent
     * row is claimed and driven by its owner's next leg; a yielded workflow run continues on its next resume
     * (`resumeFromRunId`), which drives its yielded legs with no decision.
     */
    yieldBackground(access?: TaskAccess, opts?: BackgroundYieldOptions): BackgroundYieldReport;
    /** A background agent's leg reports its own yield controller and whether it can suspend durably (the delegation lane wires
     *  it into the leg's trusted internals; see {@link RunInternals.reportSuspendLane}). */
    attachYieldLeg(id: string, controller: AbortController, ready: boolean): void;
    /** The whole-registry yield in force, if any (it covers agents that enter `running` after it). */
    private registryYield;
    /** Pending `drained()` checks, re-run after every transition poke. */
    private readonly drainChecks;
    /** A yield's `drained()` re-reads on every transition (an agent's park or settle, a workflow run's end), one microtask
     *  later: a park or a settle queues its durable write in the same synchronous stretch as its poke, so the write is in
     *  the chain the check then awaits. */
    private pokeYieldDrains;
    private whenDrained;
    /** #22 — persist this leg's org-memory admission verdict on the durable row (the cross-process
     *  revival's only carrier). See {@link recordBackgroundAgentOrgAdmissionLane}. */
    recordBackgroundAgentOrgAdmission(id: string, verdict: import("./memory-admission.js").OwnOrgAdmissionVerdict): void;
    parkBackgroundAgent(id: string, park: {
        checkpointToken: string;
        resolveStop?: () => Promise<boolean>;
        completionSink?: BackgroundAgentTaskHandle["parkedCompletionSink"];
    }): "parked" | undefined;
    /** #3334 — the completion sink a PARKED handle's cycle is still owed to in this process (the park's own lane), for the
     *  redemption to complete into when its call carries none; `undefined` when this process holds no park of `id`. */
    parkedCompletionSink(id: string): BackgroundAgentTaskHandle["parkedCompletionSink"];
    reconcileParkedAgents(stores: {
        agentStore: import("./background-agent-store.js").BackgroundAgentStore;
        checkpointStore: import("./background-agent-store.js").ParkedCardStore;
    }, scope: string, now: number, opts?: {
        staleClaimMaxAgeMs?: number;
    }): Promise<{
        failed: number;
        rolledBack: number;
        unreadable: number;
    }>;
    claimParkedAgent(stores: {
        agentStore: import("./background-agent-store.js").BackgroundAgentStore;
        checkpointStore: Pick<import("./checkpoint-store.js").CheckpointStore, "get">;
    }, handle: string, access: TaskAccess): Promise<{
        ok: true;
        ticket: ParkedClaimTicket;
    } | {
        ok: false;
        reason: "not_found" | "not_parked" | "binding_broken" | "checkpoint_not_pending" | "claim_lost" | "store_unreachable";
    }>;
    rollbackParkedClaim(stores: {
        agentStore: import("./background-agent-store.js").BackgroundAgentStore;
        checkpointStore: Pick<import("./checkpoint-store.js").CheckpointStore, "get">;
    }, ticket: ParkedClaimTicket): Promise<ParkedClaimRollback>;
    /** The consume flip (parked → running): the stop-cycle number it wrote on the row — the resumed cycle's — or
     *  `undefined` when the row moved and the resume must abort. See {@link consumeParkedFlipLane}. */
    consumeParkedFlip(id: string, stores: {
        agentStore: import("./background-agent-store.js").BackgroundAgentStore;
    }, ticket: ParkedClaimTicket): Promise<number | undefined>;
    finalizeParkedResume(id: string): void;
    /** `outcome.cycle` names the revive cycle this settle speaks for (absent = 0 = the original
     *  spawn cycle). A spawn leg never passes it; a caller that settles by LIFECYCLE AUTHORITY (reap /
     *  session release — "whatever is running under this row dies") passes the row's current cycle. See
     *  {@link settleBackgroundAgentLane} for why a stale stamp must be a no-op. */
    settleBackgroundAgent(id: string, outcome: import("./task-registry-agent.js").BackgroundAgentSettle): BackgroundAgentSettledStatus | undefined;
    /** design/164 — record one tool-lifecycle beat on a running background-agent row; see
     *  {@link noteBackgroundAgentActivityLane} for why the in-memory row needed a stall signal at all. `atMono` is an instant on the
     *  process-monotonic clock (`performance.now()` milliseconds), never a wall-clock time, from 0 to the clock's now (anything else
     *  throws); absent ⇒ now. The row's stamp never goes back: an earlier instant leaves it. */
    noteBackgroundAgentActivity(id: string, atMono?: number): void;
    /** The row's running leg hands it a reader of the calls the leg holds at its gate for an approver
     *  ({@link import("./runner/contracts.js").RunInternals.reportApprovalHolds}); the latest leg's reader stands, and the faces that state
     *  the agent's state read it ({@link attachBackgroundAgentApprovalHoldsLane}). A handle that is not a background agent takes none. */
    attachBackgroundAgentApprovalHolds(id: string, read: () => readonly import("./agent-state.js").ApprovalHeldCall[]): void;
    /** design/164 — collect SESSION-SCOPED background agents that have gone silent for `staleMs`, the
     *  stall-based replacement for the retired wall-clock ceiling on that lane. Caller-supplied policy
     *  like every other retention knob here; see {@link reapStaleSessionBackgroundAgentsLane}. Silence is measured on the
     *  process-monotonic clock: `nowMono` is `performance.now()` milliseconds (absent ⇒ now), never a wall-clock time. A row whose
     *  leg holds a call at its gate for an approver (a person's card, a question routed to the question face, a deployment's policy
     *  or manager deciding) is not collected while it waits. */
    reapStaleSessionBackgroundAgents(staleMs: number, nowMono?: number): number;
    abortBackgroundAgentsForOwner(access: TaskAccess, opts?: {
        skipSessionScoped?: boolean;
        sessionScopedOnly?: boolean;
    }): number;
    /** A durable row's answer with its state: only a parked row waits on the card read; any other row is
     *  answered in place. */
    private serveDurableAgentRow;
    /** The row facts {@link import("./agent-state.js").readAgentState} reads for a background agent this
     *  caller can see — the live handle only (a durable-only row is projected by its reader from the record,
     *  {@link import("./agent-state.js").agentStateSourceOfRecord}). Same access guard as a poll; unknown and
     *  out-of-scope ids read identically (undefined). */
    agentStateSource(taskId: string, access: TaskAccess): AgentStateSource | undefined;
    resolveBackgroundAgentByName(name: string, access: TaskAccess, opts?: {
        preferRunning?: boolean;
    }): {
        status: "found";
        handle: BackgroundAgentTaskHandle;
    } | {
        status: "ambiguous";
        message: string;
    } | {
        status: "not_found";
        suggestion?: string;
    };
    /** Bind a spawn name for a launch from the seat `access` names: the requested name, or the first free `<name>-N` when an
     *  agent this seat can see (any status) or another launch from it already answers to it. The claim holds the name until
     *  `release()` (see {@link claimBackgroundAgentNameLane}). */
    claimAgentName(requested: string, access: TaskAccess): {
        name: string;
        release(): void;
    };
    markRetainedContinuation(id: string): void;
    /** The row's stop-cycle number as its last won claim left it (a parked row: the cycle that parked) — the one number
     *  every frame, notification, tick and poll of the row reads; see {@link backgroundAgentCycleSeqLane}. */
    backgroundAgentCycleSeq(id: string): number | undefined;
    /** Subagent transcript persistence (delegation entry caps) — one delegation tree's ACTIVE
     *  (running/pending) a* handles in THIS process, keyed `(scope, rootSessionId)`; SYNCHRONOUS by
     *  contract (the entry gate hands an admitted child's slot to its row in the segment that registers it). See
     *  {@link activeDelegationHandlesLane}. */
    activeDelegationHandles(scope: string, rootSessionId: string): string[];
    /** The same rows as {@link activeDelegationHandles}, each with its addressing name and whether `caller` reaches it — what a refusal
     *  of one more child may tell its caller about who holds the tree's slots. See {@link activeDelegationOccupantsLane}. */
    activeDelegationOccupants(scope: string, rootSessionId: string, caller?: TaskAccess): DelegationOccupant[];
    /** The ACTIVE (running / pending) rows of one delegation tree in THIS process, in EVERY scope, each with the scope it is registered
     *  in — the live twin of `BackgroundAgentStore.listByRoot` (one tree reading, one root judge: a root that is not a non-empty string
     *  of at most 256 characters without control characters is refused with `config.invalid_argument`). A host enumerating a
     *  session's children for deletion reads both and acts on each row in that row's own scope. See {@link activeDelegationHandlesByRootLane}. */
    activeDelegationHandlesByRoot(rootSessionId: string): DelegationRowAddress[];
    /** ASYNC (revive arbitration) — the durable half is a guarded ownership claim on the row (awaited before the
     *  in-memory flip), so this leg and a cross-process claim arbitrate in one domain instead of both
     *  believing they own the cycle. See {@link reviveBackgroundAgentLane}. */
    reviveBackgroundAgent(id: string, access: TaskAccess, abort?: AbortController): Promise<{
        ok: true;
        cycle: number;
    } | {
        ok: false;
        reason: "not_found" | "still_running" | "recycling";
    }>;
    settleRevivedAgent(id: string, cycle: number, outcome: Omit<import("./task-registry-agent.js").BackgroundAgentSettle, "stoppedBy" | "cycle">): BackgroundAgentSettledStatus | undefined;
    unmarkRetainedContinuation(id: string): void;
    /** A retained entry's departure is settled: the terminal GC stops keeping this handle (see `retentionHeld`). */
    endRetentionHold(id: string): void;
    attachAgentNotify(id: string, notify: NonNullable<BackgroundAgentTaskHandle["notify"]>, cycle?: number): void;
    /** RB-375 A1 — hang the terminal notifier on a live background-agent row: what the registry calls, once, when it lands
     *  that row's terminal without the cycle's attempt (see {@link BackgroundAgentTaskHandle.terminalNotifier}). No-op on
     *  unknown/terminal rows: a row that already settled has its unwind (or the settle itself) owning the terminal story. */
    attachAgentTerminalNotifier(id: string, fn: (ending: LandedAgentTerminal) => void): void;
    /** RB-375 A1 — the child-unwind side of the terminal-notification once-latch: returns `true` when
     *  the CALLER now owns sending the terminal faces (and claims the latch), `false` when the reap
     *  sweep already sent them (the caller must stay silent — the registry row still takes the settle's
     *  payload/backfill either way; only the announcement is deduplicated). Unknown/GC'd row ⇒ `true`
     *  (no latch survives eviction; the L1-1 late-report posture is unchanged). */
    claimAgentTerminalNotify(id: string): boolean;
    deliverToRunningAgent(id: string, access: TaskAccess, notification: import("./task-notification.js").TaskNotificationPayload, opts?: {
        priority?: import("./task-notification.js").SystemInjectionPriority;
    }): Promise<{
        ok: true;
        disposition: "queued" | "parked" | "pending";
    } | {
        ok: false;
        reason: "not_found" | "not_running" | "no_channel" | "queue_full" | "refused";
    }>;
    runningBackgroundAgentLabels(access: TaskAccess): string[];
    private pollBackgroundAgent;
    private stopBackgroundAgent;
    /** design/151 §3.1d (HIGH-3): this process instance's durable-row writer identity (random per
     *  registry instance). A fallback read of a `running` row written by a DIFFERENT instance must
     *  never claim liveness — it serves the honest "outcome unknown here" instead. */
    readonly writerId: string;
    /** the writer-liveness LEASE: while any armed durable row is running, one lazy
     *  unref'd interval bumps their `updatedAt` (an empty patch), so row age measures SILENCE, not
     *  run length. A `staleRunningMaxAgeMs` reap policy must therefore be ≫ this period (the store
     *  contract recommends ≥10min) — and even a premature flip self-heals: the real settle's
     *  read-back adopts the bumped rev and re-CASes the truth over the reaper's guess. */
    /** 增量 R-1 — handles a reap sweep is CURRENTLY adjudicating (between its live-handle check
     *  and the delete/release outcome). A revive admitted inside that await window would race the
     *  conditional delete with its own durable transition still unflushed (old rev ⇒ the delete wins,
     *  the session is released under an ADMITTED resume, and the revive's queued write poisons on
     *  "gone"). Membership is synchronous on both sides, with three readers (the `claimingHandles` twin
     *  below carries the same fence set): reap marks BEFORE its terminal check, a revival lane refuses
     *  while marked (the row is being recycled), and the terminal-handle
     *  GC skips a marked id instead of evicting it. */
    private reapingHandles;
    /** The post-delete half of the window above (see {@link DurableAgentCore.reapedHandles}): the sweep's
     *  guarded delete has WON, and the fence is still held while the mailbox is dropped and the session
     *  released. The fence's readers are unchanged — this only splits what a refused revival is TOLD,
     *  since a caller advised to retry a row that no longer exists would retry forever. */
    private reapedHandles;
    /** design/151 §7.3 (F-8) — handles a revival lane is CURRENTLY claiming (between the claim-CAS
     *  decision and the revive registration/rollback). BOTH lanes are writers: the tier-3 SendMessage
     *  claim, and (since the retained revive started claiming its own row) the in-process retained-revive
     *  path, which holds the mark across its store round trip. Synchronous membership on both sides, the
     *  `reapingHandles` twin, with three readers: the reap sweep skips a mid-claim row (its rev is about
     *  to move), the sibling revival lane refuses one (`reviveBackgroundAgent` recycling — a transient
     *  hold, told apart from a row that is actually gone), and the
     *  terminal-handle GC skips it — so the revival lanes, the reaper and the GC can never adjudicate the
     *  same handle concurrently in-process. */
    private claimingHandles;
    /** Spawn names held by launches whose rows do not exist yet ({@link claimAgentName}). */
    private agentNameClaims;
    private durableHeartbeatTimer;
    mintTaskId(type: SemaTaskType): string;
    registerBackgroundBash(input: RegisterBackgroundBashInput): string;
    /** Hold a peer task the peer task lane minted (its id from {@link mintTaskId}): born `running`, filed under the call's access. The
     *  lane keeps the handle and writes its ending onto it, then tells the registry ({@link notePeerTaskSettled}). */
    registerPeerTask(input: RegisterPeerTaskInput): PeerTaskTaskHandle;
    /** A peer task settled (its handle carries the ending): the owner's quiescence watchers and the run-end drain checks look again. */
    notePeerTaskSettled(id: string): void;
    /** {@link commandRecordSink} over this registry's rows, ref book and guarded send. */
    private commandRecordSink;
    /** Background output-file read exemption: true iff `canonicalPath` is EXACTLY the registered output
     *  file of a background bash or monitor row that (a) the caller can access (same owner/scope/session visibility as
     *  a task poll — {@link canAccess}) and (b) was registered on the caller's OWN execution env —
     *  `env` identity is part of the match, same discipline as {@link runningShellIds}. A canonical path only names a file within ONE env's filesystem
     *  namespace: on a shared registry, a row minted on env A must never exempt a same-named outside-root
     *  file in env B's namespace (same session or not), so instance equality — never a string proxy — is
     *  required. The output file is minted by the ENGINE itself (createTempFile
     *  at spawn/adopt) in the OS temp dir — structurally outside the hands containment root — and its path
     *  is handed to the model in the launch receipt and the completion notification; Read consults this so
     *  it can honor that instruction without widening the root fence (exact registered file only, no
     *  directory/prefix admission). Membership dies with the row (per-run evict / session reap / terminal
     *  GC), so the exemption never outlives the task's addressability. Exact string compare: both sides are
     *  `canonicalPath` outputs for the same env, so a symlinked temp dir cannot cause a miss or a false hit. */
    isBackgroundOutputFile(canonicalPath: string, access: TaskAccess, env: unknown): boolean;
    /** [c209-D]: display-cap-free EXACT id lookup with the same access guard as a poll — identity
     *  resolution must NEVER ride the display-capped `list()` (with >LIMIT visible rows the cap can evict
     *  the addressed id, and a name-layer fallback then MISROUTES the message to a同名 row instead of an
     *  honest not-found). Unknown and out-of-scope ids read identically (info-hiding, undefined both). */
    getAccessibleTask(taskId: string, access: TaskAccess): AccessibleTaskRow | undefined;
    /** design/134 §3.3 (R3 single-source): record WHO is about to kill `id`, at the initiation site,
     *  BEFORE the abort()/status flip — the ordering is load-bearing: the guard below refuses markers on a
     *  non-running handle, so a caller that flips first loses its claim and attribution falls back to
     *  "system". First-marker-wins: an earlier marker (e.g. a service-wire "user") is never overwritten.
     *  Applies to background_agent, background_bash AND monitor handles (the markable kinds — the monitor
     *  watcher/stop lanes mark and read it too); workflow cancellation is out of scope. */
    markStopSource(id: string, source: StopSource): void;
    /**
     * Attribute an ENV-LEVEL blanket sweep before it runs.
     *
     * The incident: a user's `run_in_background` Bash died mid-run reporting `stopped-by:"system"` with a
     * zero-byte output file, and diagnosing it took a cross-repo investigation with a timeline argument.
     * `"system"` is not a cause — it is the DEFAULT, i.e. the signature of a kill that never passed through
     * this registry. Every kill that does pass through records who did it; `disposeBackgroundShells` lives in
     * the execution-env layer, cannot reach the registry, and so left the one class of kill a user actually
     * notices as the only one with no attribution at all.
     *
     * This marks every background_bash row on `env` that the sweep is about to take, so the row the user
     * reads says what happened to it. `except` mirrors the sweep's own keep-list exactly — a spared shell
     * must not be marked, or the next reader would be told a live process had been killed.
     *
     * Attribution only: it never kills anything. The caller has already demonstrated kill capability on the
     * env, which is why there is no access guard.
     */
    markStopSourceForEnvSweep(env: unknown, source: StopSource, except?: readonly string[]): string[];
    /** design/134 §3.3: narrow terminal read for consumers (subagent sinkEmit/notify) — only a KILLED row
     *  has an attribution; "system" is the defensive floor for a row that went killed without a landed
     *  stoppedBy (e.g. env-direct flips). Returns undefined for running/completed/failed/evicted rows. */
    getStopAttribution(id: string): StopSource | undefined;
    /** P1-3 — the fill-once completion correlation id (see {@link UnifiedTaskOutput.completionId}), for a
     *  notification-construction call site that already has the task's `id` and needs to attach it to the
     *  payload it is building. Deliberately NOT restricted to a subset of task types (unlike
     *  {@link getStopAttribution}) — `completionId` lives on the shared {@link SemaTaskHandle} base and
     *  every registered task kind, workflow included, carries it the same way. Undefined until the task's
     *  own settle point has run ({@link mintCompletionId}), or for an id this registry never held. */
    getCompletionId(id: string): string | undefined;
    /** How a loop-type task's row — a background agent's, a peer task's — says it ended (`MemberOutcome`): the outcome the settle that
     *  won the row minted, for the call site building that settle's completion frame (read in the settle's own step, like
     *  {@link getCompletionId}). Undefined for a row still running or parked, a row of another task kind, or an id this registry never held. */
    getAgentOutcome(id: string): import("./member-outcome.js").MemberOutcome | undefined;
    /** How a workflow run's own members ended, as the row holds it once the run settled ({@link WorkflowTaskHandle.members}) —
     *  undefined while it runs, for a row of another task kind, or an id this registry never held. */
    getWorkflowMembers(id: string): import("./member-outcome.js").MemberLedger | undefined;
    /** Record the ref a task's result was stored under (`persistTaskArtifact` landed it) — the read handle a later list of
     *  tasks names for it. `completionId` = the settle the result belongs to ({@link getCompletionId}, read in that settle's own
     *  synchronous step — every terminal frame carries it): the write records only while the row still holds that settle. A row revived
     *  since (a new cycle clears the id and mints its own), replaced under the same id (a revival in another registration),
     *  or gone (terminal GC) records nothing — and so does a write that names no settle. */
    recordArtifactRef(id: string, ref: string, completionId: string | undefined): void;
    /** The legs a page-back of `ref` travels (ReadToolResult's per-call reading): a ref holding a background task's result —
     *  its origin is part of the ref ({@link taskArtifactOriginOf}), so no row eviction, restart or other store forgets it —
     *  travels what a poll of that task travels ({@link boundaryLegsOf}, `"output"` — another tree's agent, a workflow run, a
     *  row gone or out of reach are off-target reads); any other ref (offloaded tool output) stays inside the engine. */
    artifactBoundaryLegs(ref: string, access: TaskAccess, tree: object): BoundaryLegsGiven;
    /** The read handle ({@link taskReadHandleText}) of a task `access` reaches — `undefined` for an unknown or unreachable
     *  id (the same info-hiding a poll gives) and for a task with nothing to read beyond its notification. */
    readHandleOf(id: string, access: TaskAccess): string | undefined;
    /** The run teardown's "a person stopped this run" judgement, marked on the background agents the run-end reap takes (the reap's
     *  own row set: owner + scope, session-resident rows skipped when `skipSessionScoped`) before that reap marks them "parent" —
     *  first-marker-wins then holds "user". Read by the shell settle ({@link settleKilledForOwner}) and by a run whose member ledger
     *  reads its last word after the reap (`reapTaskAgentsBeforeLastWord`), whichever runs first. */
    markRunEndAgentsStoppedByUser(access: TaskAccess, opts?: {
        skipSessionScoped?: boolean;
    }): void;
    /** Bulk stop-source attribution for one owner — the registry-side primitive that
     *  replaces the service's `list()+markStopSource` per-row loop, which had TWO holes: ① `list()` didn't
     *  expose `sessionScoped`, so on the resume leg (canonical taskId==sessionId, rebuilt taskConfig without
     *  spec.taskId) task-scoped and session-scoped children share the same owner KEY VALUE and can't be told
     *  apart; ② `list()`'s 500-row display cap silently skipped rows on >500-children runs.
     *  Same owner-filter semantics as {@link abortBackgroundAgentsForOwner}: {@link canAccess} + the EXPLICIT
     *  `sessionScoped` flag (design/129 — never inferred from key values), over a DIRECT handle-map walk
     *  (no list() cap in the path). Covers every markable kind ({@link markStopSource}'s own set:
     *  background_agent / background_bash / monitor); each row is delegated to `markStopSource`, so the
     *  running-only + first-marker-wins guards hold unchanged — an existing claim is never overwritten.
     *  Returns how many rows NEWLY took the marker (already-marked / non-running rows don't count). */
    markStopSourceForOwner(access: TaskAccess, source: StopSource, opts?: {
        skipSessionScoped?: boolean;
    }): number;
    /** The run-teardown KILLED-receipt producer for the SHELL lanes (background_bash + per-run
     *  monitor). The runner teardown disposes the processes (`disposeBackgroundShells`) and evicts the rows
     *  (`clearBackgroundForOwner`) — after which NO producer can ever mint the killed notification: the bash
     *  watcher's next poll sees a vanished shell ("nothing to notify about") or its evicted handle and just
     *  stops. So a mid-turn abort (or a normal turn end) silently swallowed children the model had been
     *  promised notifications for ("You will be notified when it completes — do not poll"). The AGENT lane
     *  already has its producer (the child promise's settle → notify); this is the same receipt for
     *  the shell lanes — call it BEFORE dispose/evict so the sink chain (onTerminal/onEvent → the run's
     *  notification wrapper, whose lane is already down at teardown) PARKS the receipt on the per-session
     *  pending store and the session's next run drains it (the pending lane, one shape for all producers).
     *
     *  Attribution (design/134 §3.3): `markStopSource(source)` first — first-marker-wins, so a deployment's
     *  earlier explicit mark (e.g. a service-wire "user" on abort) is never overwritten; `stoppedBy` then
     *  lands from the marker. Rows without a sink still settle (registry truth), they just have no receipt
     *  to send. Session-scoped rows are skipped under `skipSessionScoped` (they outlive the turn; their
     *  terminal anchor is `reapSessionBackground`). KNOWN small race, recorded: a child that exited within
     *  the last watcher-poll interval (~1s) but whose exit the watcher hasn't observed yet still reads
     *  "running" here and is settled `killed` — the receipt is at worst one status coarser, never silent.
     *
     *  (HIGH): the settle EXECUTES the kill itself (await `killBackground`, Result-typed)
     *  before minting the receipt — previously the receipt claimed "killed" while the actual kill was left to
     *  the later `disposeBackgroundShells`, whose failure was swallowed (process alive + registry cleared =
     *  the receipt lied). A failed kill now mints an HONEST receipt naming the failure (the env dispose is
     *  still the idempotent backstop). Returns how many rows were settled. */
    settleKilledForOwner(access: TaskAccess, opts?: {
        source?: StopSource;
        skipSessionScoped?: boolean;
        envDying?: boolean;
        /** Spec-level retain (`TaskSpec.retainBackgroundProcesses`): treat every shell-lane row as if its
         *  env had declared retain — skip entirely (no kill, no killed receipt: nothing died, a receipt
         *  would lie). Same `envDying` exception as the env-capability gate: retain on a dying owned env
         *  is illusory, so those rows still settle with the honest killed receipt. */
        retainProcesses?: boolean;
    }): Promise<number>;
    /** A-005.4/5: the best-effort kill `reapSessionBackground`'s monitor/background_bash arms fire is
     *  fire-and-forget by DESIGN (the reap is synchronous and settles the row regardless of the kill
     *  outcome — see the callers) but was fire-and-FORGET-the-evidence-too: a resolved `{ok:false}` was
     *  never read, and even a promise rejection landed on `.catch(() => undefined)`. Reads the Result,
     *  drops the benign `not_found` case (already dead — same filter the awaited TaskStop kill path uses,
     *  see `killFailed` above), and routes anything else through `shutdownDebug` — the SAME kill-path
     *  forensics channel the row-scoped calls right above these call sites already use for this reap, so
     *  a `SEMA_DEBUG_SHUTDOWN=1` "who killed my process" hunt no longer dead-ends at a silently-swallowed
     *  reap-time failure. Never throws (a forensics call must not fault the reap it is reporting on). */
    private reportSessionReapKillFailure;
    /** design/129: the session-scoped children's TERMINAL anchor — call from your session release/sweep.
     *  Aborts every running session-scoped background child registered under `sessionId` and settles it
     *  `killed` (the child's own catch/then would also classify the abort as killed; this makes the registry
     *  state immediate rather than waiting on the child's promise). Idempotent.
     *  RETAINED shell-lane rows (THE retain predicate over the row's mark and the env's declaration) are left
     *  whole — row, watcher and process (the deliver-a-living-service contract; their terminals: TaskStop, own
     *  exit, env destruction, the hard face under `includeRetained: true`). Every other running shell-lane row
     *  this session owns is killed and settled. {@link reapAllSessionBackground} delegates here.
     *  RB-375 A3 — RETURN-VALUE semantics: the count covers DIRECT hits of this sweep only (rows whose
     *  own arm above matched). Children the reaped agents themselves spawned (`sessionScoped:false`
     *  grandchildren) die COLLATERALLY, via each reaped agent's own teardown
     *  (`abortBackgroundAgentsForOwner` in the child's unwind) — this function never sees those rows,
     *  so they are NOT counted here.
     *  RB-375 A1 — a directly reaped `background_agent` row's terminal notification is sent
     *  SYNCHRONOUSLY by this sweep (through the spawn-lane-hung {@link BackgroundAgentTaskHandle.terminalNotifier},
     *  once-latched against the child's own unwind), so consumers observe the terminal immediately
     *  instead of after the in-flight tool honors the abort (unbounded). */
    reapSessionBackground(sessionId: string, scope?: string): number;
    /** The FULL-registry reap for the ENGINE's own exit path. TOC form:
     *  the engine process IS the session terminal (the shell has no line to call — live evidence:
     *  detached bg children reparent to PID 1 and outlive the engine), so the engine's SIGHUP/SIGTERM/
     *  normal-exit terminus calls THIS. Enumerates every running session-scoped row's (sessionId, scope)
     *  pair — `owner` = the sessionId by design/129 discipline for background_bash/monitor/background_agent
     *  (RB-215 note: NOT for workflow, whose `owner` is the launching LEG's taskId; its session anchor is
     *  `originatingSessionId` — see {@link reapSessionBackground}'s own workflow arm for why) — and runs
     *  the per-session reap on each pair; retained rows are left alone (row and process), exactly like the
     *  per-session anchor. Timing discipline: call at the hardShutdown TERMINUS, never at drain start — an
     *  in-flight turn may still be following a bg process. Returns total rows reaped.
     *
     *  Its kills go through each env's `killBackground` (possibly a TERM-then-timer ladder), and it reaches
     *  session-resident rows only: every exit terminus calls {@link killAllBackgroundShellsNow} after it. */
    reapAllSessionBackground(): number;
    /** The EXIT-BOUNDARY hard face over every shell-lane row (`background_bash` + `monitor`), session-resident or
     *  not (docs/background-process-lifetime.md is the contract). SYNCHRONOUS (no await, no timer) and
     *  IDEMPOTENT. Visits every row except `completed` (a `killed` row may sit inside a softer stop's grace
     *  window; a `failed` one may have lost its watcher, not its process). A retained row (THE retain predicate)
     *  is left alone under `includeRetained: false` — no default — unless an explicit stop already settled it
     *  `killed`. Every other visited row goes through the seat {@link BackgroundShellCapability.killBackgroundNow}.
     *  One receipt per visited row: `killed` (the seat delivered its kill now) / `already_gone` / `retained_skipped`
     *  / `no_pgid` (no synchronous kill landed — no seat, the seat said so or threw; the env's ordinary
     *  `killBackground` is then dispatched, nothing claimed). Only a running row the seat killed is settled
     *  `killed` (stop source "system", no notification). `reason` is forensics only.
     *  `sessionId` + `scope` narrow the visit to the rows {@link reapSessionBackground} (sessionId, scope) keys on
     *  — the same access (`canAccess` with owner = session = sessionId, in that scope): every session-resident
     *  row of the session, plus its run rows where the run's task id is the session id (the default); a run
     *  named with its own task id is not reached. Absent ⇒ the whole registry. Same receipts either way. */
    killAllBackgroundShellsNow(opts: {
        includeRetained: boolean;
        reason?: string;
    } & ({
        sessionId?: undefined;
        scope?: undefined;
    } | {
        sessionId: string;
        scope: string;
    })): BackgroundShellHardKillReceipt[];
    /** How many shell-lane rows (`background_bash` + `monitor`) the exit-boundary hard face would take down if it ran now: the
     *  registry's `running` shell rows, over the WHOLE registry — no owner, session, scope or env narrowing — with a retained row
     *  counted only under `includeRetained: true` (no default, as on {@link killAllBackgroundShellsNow}). The rows are chosen
     *  by the hard face's own reading ({@link hardFaceVisitOf}), so the count and the walk cannot drift. SYNCHRONOUS and READ-ONLY:
     *  the count calls no seat and changes no row; like the hard face it reads each row's env declaration of retention (host-provided
     *  data), so a host whose env makes that read throw makes the count throw. It counts registry rows, not process truth: a row whose seat later answers `already_gone`
     *  or `no_pgid` stays `running` and is counted until its watcher settles it. A row an earlier stop settled `killed` or
     *  `failed` is visited by the hard face but is not running, so it is not counted; `completed` rows are not visited.
     *  Not {@link list}'s length: `list(access)` is the caller's own reach, capped at `limit`, every task type and status;
     *  {@link countRunningBackgroundForOwner} is one owner key's running tasks, agents included. */
    countRunningBackgroundShells(opts: {
        includeRetained: boolean;
    }): number;
    /** `Runner.drain`'s census, SYNCHRONOUS and READ-ONLY: the running background agents a whole-registry yield covers
     *  ({@link yieldCovers}, the request's own reading; workflow runs are not counted), and the running shell-lane rows the hard
     *  face would take down with retained rows included ({@link hardFaceVisitOf}, the hard face's own reading). */
    drainCensus(): {
        agents: Array<{
            id: string;
            sessionId?: string;
        }>;
        shells: Array<{
            id: string;
            type: "background_bash" | "monitor";
            retained?: true;
            sessionId?: string;
        }>;
    };
    /** One row's status as `Runner.drain` reads it back, with the checkpoint a parked agent is parked on; `undefined` when the
     *  registry no longer holds the id. */
    drainReading(id: string): {
        status: SemaTaskStatus;
        token?: string;
    } | undefined;
    /** `Runner.drain`'s answer about THESE agents' own rows: settles the durable writes queued so far for `ids` and answers the
     *  ones whose latest write did not land ({@link yieldPopulationWrites}, the reading a yield's `drained()` takes). Never rejects. */
    drainWrites(ids: readonly string[]): Promise<string[]>;
    /** How many session-scoped background agents have a child run in flight in this process: the registry's `running`
     *  `background_agent` rows that carry the explicit `sessionScoped` flag, over the WHOLE registry — no owner, session, scope or
     *  access narrowing. The rows are chosen by the reading both reaps use ({@link isLiveSessionResidentAgent}), so the count and
     *  the sweeps cannot drift: a `parked` row (a wait on a person) and a settled row are not counted, a task-scoped agent is
     *  not, and a workflow or a shell row is not an agent. SYNCHRONOUS and READ-ONLY, and it never throws: it reads three of the
     *  registry's own row fields and nothing a host provides. It counts registry rows, not process truth — a row stays counted
     *  until its settle lands (a reap, the child's own end, a TaskStop). Not {@link list}'s length (the caller's reach, capped,
     *  every type and status), not {@link liveTasks} (the caller's reach), not {@link countRunningBackgroundForOwner} (one owner
     *  key, shells included); the shell-lane twin is {@link countRunningBackgroundShells}. */
    countRunningSessionBackgroundAgents(): number;
    /** How many workflow runs this registry holds as running: the registry's `workflow` rows covered by the whole-registry yield
     *  reading ({@link yieldCovers}), over the WHOLE registry — no owner, session, scope or access narrowing. Because it shares
     *  `yieldCovers` with {@link yieldBackground}, this count and the drain barrier read the exact same rows. SYNCHRONOUS and
     *  READ-ONLY, and it never throws: it calls no member on any row's handle. It counts registry rows, not process truth — a run
     *  a host starts without registering it is not counted, and a run stopped by a stop request stops counting when its
     *  `cancelled` state lands (even before its terminal record write finishes). A running run with a parked leg is not idle
     *  (another leg is still running or the run is winding down to suspend) and is counted; parked rows are not subtracted. This is
     *  a cross-tenant process count: a host that exposes it to a principal discloses other tenants' activity. Not {@link list}'s
     *  length or {@link liveTasks} (the caller's reach), and not {@link countRunningSessionBackgroundAgents} (background agents). */
    countRunningWorkflows(): number;
    /** subscribe to `reapSessionBackground` (the design/129 session terminal anchor).
     *  Returns an unsubscribe. Hooks are best-effort observers; a throwing hook is swallowed. */
    onSessionReap(hook: (sessionId: string, scope?: string) => void): () => void;
    /** design/144 §1.2 — the child gate's liveness read: how many BACKGROUND tasks (bg bash / monitor /
     *  bg agent) registered under EXACTLY this owner key are still running. Deliberately an owner-equality
     *  walk, NOT {@link canAccess}: an owner-less handle is world-*readable* but attributable to nobody —
     *  counting it against every owner would park every parent's completion frame behind a stranger's task.
     *  Workflow rows are out of the gate's task class by design (§1.2 names bg bash/monitor/grandchild
     *  agents; a workflow's terminal already notifies on its own lane). */
    countRunningBackgroundForOwner(owner: string): number;
    /** design/144 §1.2 — hard cap on concurrently watched owners (each parked parent notification holds
     *  exactly one watcher; the retain-ledger caps bound this in practice — the cap is a defensive floor).
     *  1.284 C3: overflow notifies the OLDEST owner's watchers with reason "evicted" (CANCELLATION
     *  semantics, not a fake quiescence — the pre-fix synchronous no-arg fire read as "count reached
     *  zero" while the owner's tasks were still running, an early FALSE completion). The subscriber
     *  decides its own degradation (the child gate delivers its parked frame immediately, undecorated —
     *  宁发勿丢); a silently leaked/never-fired watcher would lose the frame forever. */
    private static readonly BG_QUIESCENCE_WATCHERS_MAX;
    /** design/144 §1.2 (child gate, 补发钩子) — subscribe a ONE-SHOT callback fired when `owner`'s running
     *  background-task count reaches zero (reason "quiescent"). Exactly-once discipline for the N-children
     *  race: every terminal transition pokes, only the poke that OBSERVES count==0 fires, and firing removes
     *  the whole owner set first (count-zero judgement + once latch). NEVER fires synchronously from this
     *  call — the caller checks the count itself in the same synchronous block (count > 0 → subscribe; no
     *  await between, so no missed-settle window). 1.284 C3: a cap-overflow eviction fires the victims with
     *  reason "evicted" instead, and ASYNCHRONOUSLY (queueMicrotask) — the new watcher is installed before
     *  any victim runs, closing the re-entrant window where a victim's callback observed a half-updated map.
     *  Returns an unsubscribe. Callbacks are swallow-guarded observers. */
    onBackgroundQuiescence(owner: string, cb: (reason: "quiescent" | "evicted") => void): () => void;
    /** design/144 §1.2 — poke the quiescence watchers of `owner` after a terminal transition (or a
     *  running-row eviction). Cheap no-op without watchers; fires + removes the owner's whole set only
     *  when the running count is zero (the LAST settling task's poke wins — count-zero judgement). */
    private pokeBgQuiescence;
    /** fidelity R1-3: the terminal-notification once-latch — every background kind's (an agent's terminal the registry
     *  lands without its cycle's attempt comes through here as well, `announceLandedAgentTerminal`; the attempt's own
     *  unwind claims the same latch with `claimAgentTerminalNotify`). Checks-and-sets BEFORE sending (single-threaded,
     *  no await between check and set — atomic), so a racing producer pair (a teardown settle vs an in-flight
     *  watcher tick that passed its status gate before the settle landed) emits exactly ONE terminal notice.
     *  The latch stays set even if the sink throws — a faulty sink must not re-arm it. */
    private notifyTerminalOnce;
    /** G2b watcher (design/116 §7): 1s poll loop (its first beat at registration) that spools increments (rolling bound) and fires ONE
     *  completion notification at the terminal state. `unref()`d — a watcher never keeps the process alive.
     *  Stops itself on terminal, on a vanished shell (env disposed), or when the handle is evicted. */
    private startBashWatcher;
    /** Every shell-lane row still RUNNING on this env, any owner — the run-boundary dispose's except-list (the
     *  run teardown and the park-only parks: `sweepRunBoundaryBackgroundShells`).
     *  A run's teardown disposes only shells it can attribute to itself: its settle sweep has already killed
     *  and settled the rows of this run that end with it, so whatever registered row is still running here is
     *  either something that settle kept (session-resident, an in-window Monitor, retained) or belongs to
     *  another run or session sharing the env. Unregistered env shells are still disposed. */
    runningShellIds(env: unknown): BackgroundShellId[];
    /** design/135 G2: register a spawned background process as a MONITOR — the watcher polls at the batch
     *  window (200ms), turns each completed stdout line into an event, batches lines within one tick into
     *  ONE notification, enforces the non-persistent timeout, auto-stops an event storm, and fires exactly
     *  one terminal notification (exit code / timeout / auto-stop / env-side kill). */
    registerMonitor(input: RegisterMonitorInput): string;
    registerWorkflow(input: RegisterWorkflowInput): string;
    /** The legs one read of a task's output (`"output"`: a stored artifact read back by ref) or TaskStop (`"stop"`) call travels, read off the handle the call dispatches to by the same
     *  resolution the poll and the stop take: a background shell's or a monitor's process lives in its own environment (the `env` leg
     *  reaches that one); an agent handle that recorded the calling tree's own token moves nothing across the boundary; any other handle — an
     *  agent of another tree, a workflow run, an id no live handle answers (a durable row read back) — is content from beyond the
     *  boundary on a poll and nothing on a stop. */
    boundaryLegsOf(id: string, access: TaskAccess, verb: "output" | "stop", tree: object): BoundaryLegsGiven;
    /** The tree a background agent runs in, off the handle `id` resolves to under `access` ({@link RegisterBackgroundAgentInput.delegationTree});
     *  `undefined` for an agent registered with none (a call with no seat: an anonymous tree's). */
    backgroundAgentTree(id: string, access: TaskAccess): import("./runner/delegation-owner.js").DelegationOwnerSeat | undefined;
    /** What a session is still owed when one of its legs ends: each of its {@link liveTasks} delivers into a LATER leg of the session —
     *  another tree — so each is read as that leg's poll of it ({@link boundaryLegsOf}, `"output"`, under a tree no handle recorded). */
    owedDeliveries(access: TaskAccess): BoundaryLegsGiven[];
    /** The live handle this process holds for a workflow run of `store`, read beside its durable record there (the record's
     *  occupant is the handle's); a handle of the same id over another store is another run. */
    private heldWorkflow;
    pollTask(id: string, access: TaskAccess, opts?: TaskPollOptions): Promise<UnifiedTaskResult>;
    /**
     * #4760 — stop ONE member of a workflow run, by the member's call key (`WorkflowAgentRun.callKey`); the run goes on. The run held
     * in this process answers through its own `stopAgent` (`stoppedBy` defaults to `parent`; a service passes `user` for a person). A
     * run not held here, read from `workflowStore`: one it records `running` is another process's (`not_local`); one that has ended
     * answers `already_terminal` (its status); none the caller can see, or a handle that does not answer member stops: `not_found`. A
     * store read that throws rejects (an outage is not "no such run"); a run registered here while the store was read answers live.
     * Stopping a whole run (one that waits on an approval included) is {@link stopTask}'s.
     */
    stopWorkflowAgent(runId: string, callKey: string, access: TaskAccess, opts?: {
        readonly stoppedBy?: StopSource;
        readonly workflowStore?: WorkflowRunStore;
    }): Promise<WorkflowAgentStopReceipt>;
    /**
     * #5291 — stop the WORKFLOW `runId` belongs to, for good (`WorkflowHandle.stop`): no run of it starts another step, whichever process
     * continues it, and every approval card of it still waiting is withdrawn. The caller's access is judged before any tree read or write,
     * on the run held here or the record `workflowStore` gives — a run the caller cannot see answers `not_found`, with nothing written. A run held
     * here is stopped through its own handle (its own stores); one read from the store is stopped through the stores given
     * (`journalStore` keeps the stop — without one, or one without `stopResumeClaim`, the stop is not durable; `checkpointStore` is where
     * its cards are withdrawn). The record is read before access is judged (access is judged on it): a row that does not read answers
     * `not_found`, as a missing one does; a store read that throws otherwise rejects. TaskStop ({@link stopTask}) only cancels: a cancelled
     * run can be continued.
     */
    stopWorkflowRun(runId: string, access: TaskAccess, opts?: {
        readonly stoppedBy?: StopSource;
        readonly workflowStore?: WorkflowRunStore;
        readonly journalStore?: WorkflowJournalStore;
        readonly checkpointStore?: CheckpointStore;
    }): Promise<WorkflowRunStopReceipt>;
    stopTask(id: string, access: TaskAccess, opts?: TaskStopOptions): Promise<UnifiedTaskResult>;
    /** S2b — bounded delivery-confirmation wait (see deliverToRunningAgent). Test-tunable. */
    deliverConfirmTimeoutMs: number;
    private lastGcAt;
    /**
     * The data source behind a shell's task list and footer pill: list the caller's OWN tasks as a bounded DISPLAY
     * projection — never the internal handles (no shellId/env/abort). Same owner/scope guard as poll/stop;
     * a caller only ever sees its own tasks. Sorted newest-first, capped at `limit` (default 50).
     * CC parity note: CC's /tasks is a UI/SDK surface, NOT an LLM tool — expose this via SDK/service,
     * do not mount it as a model tool by default.
     */
    list(access: TaskAccess, opts?: {
        limit?: number;
    }): TaskListRow[];
    /** The tasks `access` reaches that have not finished (`pending`, `running` or `parked`), newest first — EVERY one, with no display
     *  cap ({@link list}'s): the one reading of a leg's live background tasks (its end's {@link owedDeliveries}, the post-compaction
     *  listing and the resume's orphan diff, the suspend's snapshot), each consumer projecting its own columns from it. */
    liveTasks(access: TaskAccess): TaskListRow[];
    /** The rows `access` reaches whose row names `taskId` as the task that dispatched them (`parentTaskId`) — background agents,
     *  workflow runs and peer tasks alike (`isRegistryMemberKind`, one law) — newest first, EVERY one, with no display cap: a task's
     *  members read as one set, however many rows of other tasks the reach holds. */
    membersOfTask(access: TaskAccess, taskId: string): TaskListRow[];
    /** The child session task `taskId`'s row is anchored to — its id and the store the child's run holds it through — when
     *  `access` reaches the row (the reach {@link list} reads with): `undefined` for an unknown or out-of-reach id, `null` for a
     *  reached row with no anchor (no background agent's row, not bound yet, or released). */
    anchoredSession(taskId: string, access: TaskAccess): ChildSessionAnchor | null | undefined;
    /**
     * What a run's end does to each of `taskIds`, read now: the row `read` reaches, in {@link list}'s projection (absent for an id this
     * process holds no row of, or one `read` does not reach), and whether the run-end sweep of `owner`'s background agents
     * (`abortBackgroundAgentsForOwner(owner, { skipSessionScoped: true })`, the same selection) takes it. One lookup per id, no display cap.
     */
    runEndReading(taskIds: readonly string[], read: TaskAccess, owner: TaskAccess): Array<{
        taskId: string;
        row?: TaskListRow;
        sweptWithOwner: boolean;
    }>;
    /** Every row `access` reaches, newest first, in {@link list}'s projection — the one walk both readings take. */
    private rowsUnder;
    /** One handle in {@link list}'s projection. */
    private projectedRow;
    /** Throttled {@link gc} for hot-path callers (design/115 review B5): prepare-task runs once per task,
     *  and a full-map sweep per prepare is pure overhead — sweep at most once per minute. */
    maybeGc(now?: number): number;
    gc(now?: number, terminalTtlMs?: number): number;
    clearBackgroundForOwner(access: TaskAccess): number;
    private resolveInternal;
    private pollBackgroundBash;
    private pollWorkflow;
    private stopBackgroundBash;
    private pollMonitor;
    private stopMonitor;
    private stopWorkflow;
}
export declare const defaultTaskRegistry: TaskRegistry;
export declare function createTaskStopTool(opts: TaskToolOptions): AgentTool;