UNPKG

@phren/cli

Version:

Knowledge layer for AI agents - CLI, MCP server, and data layer

1,931 lines • 117 kB
import { dispatchIssueSchema, issueBriefBlock, writeDispatchIssue } from "./dispatch-issue.js";
import { redactPeerHandoff } from "./peer-handoff.js";
import { integratorSchema, prsSchema } from "./return-contract.js";
import { randomBytes, randomUUID } from "node:crypto";
import { lstat, mkdir, readFile, readdir, realpath, stat } from "node:fs/promises";
import path from "node:path";
import { z } from "zod";
import { logger } from "../logger.js";
import { homeDir } from "../home-paths.js";
import { getMachineName } from "../machine-identity.js";
import { getProjectSourcePath } from "../project-config.js";
import { computerName } from "./computers.js";
import { dispatchParentSchema, validateDispatchParent } from "./dispatch-tree.js";
import { findGrant, grantLabel, permissionModeAllowed, DEFAULT_MAX_PERMISSION_MODE } from "./grants.js";
import { checkAgentDispatch, projectAuthority, readAuthority, RELEASE_ACTIONS, releaseAction } from "./authority.js";
import { hookPeers } from "./peers.js";
import { callerQuery, localCaller, oneWayHint } from "./conductor-group.js";
import { prepareDispatchOriginHandover, trackDispatchOrigin } from "./dispatch-origins.js";
import { readRoleState, recordedConductor } from "./conductor-role.js";
import { linkedComputer } from "./computer-identity.js";
import { isLocalComputer, localHost, peerHost } from "./dispatch-hosts.js";
import { object, objects, atomic, BridgeError, bridgeRoot, id, launchEfforts, PERMISSION_MODES, PROTOCOL, provider, serverName, startingTargetSchema, targetSchema } from "./protocol.js";
import { phrenStoreRoot } from "./transcripts.js";
import { isAccountSlug } from "./claude-accounts.js";
import { hasUsable } from "./harnesses.js";
import { limitedBy, limitKey, readAccountLimits } from "./account-choice.js";
import { allowedRooms, choosePolicyAccount, computerRule, openRoom, policyApplies, poolRefusal, projectRule, withPolicy } from "./account-policy.js";
import { arrivalSchema, briefArrival } from "./launch-brief.js";
import { worktreeBranch } from "./launch-worktree.js";
import { dispatchClonePaths, removeDispatchClone, removeDispatchSecrets } from "./dispatch-clone.js";
import { launchInProgress, markSubmitted, removeWorkerFile, workerAlive } from "./worker-identity.js";
import { findIdempotencyKey, idempotencyKeySchema, LAUNCH_INTERRUPTED_MS, listIdempotencyRecords, releaseIdempotencyKey, reserveIdempotencyKey, updateIdempotencyPhase, waitForIdempotencyKey, withIdempotencyKeyLock, worktreeBranchFor } from "./dispatch-idempotency.js";
const text = (max) => z.string().min(1).max(max).refine(value => !!value.trim() && !/[\x00-\x1f\x7f]/.test(value));
export const projectName = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/);
/** The longest worker brief a dispatch takes, in characters. */
export const DISPATCH_PROMPT_LIMIT = 32768;
/** The harnesses a dispatch, a code note's hand-off or a schedule can start. */
export const PEER_COPILOT_REASON = "Copilot cannot continue on another computer: its harness does not confirm launch-brief arrival. Continue locally or choose another harness.";
export const DISPATCH_HARNESSES = ["codex", "claude", "opencode", "copilot"];
const dispatchMetadataSchema = z.object({
    computer: z.union([z.literal("anywhere"), computerName]).describe("Enrolled computer name, local for this computer, or anywhere for the least busy connected computer."),
    project: projectName.describe("Project slug registered on the receiving computer."),
    harness: z.enum(DISPATCH_HARNESSES).describe("Agent harness on the receiving computer."),
    model: text(200).optional().describe("Explicit model, otherwise the remote harness default."),
    effort: z.enum(launchEfforts).optional().describe("Reasoning effort for the worker (minimal, low, medium, high, xhigh, max), otherwise the harness default."),
    account: z.string().refine(isAccountSlug, "Account must be default or a lowercase slug.").optional()
        .describe("Claude account id to run the worker under (default, or a slug from `phren bridge accounts`). anywhere only picks computers where that account is signed in; a named computer without it fails. Without it, a computer with several signed-in Claude accounts picks the one with the most 5-hour room, then weekly; the receipt's accountChoice says why."),
    permissionMode: z.enum(PERMISSION_MODES).optional().describe("Permission mode the worker starts in: supervised, auto-edits, auto or full-access (Claude, Codex and Copilot; not OpenCode); otherwise the receiving computer's own default."),
    releaseActions: z.array(releaseAction).min(1).max(RELEASE_ACTIONS.length).optional()
        .describe("Release-type actions the brief asks the worker to do (merge, publish, deploy, app-store, github-admin). Ask-first projects refuse them from an agent unless the owner confirmed."),
    prompt: z.string().min(1).max(DISPATCH_PROMPT_LIMIT).refine(value => !/[\x00-\x08\x0b-\x1f\x7f]/.test(value)).describe(`Worker brief, at most ${DISPATCH_PROMPT_LIMIT} characters.`),
    label: text(200).describe("Short worker label."),
    idempotencyKey: idempotencyKeySchema.optional()
        .describe("Caller-supplied key (1 to 200 characters of letters, digits and : . _ @ / -). The Hook returns the dispatch this key already started instead of starting another, for 30 days. Dispatches with a key run in their harness's standard permission mode."),
    worktree: z.boolean().optional().describe("Start the worker in a fresh git worktree of the project's checkout, on a new branch. Never reused."),
    branch: worktreeBranch.optional().describe("Branch for the worktree; defaults to agent/<key-slug or dispatch id>. Needs worktree."),
    closeOnFinish: z.boolean().optional().describe("Close the finished worker pane after its done return is read. Defaults to true; false keeps it open."),
    integrator: integratorSchema.optional().describe("Forward structured PR reports to this integrator, overriding the Hook default."),
    parent: dispatchParentSchema.optional().describe("Explicit local conversation parent for work-tree attachment."),
    parentTarget: targetSchema.optional().describe("Complete live target for the explicit parent."),
}).strict();
export const dispatchSchema = dispatchMetadataSchema.extend({ issue: dispatchIssueSchema.optional() });
/** Where a session moves to (session-move.ts): a harness with its account, model and effort, as a dispatch names them. */
export const moveToSchema = z.object({
    computer: computerName.optional().describe("Verified destination computer; omitted means this computer."),
    harness: z.enum(DISPATCH_HARNESSES).describe("Harness to continue in: claude, codex, opencode or copilot."),
    account: z.string().refine(isAccountSlug, "Account must be default or a lowercase slug.").optional()
        .describe("Claude account id (default, or a slug from `phren bridge accounts`); only for claude."),
    model: text(200).optional().describe("Model for the new agent, otherwise the harness default."),
    effort: z.enum(launchEfforts).optional().describe("Reasoning effort for the new agent, otherwise the harness default."),
}).strict().superRefine((value, context) => {
    if (value.account && value.harness !== "claude")
        context.addIssue({ code: "custom", message: "Only a Claude target takes an account." });
});
const remoteTarget = z.union([targetSchema, startingTargetSchema]);
/** The local pane that asked for the dispatch, where return notices go. */
export const originPaneSchema = z.object({ server: serverName, workspace: id, tab: id, pane: id }).strict();
export const workerStates = ["working", "waiting", "done", "needs-you", "failed", "blocked", "stalled", "gone"];
const timestamp = z.string().datetime();
const receiptSchema = dispatchMetadataSchema.omit({ prompt: true }).extend({
    id: z.string().uuid(), createdAt: z.string().datetime(), updatedAt: z.string().datetime(),
    computerId: z.string().uuid().optional(),
    state: z.enum(["launching", "sending", "accepted", "uncertain", "failed"]),
    target: remoteTarget.optional(), error: z.string().max(500).optional(),
    brief: z.enum(["launch", "typed"]).optional()
        .describe("How the brief reached the worker: as its first prompt at launch (confirmed by the worker's hook), or typed into its pane."),
    accountChoice: z.string().max(400).optional().describe("Why the receiving Hook ran the worker under `account` when the dispatch named none."),
    continued: z.object({ id: z.string().uuid().optional(), computer: z.string().max(200).optional(), account: z.string().max(64).optional(),
        at: timestamp, error: z.string().max(500).optional() }).strict().optional()
        .describe("The worker hit its Claude usage limit: the dispatch that continues it on another account, or why none could."),
    continues: z.string().uuid().optional().describe("The dispatch this one continues after its worker hit its usage limit."),
    moves: z.array(z.object({ id: z.string().uuid(), at: timestamp, handoff: z.string().max(4096).optional(),
        computerFingerprint: z.string().regex(/^[a-f0-9]{64}$/).optional(), computerId: z.string().uuid().optional(),
        from: z.object({ harness: provider, account: z.string().max(64).optional() }).strict(), to: moveToSchema }).strict()).max(16).optional()
        .describe("Each move of this worker to another agent (session-move.ts): from, to, when, and the hand-off file on the worker's computer. `target`, `harness`, `account`, `model` and `effort` are the current agent's."),
    granted: z.string().max(200).optional().describe("Scope of the conductor grant that allowed this call."),
    authority: z.string().max(600).optional().describe("The release authority policy's line for this project, as a conductor quotes it."),
    authorityConfirmed: z.string().datetime().optional().describe("When the owner confirmed the ask-first release actions this agent dispatch used."),
    skipped: z.array(z.object({ computer: computerName, reason: z.string().max(200) }).strict()).max(32).optional()
        .describe("Computers left out of anywhere placement, with the reason each could not report capacity."),
    origin: originPaneSchema.extend({ agent: provider, terminal: z.string().min(1).max(200) }).strict().optional()
        .describe("The local agent pane that placed this dispatch; return notices go there."),
    closedAt: timestamp.optional(),
    cancelRequestedAt: timestamp.optional(),
    closePending: z.object({ at: timestamp, turn: z.string().optional() }).strict().optional(),
    agentTokenFile: z.string().max(4096).optional().describe("Private file holding the keyed worker's gitboy agent token; removed when it closes or finishes."),
    cloneDir: z.string().max(4096).optional().describe("The keyed dispatch's isolated clone; removed when it closes or finishes, or after its retention date."),
    gitConfigFile: z.string().max(4096).optional().describe("The keyed dispatch's managed global Git config; removed with the clone or as soon as a failed/cancelled worker ends."),
    workerFile: z.string().max(4096).optional().describe("The keyed worker's PID and start-time record, written before the harness execs."),
    retainedUntil: timestamp.optional().describe("When a failed, cancelled or keep-open clone may be removed by reconciliation."),
    endedAt: timestamp.optional().describe("When the worker was observed gone or closed; retention is measured from here."),
    launchOutcome: z.enum(["not-started", "ambiguous", "started"]).optional()
        .describe("Whether the launch request was never sent, was sent with an unknown outcome, or produced a target or arrival."),
    startingToken: z.string().regex(/^[a-f0-9]{64}$/).optional()
        .describe("The launch's own starting token, recorded before the request and carried by its pane."),
    launchServer: z.string().max(200).optional().describe("The terminal server the launch request targeted."),
    scanSince: timestamp.optional().describe("When a successful snapshot first found no pane carrying this launch's starting token."),
    submittedAt: timestamp.optional().describe("When the launch command was submitted; a missing worker file is only gone after its grace period."),
    worker: z.object({ state: z.enum(workerStates), since: timestamp, checkedAt: timestamp, sawWorking: z.boolean(),
        background: z.number().int().min(0).max(999).optional().describe("The most background tasks seen running while the worker was working."),
        waitingSince: timestamp.optional().describe("When the dispatching Hook first saw the worker's finished turn waiting on background tasks; bounds that wait."),
        waitingOn: z.enum(["ci", "background", "queue", "other"]).optional()
            .describe("What the worker waits on: background work while its finished turn still runs, or what its waiting return named.") }).strict().optional()
        .describe("The worker pane's last observed state."),
    returned: z.object({
        state: z.enum(["done", "needs-you", "failed", "blocked", "stalled", "gone", "waiting"]), at: timestamp,
        reply: z.string().max(4000).optional(), error: z.string().max(500).optional(), truncated: z.boolean().optional(), question: z.string().max(200).optional(),
        waitingOn: z.enum(["ci", "background", "queue", "other"]).optional()
            .describe("A waiting return's one word: CI, this worker's own background work, a queue, or other work. Not an owner action."),
        waitingFor: z.string().max(200).optional().describe("The sentence the worker's turn ended on, when it waits on something that is not the owner."),
        checkout: z.object({ path: z.string().max(4096), branch: z.string().max(256).optional() }).strict().optional()
            .describe("Where a worker that failed was working, for the dispatch that continues it."),
        prs: prsSchema.optional(),
        integratorDelivery: z.object({ deliveryId: z.string(), state: z.enum(["pending", "queued", "delivered", "uncertain", "failed"]), at: timestamp, integrator: integratorSchema.optional() }).strict().optional(),
        stalledSince: timestamp.optional(), stallFor: z.number().nonnegative().optional(),
        turn: z.string().regex(/^[a-f0-9]{16}$/).optional(), read: z.boolean(), notifiedAt: timestamp.optional(),
        background: z.number().int().min(1).max(999).optional().describe("Background tasks the worker left running when it was counted done."),
        waited: z.number().int().min(1).max(999).optional().describe("The most background tasks the worker waited on before it finished."),
    }).optional().describe("The latest return: the worker finished, is parked waiting on CI, background work or a queue, needs the owner, failed, is blocked or is gone."),
    approval: z.object({
        actionId: z.string().min(1).max(200), tool: z.string().max(200), title: z.string().max(200).optional(), request: z.string().max(500).optional(),
        requestKind: z.enum(["command", "tool", "edit", "question", "other"]).optional(), terminal: z.boolean().optional(),
        conductor: z.object({ action: z.enum(["dispatch", "hand_off"]), project: z.string().max(200).optional(), computer: z.string().max(200).optional() }).strict().optional(),
        expiresAt: z.string().max(40).optional(), at: timestamp, pushed: z.boolean().optional(),
    }).strict().optional().describe("A permission request the worker is waiting on, forwarded by its Hook; answer it with dispatch_approve."),
});
/** Where a checkout usually sits when the store names none for this computer. */
const CHECKOUT_ROOTS = ["Projects", "projects", "Sites", "Code", "code", "dev", "src", "repos"];
async function directoryAt(source) {
    if (typeof source !== "string" || !path.isAbsolute(source) || /[\x00-\x1f\x7f]/.test(source))
        return undefined;
    const directory = await realpath(source).catch(() => undefined);
    return directory && (await stat(directory)).isDirectory() ? directory : undefined;
}
/**
 * The project's folder on this computer. The store syncs between computers,
 * so its shared `sourcePath` is often another machine's folder: this
 * machine's `sourcePaths` entry wins, as everywhere else in phren. With
 * neither here, a git checkout named after the project in a usual project
 * root is taken (the owner's layout is `~/Projects/<name>` on every computer).
 */
export async function dispatchProjectDirectory(project, home = homeDir()) {
    const name = projectName.parse(project);
    const configured = await directoryAt(getProjectSourcePath(phrenStoreRoot(), name));
    if (configured)
        return configured;
    for (const root of [...(process.env.PROJECTS_DIR ? [process.env.PROJECTS_DIR] : []), ...CHECKOUT_ROOTS.map(folder => path.join(home, folder))]) {
        const checkout = await directoryAt(path.join(root, name));
        if (checkout && await stat(path.join(checkout, ".git")).catch(() => undefined))
            return checkout;
    }
    throw new BridgeError(404, `Project ${name} is not on this computer: the store names no folder for ${getMachineName()} that exists here, and there is no ~/Projects/${name} checkout.`);
}
function save(receipt, originWindow) {
    return serializeReceiptUpdate(async () => {
        // Only this already-running dispatch can inherit a hand-over alias.
        // Resolve it under the receipt lock, after any role change invalidation.
        const origin = originWindow.rewrite(receipt.origin);
        if (origin !== receipt.origin && !receipt.closedAt) {
            receipt.origin = origin;
            if (receipt.returned && !receipt.returned.read)
                delete receipt.returned.notifiedAt;
        }
        await saveReceipt(receipt);
    });
}
const PLACEMENT_FIELDS = ["state", "error", "brief", "target", "account", "accountChoice", "agentTokenFile", "cloneDir", "gitConfigFile", "workerFile", "returned", "closedAt", "launchOutcome", "submittedAt"];
/** Every placement write re-reads the receipt under the lock, so a concurrent cancelRequestedAt is never lost. */
async function persistReceipt(receipt, originWindow, change = () => undefined) {
    const updated = await updateReceipt(receipt.id, value => {
        // A concurrent close finalizes the receipt; a placement write must not
        // resurrect it with a stale state or return.
        if (value.closedAt || value.error === "cancelled")
            return false;
        const origin = originWindow.rewrite(value.origin);
        if (origin !== value.origin && !value.closedAt) {
            value.origin = origin;
            if (value.returned && !value.returned.read)
                delete value.returned.notifiedAt;
        }
        for (const key of PLACEMENT_FIELDS) {
            const next = receipt[key];
            if (next !== undefined)
                value[key] = next;
        }
        change(value);
        value.updatedAt = new Date().toISOString();
        return true;
    }, { duringPlacement: true });
    if (updated)
        Object.assign(receipt, updated);
}
async function saveReceipt(receipt) {
    const root = path.join(bridgeRoot(), "dispatches");
    await mkdir(root, { recursive: true, mode: 0o700 });
    await atomic(path.join(root, `${receipt.id}.json`), receipt);
}
const IGNORED_MODE = "The receiving Hook is older and ignored permissionMode; the worker runs in that computer's default mode. Update its Hook.";
const MAX_RECEIPT_BYTES = 65_536;
let receiptUpdates = Promise.resolve();
/**
 * Change one settled receipt: read it, let `change` edit it, and write it back
 * when `change` returns true. Updates run one at a time in this process, and a
 * receipt still being placed (launching or sending) is never touched.
 */
export function updateReceipt(receiptID, change, options = {}) {
    return serializeReceiptUpdate(() => changeReceipt(receiptID, change, options.duringPlacement === true));
}
function serializeReceiptUpdate(change) {
    const run = receiptUpdates.then(change);
    receiptUpdates = run.catch(() => undefined);
    return run;
}
/** One dispatch receipt by id, for a worker. */
export function dispatchReceipt(receiptID) {
    return readReceipt(receiptID);
}
async function readReceipt(receiptID) {
    const file = path.join(bridgeRoot(), "dispatches", `${z.string().uuid().parse(receiptID)}.json`);
    const info = await lstat(file).catch(error => {
        if (error.code !== "ENOENT")
            throw error;
        return undefined;
    });
    if (!info?.isFile() || info.isSymbolicLink() || info.size > MAX_RECEIPT_BYTES)
        return undefined;
    return receiptSchema.parse(JSON.parse(await readFile(file, "utf8")));
}
/** Caller holds receiptUpdates; ordinary polling never edits a placing receipt. */
async function changeReceipt(receiptID, change, duringPlacement = false) {
    const receipt = await readReceipt(receiptID);
    if (!receipt || (!duringPlacement && ["launching", "sending"].includes(receipt.state)))
        return undefined;
    if (!change(receipt))
        return receipt;
    receipt.updatedAt = new Date().toISOString();
    await saveReceipt(receiptSchema.parse(receipt));
    return receipt;
}
/** Hand over all open worker routes using the receipt writer's own lock and
 * update path. Commit the role last; any failure restores the old origins.
 * Placing receipts are refused because placement can still overwrite them. */
export function repointDispatchOrigins(from, to, commit) {
    return serializeReceiptUpdate(async () => {
        const seal = prepareDispatchOriginHandover(from, to);
        const names = await readdir(path.join(bridgeRoot(), "dispatches")).catch(error => {
            if (error.code !== "ENOENT")
                throw error;
            return [];
        });
        const matches = (origin) => origin?.server === from.server && origin.pane === from.pane
            && (from.terminal === undefined || origin.terminal === from.terminal);
        const selected = [];
        for (const name of names.filter(name => /^[a-f0-9-]{36}\.json$/.test(name))) {
            const receipt = await readReceipt(name.slice(0, -5));
            if (!receipt || receipt.closedAt || !matches(receipt.origin))
                continue;
            if (["launching", "sending"].includes(receipt.state))
                throw new BridgeError(409, "A conductor dispatch is still being placed; retry the move after it settles.");
            selected.push(receipt);
        }
        const changed = [];
        try {
            for (const before of selected) {
                await changeReceipt(before.id, receipt => {
                    if (receipt.closedAt || !matches(receipt.origin))
                        return false;
                    receipt.origin = to;
                    // Unread returns already announced to the old chat need a new notice.
                    if (receipt.returned && !receipt.returned.read)
                        delete receipt.returned.notifiedAt;
                    return true;
                });
                changed.push(before);
            }
            await commit();
            seal();
        }
        catch (error) {
            const failures = [];
            for (const before of changed.reverse()) {
                try {
                    await changeReceipt(before.id, receipt => {
                        receipt.origin = before.origin;
                        if (receipt.returned && receipt.returned.at === before.returned?.at) {
                            if (before.returned.notifiedAt)
                                receipt.returned.notifiedAt = before.returned.notifiedAt;
                            else
                                delete receipt.returned.notifiedAt;
                        }
                        return true;
                    });
                }
                catch (rollback) {
                    failures.push(`${before.id}: ${failureReason(rollback)}`);
                }
            }
            if (failures.length)
                throw new Error(`${failureReason(error)} Receipt routing rollback failed: ${failures.join("; ")}`);
            throw error;
        }
    });
}
/** No ledger yet is normal; any other read failure is logged before it reads as empty. */
async function receiptNames(root) {
    try {
        return await readdir(root);
    }
    catch (error) {
        if (error.code !== "ENOENT")
            logger.warn("dispatch", `Could not list dispatch receipts: ${failureReason(error)}`);
        return [];
    }
}
/** One bounded line for a log or a receipt: a Bridge message, an errno code, or the error's first line. */
export function failureReason(error) {
    if (error instanceof z.ZodError)
        return "The remote Hook sent an unexpected reply (protocol mismatch).";
    const code = error?.code;
    const message = error instanceof Error ? error.message.split("\n")[0] : String(error);
    return `${typeof code === "string" && !(error instanceof BridgeError) ? `${code}: ` : ""}${message}`.replace(/[\x00-\x1f\x7f]/g, " ").slice(0, 200);
}
/** A fresh terminal snapshot proves the bound worker gone; a failed snapshot does not. */
export async function boundWorkerGone(receipt) {
    const target = receipt.target;
    if (!target)
        return false;
    try {
        const { findPane } = await import("./herdr.js");
        const { terminalProvider } = await import("./terminal.js");
        const snapshot = await terminalProvider().snapshot(target.server);
        // A launch token binds the pane itself; without one, the agent must match.
        const address = "starting" in target && target.starting === true
            ? { workspace: target.workspace, tab: target.tab, pane: target.pane }
            : target;
        return !findPane(snapshot, address);
    }
    catch {
        return false;
    }
}
/** A worker that may still run has no termination time; drop any stale retention clock. */
export async function clearWorkerEnded(id) {
    await updateReceipt(id, value => {
        if (!value.endedAt && !value.retainedUntil)
            return false;
        delete value.endedAt;
        delete value.retainedUntil;
        return true;
    }).catch(() => undefined);
}
/**
 * A successful terminal snapshot on the launch's server, and the pane carrying
 * this launch's starting token. `ok: false` means the snapshot or an identity
 * read failed, so no conclusion can be drawn.
 */
export async function scanStartingToken(receipt) {
    const token = receipt.startingToken;
    const server = receipt.launchServer ?? receipt.target?.server;
    if (!token || !server)
        return { ok: false };
    try {
        const { paneChatState, paneStartingToken } = await import("./herdr.js");
        const { terminalProvider } = await import("./terminal.js");
        const snapshot = await terminalProvider().snapshot(server);
        const panes = objects(snapshot.panes);
        for (const pane of panes) {
            if (pane.startingToken === token || paneStartingToken(server, pane) === token)
                return { ok: true, pane };
        }
        for (const pane of panes) {
            if (typeof pane.agent === "string" && pane.agent) {
                const chat = await paneChatState(server, pane).catch(() => undefined);
                if (!chat)
                    return { ok: false };
                if (chat.startingToken === token)
                    return { ok: true, pane };
            }
        }
        return { ok: true };
    }
    catch {
        return { ok: false };
    }
}
/** The exact binding for a pane that carries the launch's starting token. */
export function startingTargetFromPane(receipt, pane) {
    const server = receipt.launchServer ?? receipt.target?.server;
    const source = provider.safeParse(pane.agent);
    if (!server || !source.success || !id.safeParse(pane.workspace_id).success || !id.safeParse(pane.tab_id).success || !id.safeParse(pane.pane_id).success)
        return undefined;
    const binding = { server, workspace: String(pane.workspace_id), tab: String(pane.tab_id), pane: String(pane.pane_id), source: source.data };
    const session = typeof pane.sessionId === "string" ? pane.sessionId : typeof pane.session_id === "string" ? pane.session_id : undefined;
    if (session)
        return { ...binding, session };
    const token = typeof pane.startingToken === "string" ? pane.startingToken : receipt.startingToken;
    return token ? { ...binding, starting: true, startingToken: token } : undefined;
}
/** A launch error before any target: an explicit 4xx refusal is not-started;
 * timeouts, 5xx and transport errors leave the outcome unknown. */
function launchFailureOutcome(error) {
    if (!(error instanceof BridgeError))
        return "ambiguous";
    if (error.status === 504 || error.status >= 500)
        return "ambiguous";
    if (error.status >= 400 && error.status < 500) {
        const code = typeof error.details?.code === "string" ? error.details.code : undefined;
        if (code === "harness_unavailable" || code === "account_unavailable" || code === "outside_set" || code === "account_pool")
            return "not-started";
        if ([400, 401, 403, 404, 422].includes(error.status))
            return "not-started";
        return "ambiguous";
    }
    return "ambiguous";
}
/** A keyed lookup, after reconciling a launch that was interrupted. */
async function lookupKeyedDispatch(key) {
    const record = await findIdempotencyKey(key);
    if (!record)
        return undefined;
    await reconcileIdempotencyRecord(record);
    let receipt = await readReceipt(record.dispatchId).catch(() => undefined);
    if (!receipt)
        return undefined;
    if (record.cancelRequestedAt && !receipt.cancelRequestedAt) {
        await withIdempotencyKeyLock(record.key, async (current) => {
            if (!current?.cancelRequestedAt)
                return;
            await updateReceipt(record.dispatchId, value => {
                if (value.cancelRequestedAt)
                    return false;
                value.cancelRequestedAt = current.cancelRequestedAt;
                return true;
            }, { duringPlacement: true }).catch(() => undefined);
        });
        const reread = await readReceipt(record.dispatchId).catch(() => undefined);
        if (reread)
            receipt = reread;
    }
    const settled = receipt;
    return { ok: settled.state === "accepted", ...settled, dispatch: settled.id, existing: true };
}
/** A key cancelled before its receipt existed: settle it as failed/cancelled without launching. */
export async function settleCancelledReservation(record) {
    if (await launchInProgress(record.dispatchId)) {
        throw new BridgeError(409, "This dispatch's launch is in progress; its cancel is recorded and will be applied.");
    }
    const existing = await readReceipt(record.dispatchId).catch(() => undefined);
    if (existing)
        return existing;
    const at = new Date().toISOString();
    const receipt = {
        id: record.dispatchId,
        computer: record.computer ?? "local",
        project: record.project ?? "unknown",
        harness: record.harness ?? "claude",
        label: record.label ?? "gitboy agent",
        createdAt: record.createdAt,
        updatedAt: at,
        state: "failed",
        error: "cancelled",
        returned: { state: "failed", at, error: "cancelled", read: false },
        idempotencyKey: record.key,
        launchOutcome: "not-started",
        ...(record.startingToken ? { startingToken: record.startingToken } : {}),
        endedAt: at,
        retainedUntil: new Date(Date.parse(at) + 7 * 24 * 60 * 60_000).toISOString(),
        ...(record.cloneDir ? { cloneDir: record.cloneDir } : {}),
        ...(record.gitConfigFile ? { gitConfigFile: record.gitConfigFile } : {}),
        ...(record.agentTokenFile ? { agentTokenFile: record.agentTokenFile } : {}),
        ...(record.workerFile ? { workerFile: record.workerFile } : {}),
    };
    await saveReceipt(receipt);
    await removeDispatchSecrets({ cloneDir: record.cloneDir, gitConfigFile: record.gitConfigFile, agentTokenFile: record.agentTokenFile });
    await updateIdempotencyPhase(record.key, record.owner, "failed").catch(() => undefined);
    return receipt;
}
/**
 * An interrupted launch is resolved by durable proof: a keyed worker's PID and
 * start time, or (for unkeyed work) the launch's starting token. A live launch
 * lock means the launch is still placing, so nothing is final.
 */
async function confirmInterruptedLaunch(receipt) {
    const paths = { cloneDir: receipt.cloneDir, gitConfigFile: receipt.gitConfigFile, agentTokenFile: receipt.agentTokenFile, workerFile: receipt.workerFile };
    const clearSeed = async () => {
        if (receipt.startingToken)
            (await import("./herdr.js")).clearStartingTokenByToken(receipt.startingToken);
    };
    const finish = async () => {
        const at = new Date().toISOString();
        await updateReceipt(receipt.id, value => {
            if (!value.endedAt)
                value.endedAt = at;
            if (!value.retainedUntil)
                value.retainedUntil = new Date(Date.parse(at) + 7 * 24 * 60 * 60_000).toISOString();
            return true;
        }, { duringPlacement: true }).catch(() => undefined);
        const until = receipt.retainedUntil ? Date.parse(receipt.retainedUntil) : NaN;
        if (Number.isFinite(until) && Date.now() >= until)
            await removeDispatchClone(paths);
    };
    if (receipt.idempotencyKey) {
        const alive = await workerAlive(receipt.id, receipt.workerFile ?? dispatchClonePaths(receipt.id).workerFile, receipt.submittedAt);
        if (alive === "unknown")
            return;
        if (alive === "alive") {
            await updateReceipt(receipt.id, value => {
                value.launchOutcome = "started";
                return true;
            }, { duringPlacement: true }).catch(() => undefined);
            return;
        }
        await removeDispatchSecrets(paths);
        await removeWorkerFile(receipt.id);
        await finish();
        return;
    }
    if (receipt.launchOutcome === "not-started") {
        await removeDispatchSecrets(paths);
        await clearSeed();
        await finish();
        return;
    }
    if (!receipt.startingToken)
        return;
    const scan = await scanStartingToken(receipt);
    if (!scan.ok)
        return;
    if (scan.pane) {
        const target = startingTargetFromPane(receipt, scan.pane);
        if (!target)
            return;
        await updateReceipt(receipt.id, value => {
            if (!value.target)
                value.target = target;
            value.launchOutcome = "started";
            return true;
        }, { duringPlacement: true }).catch(() => undefined);
        return;
    }
    const since = receipt.scanSince;
    if (!since) {
        await updateReceipt(receipt.id, value => {
            if (!value.scanSince)
                value.scanSince = new Date().toISOString();
            return true;
        }, { duringPlacement: true }).catch(() => undefined);
        return;
    }
    if (!Number.isFinite(Date.parse(since)) || Date.now() - Date.parse(since) < 24 * 60 * 60_000)
        return;
    await removeDispatchSecrets(paths);
    await clearSeed();
    await finish();
}
/**
 * A reservation stuck in `reserved` or `launching` for five minutes with no
 * target and no live worker is an interrupted launch. It becomes a failed
 * receipt with "launch interrupted"; nothing is relaunched automatically.
 */
export async function reconcileIdempotencyRecord(record) {
    const terminal = await readReceipt(record.dispatchId).catch(() => undefined);
    if (terminal && isLocalComputer(terminal.computer)) {
        const state = terminal.returned?.state;
        const done = state === "done";
        const keepOpen = terminal.closeOnFinish === false;
        const paths = {
            cloneDir: record.cloneDir ?? terminal.cloneDir,
            gitConfigFile: record.gitConfigFile ?? terminal.gitConfigFile,
            agentTokenFile: record.agentTokenFile ?? terminal.agentTokenFile,
            workerFile: record.workerFile ?? terminal.workerFile,
        };
        // Failed, cancelled and interrupted work keeps its clone (recoverable).
        // Retention starts only once durable proof confirms the worker gone;
        // a failed return alone never removes its token.
        if (state === "failed" || state === "gone" || (terminal.closedAt && !done)) {
            if (terminal.idempotencyKey) {
                const alive = await workerAlive(terminal.id, terminal.workerFile ?? paths.workerFile, terminal.submittedAt);
                if (alive !== "gone") {
                    await clearWorkerEnded(terminal.id);
                    return;
                }
                await removeDispatchSecrets(paths);
                await removeWorkerFile(terminal.id);
                let endedAt = terminal.endedAt;
                let retainedUntil = terminal.retainedUntil;
                if (!endedAt) {
                    const at = terminal.closedAt ?? new Date().toISOString();
                    const until = new Date(Date.parse(at) + 7 * 24 * 60 * 60_000).toISOString();
                    endedAt = at;
                    retainedUntil = until;
                    await updateReceipt(terminal.id, value => {
                        if (!value.endedAt)
                            value.endedAt = at;
                        if (!value.retainedUntil)
                            value.retainedUntil = until;
                        return true;
                    }).catch(() => undefined);
                }
                else if (!retainedUntil) {
                    const until = new Date(Date.parse(endedAt) + 7 * 24 * 60 * 60_000).toISOString();
                    retainedUntil = until;
                    await updateReceipt(terminal.id, value => {
                        if (!value.retainedUntil)
                            value.retainedUntil = until;
                        return true;
                    }).catch(() => undefined);
                }
                if (retainedUntil && Number.isFinite(Date.parse(retainedUntil)) && Date.now() >= Date.parse(retainedUntil)) {
                    if (await workerAlive(terminal.id, terminal.workerFile ?? paths.workerFile, terminal.submittedAt) === "gone")
                        await removeDispatchClone(paths);
                }
                return;
            }
            if (!terminal.target) {
                // An ambiguous launch has no binding to snapshot: its own starting
                // token decides whether a worker runs.
                await confirmInterruptedLaunch(terminal);
                return;
            }
            if (!await boundWorkerGone(terminal)) {
                await clearWorkerEnded(terminal.id);
                return;
            }
            await removeDispatchSecrets(paths);
            let endedAt = terminal.endedAt;
            let retainedUntil = terminal.retainedUntil;
            if (!endedAt) {
                const at = terminal.closedAt ?? new Date().toISOString();
                const until = new Date(Date.parse(at) + 7 * 24 * 60 * 60_000).toISOString();
                endedAt = at;
                retainedUntil = until;
                await updateReceipt(terminal.id, value => {
                    if (!value.endedAt)
                        value.endedAt = at;
                    if (!value.retainedUntil)
                        value.retainedUntil = until;
                    return true;
                }).catch(() => undefined);
            }
            else if (!retainedUntil) {
                const until = new Date(Date.parse(endedAt) + 7 * 24 * 60 * 60_000).toISOString();
                retainedUntil = until;
                await updateReceipt(terminal.id, value => {
                    if (!value.retainedUntil)
                        value.retainedUntil = until;
                    return true;
                }).catch(() => undefined);
            }
            if (retainedUntil && Number.isFinite(Date.parse(retainedUntil)) && Date.now() >= Date.parse(retainedUntil)) {
                // Confirm again at the moment of deletion; a live worker keeps its clone.
                if (!await boundWorkerGone(terminal)) {
                    await clearWorkerEnded(terminal.id);
                    return;
                }
                await removeDispatchClone(paths);
            }
            return;
        }
        if (done) {
            if (terminal.idempotencyKey) {
                if (terminal.closedAt) {
                    await removeDispatchClone(paths);
                    return;
                }
                if (keepOpen) {
                    await clearWorkerEnded(terminal.id);
                    return;
                }
                const alive = await workerAlive(terminal.id, terminal.workerFile ?? paths.workerFile, terminal.submittedAt);
                if (alive === "gone") {
                    await removeDispatchClone(paths);
                    return;
                }
                await clearWorkerEnded(terminal.id);
                return;
            }
            if (terminal.closedAt) {
                await removeDispatchClone(paths);
                return;
            }
            if (keepOpen) {
                // Keep-open work is never deleted before it is closed.
                await clearWorkerEnded(terminal.id);
                return;
            }
            if (await boundWorkerGone(terminal)) {
                await removeDispatchClone(paths);
                return;
            }
            await clearWorkerEnded(terminal.id);
        }
    }
    const closeIfCancelled = async () => {
        const current = await updateReceipt(record.dispatchId, () => false, { duringPlacement: true }).catch(() => undefined);
        if (!current?.cancelRequestedAt || !current.target)
            return false;
        const { closeVerifiedWorker } = await import("./worker-close.js");
        await closeVerifiedWorker(current);
        return true;
    };
    if (await closeIfCancelled())
        return;
    if (record.phase !== "reserved" && record.phase !== "launching")
        return;
    if (Date.now() - Date.parse(record.createdAt) < LAUNCH_INTERRUPTED_MS)
        return;
    let receipt;
    try {
        receipt = await readReceipt(record.dispatchId);
    }
    catch {
        return;
    }
    if (receipt) {
        if (receipt.target) {
            if (receipt.state === "launching" || receipt.state === "sending") {
                await updateReceipt(receipt.id, value => {
                    if (value.state === "launching" || value.state === "sending")
                        value.state = "uncertain";
                    return true;
                }, { duringPlacement: true }).catch(() => undefined);
            }
            await updateIdempotencyPhase(record.key, record.owner, "launched").catch(() => undefined);
            await closeIfCancelled();
            return;
        }
        // The launch's own arrival record names the pane or session it created,
        // even when the receipt died before saving the target.
        const arrival = await briefArrival(record.dispatchId).catch(() => undefined);
        const arrived = arrival?.accepted?.target ?? arrival?.started?.target;
        if (arrived) {
            await serializeReceiptUpdate(async () => {
                const current = await readReceipt(record.dispatchId);
                if (!current || current.target)
                    return;
                current.target = remoteTarget.parse(arrived);
                current.state = arrival?.accepted ? "accepted" : "uncertain";
                if (!current.cloneDir && record.cloneDir)
                    current.cloneDir = record.cloneDir;
                if (!current.gitConfigFile && record.gitConfigFile)
                    current.gitConfigFile = record.gitConfigFile;
                if (!current.agentTokenFile && record.agentTokenFile)
                    current.agentTokenFile = record.agentTokenFile;
                current.updatedAt = new Date().toISOString();
                await saveReceipt(current);
            }).catch(() => undefined);
            await updateIdempotencyPhase(record.key, record.owner, "launched").catch(() => undefined);
            await closeIfCancelled();
            return;
        }
        const worker = receipt.worker;
        const workerLive = worker && ["working", "blocked", "needs-you", "waiting"].includes(worker.state)
            && Number.isFinite(Date.parse(worker.checkedAt)) && Date.now() - Date.parse(worker.checkedAt) < LAUNCH_INTERRUPTED_MS;
        if (workerLive) {
            if (receipt.state === "launching" || receipt.state === "sending") {
                await updateReceipt(receipt.id, value => {
                    if (value.state === "launching" || value.state === "sending")
                        value.state = "uncertain";
                    return true;
                }, { duringPlacement: true }).catch(() => undefined);
            }
            return;
        }
        if (receipt.returned && ["done", "failed", "gone"].includes(receipt.returned.state)) {
            if (receipt.returned.state !== "done" && !receipt.target)
                await confirmInterruptedLaunch(receipt);
            await updateIdempotencyPhase(record.key, record.owner, "failed").catch(() => undefined);
            return;
        }
        // Never publish an interrupted-launch failure while a launch lock is live
        // or the durable process proof says the worker may still run.
        let lockLive = false;
        try {
            lockLive = await launchInProgress(record.dispatchId);
        }
        catch {
            lockLive = true;
        }
        if (lockLive)
            return;
        let alive = "unknown";
        try {
            alive = await workerAlive(record.dispatchId, receipt.workerFile ?? record.workerFile ?? dispatchClonePaths(record.dispatchId).workerFile, receipt.submittedAt);
        }
        catch {
            return;
        }
        if (alive !== "gone")
            return;
        // A stale receipt can still say launching/sending; the ordinary writer
        // refuses those, so reconcile it under the receipt lock directly.
        const interrupted = await serializeReceiptUpdate(async () => {
            const current = await readReceipt(receipt.id);
            if (!current || current.target || current.closedAt)
                return undefined;
            if (current.returned && ["done", "failed", "gone"].includes(current.returned.state))
                return current;
            current.state = "failed";
            current.error = "launch interrupted";
            current.updatedAt = new Date().toISOString();
            current.returned = { state: "failed", at: current.updatedAt, error: "launch interrupted", read: false };
            if (!current.startingToken && record.startingToken)
                current.startingToken = record.startingToken;
            if (!current.workerFile && record.workerFile)
                current.workerFile = record.workerFile;
            if (!current.launchServer)
                current.launchServer = localHost().server;
            current.launchOutcome = current.launchOutcome ?? (record.phase === "reserved" ? "not-started" : "ambiguous");
            if (current.launchOutcome === "not-started") {
                current.endedAt = current.updatedAt;
                current.retainedUntil = new Date(Date.now() + 7 * 24 * 60 * 60_000).toISOString();
            }
            await saveReceipt(current);
            return current;
        }).catch(() => undefined);
        if (interrupted)
            await confirmInterruptedLaunch(interrupted);
        await updateIdempotencyPhase(record.key, record.owner, "failed").catch(() => undefined);
        return;
    }
    // The launch may have recorded its arrival even if the receipt write was lost.
    const arrival = await briefArrival(record.dispatchId).catch(() => undefined);
    const arrived = arrival?.accepted?.target ?? arrival?.started?.target;
    if (arrived) {
        const at = new Date().toISOString();
        const recovered = {
            id: record.dispatchId,
            computer: record.computer ?? "local",
            project: record.project ?? "unknown",
            harness: record.harness ?? "claude",
            label: record.label ?? "gitboy agent",
            createdAt: record.createdAt,
            updatedAt: at,
            state: "accepted",
            target: remoteTarget.parse(arrived),
            ...(record.cloneDir ? { cloneDir: record.cloneDir } : {}),
            ...(record.gitConfigFile ? { gitConfigFile: record.gitConfigFile } : {}),
            ...(record.agentTokenFile ? { agentTokenFile: record.agentTokenFile } : {}),
        };
        await saveReceipt(recovered);
        await updateIdempotencyPhase(record.key, record.owner, "launched").catch(() => undefined);
        return;
    }
    // The process died after reserving but before its first receipt write.
    const at = new Date().toISOString();
    // A no-receipt reservation is only an interrupted launch once the lock is
    // over and the durable process proof says no worker is running.
    let lockLive = false;
    try {
        lockLive = await launchInProgress(record.dispatchId);
    }
    catch {
        lockLive = true;
    }
    if (lockLive)
        return;
    let alive = "unknown";
    try {
        alive = await workerAlive(record.dispatchId, record.workerFile ?? dispatchClonePaths(record.dispatchId).workerFile);
    }
    catch {
        return;
    }
    if (alive !== "gone")
        return;
    const outcome = record.phase === "reserved" ? "not-started" : "ambiguous";
    const fallback = {
        id: record.dispatchId,
        computer: record.computer ?? "local",
        project: record.project ?? "unknown",
        harness: record.harness ?? "claude",
        label: record.label ?? "gitboy agent",
        createdAt: record.createdAt,
        updatedAt: at,
        state: "failed",
        error: "launch interrupted",
        returned: { state: "failed", at, error: "launch interrupted", read: false },
        idempotencyKey: record.key,
        launchOutcome: outcome,
        launchServer: localHost().server,
        ...(record.startingToken ? { startingToken: record.startingToken } : {}),
        ...(outcome === "not-started" ? { endedAt: at, retainedUntil: new Date(Date.parse(at) + 7 * 24 * 60 * 60_000).toISOString() } : {}),
        ...(record.cloneDir ? { cloneDir: record.cloneDir } : {}),
        ...(record.gitConfigFile ? { gitConfigFile: record.gitConfigFile } : {}),
        ...(record.agentTokenFile ? { agentTokenFile: record.agentTokenFile } : {}),
        ...(record.workerFile ? { workerFile: record.workerFile } : {}),
    };
    await saveReceipt(fallback);
    await confirmInterruptedLaunch(fallback);
    await updateIdempotencyPhase(record.key, record.owner, "failed").catch(() => undefined);
}
/** Reconcile every live reservation; called on Hook start. */
export async function reconcileInterruptedDispatches() {
    for (const record of await listIdempotencyRecords()) {
        await reconcileIdempotencyRecord(record).catch(error => logger.warn("dispatch", `Could not reconcile idempotency key ${record.key}: ${failureReason(error)}`));
    }
}
/** The durable record for a key after reconciliation, for cancel-by-key and dispatch retries. */
export async function reconcileIdempotencyKey(key) {
    const record = await findIdempotencyKey(key);
    if (record)
        await reconcileIdempotencyRecord(record);
    return record;
}
export function dispatchStatus() {
    return serializeReceiptUpdate(readDispatchStatus);
}
/** Receipts `GET /v1/dispatch` lists when the caller names no `limit`. */
export const DISPATCH_LIST_DEFAULT = 20;
/** Bytes of receipts one `GET /v1/dispatch` answer carries, whatever its `limit`. */
export const DISPATCH_LIST_BYTES = 262_144;
/**
 * The receipts with the newest activity (the later of a return and the last
 * update), in the ledger's newest-first order. The ledger keeps up to 1024
 * receipts with each worker's final reply, and a phone reads this list on a
 * timer for one line about the newest one: sending all of it was a megabyte
 * per read. Code inside the Hook reads the whole ledger with `dispatchStatus`.
 */
export function recentDispatches(receipts, limit = DISPATCH_LIST_DEFAULT, byteLimit = DISPATCH_LIST_BYTES) {
    const activity = (receipt) => receipt.returned && receipt.returned.at > receipt.updatedAt ? receipt.returned.at : receipt.updatedAt;
    const kept = new Set();
    let bytes = 0;
    for (const receipt of [...receipts].sort((a, b) => activity(b).localeCompare(activity(a)))) {
        if (kept.size >= limit)
            break;
        bytes += Buffer.byteLength(JSON.stringify(receipt));
        // The newest receipt is always listed, whatever its size.
        if (kept.size && bytes > byteLimit)
            break;
        kept.add(receipt);
    }
    return { dispatches: receipts.filter(receipt => kept.has(receipt)), total: receipts.length, truncated: kept.size < receipts.length };
}
/** One word for clients that do not fold the receipt's states themselves
 * (the phone's dispatch rows, `dispatch_returns` rows). The latest return
 * decides unless the worker is back at work after it. A stalled return is
 * still work in progress; a worker whose finished turn waits on background
 * work is waiting, not working. */
export function dispatchPhase(receipt) {
    const fold = (state) => state === "done" ? "done"
        : state === "waiting" ? "waiting"
            : state === "needs-you" || state === "blocked" || state === "failed" || state === "gone" ? "needs-owner"
                : "working";
    const returned = receipt.returned;
    const workingAgain = receipt.worker?.state === "working" && returned !== undefined && Date.parse(receipt.worker.since) > Date.parse(returned.at);
    if (returned && !workingAgain)
        return fold(returned.state);
    if (receipt.worker)
        return receipt.worker.state === "working" && receipt.worker.waitingOn ? "waiting" : fold(receipt.worker.state);
    if (receipt.state === "failed")
        return "needs-owner";
    if (receipt.closedAt)
        return "done";
    return "working";
}
/** Caller holds receiptUpdates, including for the entire routing snapshot. */
async function readDispatchStatus() {
    const root = path.join(bridgeRoot(), "dispatches");
    const names = (await receiptNames(root)).filter(name => /^[a-f0-9-]{36}\.json$/.test(name)).slice(0, 1024);
    const receipts = [];
    for (const name of names) {
        try {
            const file = path.join(root, name);
            const info = await lstat(file);
            if (!info.isFile() || info.isSymbolicLink() || info.size > MAX_RECEIPT_BYTES)
                continue;
            const receipt = receiptSchema.parse(JSON.parse(await readFile(file, "utf8")));
            // A service restart cannot prove whether an in-flight mutation arrived.
            if (["launching", "sending"].includes(receipt.state))
                receipt.state = "uncertain";
            receipts.push(receipt);
        }
        catch { /* Interrupted or old receipts do not become live dispatches. */ }
    }
    return receipts.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
}
const windowRoom = z.object({ leftPercent: z.number().min(0).max(100).optional(), resetsAt: z.string().max(40).optional() }).passthrough().optional();
async function capacity(host, caller) {
    const value = await host.request(caller && !host.local ? `/v1/dispatch/capacity?${caller}` : "/v1/dispatch/capacity");
    const result = z.object({ product: z.literal("phren-hook"), protocol: z.literal(PROTOCOL), working: z.number().int().nonnegative(),
        servers: z.array(z.string()), computer: z.object({ id: z.string().uuid() }).passthrough(),
        // Missing from an older Hook, or when its inventory was not ready in time: unknown, not unavailable.
        harnesses: z.array(z.object({ source: z.string(), installed: z.boolean(), usable: z.boolean(), reason: z.string().optional(),
            accounts: z.array(z.object({ id: z.string(), usable: z.boolean(), reason: z.string().optional() }).passthrough()).optional() }).passthrough()).optional(),
        // Missing from an older Hook or a slow read: that computer's quota is unknown, so it is never ruled out by it.
        usage: z.array(z.object({ source: z.string(), account: z.string().optional(), leftPercent: z.number().min(0).max(100).optional(),
            exhausted: z.boolean().optional(), until: z.string().max(40).optional(), fiveHour: windowRoom, week: windowRoom }).passthrough()).max(64).optional(),
        knowsCaller: z.boolean().optional(),
        // Missing from an older Hook: its memory and load are unknown, never a reason to pass it over.
        overBudget: z.string().max(500).optional() }).parse(value);
    // This computer places on whichever Herdr server its own Hook runs.
    if (host.local && !result.servers.includes(host.server) && result.servers[0])
        host.server = result.servers[0];
    if (!result.servers.includes(host.server))
        throw new BridgeError(503, "Herdr is not running on the selected computer. Headless dispatch is not installed yet.");
    return { working: result.working, computerId: result.computer.id, ...(result.harnesses ? { harnesses: result.harnesses } : {}),
        ...(result.usage ? { usage: result.usage } : {}), ...(result.overBudget ? { overBudget: result.overBudget } : {}),
        ...(caller && result.knowsCaller === false ? { outside: true } : {}) };
}
/** The account this dispatch would run under there, as its capacity probe reports it: Codex's one, or the named Claude home. */
export function roomFor(data, usage) {
    const account = data.account ?? "default";
    return usage?.find(item => item.source === data.harness && (data.harness !== "claude" || (item.account ?? "default") === account));
}
/** " for about 3 more hours" until `until`, or nothing when it is unknown. */
function backIn(until, now) {
    const at = until ? Date.parse(until) : NaN;
    const minutes = Number.isFinite(at) ? Math.max(1, Math.round((at - now) / 60_000)) : undefined;
    return minutes === undefined ? "" : minutes >= 1440 ? ` for about ${Math.round(minutes / 1440)} more days` : minutes >= 60 ? ` for about ${Math.round(minutes / 60)} more hours` : ` for about ${minutes} more minutes`;
}
/** Why `anywhere` must not pick a computer for quota: only an account with none left (at 100% or refusing requests).
 *  Low quota is not a reason; the owner often wants it used before it resets. A Claude dispatch that names no
 *  account runs under whichever has room there, so with several accounts that computer is out only when all are. */
export function outOfQuota(data, usage, now = Date.now()) {
    const claude = usage?.filter(item => item.source === "claude") ?? [];
    if (data.harness === "claude" && !data.account && claude.length > 1) {
        if (claude.some(item => !item.exhausted))
            return undefined;
        return `Its claude accounts all have no quota left${backIn(claude.map(item => item.until).filter((value) => Boolean(value)).sort()[0], now)}.`;
    }
    const room = roomFor(data, usage);
    if (!room?.exhausted)
        return undefined;
    return `Its ${data.harness}${data.harness === "claude" ? ` account ${data.account ?? "default"}` : ""} has no quota left${backIn(room.until, now)}.`;
}
/** A computer's signed-in Claude accounts with their room, pool and role, from its capacity probe. */
export function capacityClaudeRooms(harnesses, usage) {
    const accounts = harnesses?.find(entry => entry.source === "claude")?.accounts ?? [];
    return accounts.map(account => {
        const room = usage?.find(item => item.source === "claude" && (item.account ?? "default") === account.id);
        return withPolicy({ account: account.id, ...(account.key ? { key: account.key } : {}), usable: account.usable,
            ...(room?.fiveHour ? { fiveHour: room.fiveHour } : {}), ...(room?.week ? { week: room.week } : {}),
            ...(room?.exhausted ? { exhausted: true, ...(room.until ? { until: room.until } : {}) } : {}) }, account);
    });
}
/**
 * The Claude account a dispatch runs under on `computer` once pools and roles apply (account-policy.ts):
 * `account` (and why) to name in the launch, or `refused` with why. Undefined leaves the choice to that
 * computer's launch as before: not Claude, nothing reported, or no pool, role or API login in play.
 * A named account is only checked against the pools; roles bind automatic choices only.
 */
export function policyAccount(data, harnesses, usage, computer, project, blocked) {
    if (data.harness !== "claude")
        return undefined;
    // Accounts not reported (a slow read, launch checks off): with the project's pools set they can't be checked.
    if (!harnesses)
        return project.pools ? { refused: `Its Hook did not report its Claude accounts, so ${project.owner}'s allowed pools can't be checked.` } : undefined;
    const rules = [project, claudeComputerRule(computer, harnesses)];
    const rooms = capacityClaudeRooms(harnesses, usage);
    if (data.account) {
        const room = rooms.find(item => item.account === data.account);
        const why = room && poolRefusal(room, rules);
        return why ? { refused: `Claude account ${data.account} may not do this work: ${why}.` } : undefined;
    }
    if (!policyApplies(rooms, rules))
        return undefined;
    const { choice, skipped, lastResort } = choosePolicyAccount(rooms, rules, blocked);
    return choice ? { account: choice.account, reason: choice.reason, ...(lastResort ? { lastResort } : {}) }
        : { refused: `No Claude account there may do this work${skipped.length ? `: ${skipped.join("; ")}` : ""}.`.slice(0, 500) };
}
/** A computer's own pool rule from its Claude listing entry. */
function claudeComputerRule(computer, harnesses) {
    const entry = harnesses?.find(item => item.source === "claude");
    return computerRule(computer, entry?.allowedPools, entry?.poolsUnreadable === true);
}
/** Why a computer cannot run this dispatch's harness and account, or undefined when it can or cannot yet be told.
 * `unknown` (no `harnesses`) only counts against a computer when a non-default account was asked for. */
function unusable(data, harnesses, strictUnknown) {
    if (!harnesses)
        return strictUnknown && data.account && data.account !== "default" ? "Its Hook does not report harnesses or accounts (update it)." : undefined;
    // No account named: any signed-in Claude account there will do (the launch picks one).
    if (data.harness === "claude" && !data.account) {
        const usable = harnesses.find(entry => entry.source === "claude")?.accounts?.find(account => account.usable);
        if (usable)
            return unusable({ harness: "claude", account: usable.id }, harnesses, strictUnknown);
    }
    const availability = hasUsable({ harnesses }, data.harness, data.account);
    return availability.ok ? undefined : availability.reason;
}
/**
 * A freshly started agent may not have written its session yet when the launch
 * returns, so the launch carries no target. Ask the remote pane for a few
 * seconds; the pane ids from the launch are enough to find it. Until its first
 * prompt a new Codex or Claude has no conversation at all, only a starting
 * binding, and that is the target its brief goes to (as the phone's first
 * message does). `status` is the pane's last status when neither appeared.
 */
async function settledTarget(peer, launched, harness, intervalMs = 1_000) {
    const workspace = launched.workspaceId, tab = launched.tabId, pane = launched.paneId;
    if (typeof workspace !== "string" || typeof tab !== "string" || typeof pane !== "string")
        return {};
    let status;
    for (let attempt = 0; attempt < 15; attempt++) {
        await new Promise(resolve => setTimeout(resolve, intervalMs));
        try {
            const result = await peer.request(`/v1/workspaces/panes?server=${encodeURIComponent(peer.server)}&groupId=${encodeURIComponent(workspace)}&childId=${encodeURIComponent(tab)}`);
            const found = (Array.isArray(result.panes) ? result.panes : []).find((p) => p && typeof p === "object" && p.id === pane);
            if (typeof found?.agentStatus === "string")
                status = found.agentStatus;
            const binding = { server: peer.server, workspace, tab, pane, source: harness };
            const session = found?.sessionId;
            if (typeof session === "string" && session)
                return { target: { ...binding, session } };
            if (found?.starting === true && typeof found.startingToken === "string")
                return { target: { ...binding, starting: true, startingToken: found.startingToken } };
        }
        catch { /* The pane list can lag the launch; try again. */ }
    }
    return { status };
}
/** The new agent is holding a screen of its own before it takes any prompt:
 * Claude's folder trust or a sign-in. Only the owner answers those. */
class StartupScreen extends Error {
    status;
    constructor(status) {
        super(`The agent is ${status} on a startup screen.`);
        this.status = status;
    }
}
/**
 * Sends the brief. A fresh agent can read `unknown` to Herdr for a while (long
 * on a loaded machine), and the Hook refuses a prompt to such a pane before
 * typing anything. So that refusal is retried while the pane is still
 * unclassified; a pane that is blocked or waiting really needs its terminal,
 * and that refusal stands.
 */
async function sendBrief(peer, target, text, deliveryId) {
    for (let attempt = 0;; attempt++) {
        // One delivery id for every attempt: the receiving Hook types it once.
        try {
            return await peer.request("/v1/prompt", { target, text, deliveryId });
        }
        catch (error) {
            const unsettled = error instanceof BridgeError && error.status === 409 && /needs input in the terminal first/.test(error.message);
            if (!unsettled || attempt >= 20)
                throw error;
            const panes = await peer.request(`/v1/workspaces/panes?server=${encodeURIComponent(peer.server)}&groupId=${encodeURIComponent(String(target.workspace))}&childId=${encodeURIComponent(String(target.tab))}`).catch(() => undefined);
            const pane = (Array.isArray(panes?.panes) ? panes.panes : []).find((p) => p && typeof p === "object" && p.id === target.pane);
            const status = pane?.agentStatus;
            // Nothing was typed: the refusal came before any text reached the pane.
            if (typeof status === "string" && ["blocked", "waiting"].includes(status))
                throw new StartupScreen(status);
            await new Promise(resolve => setTimeout(resolve, 1_000));
        }
    }
}
/** The pane as the remote Hook lists it now, or undefined when it does not list it. */
async function listedPane(peer, place) {
    const panes = await peer.request(`/v1/workspaces/panes?server=${encodeURIComponent(peer.server)}&groupId=${encodeURIComponent(String(place.workspace))}&childId=${encodeURIComponent(String(place.tab))}`).catch(() => undefined);
    return (Array.isArray(panes?.panes) ? panes.panes : []).find((p) => p && typeof p === "object" && p.id === place.pane);
}
/** Tries of a brief typed into a starting pane before the dispatch fails. */
const BRIEF_TRIES = 2;
/** Looks, one settle interval apart, for a starting pane to read ready, and for a typed brief to show. */
const READY_LOOKS = 15;
const LANDED_LOOKS = 20;
/**
 * A starting agent's terminal takes typed text only once its prompt is drawn,
 * which Herdr reads as idle: text typed while it is still `unknown` can be
 * swallowed with nothing to show for it (Mini w4E, 2026-09-30). Waits for that,
 * at most READY_LOOKS. A startup screen is the owner's to answer; a pane the
 * Hook does not list is not waited on.
 */
async function readyForBrief(peer, target, intervalMs) {
    for (let look = 0; look < READY_LOOKS; look++) {
        const pane = await listedPane(peer, target);
        const status = pane?.agentStatus;
        if (!pane || ["idle", "done", "working"].includes(String(status)))
            return;
        if (status === "blocked" || status === "waiting")
            throw new StartupScreen(String(status));
        await new Promise(resolve => setTimeout(resolve, intervalMs));
    }
}
/**
 * Before a brief is typed again. The first try can reach the agent after its
 * landed window (a loaded machine starts the turn late), and a second copy
 * would hand the worker its task twice, so the pane is read first. It is typed
 * again only into a pane that still sits idle on the same starting binding with
 * no conversation. A conversation, or the agent working, blocked, waiting or
 * done, means it took the first brief; a pane the Hook does not list, on
 * another binding or never classified, cannot be told, and nothing is typed.
 */
async function readyForRetry(peer, target, intervalMs) {
    for (let look = 0; look < READY_LOOKS; look++) {
        if (look)
            await new Promise(resolve => setTimeout(resolve, intervalMs));
        const pane = await listedPane(peer, target);
        if (!pane)
            return { state: "unknown" };
        if (typeof pane.sessionId === "string" && pane.sessionId)
            return { state: "arrived", session: pane.sessionId };
        if (pane.starting === true && pane.startingToken !== target.startingToken)
            return { state: "unknown" };
        const status = String(pane.agentStatus);
        if (status === "idle")
            return { state: "ready" };
        if (["working", "blocked", "waiting", "done"].includes(status))
            return { state: "arrived" };
    }
    return { state: "unknown" };
}
/**
 * Whether a brief typed into a starting pane reached its agent: a conversation
 * appeared, or the agent went to work. Lost when the pane still sits idle on
 * the same starting binding after LANDED_LOOKS; unknown when the Hook does not
 * list the pane, or it no longer holds that binding.
 */
async function briefLanded(peer, target, intervalMs) {
    for (let look = 0; look < LANDED_LOOKS; look++) {
        await new Promise(resolve => setTimeout(resolve, intervalMs));
        const pane = await listedPane(peer, target);
        if (!pane)
            return { state: "unknown" };
        if (typeof pane.sessionId === "string" && pane.sessionId)
            return { state: "arrived", session: pane.sessionId };
        if (pane.starting === true && pane.startingToken !== target.startingToken)
            return { state: "unknown" };
        if (["working", "blocked", "waiting"].includes(String(pane.agentStatus)))
            return { state: "arrived" };
    }
    return { state: "lost" };
}
/** What the worker's own hooks reported for a brief that went with its
 * launch, or undefined when the receiving Hook has no such brief. */
export async function arrivalOf(peer, id) {
    const answer = await peer.request(`/v1/dispatch/arrival?id=${encodeURIComponent(id)}`);
    const arrival = answer.arrival === null ? undefined : arrivalSchema.parse(answer.arrival);
    return arrival;
}
/**
 * A brief that went with the launch is the new agent's first prompt; its
 * UserPromptSubmit hook echoes the dispatch id when the harness submits it.
 * Waits for that echo, and returns the conversation it named.
 */
async function awaitArrival(peer, id, intervalMs) {
    let last = {};
    for (let attempt = 0; attempt < ARRIVAL_ATTEMPTS; attempt++) {
        await new Promise(resolve => setTimeout(resolve, intervalMs));
        last = await arrivalOf(peer, id).catch(() => undefined) ?? last;
        if (last.accepted)
            break;
    }
    return last;
}
/** Claude and Codex take a few seconds to start, load their MCP servers and submit the prompt. */
const ARRIVAL_ATTEMPTS = 30;
/** The pane's status as the remote Hook lists it now. */
async function paneStatus(peer, launched) {
    const panes = await peer.request(`/v1/workspaces/panes?server=${encodeURIComponent(peer.server)}&groupId=${encodeURIComponent(String(launched.workspaceId))}&childId=${encodeURIComponent(String(launched.tabId))}`).catch(() => undefined);
    const pane = (Array.isArray(panes?.panes) ? panes.panes : []).find((p) => p && typeof p === "object" && p.id === launched.paneId);
    return typeof pane?.agentStatus === "string" ? pane.agentStatus : undefined;
}
export class DispatchService {
    identity;
    local;
    settleIntervalMs;
    /** One placement at a time: choosing a computer, saving the receipt and the
     * launch request. Confirming the brief afterwards (up to a minute and a half
     * for a slow starting pane) runs outside it, so other dispatches are not
     * refused meanwhile; `placing` counts those launches toward their
     * computer's load for the next `anywhere` choice. */
    active = false;
    placing = new Map();
    /** `local` is this computer as a dispatch destination (its own Hook's
     * socket); tests replace it so they never reach a real Hook. */
    constructor(identity, local = () => localHost(), settleIntervalMs = 1_000) {
        this.identity = identity;
        this.local = local;
        this.settleIntervalMs = settleIntervalMs;
    }
    /** `originValue` is the local pane the request came from, as its agent's
     * Herdr variables name it; a pane without a running agent is left out.
     * `continues` names the dispatch whose worker hit its usage limit (account-failover.ts). */
    async dispatch(input, originValue, continues) {
        const data = dispatchSchema.parse(input);
        if (data.idempotencyKey && data.worktree !== true) {
            throw new BridgeError(400, "A dispatch with an idempotency key requires --worktree: keyed workers run only in a Phren-managed clone.");
        }
        if (data.idempotencyKey)
            return this.dispatchKeyed(data, randomUUID(), originValue, continues);
        return this.place(data, randomUUID(), originValue, continues);
    }
    /**
     * The gitboy path: a caller that may retry after a crash names a key and
     * gets the dispatch that key already started. The dispatch id is generated
     * before the reservation, and the reservation is published atomically, so
     * two concurrent calls start one agent; the loser returns the winner's
     * receipt.
     */
    async dispatchKeyed(data, dispatchId, originValue, continues) {
        const key = data.idempotencyKey;
        const existing = await lookupKeyedDispatch(key);
        if (existing)
            return existing;
        const known = await findIdempotencyKey(key);
        if (known?.cancelRequestedAt) {
            if (await launchInProgress(known.dispatchId))
                return { ok: false, dispatch: known.dispatchId, pending: true, existing: true };
            const receipt = await settleCancelledReservation(known);
            return { ok: false, ...receipt, dispatch: receipt.id, existing: true };
        }
        const owner = randomUUID();
        const paths = data.worktree === true ? dispatchClonePaths(dispatchId) : undefined;
        const startingToken = randomBytes(32).toString("hex");
        const reservation = await reserveIdempotencyKey(key, dispatchId, owner, { project: data.project, harness: data.harness, label: data.label, computer: data.computer, startingToken, ...(paths ?? {}) });
        if (!reservation.reserved) {
            const record = await waitForIdempotencyKey(key);
            if (!record)
                throw new BridgeError(503, "Another dispatch with this idempotency key did not settle; try again.");
            const receipt = await lookupKeyedDispatch(key);
            if (!receipt)
                throw new BridgeError(503, "The dispatch for this idempotency key has no receipt.");
            return receipt;
        }
        try {
            const result = await this.place(data, dispatchId, originValue, continues, { key, owner, startingToken, ...(paths ? { paths } : {}) });
            return { ...result, existing: false };
        }
        catch (error) {
            // A placement that never saved a receipt gives the key back; once a
            // receipt exists the key stays, so a retry returns that dispatch. A
            // receipt read failure is not proof that none exists.
            let receipt;
            try {
                receipt = await readReceipt(dispatchId);
            }
            catch {
                throw error;
            }
            if (!receipt)
                await releaseIdempotencyKey(key, owner).catch(() => undefined);
            throw error;
        }
    }
    async place(data, dispatchId, originValue, continues, keyed) {
        if (data.idempotencyKey) {
            if (data.harness !== "claude" && data.harness !== "codex") {
                throw new BridgeError(400, "A dispatch with an idempotency key may run only claude or codex; copilot, opencode and other harnesses are refused.");
            }
            if (data.permissionMode && data.permissionMode !== "supervised") {
                throw new BridgeError(400, `A dispatch with an idempotency key runs supervised; --permission-mode ${data.permissionMode} is refused.`);
            }
            data.permissionMode = "supervised";
        }
        if (data.branch && data.worktree !== true)
            throw new BridgeError(400, "--branch needs --worktree.");
        if (data.permissionMode && data.harness === "opencode")
            throw new BridgeError(400, "OpenCode takes its permissions from its own config; permissionMode is for Claude, Codex and Copilot workers.");
        if (this.active)
            throw new BridgeError(429, "A dispatch is already being placed. Try again after its receipt arrives.");
        this.active = true;
        const originWindow = trackDispatchOrigin();
        let holding = true, placed;
        const release = () => { if (holding) {
            holding = false;
            this.active = false;
        } };
        try {
            if (data.parent !== undefined || data.parentTarget !== undefined) {
                if (!this.identity)
                    throw new BridgeError(503, "This Hook cannot validate a dispatch parent.");
                await validateDispatchParent(data, this.identity.computerID, this.identity.validateParentTarget);
            }
            if ((await receiptNames(path.join(bridgeRoot(), "dispatches"))).length >= 1024)
                throw new BridgeError(429, "Dispatch history is full. Archive old receipts before dispatching again.");
            // This computer needs no hooks.yaml entry, so a missing file only
            // matters when the dispatch names another computer.
            const here = this.local();
            // An alias or hostname (`Mac`, `Sams-Mac-mini.local`) names the same computer as its hooks.yaml name.
            const named = data.computer === "anywhere" || isLocalComputer(data.computer, here.names) ? undefined : await linkedComputer(data.computer).catch(() => undefined);
            const toLocal = data.computer !== "anywhere" && (isLocalComputer(data.computer, here.names) || (named !== undefined && "local" in named));
            if (data.idempotencyKey && data.computer !== "anywhere" && !toLocal) {
                throw new BridgeError(400, "Keyed dispatches run on this computer only.");
            }
            const peerName = named && "peer" in named ? named.peer : data.computer;
            const enrolled = await hookPeers().catch(error => { if (toLocal || data.computer === "anywhere")
                return []; throw error; });
            // A conductor dispatches only within its set: each peer says whether it links this computer back.
            const caller = await this.conductorCaller(originValue);
            const peers = [...enrolled.map(candidate => peerHost(candidate)), here];
            let peer;
            let remoteComputerID;
            const skipped = [];
            let incapable = false, spentSeen = false;
            const pooledOut = [], overBudget = [];
            // Pools and roles (account-policy.ts): which Claude account may run this on each computer.
            const projectPools = projectRule(phrenStoreRoot(), data.project);
            const limits = data.harness === "claude" ? await readAccountLimits() : [];
            const pooled = new Map();
            const poolCheck = (host, reported) => {
                const result = policyAccount(data, reported.harnesses, reported.usage, host.name, projectPools, limitedBy(limits, host.name));
                pooled.set(host.name, result);
                return result?.refused;
            };
            if (data.computer === "anywhere") {
                const available = await Promise.all(peers.map(async (candidate) => {
                    try {
                        return { peer: candidate, ...await capacity(candidate, caller) };
                    }
                    catch (error) {
                        // A peer that cannot report capacity sits out this placement, and the receipt says why.
                        skipped.push({ computer: candidate.name, reason: failureReason(error) });
                        return undefined;
                    }
                }));
                skipped.sort((a, b) => a.computer.localeCompare(b.computer));
                const capable = available.filter((item) => !!item).filter(item => {
                    if (item.outside) {
                        skipped.push({ computer: item.peer.name, reason: oneWayHint(item.peer.name) });
                        return false;
                    }
                    const reason = unusable(data, item.harnesses, true);
                    if (reason)
                        incapable = true;
                    if (reason)
                        skipped.push({ computer: item.peer.name, reason: reason.slice(0, 200) });
                    if (reason)
                        return false;
                    // The one quota rule: never place a worker on an account with none left. Low quota still counts as room.
                    const spent = outOfQuota(data, item.usage);
                    if (spent) {
                        spentSeen = true;
                        skipped.push({ computer: item.peer.name, reason: spent });
                        return false;
                    }
                    const refused = poolCheck(item.peer, item);
                    if (refused) {
                        pooledOut.push(item.peer.name);
                        skipped.push({ computer: item.peer.name, reason: refused.slice(0, 200) });
                    }
                    // Out of memory or CPU by its own budget: a worker started there would stall it and every agent on it.
                    if (!refused && item.overBudget) {
                        overBudget.push(item.peer.name);
                        skipped.push({ computer: item.peer.name, reason: `over budget: ${item.overBudget}`.slice(0, 200) });
                        return false;
                    }
                    return !refused;
                });
                skipped.sort((a, b) => a.computer.localeCompare(b.computer));
                // A computer that could only use a last-resort account comes after every computer with another account that fits.
                const lastResort = (name) => Number(pooled.get(name)?.lastResort === true);
                const selected = capable
                    .sort((a, b) => lastResort(a.peer.name) - lastResort(b.peer.name)
                    || a.working + this.inFlight(a.peer.name) - b.working - this.inFlight(b.peer.name) || a.peer.name.localeCompare(b.peer.name))[0];
                peer = selected?.peer;
                remoteComputerID = selected?.computerId;
                // Pools ruled some computers out: say so whatever ruled out the rest, with each computer's reason in `skipped`.
                if (!peer && pooledOut.length)
                    throw new BridgeError(409, `No connected computer has a Claude account that may do this work: pools and roles rule out ${pooledOut.join(", ")}${spentSeen || incapable ? ", and the others are out of quota or can't run it" : ""}.`.slice(0, 500), { code: "account_pool", skipped });
                if (!peer && overBudget.length)
                    throw new BridgeError(503, `Every connected computer that could run this is over its memory or load budget (${overBudget.join(", ")}); try again when one has room.`.slice(0, 500), { code: "over_budget", skipped });
                if (!peer && spentSeen)
                    throw new BridgeError(503, `No connected computer has ${data.harness}${data.harness === "claude" ? ` account ${data.account ?? "default"}` : ""} quota left right now.`, { code: "out_of_quota", skipped });
                if (!peer)
                    throw new BridgeError(503, incapable ? `No enrolled computer with a running Herdr can run ${data.harness}${data.account ? ` account ${data.account}` : ""}.` : "No enrolled computer with a running Herdr is connected.", skipped.length ? { skipped } : undefined);
            }
            else {
                peer = toLocal ? peers.find(candidate => candidate.local) : peers.find(candidate => !candidate.local && candidate.name === peerName);
                if (!peer)
                    throw new BridgeError(404, "Unknown computer. Add its verified connection to hooks.yaml.");
                const reported = await capacity(peer, caller);
                if (reported.outside)
                    throw new BridgeError(409, `${peer.name} is not in this conductor's set. ${oneWayHint(peer.name)}`, { code: "outside_set" });
                remoteComputerID = reported.computerId;
                // A Hook that reports what it can run is believed. An older one that does not is left to answer the launch
                // itself, except for a non-default account: it would ignore `account` and launch under its default login.
                const reason = unusable(data, reported.harnesses, true);
                if (reason)
                    throw new BridgeError(409, `${peer.name} cannot run ${data.harness}${data.account ? ` account ${data.account}` : ""}: ${reason}`);
                const refused = poolCheck(peer, reported);
                if (refused)
                    throw new BridgeError(409, `${peer.name}: ${refused}`, { code: "account_pool" });
                // An agent naming a computer past its budget waits; the owner's own dispatch is never held back.
                if (reported.overBudget && originPaneSchema.safeParse(originValue).success) {
                    throw new BridgeError(503, `${peer.name} is over its memory or load budget: ${reported.overBudget}. Try again when it has room, or dispatch to anywhere.`.slice(0, 500), { code: "over_budget" });
                }
            }
            // Chosen here by pools and roles, the account goes in the launch; otherwise that computer picks, as before.
            // Keyed work is gitboy's runner: its clone and token never leave this Hook.
            if (data.idempotencyKey && !peer.local)
                throw new BridgeError(400, "Keyed dispatches run on this computer only.");
            const policyChoice = data.account ? undefined : pooled.get(peer.name);
            const grant = await findGrant({ action: "dispatch", project: data.project, computer: peer.name });
            // An agent (a call that names its pane) may start a worker only up to its grant's
            // permission ceiling; the owner, calling from the phone or the CLI without a pane, is not capped.
            const agent = originPaneSchema.safeParse(originValue).success;
            if (data.permissionMode && agent && !permissionModeAllowed(data.permissionMode, grant)) {
                throw new BridgeError(403, `No standing grant lets an agent start a worker in ${data.permissionMode} on ${peer.name}. Add maxPermissionMode: ${data.permissionMode} to a grant in conductor.yaml, or dispatch it yourself.`);
            }
            // The owner's release authority policy binds an agent's dispatch (and may
            // lower its mode); the owner's own dispatch only carries the policy's line.
            const checked = agent ? await checkAgentDispatch(data, grant?.maxPermissionMode ?? DEFAULT_MAX_PERMISSION_MODE) : undefined;
            if (checked?.permissionMode)
                data.permissionMode = checked.permissionMode;
            // A keyed dispatch never leaves supervised, whatever a grant or policy says.
            if (data.idempotencyKey)
                data.permissionMode = "supervised";
            const authority = checked?.authority ?? await readAuthority().then(policy => projectAuthority(policy, data.project)).catch(() => undefined);
            const origin = await this.origin(originValue);
            // Prompts are sent over the pipe, never stored in the dispatch ledger.
            const { prompt: originalPrompt, issue, ...metadata } = data;
            const body = peer.local ? originalPrompt : redactPeerHandoff(originalPrompt);
            const issueBlock = issue ? issueBriefBlock(issue) : undefined;
            const prompt = issueBlock ? `${body.trimEnd()}\n\n${issueBlock}` : body;
            if (issueBlock && prompt.length > DISPATCH_PROMPT_LIMIT)
                throw new BridgeError(400, "The prompt and issue instructions exceed the worker brief limit. Shorten the prompt.");
            // A fresh worktree per dispatch: the caller may name its branch (gitboy's
            // brief does), otherwise it is derived from the idempotency key or the id.
            const worktree = data.worktree === true ? (data.branch ?? worktreeBranchFor(data.idempotencyKey, dispatchId)) : undefined;
            const startingToken = keyed?.startingToken ?? randomBytes(32).toString("hex");
            const receipt = { ...metadata, computer: peer.name, computerId: remoteComputerID, id: dispatchId,
                createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), state: "launching",
                startingToken, launchServer: peer.server, launchOutcome: "not-started",
                ...(worktree ? { branch: worktree } : {}),
                ...(grant ? { granted: grantLabel(grant) } : {}), ...(authority?.listed ? { authority: authority.line.slice(0, 600) } : {}),
                ...(checked?.confirmation ? { authorityConfirmed: checked.confirmation.confirmedAt } : {}),
                ...(skipped.length ? { skipped } : {}), ...(origin ? { origin } : {}), ...(continues ? { continues } : {}),
                ...(keyed?.paths ? { cloneDir: keyed.paths.cloneDir, gitConfigFile: keyed.paths.gitConfigFile, agentTokenFile: keyed.paths.agentTokenFile, ...(keyed.paths.workerFile ? { workerFile: keyed.paths.workerFile } : {}) } : {}) };
            if (issue)
                await writeDispatchIssue(receipt.id, issue);
            if (keyed) {
                await withIdempotencyKeyLock(keyed.key, async (record) => {
                    if (record?.cancelRequestedAt) {
                        receipt.cancelRequestedAt = record.cancelRequestedAt;
                        receipt.state = "failed";
                        receipt.error = "cancelled";
                        receipt.returned = { state: "failed", at: new Date().toISOString(), error: "cancelled", read: false };
                    }
                    await save(receipt, originWindow);
                });
            }
            else
                await save(receipt, originWindow);
            const keyCancelled = async () => {
                if (!keyed)
                    return false;
                const durable = await updateReceipt(receipt.id, () => false, { duringPlacement: true });
                const record = await findIdempotencyKey(keyed.key);
                if (!durable?.cancelRequestedAt && !record?.cancelRequestedAt)
                    return false;
                receipt.state = "failed";
                receipt.error = "cancelled";
                receipt.returned = { state: "failed", at: new Date().toISOString(), error: "cancelled", read: false };
                await persistReceipt(receipt, originWindow);
                await updateIdempotencyPhase(keyed.key, keyed.owner, "failed").catch(() => undefined);
                return true;
            };
            if (await keyCancelled())
                return { ok: false, ...receipt, dispatch: receipt.id, existing: false };
            const cancelIfRequested = async () => {
                const durable = await updateReceipt(receipt.id, () => false, { duringPlacement: true });
                if (!durable?.cancelRequestedAt)
                    return undefined;
                const { closeVerifiedWorker } = await import("./worker-close.js");
                const result = await closeVerifiedWorker(durable);
                if (result.pending && (durable.state === "launching" || durable.state === "sending")) {
                    await persistReceipt(receipt, originWindow, value => {
                        if (value.state === "launching" || value.state === "sending")
                            value.state = "uncertain";
                    });
                }
                // A cancelled placement settles its key, so a repeated key reports it.
                if (keyed && !result.pending)
                    await updateIdempotencyPhase(keyed.key, keyed.owner, "failed").catch(() => undefined);
                // The caller gets the dispatch's receipt, settled as cancelled (or
                // still pending), not the close result alone.
                const settled = await updateReceipt(receipt.id, () => false, { duringPlacement: true });
                return { ok: true, ...(settled ?? {}), ...(result.pending ? { pending: true } : {}), dispatch: receipt.id, existing: false };
            };
            try {
                if (keyed && !await updateIdempotencyPhase(keyed.key, keyed.owner, "launching")) {
                    throw new BridgeError(409, "This dispatch no longer owns its idempotency key.");
                }
                if (await keyCancelled())
                    return { ok: false, ...receipt, dispatch: receipt.id, existing: false };
                // The request is about to be sent: from here its outcome may be unknown.
                if (data.idempotencyKey) {
                    const submittedAt = new Date().toISOString();
                    await markSubmitted(dispatchId, new Date(submittedAt));
                    receipt.submittedAt = submittedAt;
                }
                receipt.launchOutcome = "ambiguous";
                await persistReceipt(receipt, originWindow);
                // The brief goes with the launch: a Hook that can start the harness
                // with it says so, and any other types it below.
                const launched = await peer.request(`/v1/workspaces/launch?server=${encodeURIComponent(peer.server)}`, { project: data.project, kind: data.harness, model: data.model, ...(data.effort ? { effort: data.effort } : {}), ...(data.account ?? policyChoice?.account ? { account: data.account ?? policyChoice.account } : {}), ...(data.permissionMode ? { permissionMode: data.permissionMode } : {}), ...(worktree ? { worktree: { branch: worktree } } : {}), startingToken, ...(data.idempotencyKey ? { idempotencyKey: data.idempotencyKey, dispatchId: receipt.id, ...(keyed?.paths ? { phrenPaths: keyed.paths } : {}) } : {}), label: peer.local ? data.label : redactPeerHandoff(data.label), brief: { id: receipt.id, text: prompt }, ...(issue ? { issue } : {}) });
                const parsedLaunched = remoteTarget.safeParse(launched.target);
                if (typeof launched.cloneDir === "string")
                    receipt.cloneDir = launched.cloneDir;
                if (typeof launched.gitConfigFile === "string")
                    receipt.gitConfigFile = launched.gitConfigFile;
                if (typeof launched.agentTokenFile === "string")
                    receipt.agentTokenFile = launched.agentTokenFile;
                if (typeof launched.workerFile === "string")
                    receipt.workerFile = launched.workerFile;
                // Persist the binding and cleanup paths before any snapshot or arrival wait.
                if (parsedLaunched.success && parsedLaunched.data.source === data.harness && parsedLaunched.data.server === peer.server) {
                    receipt.target = parsedLaunched.data;
                    receipt.launchOutcome = "started";
                    await persistReceipt(receipt, originWindow);
                }
                if (keyed)
                    await updateIdempotencyPhase(keyed.key, keyed.owner, "launched").catch(() => undefined);
                const cancelledAfterLaunch = await cancelIfRequested();
                if (cancelledAfterLaunch)
                    return cancelledAfterLaunch;
                // Placed: the brief is confirmed outside the lock.
                placed = peer.name;
                this.placing.set(placed, this.inFlight(placed) + 1);
                if (policyChoice?.account) {
                    receipt.account = policyChoice.account;
                    if (policyChoice.reason)
                        receipt.accountChoice = policyChoice.reason.slice(0, 400);
                    logger.info("dispatch", `${receipt.label} on ${peer.name} runs under Claude account ${policyChoice.account}: ${receipt.accountChoice ?? "pools and roles"}.`);
                    // The receiving Hook chose the Claude account (the one with the most room) when none was named.
                }
                else if (!data.account && typeof launched.account === "string" && isAccountSlug(launched.account)) {
                    receipt.account = launched.account;
                    if (typeof launched.accountChoice === "string")
                        receipt.accountChoice = launched.accountChoice.slice(0, 400);
                    logger.info("dispatch", `${receipt.label} on ${peer.name} runs under Claude account ${launched.account}${receipt.accountChoice ? `: ${receipt.accountChoice}` : ""}.`);
                }
                release();
                // An older Hook ignores the field and starts the worker in its own default mode.
                const ignored = data.permissionMode && launched.permissionMode !== data.permissionMode ? IGNORED_MODE : undefined;
                if (launched.briefLaunched === true) {
                    receipt.brief = "launch";
                    await this.confirmLaunched(peer, receipt, launched, originWindow);
                    if (ignored)
                        receipt.error = [receipt.error, ignored].filter(Boolean).join(" ").slice(0, 500);
                    await persistReceipt(receipt, originWindow);
                    const cancelledAfterConfirm = await cancelIfRequested();
                    if (cancelledAfterConfirm)
                        return cancelledAfterConfirm;
                    return { ok: receipt.state === "accepted", ...receipt, dispatch: receipt.id, existing: false };
                }
                receipt.brief = "typed";
                const settled = launched.target ? { target: launched.target } : await settledTarget(peer, launched, data.harness, this.settleIntervalMs);
                if (!settled.target) {
                    if (["blocked", "waiting"].includes(String(settled.status ?? launched.agentStatus)))
                        throw new StartupScreen(String(settled.status ?? launched.agentStatus));
                    throw new BridgeError(504, `${data.harness} started in the new "${data.label}" pane on ${peer.name} but never showed a conversation or a starting pane (last status ${settled.status ?? "unknown"}), so the brief was not sent. The pane is still open.`);
                }
                const target = remoteTarget.parse(settled.target);
                if (target.source !== data.harness || target.server !== peer.server)
                    throw new BridgeError(502, "The remote Hook returned a different launch target.");
                receipt.target = target;
                receipt.launchOutcome = "started";
                receipt.state = "sending";
                await persistReceipt(receipt, originWindow);
                if (!("starting" in target)) {
                    const result = await sendBrief(peer, target, prompt, `dispatch-${receipt.id}`);
                    receipt.state = result.ok === true && result.deliveryUncertain !== true ? "accepted" : "uncertain";
                }
                else
                    await this.typeIntoStarting(peer, receipt, target, prompt);
                const cancelledAfterSend = await cancelIfRequested();
                if (cancelledAfterSend)
                    return cancelledAfterSend;
                if (ignored)
                    receipt.error = [receipt.error, ignored].filter(Boolean).join(" ").slice(0, 500);
            }
            catch (error) {
                if (error instanceof StartupScreen) {
                    // Known, not uncertain: the brief never reached the pane. Say where
                    // the owner answers, and let the returns loop tell the conductor once.
                    receipt.launchOutcome = "started";
                    const question = `${data.harness} in "${data.label}" on ${peer.name} is waiting on a startup screen (folder trust or sign-in).`.slice(0, 200);
                    receipt.state = "failed";
                    receipt.error = `${question} The brief was not sent. Answer that screen in the pane (the phone can), then hand the brief off to the new session.`.slice(0, 500);
                    receipt.returned = { state: "needs-you", at: new Date().toISOString(), question, read: false };
                }
                else {
                    if (receipt.target)
                        receipt.launchOutcome = "started";
                    else
                        receipt.launchOutcome = launchFailureOutcome(error);
                    receipt.state = receipt.state === "launching" && error instanceof BridgeError && [400, 404, 429, 504].includes(error.status) ? "failed" : "uncertain";
                    receipt.error = error instanceof BridgeError ? error.message.slice(0, 500) : "Remote delivery was not confirmed. Inspect this dispatch before retrying.";
                }
            }
            await persistReceipt(receipt, originWindow);
            return { ok: receipt.state === "accepted", ...receipt, dispatch: receipt.id, existing: false };
        }
        finally {
            originWindow.finish();
            release();
            if (placed) {
                const left = this.inFlight(placed) - 1;
                if (left > 0)
                    this.placing.set(placed, left);
                else
                    this.placing.delete(placed);
            }
        }
    }
    /** Owner continuation: use the same pinned transport and launch/arrival
     * protocol as dispatch, without turning the new chat into a worker. */
    async continueChat(peer, intent, placed) {
        const { to, brief } = intent;
        if (to.harness === "copilot")
            throw new BridgeError(409, PEER_COPILOT_REASON);
        const readPlacement = async () => {
            const saved = await peer.request(`/v1/sessions/move/launch?id=${encodeURIComponent(brief.id)}`, undefined, 5_000).catch(() => undefined);
            if (saved?.paneTarget)
                await placed?.({ paneTarget: saved.paneTarget });
            if (object(saved?.result).target)
                await placed?.(object(saved?.result).target);
        };
        let complete = false;
        const pendingLaunch = peer.request(`/v1/sessions/move/launch?server=${encodeURIComponent(peer.server)}`, intent, 65_000).then(result => { complete = true; return { result }; }, error => { complete = true; return { error }; });
        // Track a created pane while its harness is still starting. Every probe
        // is bounded, and completion stops the monitor before any later move.
        const monitor = (async () => {
            while (!complete) {
                await new Promise(resolve => setTimeout(resolve, this.settleIntervalMs));
                if (!complete)
                    await readPlacement();
            }
        })().catch(() => undefined);
        const outcome = await pendingLaunch;
        await monitor;
        if ("error" in outcome) {
            await readPlacement();
            throw outcome.error;
        }
        const launched = outcome.result;
        if (launched.target)
            await placed?.(launched.target);
        const settled = launched.target ? { target: launched.target } : await settledTarget(peer, launched, to.harness, this.settleIntervalMs);
        const target = remoteTarget.parse(settled.target);
        await placed?.(target);
        if (target.server !== peer.server || target.source !== to.harness)
            throw new BridgeError(502, "The peer returned a different launch target.");
        if (launched.briefLaunched !== true) {
            if (!("session" in target))
                throw new BridgeError(409, "The peer chat is not ready to receive its hand-off; the old chat remains open.");
            const sent = await sendBrief(peer, target, brief.text, `move-${brief.id}-brief`);
            if (sent.ok !== true || sent.deliveryUncertain === true || sent.unsubmitted === true || (sent.delivered !== true && sent.queued !== true)) {
                throw new BridgeError(409, "The peer did not confirm the hand-off; both chats remain open.");
            }
        }
        const arrival = await awaitArrival(peer, brief.id, this.settleIntervalMs);
        const confirmed = targetSchema.parse(arrival.accepted?.target);
        if (confirmed.server !== peer.server || confirmed.source !== to.harness || confirmed.pane !== target.pane
            || confirmed.workspace !== target.workspace || confirmed.tab !== target.tab
            || ("session" in target && confirmed.session !== target.session))
            throw new BridgeError(409, "The peer did not confirm the launched conversation.");
        const listed = await listedPane(peer, confirmed);
        if (!listed || !["idle", "working"].includes(String(listed.agentStatus)))
            throw new BridgeError(409, "The peer chat is not confirmed running; the old chat remains open.");
        return confirmed;
    }
    /** Launches placed on `computer` whose brief is still being confirmed. */
    inFlight(computer) { return this.placing.get(computer) ?? 0; }
    /**
     * A brief typed into a pane that has no conversation yet: typed once the
     * pane reads ready, then confirmed by the conversation it starts. A brief
     * the pane swallowed (still idle on its starting binding) is typed again,
     * under its own delivery id, but only after `readyForRetry` finds the pane
     * still idle there: a first brief that landed late is never typed twice.
     * After BRIEF_TRIES the receipt carries a failed return yet stays watched
     * (uncertain), so a brief that lands later still brings the worker's return.
     * A Claude prompt left typed but unsubmitted is not typed again.
     */
    async typeIntoStarting(peer, receipt, target, prompt) {
        const arrived = (session) => {
            const full = session ? targetSchema.safeParse({ server: target.server, workspace: target.workspace, tab: target.tab, pane: target.pane, source: target.source, session }) : undefined;
            if (full?.success)
                receipt.target = full.data;
            receipt.launchOutcome = "started";
            receipt.state = "accepted";
        };
        for (let attempt = 1;; attempt++) {
            if (attempt === 1)
                await readyForBrief(peer, target, this.settleIntervalMs);
            else {
                const before = await readyForRetry(peer, target, this.settleIntervalMs);
                if (before.state === "arrived") {
                    arrived(before.session);
                    return;
                }
                if (before.state === "unknown") {
                    receipt.state = "uncertain";
                    receipt.error = `The brief typed into the new "${receipt.label}" pane on ${receipt.computer} did not show in time, and the pane can no longer be read as waiting for it, so it was not typed again. The Hook keeps watching the pane.`.slice(0, 500);
                    return;
                }
            }
            const result = await sendBrief(peer, target, prompt, attempt === 1 ? `dispatch-${receipt.id}` : `dispatch-${receipt.id}-${attempt}`);
            const sent = result.ok === true && result.deliveryUncertain !== true;
            const landed = await briefLanded(peer, target, this.settleIntervalMs);
            if (landed.state === "arrived") {
                arrived(landed.session);
                return;
            }
            if (landed.state === "unknown" || result.unsubmitted === true) {
                receipt.state = sent ? "accepted" : "uncertain";
                return;
            }
            logger.info("dispatch", `The brief for ${receipt.computer} ${receipt.label} did not reach the starting pane (try ${attempt} of ${BRIEF_TRIES}).`);
            if (attempt < BRIEF_TRIES)
                continue;
            const error = `The brief typed into the new "${receipt.label}" pane on ${receipt.computer} never reached ${receipt.harness}: after ${BRIEF_TRIES} tries the pane still sits idle with no conversation. The pane is still open; hand the brief off to it or close it.`.slice(0, 500);
            // Watched still: a brief that lands after all brings the worker's own return.
            receipt.state = "uncertain";
            receipt.error = error;
            receipt.returned = { state: "failed", at: new Date().toISOString(), error, read: false };
            return;
        }
    }
    /**
     * A brief that went with the launch: wait for the worker's hook to confirm
     * it by dispatch id. A startup screen (folder trust, sign-in) holds the
     * prompt until the owner answers it, and the harness then submits it by
     * itself, so that is not a failure. Neither confirmed nor held reads
     * uncertain, and the returns loop keeps asking.
     */
    async confirmLaunched(peer, receipt, launched, originWindow) {
        const known = remoteTarget.safeParse(launched.target);
        if (known.success && known.data.source === receipt.harness && known.data.server === peer.server) {
            receipt.target = known.data;
            receipt.launchOutcome = "started";
        }
        receipt.state = "sending";
        await persistReceipt(receipt, originWindow);
        const held = (status) => ["blocked", "waiting"].includes(String(status));
        const arrival = held(launched.agentStatus) ? await arrivalOf(peer, receipt.id).catch(() => undefined) ?? {}
            : await awaitArrival(peer, receipt.id, this.settleIntervalMs);
        const named = arrival.accepted?.target ?? arrival.started?.target;
        if (named && named.source === receipt.harness && named.server === peer.server) {
            receipt.target = named;
            receipt.launchOutcome = "started";
        }
        if (arrival.accepted) {
            receipt.state = "accepted";
            return;
        }
        const status = held(launched.agentStatus) ? String(launched.agentStatus) : await paneStatus(peer, launched);
        receipt.state = "uncertain";
        if (held(status)) {
            const question = `${receipt.harness} in "${receipt.label}" on ${receipt.computer} is waiting on a startup screen (folder trust or sign-in).`.slice(0, 200);
            receipt.error = `${question} The brief is queued as its first prompt and starts once that screen is answered in the pane (the phone can).`.slice(0, 500);
            receipt.returned = { state: "needs-you", at: new Date().toISOString(), question, read: false };
            return;
        }
        receipt.error = `${receipt.harness} started with the brief on ${receipt.computer} but has not confirmed it yet (last status ${status ?? "unknown"}). The Hook keeps checking.`.slice(0, 500);
    }
    /** Every connected computer's signed-in Claude accounts and their room, this computer first:
     * where a worker that hit its usage limit can continue (account-failover.ts). */
    async claudeRooms(context) {
        const here = this.local();
        const hosts = [here, ...(await hookPeers().catch(() => [])).map(candidate => peerHost(candidate))];
        const project = context ? projectRule(phrenStoreRoot(), context.project) : undefined;
        const found = await Promise.all(hosts.map(async (host) => {
            try {
                const reported = await capacity(host);
                const rooms = capacityClaudeRooms(reported.harnesses, reported.usage);
                // Accounts not reported can't be checked against the project's pools: none of them is offered.
                if (!reported.harnesses && project?.pools)
                    return { computer: host.name, local: host.local, rooms: [], all: rooms };
                // Only accounts an automatic choice may take there, under the project's and that computer's pools.
                const rules = [...(project ? [project] : []), claudeComputerRule(host.name, reported.harnesses)];
                return { computer: host.name, local: host.local, rooms: allowedRooms(rooms, rules), all: rooms };
            }
            catch {
                return undefined;
            }
        }));
        const listed = found.filter((item) => !!item);
        // Last-resort accounts only when no other allowed account anywhere has room: the stopped login and any the
        // limits ledger holds back have none.
        const limits = await readAccountLimits();
        // The stopped login by its key, so the same login signed in on another computer has no room either.
        const stoppedRoom = context ? listed.find(item => item.computer === context.stopped.computer)?.all.find(room => room.account === context.stopped.account) : undefined;
        const stoppedKey = context ? limitKey(stoppedRoom ?? { account: context.stopped.account }, context.stopped.computer) : undefined;
        const held = (computer) => {
            const blocked = limitedBy(limits, computer);
            return (room) => !!blocked(room) || limitKey(room, computer) === stoppedKey;
        };
        const other = listed.some(item => item.rooms.some(room => room.role !== "last-resort" && openRoom(room, held(item.computer))));
        // The stopped login stays listed (unchosen, it is held back) so the failover can find its room and reset time.
        return listed.map(({ all, ...item }) => {
            const rooms = other ? item.rooms.filter(room => room.role !== "last-resort") : item.rooms;
            const stopped = context?.stopped.computer === item.computer ? all.find(room => room.account === context.stopped.account) : undefined;
            return { ...item, rooms: stopped && !rooms.includes(stopped) ? [...rooms, stopped] : rooms };
        });
    }
    /** The query a conductor's dispatch sends with each capacity probe; undefined for any other caller. */
    async conductorCaller(value) {
        const pane = originPaneSchema.safeParse(value);
        if (!pane.success)
            return undefined;
        let conductor = await recordedConductor().catch(() => undefined);
        const delegated = (await readRoleState())?.succession;
        if (!conductor && delegated?.side === "origin" && delegated.phase === "committed")
            conductor = delegated.previous;
        if (!conductor || conductor.server !== pane.data.server || conductor.pane !== pane.data.pane)
            return undefined;
        return callerQuery(await localCaller());
    }
    async origin(value) {
        const pane = originPaneSchema.safeParse(value);
        if (!pane.success || !this.identity?.originAgent)
            return undefined;
        const running = await this.identity.originAgent(pane.data).catch(() => undefined);
        return running ? { ...pane.data, ...running } : undefined;
    }
}