UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

1,286 lines • 61.4 kB
import { AsyncLocalStorage } from "node:async_hooks";
import { escapeEnvelopeTag, inlineUntrusted, sanitizeUntrustedText } from "./untrusted-text.js";
import { describeRejectedValue } from "./tool-search-setting.js";
import { egressText, redactThenCut } from "./untrusted-egress.js";
import { PEER_MESSAGE_NOTICE } from "../agents/peer-admission.js";
import { buildCrossSessionEnvelope, CROSS_PRINCIPAL_MESSAGE_NOTICE, CROSS_SESSION_MESSAGE_NOTICE, neutralizePeerBody } from "../agents/cross-session-envelope.js";
import { isMemberOutcome, isMemberCoverage, isRefusedAskList, memberRefusalFaces, outcomeOfLegacyRow, sealMemberLedger, sealMemberOutcome } from "./member-outcome.js";
import { deliverEngineNotice } from "./engine-notice.js";
import { isSubagentActions, subagentActionsLine } from "./actions-digest.js";
import { isAutoModeFallbackCause } from "./auto-mode.js";
import { isOccupantToken, sameOccupant } from "../engine/session/repo-utils.js";
import { codedRefusal } from "./thrown-value.js";
import { PEER_TASK_HANDLE_RE } from "./task-registry-shared.js";
import { A2A_WAITING_FOR } from "./a2a-task-state.js";
import { ONE_SHOT_WAIT_CEILING_DEFAULT_MS } from "../config/defaults.js";
import { readsTaskFrame } from "./a2a-deployment-switches.js";
import { waitForOffloadPuts } from "./tool-result-store.js";
export { ONE_SHOT_WAIT_CEILING_DEFAULT_MS };
export const TASK_NOTIFICATION_TERMINAL_STATUSES = Object.freeze(["completed", "failed", "killed", "cancelled"]);
export const NOTIFICATION_INJECTION_OUTCOMES = Object.freeze(["queued", "parked", "parked_durably", "dropped_duplicate", "refused"]);
export function isNotificationInjectionOutcome(value) {
    return typeof value === "string" && NOTIFICATION_INJECTION_OUTCOMES.includes(value);
}
export const SYSTEM_INJECTION_PRIORITIES = ["now", "next", "later"];
export function isSystemInjectionPriority(value) {
    return typeof value === "string" && SYSTEM_INJECTION_PRIORITIES.includes(value);
}
function requireSystemInjectionPriority(value) {
    if (isSystemInjectionPriority(value))
        return value;
    const refusal = new Error(`a steer priority must be one of ${SYSTEM_INJECTION_PRIORITIES.join("/")}, got ${describeRejectedValue(value)}`);
    refusal.code = "steering.invalid_content";
    throw refusal;
}
export function steerPriorityOf(x) {
    return x.priority === undefined ? "next" : requireSystemInjectionPriority(x.priority);
}
const LANE_OF_PRIORITY = { now: "steer", next: "steer", later: "followUp" };
export function injectionLaneOf(priority) {
    return LANE_OF_PRIORITY[requireSystemInjectionPriority(priority)];
}
const TASK_NOTIFICATION_TAGS = [
    "task-notification",
    "task-id",
    "task-type",
    "tool-use-id",
    "status",
    "summary",
    "result",
    "output-file",
    "usage",
    "diagnostics",
    "session-id",
    "recent-steps",
    "edited-files",
    "actions",
    "refused-asks",
    "resumable",
    "agent-name",
    "handback",
    "context",
];
function renderResidual(n) {
    const lines = [];
    if (n.recentSteps && n.recentSteps.length > 0) {
        lines.push(...n.recentSteps.map((s) => `- ${s.tool}${s.target ? ` ${s.target}` : ""}${s.outcome ? ` → ${s.outcome}` : ""}`));
    }
    if (n.editedFiles && n.editedFiles.length > 0) {
        lines.push(`edited: ${n.editedFiles.map((f) => `${f.path}${f.edits > 1 ? ` (×${f.edits})` : ""}`).join(", ")}`);
    }
    return lines.length > 0 ? lines.join("\n") : undefined;
}
function tag(name, value) {
    let shown;
    try {
        shown = typeof value === "string" ? value : String(value);
    }
    catch {
        shown = `[unrenderable ${typeof value}]`;
    }
    const text = sanitizeUntrustedText(shown, TASK_NOTIFICATION_TAGS)
        .replace(/&/g, "&")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;");
    return `<${name}>${text}</${name}>`;
}
export function taskNotificationDedupKey(n) {
    const attempt = n.attempt !== undefined && Number.isInteger(n.attempt) && n.attempt > 1 ? `:a${n.attempt}` : "";
    return `task_notification:${taskNotificationLaneKey(n)}:${n.status}${n.seq !== undefined ? `:${n.seq}` : ""}${attempt}`;
}
export function taskNotificationNoteOptions(payload, priority) {
    return { provenance: "engine-note", enginePayload: payload, engineNoteKey: taskNotificationDedupKey(payload), ...(priority !== undefined ? { engineTier: priority } : {}) };
}
export function taskNotificationFrame(payload, priority) {
    return { type: "task_notification", notification: payload, noteKey: taskNotificationDedupKey(payload), ...(priority !== undefined ? { priority } : {}) };
}
export function taskNotificationLaneKey(n) {
    return n.task_type === "external" ? `external:${n.task_id}` : n.task_id;
}
export function attrEscape(value) {
    return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}
export const EXTERNAL_SOURCE_MAX = 120;
export const AGENT_MESSAGE_TAG = "agent-message";
export function renderAgentMessageFrame(frame) {
    const body = escapeEnvelopeTag(AGENT_MESSAGE_TAG, neutralizePeerBody(frame.body));
    return `<${AGENT_MESSAGE_TAG} from="${attrEscape(frame.from)}">\n${body}\n</${AGENT_MESSAGE_TAG}>\n\n${PEER_MESSAGE_NOTICE}`;
}
export function renderCrossSessionMessageFrame(frame) {
    const { body, ...fields } = frame;
    return `${buildCrossSessionEnvelope(fields, body)}\n\n${fields.fromScope !== undefined ? CROSS_PRINCIPAL_MESSAGE_NOTICE : CROSS_SESSION_MESSAGE_NOTICE}`;
}
export function renderCrossSessionNoticeLine(notice) {
    return sanitizeUntrustedText(notice.text);
}
export const RESUPPLIED_FRAME_PREAMBLE = "[Re-supplied] You were shown this message once before; the compaction that replaced older context with a summary did not keep it, so the engine is handing it over again. It is the SAME message, not a new one \u2014 act on it once.";
export function renderTaskNotificationXml(n) {
    if (n.received !== undefined)
        return n.received.text;
    const body = renderTaskNotificationCarrier(n);
    return n.resupplied === true ? `${RESUPPLIED_FRAME_PREAMBLE}\n\n${body}` : body;
}
function renderTaskNotificationCarrier(n) {
    if (n.agentMessage !== undefined)
        return renderAgentMessageFrame(n.agentMessage);
    if (n.crossSessionMessage !== undefined)
        return renderCrossSessionMessageFrame(n.crossSessionMessage);
    if (n.crossSessionNotice !== undefined)
        return renderCrossSessionNoticeLine(n.crossSessionNotice);
    if (n.inboxNotice !== undefined)
        return renderInboxNoticeLine(n.inboxNotice);
    const usage = n.usage === undefined
        ? undefined
        : (() => {
            try {
                return JSON.stringify(n.usage);
            }
            catch {
                return undefined;
            }
        })();
    const open = n.task_type === "external"
        ? `<task-notification type="external"${n.source !== undefined
            ? ` from="${attrEscape(inlineUntrusted(n.source, EXTERNAL_SOURCE_MAX))}" from-unverified="true"`
            : ""}>`
        : "<task-notification>";
    return [
        open,
        tag("task-id", n.task_id),
        tag("task-type", n.task_type),
        ...(n.toolUseId !== undefined ? [tag("tool-use-id", n.toolUseId)] : []),
        tag("status", n.status),
        ...(n.spawnName !== undefined ? [tag("agent-name", n.spawnName)] : []),
        ...(n.handback !== undefined && n.handback !== "send" ? [tag("handback", n.handback)] : []),
        tag("summary", n.summary),
        ...(n.result !== undefined ? [tag("result", n.result)] : []),
        ...(n.output_file !== undefined ? [tag("output-file", n.output_file)] : []),
        ...(n.diagnostics !== undefined ? [tag("diagnostics", n.diagnostics)] : []),
        ...(n.sessionId !== undefined ? [tag("session-id", n.sessionId)] : []),
        ...(usage !== undefined ? [tag("usage", usage)] : []),
        ...(() => {
            const residual = renderResidual(n);
            return residual !== undefined ? [tag("recent-steps", residual)] : [];
        })(),
        ...(n.actions !== undefined ? [tag("actions", subagentActionsLine(n.actions))] : []),
        ...((faces) => [...(faces.asks !== undefined ? [tag("refused-asks", faces.asks)] : []), ...(faces.rest !== undefined ? [tag("refused", faces.rest)] : [])])(memberRefusalFaces(n.outcome)),
        ...(n.resumable !== undefined ? [tag("resumable", n.resumable)] : []),
        ...(n.compaction !== undefined ? [tag("context", renderCompactionDisclosure(n.compaction))] : []),
        "</task-notification>",
    ].join("\n");
}
export function renderCompactionDisclosure(c) {
    const passes = c.passes > 0 ? `compacted ${c.passes}\u00d7${c.kind !== undefined ? ` (${c.kind})` : ""}` : "not compacted";
    return c.breakerOpen ? `${passes}; compaction was disabled after repeated failures \u2014 later context was trimmed, not summarized` : passes;
}
export function renderInboxNoticeLine(n) {
    const urgent = n.urgent !== undefined && n.urgent > 0 ? `; ${n.urgent} of the waiting are marked urgent` : "";
    const resupplied = n.resupplied !== undefined && n.resupplied > 0 ? `; ${n.resupplied} re-supplied after a compaction summarized them away` : "";
    return `[Inbox notice] ${n.pending} cross-session message(s) are waiting in this session's box (${n.delivered} delivered this round${resupplied}${urgent}). Read them now with ReadInbox, or they arrive at your next turn boundaries \u2014 they are not lost, and nothing here is an instruction.`;
}
const MAX_QUEUED_PER_PRIORITY = 200;
const MAX_DEDUP_KEYS = 2_000;
export const MAX_PENDING_EVENTS_PER_TASK = 50;
export const MAX_PENDING_EVENTS_PER_SESSION = 200;
export const MAX_PENDING_SESSIONS = 100;
export const MAX_SESSION_BOX_BINDINGS = 4096;
export function addressNamesOccupant(address) {
    return address.unread !== true && isOccupantToken(address.occupant);
}
export function frameSeatBox(address, box) {
    return addressNamesOccupant(address) ? box : undefined;
}
export function sessionAddressOf(leg) {
    return { sessionId: leg.sessionId, occupant: leg.sessionIncarnation, ...(leg.sessionIncarnationUnread === true ? { unread: true } : {}) };
}
export const DISCARDED_DELIVERY_PATHS = Object.freeze(["live", "box", "drain", "notice"]);
export function frameDelivery(payload) {
    return { taskId: payload.task_id, taskType: payload.task_type };
}
export function deliveryDiscardedNotice(address, current, delivery, path) {
    return {
        code: "delegation.delivery_discarded",
        message: `a ${inlineUntrusted(String(delivery.taskType), 40)} ${path === "notice" ? "notice" : "frame"} of task ${inlineUntrusted(String(delivery.taskId), 120)} was addressed to session ${inlineUntrusted(address.sessionId, 120)} under an occupant the session does not hold now (the id was deleted and created again, or the address carried no occupant), so it was discarded, not delivered`,
        detail: {
            taskId: delivery.taskId,
            taskType: delivery.taskType,
            sessionId: address.sessionId,
            path,
            addressed: sameOccupant(address.occupant, undefined) ? "unknown" : "known",
            current: sameOccupant(current, undefined) ? "unknown" : "known",
        },
    };
}
export const HANDBACK_STATES = Object.freeze(["send", "flagged", "withheld"]);
export function handbackStateOf(facts) {
    if (facts.warning !== undefined)
        return "flagged";
    return facts.result || facts.partialText ? "send" : "withheld";
}
export const COMPACTION_KINDS = Object.freeze(["manual", "auto", "reactive"]);
export function compactionKindOf(trigger) {
    return trigger === "forced" ? "reactive" : trigger;
}
export function terminalFrameFacets(facts) {
    return {
        ...(facts.spawnName !== undefined ? { spawnName: facts.spawnName } : {}),
        handback: handbackStateOf(facts),
        ...(facts.compaction !== undefined ? { compaction: { passes: facts.compaction.passes, breakerOpen: facts.compaction.breakerOpen, ...(facts.compaction.kind !== undefined ? { kind: facts.compaction.kind } : {}) } } : {}),
    };
}
const COMPLETION_REPORT_MAX = 2_000;
function cutReportReading(artifact) {
    switch (artifact.kind) {
        case "stored":
            return `read the full text with ReadToolResult (ref "${artifact.ref}")`;
        case "unconfirmed":
            return "the full text could not be stored (the write failed or went unconfirmed), so no ref can read it back and it is not readable in this session — ask the agent for it via SendMessage";
        case "no_store":
            return "the full text is not stored behind a ref (no offload store), so it is not readable in this session — ask the agent for it via SendMessage";
    }
}
export const SHORT_REPORT_UNSTORED = "a background task's report could not be stored (the write failed or went unconfirmed): its completion frame carried the whole report, but its task row keeps no read handle for a later list";
export async function completionResultField(result, persist, record, notifier) {
    if (!result)
        return undefined;
    const report = egressText("same-principal", result);
    if (report.length <= COMPLETION_REPORT_MAX) {
        void notifier.notifyAsync(async () => {
            const artifact = await persist(report);
            if (artifact.kind === "unconfirmed")
                throw new Error(SHORT_REPORT_UNSTORED);
            if (artifact.kind === "stored")
                record(artifact.ref);
        }, "completionResultField.shortReportWrite");
        return { text: report };
    }
    const waited = await waitForOffloadPuts([Promise.resolve(persist(report))]);
    const first = waited.outcomes[0];
    if (first.status === "rejected")
        throw first.reason;
    const artifact = first.status === "settled" ? first.value : { kind: "unconfirmed" };
    if (artifact.kind === "stored")
        record(artifact.ref);
    return { text: `${report.slice(0, COMPLETION_REPORT_MAX)}\n[result truncated: ${report.length} chars total — ${cutReportReading(artifact)}]` };
}
export const PEER_TASK_FOLLOW_UPS = Object.freeze(["accepted", "not_accepted"]);
export const PEER_TASK_CANCEL_STATES = Object.freeze(["not_requested", "requested", "confirmed"]);
export const PEER_TASK_CLOCK_STATES = Object.freeze(["running", "paused"]);
export const PEER_TASK_REMINDER_TARGETS = Object.freeze(["peer", "peer_owner", "peer_approver"]);
export const PEER_TASK_REMINDER_DISPOSITIONS = Object.freeze(["due", "skipped_not_sent", "sent", "received", "answered"]);
export const PEER_TASK_REMINDER_ROUTES = Object.freeze(["pending_list", "run", "none"]);
export function peerTaskNotification(input) {
    if (!PEER_TASK_HANDLE_RE.test(input.task_id)) {
        throw new RangeError(`peerTaskNotification: task_id must match ${PEER_TASK_HANDLE_RE}, got ${JSON.stringify(input.task_id)}`);
    }
    if (!Number.isSafeInteger(input.seq) || input.seq < 1) {
        throw new RangeError(`peerTaskNotification: seq must be a positive safe integer, got ${String(input.seq)}`);
    }
    if (input.overdueTail === true && input.status !== "event") {
        throw new RangeError(`peerTaskNotification: overdueTail frames must carry status "event", got ${JSON.stringify(input.status)}`);
    }
    const pt = input.peerTask;
    const terminal = isTerminalTaskNotification({ status: input.status });
    const peerTask = {
        destination: pt.destination,
        followUps: pt.followUps,
        cancel: pt.cancel,
        ackBy: pt.ackBy,
        finalBy: pt.finalBy,
        ...(!terminal && pt.waitingFor !== undefined ? { waitingFor: pt.waitingFor } : {}),
        ...((terminal || input.overdueTail === true) && pt.remoteMayContinue === true ? { remoteMayContinue: true } : {}),
    };
    const bad = malformedPeerTaskFacet(peerTask);
    if (bad !== undefined)
        throw new RangeError(`peerTaskNotification: ${bad}`);
    const noWake = input.overdueTail === true && input.status === "event" && pt.destination.boundary === "outside";
    return {
        task_id: input.task_id,
        task_type: "peer_task",
        status: input.status,
        seq: input.seq,
        summary: input.summary,
        ...(input.result !== undefined ? { result: input.result } : {}),
        ...(input.error !== undefined ? { error: input.error } : {}),
        ...(input.errorCode !== undefined ? { errorCode: input.errorCode } : {}),
        ...(input.stoppedBy !== undefined ? { stoppedBy: input.stoppedBy } : {}),
        ...(input.outcome !== undefined ? { outcome: input.outcome } : {}),
        ...(input.completionId !== undefined ? { completionId: input.completionId } : {}),
        ...(noWake ? { noWake: true } : {}),
        peerTask,
    };
}
export const ENGINE_FRAME_CODEC_VERSION = 2;
export const ENGINE_FRAME_TASK_TYPES = Object.freeze(["background_agent", "monitor", "workflow", "peer_task"]);
export function engineFrameCodecVersionFor(taskType) {
    return taskType === "peer_task" ? 2 : 1;
}
const SHELL_LESS_CARRIERS = ["agentMessage", "crossSessionMessage", "crossSessionNotice", "inboxNotice", "_sema_provenance"];
export function isEngineFrameParkable(payload) {
    return ENGINE_FRAME_TASK_TYPES.includes(payload.task_type) && SHELL_LESS_CARRIERS.every((k) => payload[k] === undefined);
}
export function encodeEngineFrame(payload, priority) {
    return JSON.stringify({ codecVersion: engineFrameCodecVersionFor(payload.task_type), priority, payload });
}
export function decodeEngineFrame(content) {
    let raw;
    try {
        raw = JSON.parse(content);
    }
    catch {
        return { ok: false, reason: "malformed", detail: "not JSON" };
    }
    if (raw === null || typeof raw !== "object" || Array.isArray(raw))
        return { ok: false, reason: "malformed", detail: "not an object" };
    const r = raw;
    const version = r["codecVersion"];
    if (typeof version !== "number" || !Number.isInteger(version) || version < 1)
        return { ok: false, reason: "malformed", detail: "codecVersion missing" };
    if (version > ENGINE_FRAME_CODEC_VERSION)
        return { ok: false, reason: "newer", codecVersion: version };
    const priority = r["priority"];
    if (!isSystemInjectionPriority(priority))
        return { ok: false, reason: "malformed", detail: "priority outside the ladder" };
    const p = r["payload"];
    if (p === null || typeof p !== "object" || Array.isArray(p))
        return { ok: false, reason: "malformed", detail: "payload missing" };
    const f = p;
    if (typeof f["task_id"] !== "string" || f["task_id"] === "")
        return { ok: false, reason: "malformed", detail: "task_id missing" };
    if (!ENGINE_FRAME_TASK_TYPES.includes(f["task_type"]))
        return { ok: false, reason: "malformed", detail: "task_type outside the engine's lanes" };
    const requiredVersion = engineFrameCodecVersionFor(f["task_type"]);
    if (version < requiredVersion) {
        return { ok: false, reason: "malformed", detail: `task_type ${String(f["task_type"])} requires codec version ${requiredVersion}, got ${version}` };
    }
    if (typeof f["status"] !== "string" || typeof f["summary"] !== "string")
        return { ok: false, reason: "malformed", detail: "status/summary missing" };
    const facet = malformedFacet(f, version);
    if (facet !== undefined)
        return { ok: false, reason: "malformed", detail: facet };
    const payload = { ...p };
    for (const k of SHELL_LESS_CARRIERS)
        delete payload[k];
    if (payload.outcome !== undefined)
        payload.outcome = sealMemberOutcome(payload.outcome);
    if (payload.members !== undefined)
        payload.members = sealMemberLedger(payload.members);
    const legacy = payload.refusedAsks;
    delete payload.refusedAsks;
    if (isRefusedAskList(legacy) && payload.outcome === undefined) {
        const upgraded = outcomeOfLegacyRow({ status: payload.status, refusedAsks: legacy }, "background_agent");
        if (upgraded !== undefined)
            payload.outcome = upgraded;
    }
    return { ok: true, payload, priority };
}
const SPAWN_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
function malformedFacet(f, codecVersion) {
    if (f["spawnName"] !== undefined && (typeof f["spawnName"] !== "string" || !SPAWN_NAME_RE.test(f["spawnName"])))
        return "spawnName outside the spawn-name grammar";
    if (f["noWake"] !== undefined && f["noWake"] !== true)
        return "noWake is not true";
    if (f["handback"] !== undefined && !(typeof f["handback"] === "string" && HANDBACK_STATES.includes(f["handback"])))
        return "handback outside its closed set";
    const u = f["unreviewed"];
    if (u !== undefined && !(u !== null && typeof u === "object" && !Array.isArray(u) && Object.keys(u).length === 1 && isAutoModeFallbackCause(u.handback)))
        return "unreviewed is not a hand-back cause record";
    if (f["completionId"] !== undefined && !(typeof f["completionId"] === "string" && f["completionId"] !== ""))
        return "completionId is not a non-empty string";
    if (f["resumableUntil"] !== undefined && !(typeof f["resumableUntil"] === "number" && Number.isFinite(f["resumableUntil"]) && f["resumableUntil"] >= 0))
        return "resumableUntil is not an epoch-ms instant";
    const steps = f["recentSteps"];
    if (steps !== undefined && !(Array.isArray(steps) && steps.every((s) => s !== null && typeof s === "object" && typeof s.tool === "string" && typeof s.target === "string" && typeof s.outcome === "string")))
        return "recentSteps is not a list of steps";
    const edits = f["editedFiles"];
    if (edits !== undefined && !(Array.isArray(edits) && edits.every((e) => e !== null && typeof e === "object" && typeof e.path === "string" && typeof e.edits === "number")))
        return "editedFiles is not a list of files";
    if (f["actions"] !== undefined && !isSubagentActions(f["actions"]))
        return "actions is not an actions digest";
    const refused = f["refusedAsks"];
    if (refused !== undefined && !isRefusedAskList(refused))
        return "refusedAsks is not a non-empty list of refused asks";
    const outcome = f["outcome"];
    if (outcome !== undefined && !isMemberOutcome(outcome))
        return "outcome is not a member outcome";
    const members = f["members"];
    if (members !== undefined && !(members !== null && typeof members === "object" && !Array.isArray(members) && typeof members.final === "boolean" && isMemberCoverage(members.coverage) && Array.isArray(members.rows) && (members.rows).every((r) => isMemberOutcome(r) && typeof r.label === "string") && ((cap) => cap === undefined || (typeof cap === "number" && Number.isSafeInteger(cap) && cap > 0))(members.refusedAtMemberCap)))
        return "members is not a member ledger";
    if (f["lines"] !== undefined && !(Array.isArray(f["lines"]) && f["lines"].every((l) => typeof l === "string")))
        return "lines is not a list of strings";
    const c = f["compaction"];
    if (c !== undefined) {
        if (c === null || typeof c !== "object" || Array.isArray(c))
            return "compaction is not an object";
        const { passes, breakerOpen, kind } = c;
        if (typeof passes !== "number" || !Number.isInteger(passes) || passes < 0)
            return "compaction.passes is not a count";
        if (typeof breakerOpen !== "boolean")
            return "compaction.breakerOpen is not a boolean";
        if (kind !== undefined && !(typeof kind === "string" && COMPACTION_KINDS.includes(kind)))
            return "compaction.kind outside its closed set";
    }
    const pt = f["peerTask"];
    if (pt !== undefined && codecVersion >= engineFrameCodecVersionFor("peer_task")) {
        const ptBad = malformedPeerTaskFacet(pt);
        if (ptBad !== undefined)
            return ptBad;
    }
    return undefined;
}
const isEpochMs = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0;
function malformedPeerTaskFacet(pt) {
    if (pt === null || typeof pt !== "object" || Array.isArray(pt))
        return "peerTask is not an object";
    const { destination, followUps, cancel, waitingFor, remoteMayContinue, ackBy, finalBy, peerFinalBy, approvalBy, clock, reminder } = pt;
    if (destination !== undefined) {
        if (destination === null || typeof destination !== "object" || Array.isArray(destination))
            return "peerTask.destination is not an object";
        const { kind, peer, displayName, ownerTeam, boundary } = destination;
        if (kind !== "a2a_peer")
            return "peerTask.destination.kind is not a2a_peer";
        if (typeof peer !== "string" || peer === "")
            return "peerTask.destination.peer is not a non-empty string";
        if (boundary !== "inside" && boundary !== "outside")
            return "peerTask.destination.boundary outside its closed set";
        if (displayName !== undefined && typeof displayName !== "string")
            return "peerTask.destination.displayName is not a string";
        if (ownerTeam !== undefined && typeof ownerTeam !== "string")
            return "peerTask.destination.ownerTeam is not a string";
    }
    if (followUps !== undefined && !(typeof followUps === "string" && PEER_TASK_FOLLOW_UPS.includes(followUps)))
        return "peerTask.followUps outside its closed set";
    if (cancel !== undefined && !(typeof cancel === "string" && PEER_TASK_CANCEL_STATES.includes(cancel)))
        return "peerTask.cancel outside its closed set";
    if (waitingFor !== undefined && !(typeof waitingFor === "string" && A2A_WAITING_FOR.includes(waitingFor)))
        return "peerTask.waitingFor outside its closed set";
    if (remoteMayContinue !== undefined && remoteMayContinue !== true)
        return "peerTask.remoteMayContinue is not true";
    if (ackBy !== undefined && !isEpochMs(ackBy))
        return "peerTask.ackBy is not an epoch-ms instant";
    if (finalBy !== undefined && !isEpochMs(finalBy))
        return "peerTask.finalBy is not an epoch-ms instant";
    if (peerFinalBy !== undefined && !isEpochMs(peerFinalBy))
        return "peerTask.peerFinalBy is not an epoch-ms instant";
    if (approvalBy !== undefined && !isEpochMs(approvalBy))
        return "peerTask.approvalBy is not an epoch-ms instant";
    if (clock !== undefined && !(typeof clock === "string" && PEER_TASK_CLOCK_STATES.includes(clock)))
        return "peerTask.clock outside its closed set";
    if (reminder !== undefined) {
        if (reminder === null || typeof reminder !== "object" || Array.isArray(reminder))
            return "peerTask.reminder is not an object";
        const { n, target, disposition, routedTo } = reminder;
        if (typeof n !== "number" || !Number.isSafeInteger(n) || n < 1)
            return "peerTask.reminder.n is not a positive integer";
        if (!(typeof target === "string" && PEER_TASK_REMINDER_TARGETS.includes(target)))
            return "peerTask.reminder.target outside its closed set";
        if (!(typeof disposition === "string" && PEER_TASK_REMINDER_DISPOSITIONS.includes(disposition)))
            return "peerTask.reminder.disposition outside its closed set";
        if (routedTo !== undefined) {
            if (disposition !== "received" && disposition !== "answered")
                return "peerTask.reminder.routedTo requires disposition received or answered";
            if (!(typeof routedTo === "string" && PEER_TASK_REMINDER_ROUTES.includes(routedTo)))
                return "peerTask.reminder.routedTo outside its closed set";
        }
    }
    return undefined;
}
export function engineFrameRecordOf(payload, priority, to) {
    return {
        id: taskNotificationDedupKey(payload),
        content: encodeEngineFrame(payload, priority),
        sentAt: Date.now(),
        peerMeta: { fromRoot: to.sessionId, kind: "engine_frame", ...(to.occupant !== undefined ? { occupant: to.occupant } : {}) },
    };
}
const MAX_TOMBSTONES = 5_000;
const TERMINAL_STATUSES = new Set(TASK_NOTIFICATION_TERMINAL_STATUSES);
export function isDelegatedAgentTerminal(n) {
    return n.task_type === "background_agent" && TERMINAL_STATUSES.has(n.status);
}
export function isTerminalTaskNotification(n) {
    return TERMINAL_STATUSES.has(n.status);
}
export function resolveCompletionSink(callSink, mountSink) {
    return callSink ?? mountSink;
}
export function admitsBackgroundLaunch(sink, deploymentChannel = false) {
    return sink !== undefined || deploymentChannel;
}
export class DeliveryObligations {
    owed = new Map();
    counted = new Set();
    wakers = new Set();
    waitDeadline;
    stoppedAtCeiling = false;
    owe(task) {
        this.stoppedAtCeiling = false;
        const lane = taskNotificationLaneKey(task);
        this.owed.set(lane, (this.owed.get(lane) ?? 0) + 1);
    }
    discharge(frame) {
        const lane = taskNotificationLaneKey(frame);
        const key = taskNotificationDedupKey(frame);
        if (!this.owed.has(lane) || this.counted.has(key))
            return;
        this.counted.add(key);
        this.release(lane);
    }
    retire(task) {
        this.release(taskNotificationLaneKey(task));
    }
    release(lane) {
        const cycles = this.owed.get(lane);
        if (cycles === undefined)
            return;
        if (cycles > 1)
            this.owed.set(lane, cycles - 1);
        else
            this.owed.delete(lane);
        this.wake();
    }
    wake() {
        for (const wake of [...this.wakers])
            wake();
    }
    get pending() {
        return [...this.owed.keys()];
    }
    nextDischarge(signal, withinMs) {
        if (this.owed.size === 0 || signal.aborted || withinMs <= 0)
            return Promise.resolve();
        return new Promise((resolve) => {
            const timer = Number.isFinite(withinMs) ? setTimeout(() => wake(), Math.min(withinMs, 2_147_483_647)) : undefined;
            timer?.unref?.();
            const wake = () => {
                if (timer !== undefined)
                    clearTimeout(timer);
                this.wakers.delete(wake);
                signal.removeEventListener("abort", wake);
                resolve();
            };
            this.wakers.add(wake);
            signal.addEventListener("abort", wake, { once: true });
        });
    }
    async waitOut(signal, keepWaiting, onInput, ceilingMs) {
        this.stoppedAtCeiling = false;
        if (this.owed.size === 0)
            return "nothing_owed";
        if (this.waitDeadline === undefined)
            this.waitDeadline = ceilingMs > 0 ? performance.now() + ceilingMs : null;
        const deadline = this.waitDeadline;
        const unsubscribe = onInput(() => this.wake());
        try {
            for (;;) {
                if (this.owed.size === 0)
                    return "discharged";
                if (!keepWaiting())
                    return "input";
                if (signal.aborted)
                    return "signal";
                const left = deadline === null ? Infinity : deadline - performance.now();
                if (left <= 0) {
                    this.stoppedAtCeiling = true;
                    return "ceiling";
                }
                await this.nextDischarge(signal, left);
            }
        }
        finally {
            unsubscribe();
        }
    }
    get stoppedWaitingAtCeiling() {
        return this.stoppedAtCeiling;
    }
}
export const oneShotWaitCeilingOf = (limits) => limits?.oneShotWaitCeilingMs ?? ONE_SHOT_WAIT_CEILING_DEFAULT_MS;
export const oneShotEndingBook = (oneShot, book) => (oneShot === true ? book : undefined);
const LANE_OBLIGATIONS = new WeakMap();
export function bindDeliveryObligations(sink, book) {
    LANE_OBLIGATIONS.set(sink, book);
}
export function oweTerminalDelivery(sink, task) {
    if (typeof sink === "function")
        LANE_OBLIGATIONS.get(sink)?.owe(task);
}
export function retireTerminalDelivery(sink, task) {
    if (typeof sink === "function")
        LANE_OBLIGATIONS.get(sink)?.retire(task);
}
export function moveTerminalDelivery(from, to, task) {
    if (from === to)
        return;
    retireTerminalDelivery(from, task);
    oweTerminalDelivery(to, task);
}
export function createLiveNotificationLane(seat) {
    const handedOff = new Map();
    const enter = (admits, producer = false) => (payload, priority, onDisposition) => {
        const dedupKey = taskNotificationDedupKey(payload);
        if (seat.alreadyDelivered(dedupKey))
            return "duplicate";
        if (!admits(dedupKey))
            return "unavailable";
        if (producer && handedOff.get(dedupKey) === true && seat.parkedDurably(dedupKey)) {
            handedOff.set(dedupKey, false);
            seat.queue.forget(dedupKey);
        }
        const accepted = seat.queue.enqueue({ kind: "task_notification", priority, dedupKey, payload, ...(onDisposition !== undefined ? { onDisposition } : {}) });
        if (!accepted)
            return "pending";
        return "taken";
    };
    return {
        take: enter(() => seat.isLive(), true),
        takeAsDestination: enter((dedupKey) => seat.isLive() && seat.canTakeNow() && !handedOff.has(dedupKey)),
        handOff: (payload) => {
            if (!seat.isLive())
                return;
            handedOff.set(taskNotificationDedupKey(payload), true);
            if (handedOff.size > MAX_DEDUP_KEYS) {
                for (const k of handedOff.keys()) {
                    handedOff.delete(k);
                    if (handedOff.size <= MAX_DEDUP_KEYS)
                        break;
                }
            }
        },
        release: () => handedOff.clear(),
    };
}
export class SessionLiveNotificationLanes {
    lanes = new Map();
    register(address, lane) {
        if (!addressNamesOccupant(address))
            return;
        const existing = this.lanes.get(address.sessionId);
        const seat = { occupant: address.occupant, lane };
        if (existing === undefined)
            this.lanes.set(address.sessionId, [seat]);
        else if (!existing.some((s) => s.lane === lane))
            existing.push(seat);
    }
    unregister(address, lane) {
        const existing = this.lanes.get(address.sessionId);
        if (existing === undefined)
            return;
        const at = existing.findIndex((s) => s.lane === lane);
        if (at !== -1)
            existing.splice(at, 1);
        if (existing.length === 0)
            this.lanes.delete(address.sessionId);
    }
    deliver(address, payload, priority, opts) {
        const existing = this.lanes.get(address.sessionId);
        if (existing === undefined)
            return "unavailable";
        for (let i = existing.length - 1; i >= 0; i -= 1) {
            const seat = existing[i];
            if (!sameOccupant(seat.occupant, address.occupant))
                continue;
            const outcome = seat.lane(payload, priority, opts?.onDisposition);
            if (outcome !== "unavailable")
                return outcome;
        }
        return "unavailable";
    }
    holds(address) {
        return this.lanes.get(address.sessionId)?.some((s) => sameOccupant(s.occupant, address.occupant)) === true;
    }
    get size() {
        return this.lanes.size;
    }
}
export function parksInSessionBox(payload, deployment) {
    return payload.agentMessage !== undefined || (deployment.sessionBoxEngineFrames === true && isEngineFrameParkable(payload));
}
function keysOf(held, address) {
    const entry = held.get(address.sessionId);
    return entry !== undefined && sameOccupant(entry.occupant, address.occupant) ? entry.keys : undefined;
}
function addOccupantKey(held, address, dedupKey) {
    let mine = keysOf(held, address);
    if (mine === undefined) {
        held.delete(address.sessionId);
        if (held.size >= MAX_PENDING_SESSIONS) {
            const oldest = held.keys().next().value;
            if (oldest !== undefined)
                held.delete(oldest);
        }
        mine = new Set();
        held.set(address.sessionId, { occupant: address.occupant, keys: mine });
    }
    mine.add(dedupKey);
    if (mine.size > MAX_PENDING_EVENTS_PER_SESSION) {
        for (const k of mine) {
            mine.delete(k);
            if (mine.size <= MAX_PENDING_EVENTS_PER_SESSION)
                break;
        }
    }
}
export class SessionRouteTable {
    sessions = new Map();
    liveLanes = new SessionLiveNotificationLanes();
    droppedSessions = 0;
    evictedSessions = new Map();
    unattributedDrops = 0;
    seats = new Map();
    routed = new Map();
    durable = new Map();
}
const ROUTE_TABLES_OF_STORE = new WeakMap();
export function sessionRouteTableOf(store, mailbox, engineFrames) {
    let ofStore = ROUTE_TABLES_OF_STORE.get(store);
    if (ofStore === undefined) {
        ofStore = { byMailbox: new WeakMap() };
        ROUTE_TABLES_OF_STORE.set(store, ofStore);
    }
    if (mailbox === undefined || mailbox === null)
        return (ofStore.unboxed ??= new SessionRouteTable());
    const held = ofStore.byMailbox.get(mailbox);
    if (held !== undefined) {
        if (held.engineFrames !== engineFrames) {
            throw codedRefusal("config.session_box_floor_mismatch", `RunnerDeps.sessionBoxEngineFrames is ${engineFrames ? "true" : "not true"} on this Runner, but the box floor this process already registered for this session store object and this mailbox object is ${held.engineFrames ? "true" : "not true"} — Runners over one session store object and one mailbox object share one session route table, and whether every drainer of those boxes reads engine frames is one fact of that pair, kept for as long as the store object lives: declare it alike, or give this Runner another session store object to change it`);
        }
        return held.table;
    }
    const seat = { table: new SessionRouteTable(), engineFrames };
    ofStore.byMailbox.set(mailbox, seat);
    return seat.table;
}
export class PendingSessionNotifications {
    table;
    noticeSeat;
    unseatedBoxSeat;
    constructor(seats) {
        this.table = seats?.table ?? new SessionRouteTable();
        this.noticeSeat = seats?.onNotice ?? (() => undefined);
        this.unseatedBoxSeat = seats?.boxFor;
    }
    get liveLanes() {
        return this.table.liveLanes;
    }
    get droppedSessions() {
        return this.table.droppedSessions;
    }
    admit(address, box) {
        if (address.unread === true)
            return;
        this.table.seats.delete(address.sessionId);
        const bound = frameSeatBox(address, box);
        this.table.seats.set(address.sessionId, { occupant: address.occupant, ...(bound !== undefined ? { box: bound } : {}) });
        for (const id of this.table.seats.keys()) {
            if (this.table.seats.size <= MAX_SESSION_BOX_BINDINGS)
                break;
            if (!this.table.sessions.has(id))
                this.table.seats.delete(id);
        }
        const parked = this.table.sessions.get(address.sessionId);
        if (parked !== undefined && !sameOccupant(parked.occupant, address.occupant))
            this.discardRecord(address.sessionId, parked, address.occupant);
        for (const held of [this.table.evictedSessions, this.table.routed, this.table.durable]) {
            const entry = held.get(address.sessionId);
            if (entry !== undefined && !sameOccupant(entry.occupant, address.occupant))
                held.delete(address.sessionId);
        }
    }
    sessionBoxFor(address) {
        if (!addressNamesOccupant(address))
            return undefined;
        const seat = this.table.seats.get(address.sessionId);
        if (seat !== undefined)
            return sameOccupant(seat.occupant, address.occupant) ? seat.box : undefined;
        const verdict = this.boxVerdictOf(address);
        return verdict?.ok === true ? verdict.box : undefined;
    }
    holdsSeat(sessionId) {
        return this.table.seats.has(sessionId);
    }
    boxVerdictOf(address) {
        return address.scope !== undefined ? this.unseatedBoxSeat?.({ ...address, scope: address.scope }) : undefined;
    }
    completionLaneOf(address, unkept) {
        const verdict = this.boxVerdictOf(address);
        if (verdict === undefined)
            return { ok: false, cause: { code: "no_root_scope" } };
        if (!verdict.ok)
            return verdict;
        if (verdict.box.engineFrames !== true)
            return { ok: false, cause: { code: "floor_off" } };
        return { ok: true, sink: (n, o) => routeOrParkNotification(this, address, n, o?.priority ?? "next", undefined, unkept !== undefined ? () => unkept(n, o) : undefined) };
    }
    discardsStale(address, payload) {
        const stale = addressNamesOccupant(address) ? this.staleAgainst(address) : { seat: this.table.seats.get(address.sessionId) };
        if (stale === undefined)
            return false;
        const { seat } = stale;
        const current = { sessionId: address.sessionId, occupant: seat?.occupant };
        const path = seat !== undefined && this.table.liveLanes.holds(current) ? "live" : seat?.box !== undefined && parksInSessionBox(payload, { sessionBoxEngineFrames: seat.box.engineFrames }) ? "box" : "drain";
        this.announceDiscard(address, seat?.occupant, frameDelivery(payload), path);
        return true;
    }
    discardsStaleNotice(destination, delivery) {
        const stale = this.staleAgainst(destination);
        if (stale === undefined)
            return false;
        this.announceDiscard(destination, stale.seat?.occupant, delivery, "notice");
        return true;
    }
    staleAgainst(address) {
        const seat = this.table.seats.get(address.sessionId);
        if (address.unread !== true && (seat === undefined || sameOccupant(address.occupant, seat.occupant)))
            return undefined;
        return { seat };
    }
    announceDiscard(address, current, delivery, path) {
        deliverEngineNotice(this.noticeSeat(), deliveryDiscardedNotice(address, current, delivery, path));
    }
    discardRecord(sessionId, record, current) {
        if (this.table.sessions.get(sessionId) === record)
            this.table.sessions.delete(sessionId);
        for (const n of record.items)
            this.announceDiscard({ sessionId, occupant: record.occupant }, current, frameDelivery(n), "drain");
    }
    recordOf(address) {
        const s = this.table.sessions.get(address.sessionId);
        return s !== undefined && sameOccupant(s.occupant, address.occupant) ? s : undefined;
    }
    settleBoxDebts(address, signal) {
        const owed = this.recordOf(address)?.boxDebts;
        if (owed === undefined || owed.size === 0)
            return undefined;
        const debts = [...owed];
        return (async () => {
            for (const [copy, debt] of debts) {
                if (signal?.aborted === true)
                    return;
                await this.settleBoxDebt(address, copy, debt);
            }
        })();
    }
    keepBackOwing(sessionId, s, reader) {
        const debts = s.boxDebts;
        const owing = s.items.filter((n) => debts?.has(n) === true || !readsTaskFrame(reader, n));
        if (owing.length === 0)
            return s;
        const tiers = new Map();
        for (const n of owing) {
            const p = s.priorities?.get(n);
            if (p !== undefined)
                tiers.set(n, p);
        }
        this.table.sessions.set(sessionId, { occupant: s.occupant, items: owing, dropped: new Map(), keys: new Set(owing.map((n) => taskNotificationDedupKey(n))), priorities: tiers, ...(debts !== undefined ? { boxDebts: debts } : {}) });
        const kept = new Set(owing);
        const rest = s.items.filter((n) => !kept.has(n));
        return rest.length === 0 && s.dropped.size === 0 ? undefined : { ...s, items: rest };
    }
    async settleBoxDebt(address, copy, debt) {
        const sessionId = address.sessionId;
        let answered = false;
        try {
            await debt.box.mailbox.append(debt.box.scope, debt.box.handle, debt.record);
            answered = true;
        }
        catch (e) {
            try {
                debt.box.onError?.(e);
            }
            catch {
            }
        }
        const s = this.recordOf(address);
        if (s?.boxDebts?.get(copy) !== debt)
            return;
        s.boxDebts.delete(copy);
        const at = s.items.indexOf(copy);
        if (!answered || at === -1)
            return;
        s.items.splice(at, 1);
        const key = taskNotificationDedupKey(copy);
        s.keys.delete(key);
        s.priorities?.delete(copy);
        this.noteDurablePark(address, key);
        if (s.items.length === 0 && s.dropped.size === 0)
            this.table.sessions.delete(sessionId);
    }
    pend(address, n, priority, debt) {
        if (this.discardsStale(address, n))
            return false;
        const sessionId = address.sessionId;
        let s = this.table.sessions.get(sessionId);
        if (s !== undefined && !sameOccupant(s.occupant, address.occupant)) {
            this.discardRecord(sessionId, s, address.occupant);
            s = undefined;
        }
        if (s === undefined) {
            if (this.table.sessions.size >= MAX_PENDING_SESSIONS) {
                const oldest = this.table.sessions.keys().next().value;
                if (oldest !== undefined) {
                    const victim = this.table.sessions.get(oldest);
                    this.table.sessions.delete(oldest);
                    this.table.droppedSessions += 1;
                    const lost = (victim?.items.length ?? 0) + [...(victim?.dropped.values() ?? [])].reduce((a, d) => a + d.count, 0);
                    if (lost > 0) {
                        if (!this.table.evictedSessions.has(oldest) && this.table.evictedSessions.size >= MAX_TOMBSTONES) {
                            const oldestTomb = this.table.evictedSessions.keys().next().value;
                            if (oldestTomb !== undefined) {
                                this.table.unattributedDrops += this.table.evictedSessions.get(oldestTomb)?.count ?? 0;
                                this.table.evictedSessions.delete(oldestTomb);
                            }
                        }
                        const tomb = this.table.evictedSessions.get(oldest);
                        const occupant = victim?.occupant;
                        this.table.evictedSessions.set(oldest, { occupant, count: (tomb !== undefined && sameOccupant(tomb.occupant, occupant) ? tomb.count : 0) + lost });
                    }
                }
            }
            s = { occupant: address.occupant, items: [], dropped: new Map(), keys: new Set(), priorities: new Map() };
            this.table.sessions.set(sessionId, s);
        }
        const key = taskNotificationDedupKey(n);
        if (s.keys.has(key))
            return true;
        s.keys.add(key);
        s.items.push(n);
        if (priority !== undefined)
            s.priorities?.set(n, priority);
        if (debt !== undefined)
            (s.boxDebts ??= new Map()).set(n, debt);
        const lane = taskNotificationLaneKey(n);
        let mine = 0;
        for (const i of s.items)
            if (taskNotificationLaneKey(i) === lane)
                mine += 1;
        if (mine > MAX_PENDING_EVENTS_PER_TASK)
            evictOldest(s, (i) => taskNotificationLaneKey(i) === lane);
        if (s.items.length > MAX_PENDING_EVENTS_PER_SESSION)
            evictOldest(s, () => true);
        return true;
    }
    drain(address, reader = {}) {
        if (address.unread === true)
            return undefined;
        const sessionId = address.sessionId;
        this.table.routed.delete(sessionId);
        const held = this.table.sessions.get(sessionId);
        if (held !== undefined && !sameOccupant(held.occupant, address.occupant))
            this.discardRecord(sessionId, held, address.occupant);
        const parked = this.recordOf(address);
        if (parked !== undefined)
            this.table.sessions.delete(sessionId);
        const s = parked !== undefined ? this.keepBackOwing(sessionId, parked, reader) : undefined;
        if (s !== undefined) {
            const rank = (n) => {
                const p = s.priorities?.get(n);
                return p === "now" ? 0 : p === "next" ? 1 : 2;
            };
            s.items = [...s.items].sort((a, b) => rank(a) - rank(b));
        }
        const tombstone = this.table.evictedSessions.get(sessionId);
        const tomb = tombstone !== undefined && sameOccupant(tombstone.occupant, address.occupant) ? tombstone.count : undefined;
        if (tombstone !== undefined)
            this.table.evictedSessions.delete(sessionId);
        if (tomb === undefined && this.table.unattributedDrops === 0)
            return s;
        const carried = this.table.unattributedDrops;
        this.table.unattributedDrops = 0;
        const out = s ?? { items: [], dropped: new Map() };
        out.droppedWholeSession = (out.droppedWholeSession ?? 0) + (tomb ?? 0) + carried;
        return out;
    }
    holdsKey(address, dedupKey) {
        return this.recordOf(address)?.keys.has(dedupKey) === true || keysOf(this.table.routed, address)?.has(dedupKey) === true || this.holdsDurably(address, dedupKey);
    }
    holdsDurably(address, dedupKey) {
        return keysOf(this.table.durable, address)?.has(dedupKey) === true;
    }
    noteDurablePark(address, dedupKey) {
        addOccupantKey(this.table.durable, address, dedupKey);
    }
    forgetDurablePark(address, dedupKey) {
        const mine = keysOf(this.table.durable, address);
        if (mine === undefined)
            return;
        mine.delete(dedupKey);
        if (mine.size === 0)
            this.table.durable.delete(address.sessionId);
    }
    markDelivered(address, dedupKey) {
        if (!addressNamesOccupant(address))
            return;
        addOccupantKey(this.table.routed, address, dedupKey);
    }
    get size() {
        return this.table.sessions.size;
    }
}
export class DurableAppendObligations {
    static scope = new AsyncLocalStorage();
    inFlight = new Set();
    static current() {
        return DurableAppendObligations.scope.getStore();
    }
    run(body) {
        return DurableAppendObligations.scope.run(this, body);
    }
    track(p) {
        this.inFlight.add(p);
        void p.finally(() => this.inFlight.delete(p));
    }
    async settle() {
        while (this.inFlight.size > 0)
            await Promise.allSettled([...this.inFlight]);
    }
}
export function routeOrParkNotification(store, address, payload, priority, onDisposition, onUnkept) {
    if (store.discardsStale(address, payload)) {
        onDisposition?.("refused");
        return;
    }
    const dedupKey = taskNotificationDedupKey(payload);
    if (store.holdsKey(address, dedupKey)) {
        onDisposition?.("parked");
        return;
    }
    const routed = store.liveLanes.deliver(address, payload, priority, { ...(onDisposition !== undefined ? { onDisposition } : {}) });
    if (routed === "unavailable") {
        parkAtSeat(store, address, payload, priority, onDisposition, onUnkept);
    }
    else if (routed !== "taken") {
        onDisposition?.("queued");
    }
}
export function parkAtSeat(store, address, payload, priority, onDisposition, onUnkept) {
    if (store.discardsStale(address, payload)) {
        onDisposition?.("refused");
        return;
    }
    const dedupKey = taskNotificationDedupKey(payload);
    const box = store.sessionBoxFor(address);
    const carrier = payload.agentMessage;
    if (box !== undefined && parksInSessionBox(payload, { sessionBoxEngineFrames: box.engineFrames })) {
        store.noteDurablePark(address, dedupKey);
        const record = carrier !== undefined ? sessionBoxRecordOf({ ...payload, agentMessage: carrier }, address) : engineFrameRecordOf(payload, priority, address);
        const ask = () => {
            try {
                return Promise.resolve(box.mailbox.append(box.scope, box.handle, record));
            }
            catch (e) {
                return Promise.reject(e);
            }
        };
        const appended = ask().catch((first) => {
            try {
                box.onError?.(first);
            }
            catch {
            }
            return ask();
        });
        const settled = appended.then(() => onDisposition?.("parked_durably"), (second) => {
            store.forgetDurablePark(address, dedupKey);
            if (!store.holdsSeat(address.sessionId)) {
                try {
                    box.onError?.(new Error(`the ${inlineUntrusted(String(payload.task_type), 40)} frame of task ${inlineUntrusted(String(payload.task_id), 120)} could not be written to session ${inlineUntrusted(address.sessionId, 120)}'s durable box (asked twice), and no leg of that session is seated on any Runner of this process over the same session store and mailbox to read a copy kept in process: it was not kept`, { cause: second }));
                }
                catch {
                }
                try {
                    onUnkept?.();
                }
                catch {
                }
                onDisposition?.("refused");
                return;
            }
            const parked = store.pend(address, payload, priority, { box, record });
            onDisposition?.(parked ? "parked" : "refused");
        });
        DurableAppendObligations.current()?.track(settled);
        return;
    }
    const parked = store.pend(address, payload, priority);
    onDisposition?.(parked ? "parked" : "refused");
}
export function sessionBoxRecordOf(payload, to) {
    const peer = payload.peer;
    return {
        id: taskNotificationDedupKey(payload),
        from: payload.agentMessage.from,
        content: payload.agentMessage.body,
        sentAt: Date.now(),
        hopChain: peer !== undefined ? [...peer.hopChain] : [],
        peerMeta: {
            ...(peer?.fromSession !== undefined ? { fromSession: peer.fromSession } : {}),
            ...(peer?.senderKey !== undefined ? { senderKey: peer.senderKey } : {}),
            fromRoot: to.sessionId,
            kind: "peer_message",
            ...(to.occupant !== undefined ? { occupant: to.occupant } : {}),
        },
    };
}
function evictOldest(s, match) {
    let idx = s.items.findIndex((i) => match(i) && !TERMINAL_STATUSES.has(i.status));
    if (idx === -1)
        idx = s.items.findIndex(match);
    if (idx === -1)
        return;
    const victim = s.items.splice(idx, 1)[0];
    s.keys.delete(taskNotificationDedupKey(victim));
    s.priorities?.delete(victim);
    s.boxDebts?.delete(victim);
    const laneKey = taskNotificationLaneKey(victim);
    const prior = s.dropped.get(laneKey);
    s.dropped.set(laneKey, { count: (prior?.count ?? 0) + 1, taskType: victim.task_type, taskId: victim.task_id });
}
export function discloseDroppedPending(drained, readHandleOf, tasks) {
    const hasSessionLoss = drained.droppedWholeSession !== undefined && drained.droppedWholeSession > 0;
    if (!hasSessionLoss && drained.dropped.size === 0)
        return drained.items;
    const sessionLine = hasSessionLoss
        ? [
            {
                task_id: "session",
                task_type: "background_agent",
                status: "event",
                summary: `${drained.droppedWholeSession} pending notification(s) for this session were dropped before this turn (the pending store evicted the whole session under its session-count cap). Which tasks they came from is no longer known.${tasks === undefined ? "" : sessionLossTableClause(tasks())}`,
            },
        ]
        : [];
    if (drained.dropped.size === 0)
        return [...drained.items, ...sessionLine];
    const disclosed = new Set();
    const out = drained.items.flatMap((n) => {
        const lane = taskNotificationLaneKey(n);
        const dropped = drained.dropped.get(lane);
        if (dropped === undefined || disclosed.has(lane))
            return [n];
        disclosed.add(lane);
        if (n.agentMessage !== undefined || n.crossSessionMessage !== undefined || n.crossSessionNotice !== undefined) {
            const line = {
                task_id: n.task_id,
                task_type: n.task_type,
                status: "event",
                summary: `[${n.task_id}] ${dropped.count} earlier pending notification(s) from this task were dropped (pending-queue overflow); its latest message follows.`,
            };
            const linePriority = drained.priorities?.get(n);
            if (linePriority !== undefined)
                drained.priorities?.set(line, linePriority);
            return [line, n];
        }
        const annotated = {
            ...n,
            summary: `[${n.task_id}] ${dropped.count} earlier pending notification(s) from this task were dropped (pending-queue overflow). ${n.summary}`,
        };
        const priority = drained.priorities?.get(n);
        if (priority !== undefined)
            drained.priorities?.set(annotated, priority);
        return [annotated];
    });
    for (const [lane, dropped] of drained.dropped) {
        if (disclosed.has(lane))
            continue;
        const taskId = dropped.taskId;
        out.push({
            task_id: taskId,
            task_type: dropped.taskType,
            status: "event",
            summary: `[${taskId}] ${dropped.count} pending notification(s) from this task were dropped (pending-queue overflow) before this turn; nothing else from it survived.${dropped.taskType === "external" || readHandleOf === undefined ? "" : droppedReadClause(readHandleOf(taskId))}`,
        });
    }
    return [...out, ...sessionLine];
}
function droppedReadClause(read) {
    return read !== undefined ? ` Its ${read}.` : " Its row is no longer readable from this run.";
}
const BACKGROUND_TASK_TABLE_ROWS_MAX = 50;
const BACKGROUND_TASK_TABLE_DESCRIPTION_MAX = 80;
export function renderBackgroundTaskTable(tasks) {
    const unlisted = tasks.length - BACKGROUND_TASK_TABLE_ROWS_MAX;
    const lines = tasks.slice(0, BACKGROUND_TASK_TABLE_ROWS_MAX).map((t) => {
        const phrase = t.status === "completed"
            ? "completed in background"
            : t.status === "killed"
                ? "stopped"
                : t.status === "running"
                    ? "still running in background"
                    : t.status === "parked"
                        ? "parked awaiting an out-of-band approval — do NOT re-issue the gated call"
                        : t.status;
        return `- [${t.id}] Task "${redactThenCut(t.description ?? "background task", BACKGROUND_TASK_TABLE_DESCRIPTION_MAX)}" ${phrase}${t.read !== undefined ? ` — ${t.read}` : ""}`;
    });
    return lines.join("\n") + (unlisted > 0 ? `\n(+${unlisted} more background tasks, not listed here)` : "");
}
function sessionLossTableClause(rows) {
    return rows.length === 0
        ? " This run has no background task left to read."
        : ` This run's background tasks (read output where its row says, terminate with TaskStop):\n${renderBackgroundTaskTable(rows)}`;
}
export class SystemInjectionQueue {
    queues = {
        now: [],
        next: [],
        later: [],
    };
    dedup = new Set();
    listeners = new Set();
    droppedOldest = 0;
    enqueue(item) {
        if (!isSystemInjectionPriority(item.priority)) {
            throw new Error(`SystemInjectionQueue: unknown priority ${JSON.stringify(item.priority)} — expected one of ${SYSTEM_INJECTION_PRIORITIES.join("/")}`);
        }
        if (this.dedup.has(item.dedupKey))
            return false;
        this.dedup.add(item.dedupKey);
        if (this.dedup.size > MAX_DEDUP_KEYS) {
            for (const k of this.dedup) {
                this.dedup.delete(k);
                if (this.dedup.size <= MAX_DEDUP_KEYS)
                    break;
            }
        }
        if (this.listeners.size > 0) {
            for (const listener of this.listeners)
                listener(item);
            return true;
        }
        const q = this.queues[item.priority];
        q.push(item);
        if (q.length > MAX_QUEUED_PER_PRIORITY) {
            const evicted = q.shift();
            this.dedup.delete(evicted.dedupKey);
            this.droppedOldest += 1;
        }
        return true;
    }
    forget(dedupKey) {
        this.dedup.delete(dedupKey);
    }
    drain(priority) {
        if (priority !== undefined && !isSystemInjectionPriority(priority)) {
            throw new Error(`SystemInjectionQueue: unknown priority ${JSON.stringify(priority)} — expected one of ${SYSTEM_INJECTION_PRIORITIES.join("/")}`);
        }
        const priorities = priority ? [priority] : [...SYSTEM_INJECTION_PRIORITIES];
        const out = [];
        for (const p of priorities) {
            const q = this.queues[p];
            while (q.length > 0) {
                const item = q.shift();
                this.dedup.delete(item.dedupKey);
                out.push(item);
            }
        }
        return out;
    }
    subscribe(listener) {
        this.listeners.add(listener);
        return () => this.listeners.delete(listener);
    }
    get size() {
        return this.queues.now.length + this.queues.next.length + this.queues.later.length;
    }
}