UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

1,212 lines • 66.1 kB
import { randomUUID } from "node:crypto";
import { A2A_NAMESPACE, a2aRegistrationProblems, findNamespacePrefixCollision, mintNamespacePrefix, mintNamespacedToolName } from "@sema-agent/primitives";
import { plaintextOriginsOf } from "./plaintext-origins-seat.js";
import { noteAdmittedSend } from "./plaintext-origins-watch.js";
import { Type } from "typebox";
import { a2aPeerRegistration, peerRegistrationDigestOf } from "./peer-registration.js";
import { A2A_SEMA_EXTENSIONS, A2A_SEMA_REFUSAL_CODES, A2A_SEMA_SKILL_ID_KEY, A2A_STATE_TABLE, A2A_TASK_STATES, readA2APeerState } from "./a2a-task-state.js";
import { PROTOCOL_PLAINTEXT_CREDENTIALS_CODE, assertEndpointBound, carriesDeclaredHeaders, crossesNetworkInClear, eraseSentCredentials, foreignLine, resolveProtocolHttpHeaders, sentSecretHits, underDeclaredHeaders } from "./protocol-http-auth.js";
import { namesASecret } from "./secret-env.js";
import { carrierEcho, echoAnnouncer, erasedEcho, nameEchoes } from "./credential-echo.js";
import { NO_PIECES, PeerCarrier, PeerSeatFailure, carriedHttpHeaders, peerSeatMissing, receivePeerSeat } from "./peer-seat.js";
import { fetchFollowing, hopRefusal, HOST_FLOOR_REFUSED_CODE } from "./host-floor.js";
import { A2A_REVOCATION_UNREADABLE_CODE, ProtocolRevokedRefusal, REVOKED_PEER_CODES, libraryRevocationProbe } from "./protocol-revocation.js";
import { revokedCallResult } from "./mcp-server-link.js";
import { classifyMcpFailure, DELIVERED_BY_KIND, describeHttpTransportFailure, failureFields } from "./mcp-failure.js";
import { stampCallIdentity } from "./tools.js";
import { admitsBackgroundLaunch } from "./task-notification.js";
import { TASK_STOP_TOOL_NAME } from "./task-tool-shape.js";
import { defaultTaskRegistry } from "./task-registry.js";
import { dispatchPeerTask, peerRowScopeOf, peerTaskTermsOf } from "./peer-task-lane.js";
import { peerTaskFramesDeclared } from "./a2a-deployment-switches.js";
import { recordListedNames } from "./mcp-producer-facts.js";
import { judgeA2aEntryRegistration, judgeEntryToolAxes, refusedDeclarer, snapshotDeclaredEntry } from "./locked-config.js";
import { INLINE_TRUNCATION_MARK_CODEPOINTS, delimitUntrusted, inlineUntrusted } from "./untrusted-text.js";
import { renderListEntry } from "./allow-entry.js";
import { codedRefusal, thrownText } from "./thrown-value.js";
import { a2aInsideRelaxed, declaredPeerReader } from "./a2a-bound-grant.js";
const A2A_REQUEST_TIMEOUT_MS = 30_000;
const A2A_CARD_TIMEOUT_MS = 10_000;
const A2A_RESPONSE_MAX_BYTES = 8 * 1024 * 1024;
const A2A_SKILL_NAME_MAX_CHARS = 200;
const A2A_SKILL_TAGS_MAX_CHARS = 240;
const A2A_SKILL_EXAMPLES_MAX_CHARS = 320;
export const A2A_SKILL_DESCRIPTION_MAX_CHARS = 2_048;
const A2A_PEER_SKILLS_MAX = 128;
const A2A_CARD_NAME_MAX_CHARS = 160;
const A2A_CARD_DESCRIPTION_MAX_CHARS = 240;
const A2A_ID_MAX_CHARS = 160;
const SKILL_HEAD_BEFORE_PEER = 'Ask the remote agent "';
const SKILL_HEAD_BETWEEN = '" to perform its "';
const SKILL_HEAD_AFTER_TITLE = '" skill.';
const SKILL_TAGS_LABEL = "Tags: ";
const SKILL_EXAMPLES_LABEL = "Examples: ";
const SKILL_TAIL = "The agent acts on its own side; its reply is returned as untrusted external data.";
const SKILL_DESCRIPTION_LINES_MAX = 5;
const SKILL_SKELETON_CHARS = SKILL_HEAD_BEFORE_PEER.length + SKILL_HEAD_BETWEEN.length + SKILL_HEAD_AFTER_TITLE.length + SKILL_TAGS_LABEL.length + SKILL_EXAMPLES_LABEL.length + SKILL_TAIL.length + (SKILL_DESCRIPTION_LINES_MAX - 1);
const cutReads = (width) => width + INLINE_TRUNCATION_MARK_CODEPOINTS;
const A2A_SKILL_TEXT_MAX_CHARS = A2A_SKILL_DESCRIPTION_MAX_CHARS -
    (SKILL_SKELETON_CHARS + cutReads(A2A_ID_MAX_CHARS) + cutReads(A2A_SKILL_NAME_MAX_CHARS) + cutReads(A2A_SKILL_TAGS_MAX_CHARS) + cutReads(A2A_SKILL_EXAMPLES_MAX_CHARS)) -
    INLINE_TRUNCATION_MARK_CODEPOINTS;
const A2A_RESULT_BODY_MAX_CHARS = 100_000;
const A2A_ERROR_TEXT_MAX_CHARS = 240;
const A2A_FAILURE_WORDS_MAX_CHARS = 1_200;
const A2A_RESULT_FENCE_REASON = "the peer is an agent acting on its own, so its output is worker text, not tool data";
const A2A_CARD_PATHS = ["/.well-known/agent-card.json", "/.well-known/agent.json"];
const A2A_EXTENDED_CARD_METHOD = "agent/getAuthenticatedExtendedCard";
const A2A_WIRE_VERSION = "0.3";
const A2A_JSONRPC_TRANSPORT = "JSONRPC";
const A2A_ERROR_CODE_NAMES = new Map([
    [-32700, "ParseError"],
    [-32600, "InvalidRequest"],
    [-32601, "MethodNotFound"],
    [-32602, "InvalidParams"],
    [-32603, "InternalError"],
    [-32001, "TaskNotFound"],
    [-32002, "TaskNotCancelable"],
    [-32003, "PushNotificationNotSupported"],
    [-32004, "UnsupportedOperation"],
    [-32005, "ContentTypeNotSupported"],
    [-32006, "InvalidAgentResponse"],
    [-32009, "VersionNotSupported"],
]);
const A2A_STATE_SET = new Set(A2A_TASK_STATES);
const a2aToolAxisIsTheDeclaration = true;
const a2aToolAxisHasTheDeclarationsMembers = true;
void a2aToolAxisIsTheDeclaration;
void a2aToolAxisHasTheDeclarationsMembers;
function peerFailureFields(err) {
    return failureFields(classifyMcpFailure(err, { phase: "connect", transport: "http" }));
}
function dialStopCodeOf(err) {
    return err instanceof ProtocolRevokedRefusal && (err.code === REVOKED_PEER_CODES.a2a || err.code === A2A_REVOCATION_UNREADABLE_CODE) ? { code: err.code } : undefined;
}
export class A2aRpcError extends Error {
    code;
    constructor(peer, method, code, message, after) {
        const named = A2A_ERROR_CODE_NAMES.get(code);
        const label = inlineUntrusted(peer, A2A_ID_MAX_CHARS);
        super(`a2a: peer "${label}" refused ${method} with ${code}${named !== undefined ? ` (${named})` : ""}:\n${fenceResult(label, method, foreignLine(message, A2A_ERROR_TEXT_MAX_CHARS))}${after ?? ""}`);
        this.name = "A2aRpcError";
        this.code = code;
    }
}
export const A2A_CALL_REFUSAL_CODES = Object.freeze({
    not_retryable: "a2a.call_refused_not_retryable",
    changeable: "a2a.call_refused_changeable",
    retry_later: "a2a.call_refused_retry_later",
});
function deliveredOf(answer) {
    return "httpStatus" in answer ? DELIVERED_BY_KIND.http_status : DELIVERED_BY_KIND.protocol;
}
const A2A_REFUSAL_SENTENCES = Object.freeze({
    not_retryable: "Sending this request again, as it is or reworded, gets the same refusal — tell the user what the peer said instead of retrying.",
    changeable: "The peer refused this request as it was written, and a changed request can get another answer — its words above say what to change when they name it.",
});
const A2A_LATER_SENTENCES = Object.freeze({
    unknown: "Whether the peer acted on this request is UNKNOWN — a status can come from something in front of the peer — so sending it again may run it twice; any resend is to come later",
    yes: "The peer recorded nothing and started nothing for this request; the same request may be sent again later",
});
const A2A_RETRY_AFTER_MAX_SECONDS = 86_400;
const PROTOCOL_REFUSAL_CLASSES = new Map([
    [-32700, "not_retryable"],
    [-32600, "not_retryable"],
    [-32601, "not_retryable"],
    [-32602, "changeable"],
    [-32005, "not_retryable"],
]);
const UNREAD_REQUEST_CODES = new Set([-32700, -32600]);
const HTTP_REFUSAL_CLASSES = new Map([
    [429, "retry_later"],
    [503, "retry_later"],
]);
const SEMA_REFUSAL_CLASSES = new Map(Object.keys(A2A_SEMA_REFUSAL_CODES).map((c) => [A2A_SEMA_REFUSAL_CODES[c], c]));
function refusalClassOf(answer, declaresRefusals) {
    if ("httpStatus" in answer)
        return HTTP_REFUSAL_CLASSES.get(answer.httpStatus);
    return (declaresRefusals ? SEMA_REFUSAL_CLASSES.get(answer.rpcCode) : undefined) ?? PROTOCOL_REFUSAL_CLASSES.get(answer.rpcCode);
}
function retryAfterMsOf(value, now) {
    if (value === null)
        return undefined;
    const v = value.trim();
    const at = Date.parse(v);
    const ms = /^\d+$/.test(v) ? Number(v) * 1000 : Number.isFinite(at) && new Date(at).toUTCString() === v ? Math.max(0, at - now) : Number.NaN;
    return Number.isFinite(ms) && ms <= A2A_RETRY_AFTER_MAX_SECONDS * 1000 ? ms : undefined;
}
function callRefusal(peer, cls, answer, retryAfter) {
    const code = A2A_CALL_REFUSAL_CODES[cls];
    const delivered = deliveredOf(answer);
    const wait = cls === "retry_later" ? retryAfterMsOf(retryAfter, Date.now()) : undefined;
    const sentence = cls === "retry_later" ? `${A2A_LATER_SENTENCES[delivered]}${wait !== undefined ? `, after ${Math.ceil(wait / 1000)} s as it asks.` : "."}` : A2A_REFUSAL_SENTENCES[cls];
    return {
        sentence,
        details: Object.freeze({
            type: "a2a",
            error: code,
            code,
            peer,
            delivered,
            ...("rpcCode" in answer ? { rpcCode: answer.rpcCode } : { httpStatus: answer.httpStatus }),
            ...(wait !== undefined ? { retryAfterMs: wait } : {}),
        }),
    };
}
class A2aCallRefusedRpc extends A2aRpcError {
    details;
    constructor(peer, method, code, message, refusal) {
        super(peer, method, code, message, ` — ${refusal.sentence}`);
        this.details = refusal.details;
    }
}
function asRecord(v) {
    return typeof v === "object" && v !== null && !Array.isArray(v) ? v : undefined;
}
function asString(v) {
    return typeof v === "string" ? v : undefined;
}
function asArray(v) {
    if (!Array.isArray(v))
        return undefined;
    const items = v;
    return items;
}
function discriminantOf(v) {
    return asString(v["kind"]) ?? asString(v["type"]);
}
const PEER_ID_SHAPE = /^[A-Za-z0-9._:+/=@~-]{1,128}$/;
const NOT_SHOWN = "(a value that is not id-shaped, not shown)";
const PEER_ID_MAX_CODE_POINTS = 1_024;
const PEER_ID_REFUSED_CHARS = /[\p{Cc}\p{Zl}\p{Zp}]/u;
const PEER_ID_TAKEN_WORDS = `an id is at most ${PEER_ID_MAX_CODE_POINTS} characters and holds no control character`;
function takenPeerId(v, what, refuse) {
    const s = asString(v);
    if (s === undefined || s === "")
        return undefined;
    if (PEER_ID_REFUSED_CHARS.test(s))
        return refuse(what);
    let n = 0;
    for (const _ of s)
        if (++n > PEER_ID_MAX_CODE_POINTS)
            return refuse(what);
    return s;
}
function shownPeerId(v) {
    return v !== undefined && PEER_ID_SHAPE.test(v) ? v : undefined;
}
function peerWord(v) {
    const shown = shownPeerId(v);
    return shown !== undefined ? JSON.stringify(shown) : NOT_SHOWN;
}
function revocationTargetOf(t) {
    return t.fingerprint !== undefined ? { protocol: "a2a", peer: t.peer, fingerprint: t.fingerprint } : { protocol: "a2a", peer: t.peer };
}
function peerHopRefusal(t, url) {
    const reading = t.revocations?.(revocationTargetOf(t));
    if (reading === "revoked")
        return { reason: "the peer was revoked by the operator", code: REVOKED_PEER_CODES.a2a };
    if (reading === "unreadable" && t.inside)
        return { reason: "the revocation ledger could not be read for this inside peer", code: A2A_REVOCATION_UNREADABLE_CODE };
    return hopRefusal(url, t.floor, false);
}
function carriedBy(t, pieces) {
    return carriedHttpHeaders(A2A_NAMESPACE.id, t.carrier, pieces, t.principalHeader, t.principal);
}
const A2A_MAX_REDIRECTS = 20;
function withRequestDeadline(outer, timeoutMs) {
    const controller = new AbortController();
    let timedOut = false;
    const timer = setTimeout(() => {
        timedOut = true;
        controller.abort();
    }, timeoutMs);
    const onOuterAbort = () => controller.abort();
    if (outer !== undefined) {
        if (outer.aborted)
            controller.abort();
        else
            outer.addEventListener("abort", onOuterAbort, { once: true });
    }
    return {
        signal: controller.signal,
        timedOut: () => timedOut,
        dispose: () => {
            clearTimeout(timer);
            outer?.removeEventListener("abort", onOuterAbort);
        },
    };
}
function resolveFetch() {
    const f = globalThis.fetch;
    if (typeof f !== "function") {
        throw new Error("a2a: this runtime has no global fetch — the A2A client speaks HTTP over the built-in fetch (Node 20+)");
    }
    return f;
}
async function readBoundedText(res, what) {
    const stream = res.body;
    if (stream === null || typeof stream.getReader !== "function") {
        const text = await res.text();
        if (text.length > A2A_RESPONSE_MAX_BYTES) {
            throw new Error(`a2a: ${what} exceeded the ${A2A_RESPONSE_MAX_BYTES}-byte response limit`);
        }
        return text;
    }
    const reader = stream.getReader();
    const decoder = new TextDecoder();
    const parts = [];
    let received = 0;
    try {
        for (;;) {
            const { done, value } = await reader.read();
            if (done)
                break;
            if (!value || value.length === 0)
                continue;
            received += value.length;
            if (received > A2A_RESPONSE_MAX_BYTES) {
                await reader.cancel().catch(() => undefined);
                throw new Error(`a2a: ${what} exceeded the ${A2A_RESPONSE_MAX_BYTES}-byte response limit — the transfer was stopped`);
            }
            parts.push(decoder.decode(value, { stream: true }));
        }
    }
    finally {
        reader.releaseLock();
    }
    parts.push(decoder.decode());
    return parts.join("");
}
async function requestJson(t, what, init) {
    const doFetch = resolveFetch();
    const peerLabel = inlineUntrusted(t.peer, A2A_ID_MAX_CHARS);
    const pieces = await t.carrier.next(init.signal, init.url);
    const carried = carriedBy(t, pieces);
    if (init.needsCarried === true && !carriesDeclaredHeaders(carried === undefined ? undefined : { ...carried })) {
        throw new A2aNothingCarried(`a2a: ${what} on peer "${peerLabel}" is not sent — nothing this peer's sends carry (the peer seat's pieces, the principal header) would authenticate it for this destination`);
    }
    assertEndpointBound(A2A_NAMESPACE.id, t.peer, init.url, t.declared, carried === undefined ? undefined : { ...carried }, t.plaintextOrigins);
    const sendHop = carriesDeclaredHeaders(carried === undefined ? undefined : { ...carried }) ? (url, hopInit) => (noteAdmittedSend(t.plaintextOrigins, new URL(String(url))), doFetch(url, hopInit)) : doFetch;
    const deadline = withRequestDeadline(init.signal, init.timeoutMs);
    let hops = 0;
    try {
        const followed = await fetchFollowing(sendHop, new URL(init.url), {
            method: init.method,
            headers: underDeclaredHeaders({ accept: "application/json", "a2a-version": A2A_WIRE_VERSION, ...(init.body !== undefined ? { "content-type": "application/json" } : {}) }, carried === undefined ? undefined : { ...carried }),
            ...(init.body !== undefined ? { body: init.body } : {}),
            signal: deadline.signal,
        }, { refusal: (url) => peerHopRefusal(t, url), follows: () => init.sentOnce !== true && !t.inside && !carriesDeclaredHeaders(carried === undefined ? undefined : { ...carried }), maxRedirects: A2A_MAX_REDIRECTS, onResponse: () => void hops++ });
        if (followed.kind === "refused" && followed.code === REVOKED_PEER_CODES.a2a)
            throw new ProtocolRevokedRefusal(revocationTargetOf(t), followed.afterSentHop);
        if (followed.kind === "refused" && followed.code === A2A_REVOCATION_UNREADABLE_CODE)
            throw new ProtocolRevokedRefusal(revocationTargetOf(t), followed.afterSentHop, "unreadable");
        if (followed.kind === "refused") {
            const reason = eraseSentCredentials(followed.reason, Object.values(carried ?? {}));
            throw codedRefusal(HOST_FLOOR_REFUSED_CODE, `a2a: ${what} on peer "${peerLabel}" is not sent — ${reason}`);
        }
        if (followed.kind === "too_many")
            throw new Error(`a2a: ${what} on peer "${peerLabel}" was redirected more than ${A2A_MAX_REDIRECTS} times`);
        const res = followed.res;
        if (res.status === 401)
            await t.carrier.rejected(pieces, init.signal, init.url);
        const text = await readBoundedText(res, `${what} from A2A peer "${peerLabel}"`);
        return { status: res.status, text, retryAfter: res.headers.get("retry-after"), redirected: hops > 1 };
    }
    catch (err) {
        if (init.signal?.aborted === true)
            throw err;
        if (deadline.timedOut()) {
            throw new Error(`a2a: ${what} on peer "${peerLabel}" got no answer within ${init.timeoutMs}ms. The client stopped waiting — the peer may still be acting on the request, so treat the outcome as UNKNOWN and verify before retrying.`, { cause: err });
        }
        const classified = describeHttpTransportFailure(err);
        if (classified !== undefined) {
            throw new Error(`a2a: ${what} on peer "${peerLabel}" failed — ${classified.condition}. ${classified.delivered === "no" ? "The request was NOT delivered." : "It is not known whether the peer received the request; treat the outcome as UNKNOWN."}`, { cause: err });
        }
        throw err;
    }
    finally {
        deadline.dispose();
    }
}
class A2aNothingCarried extends Error {
}
class A2aBadAnswer extends Error {
    status;
    details;
    constructor(message, status, options, details) {
        super(message, options);
        this.status = status;
        this.details = details;
    }
}
async function jsonRpc(t, method, params, signal, timeoutMs = A2A_REQUEST_TIMEOUT_MS, needsCarried = false, call) {
    const peerLabel = inlineUntrusted(t.peer, A2A_ID_MAX_CHARS);
    const id = randomUUID();
    const stored = params !== undefined && "stored" in params && typeof params.stored === "string" ? params.stored : undefined;
    const { status, text, retryAfter, redirected } = await requestJson(t, method, {
        method: "POST",
        url: t.endpoint,
        body: stored !== undefined ? `{"jsonrpc":"2.0","id":${JSON.stringify(id)},"method":${JSON.stringify(method)},"params":${stored}}` : JSON.stringify({ jsonrpc: "2.0", id, method, ...(params !== undefined ? { params } : {}) }),
        ...(stored !== undefined ? { sentOnce: true } : {}),
        timeoutMs,
        ...(needsCarried ? { needsCarried } : {}),
        ...(signal !== undefined ? { signal } : {}),
    });
    const reads = call !== undefined && !redirected ? call : undefined;
    if (status < 200 || status >= 300) {
        const said = `a2a: peer "${peerLabel}" answered ${status} to ${method} instead of a JSON-RPC response`;
        const cls = reads !== undefined ? refusalClassOf({ httpStatus: status }, reads.refusals) : undefined;
        if (cls === undefined)
            throw new A2aBadAnswer(said, status);
        const refusal = callRefusal(t.peer, cls, { httpStatus: status }, retryAfter);
        throw new A2aBadAnswer(`${said} — ${refusal.sentence}`, status, undefined, refusal.details);
    }
    let parsed;
    try {
        parsed = JSON.parse(text);
    }
    catch (err) {
        throw new A2aBadAnswer(`a2a: peer "${peerLabel}" answered ${method} with a body that is not JSON`, undefined, { cause: err });
    }
    const envelope = asRecord(parsed);
    if (envelope === undefined) {
        throw new A2aBadAnswer(`a2a: peer "${peerLabel}" answered ${method} with a JSON value that is not a JSON-RPC envelope`);
    }
    const errorMember = asRecord(envelope["error"]);
    if (errorMember !== undefined) {
        const member = errorMember["code"];
        const code = typeof member === "number" ? member : -32603;
        const words = eraseSentCredentials(asString(errorMember["message"]) ?? "(no message)", [...t.carrier.credentials, ...t.carrier.sent]);
        const answersThis = typeof member === "number" && (envelope["id"] === id || (envelope["id"] === null && UNREAD_REQUEST_CODES.has(member))) && !("result" in envelope);
        const cls = reads !== undefined && answersThis ? refusalClassOf({ rpcCode: code }, reads.refusals) : undefined;
        if (cls === undefined)
            throw new A2aRpcError(t.peer, method, code, words);
        throw new A2aCallRefusedRpc(t.peer, method, code, words, callRefusal(t.peer, cls, { rpcCode: code }, retryAfter));
    }
    if (!("result" in envelope)) {
        throw new A2aBadAnswer(`a2a: peer "${peerLabel}" answered ${method} with neither a result nor an error member`);
    }
    return envelope["result"];
}
function semaExtensionsOf(card) {
    const uris = new Set();
    for (const entry of asArray(asRecord(card["capabilities"])?.["extensions"]) ?? []) {
        const uri = asString(asRecord(entry)?.["uri"]);
        if (uri !== undefined)
            uris.add(uri);
    }
    return { skillId: uris.has(A2A_SEMA_EXTENSIONS.skillId), taskStates: uris.has(A2A_SEMA_EXTENSIONS.taskStates), refusals: uris.has(A2A_SEMA_EXTENSIONS.refusals) };
}
async function fetchCardAt(t, url, signal) {
    const { status, text } = await requestJson(t, "agent-card discovery", { method: "GET", url, timeoutMs: A2A_CARD_TIMEOUT_MS, ...(signal !== undefined ? { signal } : {}) });
    if (status === 404 || status === 410)
        return undefined;
    const peerLabel = inlineUntrusted(t.peer, A2A_ID_MAX_CHARS);
    if (status < 200 || status >= 300) {
        const redirected = t.inside && status >= 300 && status < 400 ? " — an inside peer follows no redirect: write the final address into `cardUrl`" : "";
        throw new Error(`a2a: peer "${peerLabel}" answered ${status} for its agent card at ${url}${redirected}`);
    }
    try {
        return JSON.parse(text);
    }
    catch (err) {
        throw new Error(`a2a: peer "${peerLabel}" served an agent card at ${url} that is not JSON`, { cause: err });
    }
}
async function discoverCardBody(spec, t, signal) {
    const peerLabel = inlineUntrusted(spec.name, A2A_ID_MAX_CHARS);
    if (spec.cardUrl !== undefined) {
        const body = await fetchCardAt(t, spec.cardUrl, signal);
        if (body === undefined)
            throw new Error(`a2a: peer "${peerLabel}" has no agent card at its declared cardUrl (${spec.cardUrl} answered 404)`);
        return body;
    }
    const tried = [];
    for (const path of A2A_CARD_PATHS) {
        const url = new URL(path, spec.url).toString();
        tried.push(url);
        const body = await fetchCardAt(t, url, signal);
        if (body !== undefined)
            return body;
    }
    throw new Error(`a2a: peer "${peerLabel}" published no agent card — none of ${tried.join(", ")} answered`);
}
function negotiateEndpoint(peer, card, fallbackUrl, echo) {
    const offered = [];
    const primaryUrl = asString(card["url"]) ?? fallbackUrl;
    offered.push({ url: primaryUrl, transport: asString(card["preferredTransport"]) ?? A2A_JSONRPC_TRANSPORT });
    for (const entry of asArray(card["additionalInterfaces"]) ?? []) {
        const rec = asRecord(entry);
        if (rec === undefined)
            continue;
        const url = asString(rec["url"]);
        const transport = asString(rec["transport"]);
        if (url !== undefined && transport !== undefined)
            offered.push({ url, transport });
    }
    for (const candidate of offered) {
        if (candidate.transport.toUpperCase() !== A2A_JSONRPC_TRANSPORT)
            continue;
        if (candidate.url !== fallbackUrl && nameEchoes(candidate.url, echo, "agent_card"))
            continue;
        let absolute;
        try {
            absolute = new URL(candidate.url, fallbackUrl);
        }
        catch {
            continue;
        }
        if (absolute.protocol !== "http:" && absolute.protocol !== "https:")
            continue;
        return absolute.toString();
    }
    const names = offered.map((o) => foreignLine(erasedEcho(o.transport, echo, "agent_card"), 40)).join(", ");
    throw new Error(`a2a: peer "${inlineUntrusted(peer, A2A_ID_MAX_CHARS)}" advertises no ${A2A_JSONRPC_TRANSPORT} interface (offered: ${names || "none"}) — this client speaks ${A2A_JSONRPC_TRANSPORT} only`);
}
function readCard(peer, body, fallbackUrl, echo) {
    const card = asRecord(body);
    if (card === undefined) {
        throw new Error(`a2a: peer "${inlineUntrusted(peer, A2A_ID_MAX_CHARS)}" served an agent card that is not a JSON object`);
    }
    const skills = readSkills(peer, card, echo);
    const name = asString(card["name"]);
    const nameHolds = name !== undefined && nameEchoes(name, echo, "agent_card");
    const description = erasedEcho(asString(card["description"]), echo, "agent_card");
    return {
        ...(name !== undefined && !nameHolds ? { name: inlineUntrusted(name, A2A_CARD_NAME_MAX_CHARS) } : {}),
        ...(description !== undefined ? { description: inlineUntrusted(description, A2A_CARD_DESCRIPTION_MAX_CHARS) } : {}),
        endpoint: negotiateEndpoint(peer, card, fallbackUrl, echo),
        skills,
        extendedCard: card["supportsAuthenticatedExtendedCard"] === true,
        speaks: semaExtensionsOf(card),
    };
}
function assertSkillCount(peer, count, whose) {
    if (count <= A2A_PEER_SKILLS_MAX)
        return;
    throw new A2aBadAnswer(`a2a: peer "${inlineUntrusted(peer, A2A_ID_MAX_CHARS)}": ${whose} ${count} skills — this client mounts at most ${A2A_PEER_SKILLS_MAX} per peer and refuses the card rather than cut the list`);
}
function readSkills(peer, card, echo) {
    const listed = card["skills"];
    const entries = listed === undefined ? [] : asArray(listed);
    if (entries === undefined) {
        throw new A2aBadAnswer(`a2a: peer "${inlineUntrusted(peer, A2A_ID_MAX_CHARS)}": its card's skills are not a list (${listed === null ? "null" : typeof listed})`);
    }
    assertSkillCount(peer, entries.length, "its card lists");
    const text = (raw) => erasedEcho(raw, echo, "agent_card");
    const skills = [];
    const named = new Set();
    for (const [index, entry] of entries.entries()) {
        const rec = asRecord(entry);
        const id = rec === undefined ? undefined : asString(rec["id"]);
        if (rec === undefined || id === undefined || id === "") {
            const why = rec === undefined ? "it is not an object" : id === undefined ? "it has no string id" : "its id is empty";
            throw new A2aBadAnswer(`a2a: peer "${inlineUntrusted(peer, A2A_ID_MAX_CHARS)}": its card's skills list holds an entry that names no skill (entry ${index + 1}: ${why}) — an id names the skill a peer offers, and this client refuses the card rather than mount part of what it says`);
        }
        if (nameEchoes(id, echo, "agent_card"))
            continue;
        if (named.has(id)) {
            throw new A2aBadAnswer(`a2a: peer "${inlineUntrusted(peer, A2A_ID_MAX_CHARS)}": its card lists the id "${foreignLine(id, A2A_SKILL_NAME_MAX_CHARS)}" more than once among its skills — ids on a card are unique, and this client refuses the card rather than choose between the entries`);
        }
        named.add(id);
        const tags = (asArray(rec["tags"]) ?? []).filter((v) => typeof v === "string").map((v) => text(v));
        const examples = (asArray(rec["examples"]) ?? []).filter((v) => typeof v === "string").map((v) => text(v));
        const name = text(asString(rec["name"]));
        const description = text(asString(rec["description"]));
        skills.push({
            id,
            ...(name !== undefined ? { name } : {}),
            ...(description !== undefined ? { description } : {}),
            ...(tags.length > 0 ? { tags } : {}),
            ...(examples.length > 0 ? { examples } : {}),
        });
    }
    return skills;
}
function a2aToolParameters() {
    return Type.Object({
        message: Type.String({ description: "What to ask this agent to do, in natural language." }),
        taskId: Type.Optional(Type.String({ description: "Continue an existing task on this agent — pass the taskId a previous call returned (e.g. when it asked for more input)." })),
        contextId: Type.Optional(Type.String({ description: "Keep this call in an existing conversation — pass the contextId a previous call returned." })),
    });
}
function skillDescription(peerLabel, skill) {
    const lines = [];
    const title = inlineUntrusted(skill.name ?? skill.id, A2A_SKILL_NAME_MAX_CHARS);
    lines.push(`${SKILL_HEAD_BEFORE_PEER}${peerLabel}${SKILL_HEAD_BETWEEN}${title}${SKILL_HEAD_AFTER_TITLE}`);
    if (skill.description !== undefined)
        lines.push(inlineUntrusted(skill.description, A2A_SKILL_TEXT_MAX_CHARS));
    if (skill.tags !== undefined)
        lines.push(`${SKILL_TAGS_LABEL}${inlineUntrusted(skill.tags.join(", "), A2A_SKILL_TAGS_MAX_CHARS)}`);
    if (skill.examples !== undefined)
        lines.push(`${SKILL_EXAMPLES_LABEL}${inlineUntrusted(skill.examples.join(" | "), A2A_SKILL_EXAMPLES_MAX_CHARS)}`);
    lines.push(SKILL_TAIL);
    return lines.join("\n");
}
function a2aAxisFor(name, override, inside) {
    const axis = inside ? { name } : { name, egress: true };
    if (override === undefined)
        return axis;
    if (override.effect !== undefined)
        axis.effect = override.effect;
    if (override.egress !== undefined)
        axis.egress = override.egress;
    if (override.irreversibility !== undefined)
        axis.irreversibility = override.irreversibility;
    return axis;
}
function renderParts(parts) {
    const lines = [];
    for (const raw of parts) {
        const part = asRecord(raw);
        if (part === undefined)
            continue;
        const kind = discriminantOf(part);
        if (kind === "text") {
            const text = asString(part["text"]);
            if (text !== undefined)
                lines.push(text);
            continue;
        }
        if (kind === "file") {
            const file = asRecord(part["file"]) ?? {};
            const name = asString(file["name"]) ?? "(unnamed)";
            const mime = asString(file["mimeType"]) ?? "unknown type";
            const uri = asString(file["uri"]);
            if (uri !== undefined)
                lines.push(`[file part: ${name} (${mime}) at ${uri} — NOT downloaded by this client]`);
            else if (typeof file["bytes"] === "string")
                lines.push(`[file part: ${name} (${mime}), inline bytes not decoded by this client]`);
            else
                lines.push(`[file part: ${name} (${mime}), no content]`);
            continue;
        }
        if (kind === "data") {
            lines.push(`[data part] ${JSON.stringify(part["data"]) ?? "undefined"}`);
            continue;
        }
        lines.push(`[part of unsupported kind ${JSON.stringify(kind ?? null)}]`);
    }
    return lines;
}
function renderMessage(message) {
    const parts = asArray(message["parts"]);
    return parts === undefined ? [] : renderParts(parts);
}
function renderTask(task) {
    const lines = [];
    const status = asRecord(task["status"]);
    const statusMessage = status !== undefined ? asRecord(status["message"]) : undefined;
    if (statusMessage !== undefined)
        lines.push(...renderMessage(statusMessage));
    for (const entry of asArray(task["artifacts"]) ?? []) {
        const artifact = asRecord(entry);
        if (artifact === undefined)
            continue;
        const name = asString(artifact["name"]) ?? asString(artifact["artifactId"]) ?? "(unnamed artifact)";
        lines.push(`--- artifact: ${name} ---`);
        const parts = asArray(artifact["parts"]);
        if (parts !== undefined)
            lines.push(...renderParts(parts));
    }
    return lines;
}
function taskState(task) {
    const status = asRecord(task["status"]);
    const raw = status !== undefined ? asString(status["state"]) : undefined;
    if (raw === undefined)
        return { unrecognized: "(absent)" };
    if (!A2A_STATE_SET.has(raw))
        return { unrecognized: raw };
    return { state: raw };
}
function fenceResult(peerLabel, skillId, body) {
    return delimitUntrusted(`a2a ${peerLabel} ${inlineUntrusted(skillId, A2A_ID_MAX_CHARS)} — ${A2A_RESULT_FENCE_REASON}`, body, A2A_RESULT_BODY_MAX_CHARS);
}
function keysClause(word) {
    const keys = ["taskId", "contextId"].flatMap((k) => {
        const w = word(k);
        return w !== undefined ? [`${k} ${w}`] : [];
    });
    return keys.length > 0 ? keys.join(" and ") : undefined;
}
function namedKeys(taskId, contextId) {
    return (k) => {
        const v = k === "taskId" ? taskId : contextId;
        return v === undefined ? undefined : (shownPeerId(v) ?? NOT_SHOWN);
    };
}
const KEY_IN_FENCE = "(exactly as the fenced keys block below gives it)";
function callKeys(peerLabel, taskId, contextId) {
    const given = { taskId, contextId };
    const fenced = [];
    return {
        word: (k) => {
            const v = given[k];
            if (v === undefined)
                return undefined;
            const shown = shownPeerId(v);
            if (shown !== undefined)
                return shown;
            if (!fenced.includes(k))
                fenced.push(k);
            return KEY_IN_FENCE;
        },
        fence: () => (fenced.length === 0 ? "" : `${delimitUntrusted(`a2a ${peerLabel} keys`, fenced.map((k) => `${k}: ${given[k]}`).join("\n"))}\n`),
    };
}
function nextCallLine(stateClass, keys) {
    const waitingFor = A2A_STATE_TABLE[stateClass].waitingFor;
    if (waitingFor === "caller") {
        const clause = keysClause(keys.word);
        return clause !== undefined ? ` Continue it by calling this tool again with ${clause}.` : "";
    }
    if (waitingFor === undefined) {
        const context = keys.word("contextId");
        return ` This task is over and cannot be continued. To ask again, start a new task: call this tool without a taskId${context !== undefined ? ` (pass contextId ${context} to stay in the same conversation)` : ""}.`;
    }
    return "";
}
function personTurnLine(peerLabel, state, reading, callKeysOf) {
    if (reading.waitingFor === "peer_approver") {
        const since = shownPeerId(reading.waitingOn?.since);
        return (`The remote agent "${peerLabel}" is waiting for an approval on its own side${since !== undefined ? ` (since ${since})` : ""} — nothing is needed from you. ` +
            `Do not send it more input and do not send the request again: it goes on by itself once that approval is decided.`);
    }
    if (reading.waitingFor === "unknown" && reading.mayBe === "awaiting_own_approval") {
        const keys = keysClause(callKeysOf.word);
        return (`The remote agent "${peerLabel}" reports ${state} and does not declare the sema task-state extension, so this has two readings: ` +
            `it needs more from you before it can continue (its message is below)${keys !== undefined ? ` — then continue it by calling this tool again with ${keys}` : ""}; ` +
            `or, as an earlier sema deployment says it, it is waiting for an approval on its own side — then nothing is needed from you and nothing should be sent.`);
    }
    return `The remote agent needs more from you before it can continue (state: ${state}).${nextCallLine(reading.stateClass, callKeysOf)}`;
}
function takenReading(reading, t, refuse) {
    const on = reading.waitingOn;
    if (on === undefined)
        return reading;
    const carried = [...t.carrier.credentials, ...t.carrier.sent];
    const take = (s, what) => (s === undefined ? undefined : takenPeerId(eraseSentCredentials(s, carried), what, refuse));
    const kind = take(on.kind, "waiting-on kind") ?? refuse("waiting-on kind");
    const since = take(on.since, "waiting-on since stamp");
    const approvalRef = take(on.approvalRef, "approval reference");
    return { ...reading, waitingOn: { kind, ...(since !== undefined ? { since } : {}), ...(approvalRef !== undefined ? { approvalRef } : {}) } };
}
function taskDetails(state, reading, taskId, contextId) {
    const on = reading.waitingOn;
    return {
        type: "a2a",
        state,
        stateClass: reading.stateClass,
        ...(reading.waitingFor !== undefined ? { waitingFor: reading.waitingFor } : {}),
        ...(on !== undefined ? { waitingOn: { kind: on.kind, ...(on.since !== undefined ? { since: on.since } : {}), ...(on.approvalRef !== undefined ? { approvalRef: on.approvalRef } : {}) } } : {}),
        ...(taskId !== undefined ? { taskId } : {}),
        ...(contextId !== undefined ? { contextId } : {}),
    };
}
function unknownOutcomeLine(taskId, contextId) {
    const keys = keysClause(namedKeys(taskId, contextId));
    return ` Do not send the request again — it may already be done or still running, and this tool has no read-only way to ask after it${keys !== undefined ? ` (${keys})` : ""}.`;
}
function skillCallWhat(skillId) {
    return `The call to skill ${foreignLine(skillId, A2A_ID_MAX_CHARS)}`;
}
function revokedSkillCall(refusal, skillId, accepted) {
    const answer = revokedCallResult(refusal, skillCallWhat(skillId), accepted);
    return { ...answer, details: { type: "a2a", ...answer.details } };
}
function observeAnswer(t, peerLabel, skillId, answer, method, declaresTable) {
    const rec = asRecord(answer);
    if (rec === undefined)
        throw new Error(`a2a: peer "${peerLabel}" answered ${method} with something that is not a protocol object`);
    const kind = discriminantOf(rec);
    const refuse = (what) => {
        throw new A2aBadAnswer(`a2a: peer "${peerLabel}" answered ${method} with a ${what} this client does not take (${PEER_ID_TAKEN_WORDS}); the answer is not read`);
    };
    if (method === "message/send" && (kind === "message" || (kind === undefined && rec["parts"] !== undefined))) {
        const contextId = takenPeerId(rec["contextId"], "context id", refuse);
        const result = fenceResult(peerLabel, skillId, renderMessage(rec).join("\n").trim() || "(the agent replied with no content)");
        const details = { type: "a2a", kind: "message", ...(contextId !== undefined ? { contextId } : {}) };
        const shownContext = shownPeerId(contextId);
        return {
            remote: contextId !== undefined ? { contextId } : {},
            ending: "completed",
            shown: shownContext !== undefined ? { contextId: shownContext } : {},
            details,
            words: result,
            inline: () => ({ content: [{ type: "text", text: result }], details, terminate: false }),
        };
    }
    if (kind !== "task" && !(kind === undefined && rec["status"] !== undefined)) {
        throw new Error(`a2a: peer "${peerLabel}" answered ${method} with ${kind !== undefined ? peerWord(kind) : `"(no kind)"`}, which is ${method === "message/send" ? "neither a message nor a task" : "not a task"}`);
    }
    const taskId = takenPeerId(rec["id"], "task id", refuse);
    const contextId = takenPeerId(rec["contextId"], "context id", refuse);
    const observed = taskState(rec);
    if ("unrecognized" in observed) {
        throw new Error(`a2a: peer "${peerLabel}" reported task state ${observed.unrecognized === "(absent)" ? `"(absent)"` : peerWord(observed.unrecognized)} for skill ${peerWord(skillId)}, which is not a state this client knows. The outcome is UNKNOWN.${unknownOutcomeLine(taskId, contextId)}`);
    }
    const state = observed.state;
    const reading = takenReading(readA2APeerState({ state, metadata: rec["metadata"] }, declaresTable), t, refuse);
    const remote = {
        ...(taskId !== undefined ? { taskId } : {}),
        ...(contextId !== undefined ? { contextId } : {}),
        state,
        stateClass: reading.stateClass,
        ...(reading.waitingOn !== undefined ? { waitingOn: reading.waitingOn } : {}),
    };
    const shownTask = shownPeerId(taskId);
    const shownContext = shownPeerId(contextId);
    const shown = { ...(shownTask !== undefined ? { taskId: shownTask } : {}), ...(shownContext !== undefined ? { contextId: shownContext } : {}), state };
    const details = taskDetails(state, reading, taskId, contextId);
    const body = renderTask(rec).join("\n").trim();
    const classWaits = A2A_STATE_TABLE[reading.stateClass].waitingFor;
    if (classWaits === "caller" || classWaits === "peer_approver") {
        const none = reading.waitingFor === "peer_approver" ? "(the agent sent no message with its state)" : "(the agent sent no message with its request)";
        const keys = callKeys(peerLabel, taskId, contextId);
        const words = `${personTurnLine(peerLabel, state, reading, keys)}\n${keys.fence()}` + fenceResult(peerLabel, skillId, body || none);
        return { remote, waitingFor: reading.waitingFor ?? "unknown", shown, details, words, inline: () => ({ content: [{ type: "text", text: words }], details, terminate: false }) };
    }
    if (classWaits !== undefined) {
        return { remote, waitingFor: reading.waitingFor ?? "unknown", shown, details, words: "", inline: () => ({ content: [{ type: "text", text: `The remote agent "${peerLabel}" is still ${state}.` }], details, terminate: false }) };
    }
    if (reading.stateClass === "completed") {
        const words = fenceResult(peerLabel, skillId, body || "(the agent completed the task and returned no content)");
        return { remote, ending: "completed", shown, details, words, inline: () => ({ content: [{ type: "text", text: words }], details, terminate: false }) };
    }
    const words = fenceResult(peerLabel, skillId, carriedIn(body, t) ? A2A_FAILED_BODY_WITHHELD : body || "(the agent gave no reason)");
    const keys = callKeys(peerLabel, taskId, contextId);
    const ended = `a2a: the remote agent "${peerLabel}" ended task state ${state} for skill ${peerWord(skillId)}.${nextCallLine(reading.stateClass, keys)}\n${keys.fence()}` + words;
    return {
        remote,
        ending: reading.stateClass === "cancelled" ? "cancelled" : "failed",
        shown,
        details,
        words,
        inline: () => {
            throw new Error(ended);
        },
    };
}
const A2A_FAILED_BODY_WITHHELD = "(the agent's words are withheld: they hold a value this connection sent to the agent)";
function carriedIn(text, t) {
    const principalSent = t.principalHeader !== undefined ? t.principal : undefined;
    const values = [...t.carrier.credentials, ...t.carrier.sent.filter((v) => v !== principalSent)];
    return sentSecretHits(text, values, namesASecret) > 0;
}
export function peerCallReach(enrichCtx, toolCallId, signal) {
    const ctx = stampCallIdentity(enrichCtx({ toolCallId, signal }), toolCallId, signal);
    const completionSink = ctx.onTaskNotification;
    const sessionScoped = ctx.backgroundScope === "session" && ctx.sessionId !== undefined;
    const owner = sessionScoped ? ctx.sessionId : ctx.taskId;
    const access = owner !== undefined
        ? {
            owner,
            scope: peerRowScopeOf(ctx),
            ...(ctx.sessionId !== undefined ? { sessionId: ctx.sessionId } : {}),
            ...(ctx.rootSessionIncarnation !== undefined ? { rootSessionIncarnation: ctx.rootSessionIncarnation } : {}),
        }
        : undefined;
    return {
        registry: ctx.taskRegistry ?? defaultTaskRegistry,
        completionSink,
        admitted: admitsBackgroundLaunch(completionSink) && access !== undefined,
        ...(access !== undefined ? { access } : {}),
        sessionScoped,
        ...(ctx.taskId !== undefined && ctx.taskId !== ctx.sessionId ? { dispatchingTaskId: ctx.taskId } : {}),
        completionComesBack: sessionScoped || ctx.oneShot === true,
        taskStopMounted: ctx.toolSelector === undefined || ctx.toolSelector.admits({ name: TASK_STOP_TOOL_NAME }),
        ...(ctx.runLedgerBook !== undefined ? { ledger: ctx.runLedgerBook } : {}),
    };
}
const peerToolReach = new WeakMap();
export function peerToolReachOf(tool) {
    return peerToolReach.get(tool);
}
function buildSkillTool(spec, t, skill, lifecycle, speaks, registration, enrichCtx, laneSeat) {
    const peerLabel = inlineUntrusted(spec.name, A2A_ID_MAX_CHARS);
    const name = mintNamespacedToolName(A2A_NAMESPACE, spec.name, skill.id);
    const tool = {
        name,
        label: `${spec.name}:${skill.id}`,
        description: skillDescription(peerLabel, skill),
        parameters: a2aToolParameters(),
        peerRegistration: () => registration,
        permissionSeat: "passthrough",
        execute: async (toolCallId, params, callSignal) => {
            if (lifecycle.disposed) {
                throw new Error(`a2a: the task that mounted peer "${peerLabel}" has ended — this tool no longer sends anything to the remote agent.`);
            }
            const args = asRecord(params) ?? {};
            const message = asString(args["message"]);
            if (message === undefined || message.trim() === "") {
                throw new Error(`a2a: "message" is required — say what the remote agent "${peerLabel}" should do.`);
            }
            let reach;
            try {
                reach = enrichCtx !== undefined ? peerCallReach(enrichCtx, toolCallId, callSignal) : undefined;
            }
            catch {
                reach = undefined;
            }
            const taskId = asString(args["taskId"]);
            const contextId = asString(args["contextId"]);
            const messageId = randomUUID();
            const paramsJson = JSON.stringify({
                message: {
                    role: "user",
                    kind: "message",
                    messageId,
                    parts: [{ kind: "text", text: message }],
                    ...(taskId !== undefined && taskId !== "" ? { taskId } : {}),
                    ...(contextId !== undefined && contextId !== "" ? { contextId } : {}),
                    ...(speaks.skillId ? { metadata: { [A2A_SEMA_SKILL_ID_KEY]: skill.id } } : {}),
                },
                configuration: { blocking: false },
            });
            const destination = a2aDestinationOf(spec);
            return dispatchPeerTask({
                reach: reach !== undefined && reach.admitted && reach.access !== undefined ? { registry: reach.registry, sink: reach.completionSink } : undefined,
                seat: laneSeat,
                access: reach?.access ?? { owner: "", scope: "" },
                sessionScoped: reach?.sessionScoped === true,
                ...(reach?.dispatchingTaskId !== undefined ? { dispatchingTaskId: reach.dispatchingTaskId } : {}),
                completionComesBack: reach?.completionComesBack === true,
                taskStopMounted: reach?.taskStopMounted === true,
                ...(reach?.ledger !== undefined ? { ledger: reach.ledger } : {}),
                toolUseId: toolCallId,
                description: name,
                destination,
                skillId: skill.id,
                ...(spec.fingerprint !== undefined ? { fingerprint: spec.fingerprint } : {}),
                messageId,
                paramsJson,
                terms: peerTaskTermsOf(spec.respond, destination.boundary),
                ...(callSignal !== undefined ? { signal: callSignal } : {}),
                mount: lifecycle.ended.signal,
                wire: {
                    send: async (stored, signal) => observeAnswer(t, peerLabel, skill.id, await jsonRpc(t, "message/send", { stored }, signal, A2A_REQUEST_TIMEOUT_MS, false, speaks), "message/send", speaks.taskStates),
                    poll: async (remoteTaskId, signal) => observeAnswer(t, peerLabel, skill.id, await jsonRpc(t, "tasks/get", { id: remoteTaskId }, signal), "tasks/get", speaks.taskStates),
                    answeredByPeer: (err) => err instanceof A2aRpcError,
                    revoked: (refusal, accepted) => revokedSkillCall(refusal, skill.id, accepted),
                    failure: (err) => fenceResult(peerLabel, skill.id, foreignLine(thrownText(err), A2A_FAILURE_WORDS_MAX_CHARS)),
                    card: (members) => ({ ...members, type: "a2a" }),
                },
            });
        },
    };
    if (enrichCtx !== undefined)
        peerToolReach.set(tool, (toolCallId, signal) => peerCallReach(enrichCtx, toolCallId, signal));
    return tool;
}
function extendedCardReasonOf(err) {
    if (err instanceof A2aNothingCarried || err instanceof PeerSeatFailure)
        return "no_credentials";
    if (err instanceof A2aBadAnswer)
        return err.status !== undefined ? `http_${err.status}` : "malformed";
    if (err instanceof A2aRpcError)
        return "malformed";
    return "unreachable";
}
function readFailure(err, detail) {
    const code = err?.code;
    return Object.assign(new Error(detail), { name: err instanceof Error ? err.name : "Error", ...(typeof code === "string" || typeof code === "number" ? { code } : {}) });
}
function extendedCardWarning(peer, reason, detail, cause) {
    const warning = new Error(`a2a: peer "${inlineUntrusted(peer, A2A_ID_MAX_CHARS)}" is mounted from its public agent card — its authenticated extended card is unavailable (${reason}): ${detail}`, cause !== undefined ? { cause } : undefined);
    warning.code = "a2a.extended_card_unavailable";
    warning.reason = reason;
    return warning;
}
function mergeSkillsById(base, extended) {
    const named = new Map();
    for (const skill of extended)
        named.set(skill.id, skill);
    const held = new Set(base.map((skill) => skill.id));
    return [...base.map((skill) => named.get(skill.id) ?? skill), ...[...named.values()].filter((skill) => !held.has(skill.id))];
}
async function mergeExtendedCard(t, card, echo, signal) {
    if (!card.extendedCard)
        return { skills: card.skills, warnings: [] };
    try {
        const answered = asRecord(await jsonRpc(t, A2A_EXTENDED_CARD_METHOD, undefined, signal, A2A_CARD_TIMEOUT_MS, true));
        if (answered === undefined) {
            throw new A2aBadAnswer(`a2a: peer "${inlineUntrusted(t.peer, A2A_ID_MAX_CHARS)}" answered ${A2A_EXTENDED_CARD_METHOD} with a result that is not a JSON object`);
        }
        const merged = mergeSkillsById(card.skills, readSkills(t.peer, answered, echo));
        assertSkillCount(t.peer, merged.length, "its extended card brings it to");
        return { skills: merged, warnings: [] };
    }
    catch (err) {
        if (signal?.aborted === true || err instanceof ProtocolRevokedRefusal)
            throw err;
        const detail = foreignLine(thrownText(err), A2A_FAILURE_WORDS_MAX_CHARS);
        return { skills: card.skills, warnings: [extendedCardWarning(t.peer, extendedCardReasonOf(err), detail, readFailure(err, detail))] };
    }
}
const A2A_INSIDE_INCOMPLETE_CODE = "config.a2a_inside_incomplete";
const INSIDE_MISSING_MEMBER = {
    fingerprint_missing: "fingerprint (the registration's identity stamp, minted by whoever writes the registration — on a single machine, by confirming the registration)",
    allow_skills_missing: "allowSkills (the reviewed skills: a list of their names, not empty, no entry blank or missing)",
    principal_header_missing: "principalHeader (a header name; without it every user of this deployment is the same person to the peer, so one user's tasks and sessions there can be read and continued by another)",
    owner_team_missing: "ownerTeam (who answers for the peer — whom a person is pointed to when it does not respond)",
};
function assertInsideDeclaration(spec, plaintextOrigins) {
    const label = inlineUntrusted(spec.name, A2A_ID_MAX_CHARS);
    const problems = a2aRegistrationProblems(spec, plaintextOrigins);
    const missing = problems.flatMap((p) => (p in INSIDE_MISSING_MEMBER ? [INSIDE_MISSING_MEMBER[p]] : []));
    if (missing.length > 0) {
        throw codedRefusal(A2A_INSIDE_INCOMPLETE_CODE, `a2a: peer "${label}" is registered inside the trust boundary without ${missing.join("; without ")} — it is not mounted; add the member${missing.length > 1 ? "s" : ""} to its registration`);
    }
    if (problems.includes("url_plaintext"))
        throw insideLocationRefusal(label, new URL(spec.url), "declares");
    if (problems.includes("card_url_plaintext") && spec.cardUrl !== undefined)
        throw insideLocationRefusal(label, new URL(spec.cardUrl), "declares");
}
function insideLocationRefusal(label, url, says) {
    return codedRefusal(PROTOCOL_PLAINTEXT_CREDENTIALS_CODE, `a2a: peer "${label}" is registered inside the trust boundary and ${says} ${foreignLine(url.origin === "null" ? url.protocol : url.origin, 120)}, which is not https — an inside peer is reached only over https, or over plain http to this machine (localhost, 127.0.0.0/8, ::1); it is not mounted`);
}
function assertInsideEndpoint(label, endpoint, declared, plaintextOrigins) {
    const url = new URL(endpoint);
    if (crossesNetworkInClear(url, plaintextOrigins))
        throw insideLocationRefusal(label, url, "advertises");
    const at = url.origin;
    const origins = declared.map((u) => new URL(u).origin);
    if (origins.includes(at))
        return;
    throw codedRefusal("config.protocol_endpoint_unbound", `a2a: peer "${label}" is registered inside the trust boundary and its card advertises the endpoint origin ${foreignLine(at, 120)}, outside the origins its registration names (${origins.map((o) => inlineUntrusted(o, 120)).join(", ")}) — it is not mounted; register that origin as the peer's url (and the card's location as cardUrl)`);
}
function cardDriftOf(allowSkills, cardSkills) {
    const reviewed = new Set(allowSkills);
    const named = new Set(cardSkills);
    const shown = (ids) => ids.map(renderListEntry).sort();
    const unreviewed = shown([...named].filter((id) => !reviewed.has(id)));
    const missing = shown([...reviewed].filter((id) => !named.has(id)));
    return unreviewed.length === 0 && missing.length === 0 ? undefined : { unreviewed, missing };
}
function declaredPeerOf(declared, index) {
    let snapshot;
    try {
        snapshot = snapshotDeclaredEntry(declared, "a2a");
    }
    catch (err) {
        return { spec: { name: refusedDeclarer(err) ?? `(peer #${index + 1}, name unreadable)` }, refusal: err, unread: true };
    }
    const registration = judgeA2aEntryRegistration(snapshot);
    if (!registration.ok)
        return { spec: snapshot, refusal: registration.error };
    const judged = judgeEntryToolAxes(snapshot, "a2a");
    return judged.ok ? { spec: judged.entry } : { spec: snapshot, refusal: judged.error };
}
async function materializePeer(peer, principal, lifecycle, signal, floor, seat, announceEcho, revocations, isolatePeers, enrichCtx, laneSeat, plaintextOrigins) {
    if ("refusal" in peer)
        throw peer.refusal;
    const { spec } = peer;
    const inside = spec.boundary === "inside";
    if (inside)
        assertInsideDeclaration(spec, plaintextOrigins);
    const declaredAxes = spec.toolAxes;
    const missing = peerSeatMissing(`a2a: peer "${inlineUntrusted(spec.name, 120)}"`, spec.credentials, seat);
    if (missing !== undefined)
        throw missing;
    resolveProtocolHttpHeaders(A2A_NAMESPACE.id, spec.principalHeader !== undefined ? { principalHeader: spec.principalHeader } : {}, principal);
    const declared = spec.cardUrl === undefined ? [spec.url] : [spec.url, spec.cardUrl];
    const identity = { protocol: "a2a", peer: spec.name, url: spec.url, ...(spec.cardUrl !== undefined ? { cardUrl: spec.cardUrl } : {}), destination: spec.url, ...(spec.credentials !== undefined ? { credentials: spec.credentials } : {}) };
    const carrier = new PeerCarrier(seat, identity, principal, "a2a", spec.principalHeader !== undefined);
    const asks = { carrier, principalHeader: spec.principalHeader, principal, declared, plaintextOrigins, floor, revocations, inside, fingerprint: spec.fingerprint };
    const discovery = { peer: spec.name, endpoint: spec.url, ...asks };
    const echo = carrierEcho(carrier, (where) => announceEcho(spec.name, where));
    const card = readCard(spec.name, await discoverCardBody(spec, discovery, signal), spec.url, echo);
    const carriedAtCard = carriedBy(discovery, carrier.last ?? NO_PIECES);
    assertEndpointBound(A2A_NAMESPACE.id, spec.name, card.endpoint, declared, carriedAtCard === undefined ? undefined : { ...carriedAtCard }, plaintextOrigins);
    if (inside)
        assertInsideEndpoint(inlineUntrusted(spec.name, A2A_ID_MAX_CHARS), card.endpoint, declared, plaintextOrigins);
    const transport = { peer: spec.name, endpoint: card.endpoint, ...asks };
    const mounted = await mergeExtendedCard(transport, card, echo, signal);
    const cardDrift = inside ? cardDriftOf(spec.allowSkills ?? [], mounted.skills.map((s) => s.id)) : undefined;
    const tools = [];
    const skillAxes = [];
    const registration = peerRegistrationDigestOf("a2a", a2aPeerRegistration(spec));
    for (const skill of mounted.skills) {
        if (spec.allowSkills !== undefined && !spec.allowSkills.includes(skill.id))
            continue;
        const declared = declaredAxes?.[skill.id];
        const tool = buildSkillTool(spec, transport, skill, lifecycle, card.speaks, registration, enrichCtx, laneSeat);
        tools.push(tool);
        skillAxes.push(a2aAxisFor(tool.name, declared, a2aInsideRelaxed(spec, isolatePeers)));
    }
    const status = {
        name: spec.name,
        status: "ready",
        ...(card.name !== undefined ? { agentName: card.name } : {}),
        ...(card.description !== undefined ? { agentDescription: card.description } : {}),
        endpoint: card.endpoint,
        toolNames: tools.map((tool) => tool.name),
        ...registrationOf(peer),
        ...(cardDrift !== undefined ? { cardDrift } : {}),
    };
    if (mounted.warnings.length === 0)
        recordListedNames(status, mounted.skills.map((s) => s.id));
    return {
        tools,
        axes: skillAxes,
        status,
        warnings: mounted.warnings,
    };
}
function registrationOf(peer) {
    if ("unread" in peer)
        return {};
    const { boundary, fingerprint } = peer.spec;
    const side = boundary === undefined || boundary === "outside" ? "outside" : boundary === "inside" ? "inside" : undefined;
    return { ...(side !== undefined ? { boundary: side } : {}), ...(typeof fingerprint === "string" ? { fingerprint } : {}) };
}
function a2aDestinationOf(spec) {
    return Object.freeze({
        kind: "a2a_peer",
        peer: spec.name,
        ...(spec.displayName !== undefined ? { displayName: spec.displayName } : {}),
        ...(spec.ownerTeam !== undefined ? { ownerTeam: spec.ownerTeam } : {}),
        boundary: spec.boundary === "inside" ? "inside" : "outside",
    });
}
export function a2aDestinationReader(declared) {
    const peerOf = declaredPeerReader(declared, a2aDestinationOf);
    return (toolName) => {
        const destination = peerOf(toolName);
        return destination !== undefined ? { destination } : {};
    };
}
export function cardDriftNotices(statuses, sessionId, runId) {
    return statuses.flatMap((s) => {
        if (s.cardDrift === undefined)
            return [];
        const { unreviewed, missing } = s.cardDrift;
        const said = [
            ...(unreviewed.length > 0 ? [`its card names skills that were not reviewed (${unreviewed.length}; not mounted)`] : []),
            ...(missing.length > 0 ? [`reviewed skills are no longer on its card (${missing.length}; nothing mounts for them)`] : []),
        ].join(", and ");
        return [{
                code: "a2a.peer_card_drift",
                message: `A2A peer "${inlineUntrusted(s.name, 120)}" is registered inside the trust boundary and ${said} — review its registration's skills (allowSkills).`,
                detail: { peer: s.name, unreviewed: [...unreviewed], missing: [...missing], sessionId, runId },
            }];
    });
}
function asPeerWarning(spec, err) {
    const detail = thrownText(err);
    const warning = new Error(`a2a: peer "${spec.name}" could not be materialized — skipped (${detail})`, { cause: err });
    warning.code = "a2a.peer_unavailable";
    return warning;
}
export async function materializeA2aTools(specs, principal, signal, hostFloor, given, onCredentialEchoed, revocations) {
    return materializeLegA2aTools(libraryRevocationProbe(revocations, "materializeA2aTools revocations"), specs, principal, signal, hostFloor, receivePeerSeat(given, "materializeA2aTools peerSeat"), onCredentialEchoed);
}
export async function materializeLegA2aTools(revocations, specs, principal, signal, hostFloor, peerSeat, onCredentialEchoed, dialable, isolatePeers = false, enrichCtx, laneDeps) {
    const laneSeat = laneDeps !== undefined ? { frames: peerTaskFramesDeclared(laneDeps), onError: laneDeps.onError, ...(laneDeps.peerTaskStore !== undefined ? { store: laneDeps.peerTaskStore } : {}) } : undefined;
    const plaintextOrigins = laneDeps !== undefined ? plaintextOriginsOf(laneDeps) : undefined;
    const peers = specs.map((spec, index) => declaredPeerOf(spec, index));
    if (peers.length > 0) {
        const collision = findNamespacePrefixCollision(A2A_NAMESPACE, peers.map((p) => p.spec.name));
        if (collision) {
            const [a, b] = collision.peers;
            const e = new Error(a === b
                ? `A2A peer "${a}" is declared twice — each peer needs its own name (both mount under "${collision.prefix}").`
                : `A2A peer names "${a}" and "${b}" both mount under "${collision.prefix}" — the namespaced tool name keeps only [a-zA-Z0-9_-], so they are the same domain to this engine. Rename one.`);
            e.code = "config.a2a_peer_name_collision";
            throw e;
        }
    }
    const lifecycle = { disposed: false, ended: new AbortController() };
    const tools = [];
    const toolAxes = [];
    const warnings = [];
    const statuses = [];
    const announceEcho = echoAnnouncer(onCredentialEchoed);
    const dialed = peers.map((peer) => dialable === undefined || dialable(peer.spec));
    const undialed = new Set(peers.filter((_, i) => !dialed[i]));
    const settled = await Promise.allSettled(peers.map((peer, i) => (dialed[i] ? materializePeer(peer, principal, lifecycle, signal, hostFloor, peerSeat, announceEcho, revocations, isolatePeers, enrichCtx, laneSeat, plaintextOrigins) : Promise.resolve(null))));
    for (let i = 0; i < peers.length; i++) {
        const spec = peers[i].spec;
        const outcome = settled[i];
        if (outcome.status === "fulfilled") {
            if (outcome.value === null)
                continue;
            tools.push(...outcome.value.tools);
            toolAxes.push(...outcome.value.axes);
            statuses.push(outcome.value.status);
            warnings.push(...outcome.value.warnings);
        }
        else {
            warnings.push(asPeerWarning(spec, outcome.reason));
            statuses.push({ name: spec.name, status: "failed", ...peerFailureFields(outcome.reason), ...dialStopCodeOf(outcome.reason), error: foreignLine(thrownText(outcome.reason), A2A_ERROR_TEXT_MAX_CHARS), ...registrationOf(peers[i]) });
        }
    }
    return {
        tools,
        toolAxes,
        warnings,
        statuses,
        refresh: async (peer) => {
            const prefixOf = (name) => mintNamespacePrefix(A2A_NAMESPACE, name);
            const targets = peer !== undefined ? peers.filter((p) => p.spec.name === peer) : peers.filter((p) => !undialed.has(p));
            if (peer !== undefined && targets.length === 0) {
                return [{ peer, prefix: prefixOf(peer), status: "failed", toolCount: 0, added: [], removed: [], error: "no peer of that name is declared for this task" }];
            }
            const results = [];
            for (const target of targets) {
                const { spec } = target;
                const prefix = prefixOf(spec.name);
                if (lifecycle.disposed) {
                    results.push({ peer: spec.name, prefix, status: "disposed", toolCount: 0, added: [], removed: [] });
                    continue;
                }
                if (undialed.has(target)) {
                    results.push({ peer: spec.name, prefix, status: "failed", toolCount: 0, added: [], removed: [], error: "this peer was not dialed for this task (the run's tool valve leaves nothing of it) — the refresh did not contact it" });
                    continue;
                }
                const previous = statuses.find((s) => s.name === spec.name)?.toolNames ?? [];
                try {
                    const fresh = await materializePeer(target, principal, lifecycle, signal, hostFloor, peerSeat, announceEcho, revocations, isolatePeers, enrichCtx, laneSeat, plaintextOrigins);
                    const names = fresh.tools.map((t) => t.name);
                    results.push({
                        peer: spec.name,
                        prefix,
                        status: "refreshed",
                        toolCount: names.length,
                        added: names.filter((n) => !previous.includes(n)),
                        removed: previous.filter((n) => !names.includes(n)),
                        tools: fresh.tools,
                        axes: fresh.axes,
                        ...(fresh.warnings.length > 0 ? { warnings: fresh.warnings } : {}),
                    });
                    const at = statuses.findIndex((s) => s.name === spec.name);
                    if (at >= 0)
                        statuses[at] = fresh.status;
                }
                catch (err) {
                    if (err instanceof ProtocolRevokedRefusal && err.why === "revoked") {
                        results.push({ peer: spec.name, prefix, status: "revoked", toolCount: previous.length, added: [], removed: [], error: "peer revoked by the operator — the refresh did not contact it" });
                        continue;
                    }
                    results.push({
                        peer: spec.name,
                        prefix,
                        status: "failed",
                        toolCount: previous.length,
                        added: [],
                        removed: [],
                        ...peerFailureFields(err),
                        error: foreignLine(thrownText(err), A2A_ERROR_TEXT_MAX_CHARS),
                    });
                }
            }
            return results;
        },
        dispose: async () => {
            lifecycle.disposed = true;
            lifecycle.ended.abort();
        },
    };
}