UNPKG

@receiz/mcp-server

Version:

MCP server for agents building and verifying Receiz proof-native applications through the canonical Receiz SDK rails.

1,314 lines • 71.2 kB
import { createHash, randomBytes } from "node:crypto";
import { createReceizProofAuthorityChallenge, createReceizMaterialProgressiveCommitment, openReceizConversationSourceFamilyV1, openReceizMaterialSourceParts, openReceizSourceCarriedReplayFamilyV124, planReceizConversationEpochGrantBatchesV1, projectReceizSourceCarriedReplayBranchesV124, receizKaiNow, } from "@receiz/sdk";
const object = (properties, required = []) => ({
    type: "object",
    additionalProperties: false,
    properties,
    required,
});
const text = (description) => ({ type: "string", description });
const anyObject = (description) => ({ type: "object", additionalProperties: true, description });
const stringArray = (description) => ({ type: "array", items: { type: "string" }, description });
const integer = (description, minimum = 0) => ({ type: "integer", minimum, description });
const nullableText = (description) => ({ anyOf: [{ type: "string" }, { type: "null" }], description });
export const RECEIZ_V124_MCP_TOOL_NAMES = Object.freeze([
    "receiz_v124_kai_now",
    "receiz_v124_proof_authority_challenge_create",
    "receiz_v124_execution_plan_atomic_operation",
    "receiz_v124_execution_stage",
    "receiz_v124_execution_stage_prepared",
    "receiz_v124_execution_execute",
    "receiz_v124_execution_resolve",
    "receiz_v124_execution_resolve_by_idempotency",
    "receiz_v124_execution_cancel",
    "receiz_v124_runtime_authority_session_open",
    "receiz_v124_runtime_authority_session_refresh",
    "receiz_v124_runtime_authority_session_close",
    "receiz_v124_runtime_qualify",
    "receiz_v124_domain_verified_additions",
    "receiz_v124_domain_verified_replay",
    "receiz_v124_domain_verified_checkpoint",
    "receiz_v124_domain_verified_private_additions",
    "receiz_v124_domain_replay_proof_object_export",
    "receiz_v124_domain_replay_proof_object_restore",
    "receiz_source_carried_replay_open",
    "receiz_conversation_source_family_open",
    "receiz_conversation_epoch_grants_plan",
    "receiz_material_source_parts_open",
    "receiz_v124_subject_namespaces_resolve",
    "receiz_v124_identity_public_recipient_resolve",
    "receiz_v124_source_publish_sealed",
]);
const noScopes = Object.freeze([]);
const domainsRead = Object.freeze(["receiz:domains.read"]);
const domainsWrite = Object.freeze(["receiz:domains.write"]);
const subjectsRead = Object.freeze(["receiz:subjects.read"]);
/**
 * Fixed route scopes only. Authority-session tools additionally preserve the
 * exact challenge/grant scopes, and source publication selects exactly one
 * listed scope from the sealed source kind. A scope is never identity authority.
 */
export const RECEIZ_V124_MCP_REQUIRED_SCOPES = Object.freeze({
    receiz_v124_kai_now: noScopes,
    receiz_v124_proof_authority_challenge_create: noScopes,
    receiz_v124_execution_plan_atomic_operation: noScopes,
    receiz_v124_execution_stage: domainsWrite,
    receiz_v124_execution_stage_prepared: domainsWrite,
    receiz_v124_execution_execute: domainsWrite,
    receiz_v124_execution_resolve: domainsRead,
    receiz_v124_execution_resolve_by_idempotency: domainsRead,
    receiz_v124_execution_cancel: domainsWrite,
    receiz_v124_runtime_authority_session_open: noScopes,
    receiz_v124_runtime_authority_session_refresh: noScopes,
    receiz_v124_runtime_authority_session_close: noScopes,
    receiz_v124_runtime_qualify: noScopes,
    receiz_v124_domain_verified_additions: domainsRead,
    receiz_v124_domain_verified_replay: domainsRead,
    receiz_v124_domain_verified_checkpoint: domainsRead,
    receiz_v124_domain_verified_private_additions: Object.freeze(["receiz:world.private"]),
    receiz_v124_domain_replay_proof_object_export: noScopes,
    receiz_v124_domain_replay_proof_object_restore: noScopes,
    receiz_source_carried_replay_open: noScopes,
    receiz_conversation_source_family_open: noScopes,
    receiz_conversation_epoch_grants_plan: noScopes,
    receiz_material_source_parts_open: noScopes,
    receiz_v124_subject_namespaces_resolve: subjectsRead,
    receiz_v124_identity_public_recipient_resolve: subjectsRead,
    receiz_v124_source_publish_sealed: noScopes,
});
export const RECEIZ_V124_MCP_SCOPE_REQUIREMENTS = Object.freeze({
    receiz_v124_execution_execute: Object.freeze({
        mode: "active-session-and-route",
        sessionGrant: "exact-stored-granted-scopes",
        requiredGrantedRail: "settlement-or-reserve-when-operation-category-requires-it",
        bearerRequired: true,
    }),
    receiz_v124_execution_cancel: Object.freeze({
        mode: "active-session-and-route",
        sessionGrant: "exact-stored-granted-scopes",
        requiredGrantedRail: "settlement-or-reserve-when-operation-category-requires-it",
        bearerRequired: true,
    }),
    receiz_v124_runtime_authority_session_open: Object.freeze({
        mode: "challenge-and-rails",
        challengeScopes: "exact-signed-challenge-scopes",
        railScopePattern: "receiz:<requested-rail>.write",
        bearerRequired: true,
    }),
    receiz_v124_runtime_authority_session_refresh: Object.freeze({
        mode: "challenge-and-rails",
        challengeScopes: "exact-signed-challenge-scopes",
        railScopePattern: "receiz:<requested-rail>.write",
        bearerRequired: true,
    }),
    receiz_v124_runtime_authority_session_close: Object.freeze({
        mode: "stored-session-grant",
        bearerRequired: true,
    }),
    receiz_v124_runtime_qualify: Object.freeze({
        mode: "application-bound-bearer",
        bearerRequired: true,
    }),
    receiz_v124_domain_verified_private_additions: Object.freeze({
        mode: "active-session-and-route",
        sessionGrant: "exact-stored-granted-scopes",
        bearerRequired: true,
    }),
    receiz_v124_identity_public_recipient_resolve: Object.freeze({
        mode: "active-session-and-route",
        sessionGrant: "exact-stored-granted-scopes",
        bearerRequired: true,
    }),
    receiz_v124_source_publish_sealed: Object.freeze({
        mode: "source-kind",
        variants: Object.freeze({
            subject: Object.freeze(["receiz:subjects.write"]),
            "replay-segment": Object.freeze(["receiz:domains.write"]),
            checkpoint: Object.freeze(["receiz:domains.write"]),
        }),
        sessionBySourceKind: Object.freeze({
            subject: "not-required",
            "replay-segment": "active-session-with-exact-stored-grant",
            checkpoint: "active-session-with-exact-stored-grant",
        }),
        bearerRequired: true,
    }),
});
const mutations = new Set([
    "receiz_v124_proof_authority_challenge_create",
    "receiz_v124_execution_stage",
    "receiz_v124_execution_stage_prepared",
    "receiz_v124_execution_execute",
    "receiz_v124_execution_cancel",
    "receiz_v124_runtime_authority_session_open",
    "receiz_v124_runtime_authority_session_refresh",
    "receiz_v124_runtime_authority_session_close",
    "receiz_v124_source_publish_sealed",
]);
const identityBoundMutations = new Set([
    "receiz_v124_proof_authority_challenge_create",
    "receiz_v124_runtime_authority_session_open",
    "receiz_v124_runtime_authority_session_refresh",
    "receiz_v124_runtime_authority_session_close",
]);
function operationDescription(name) {
    const scopes = RECEIZ_V124_MCP_REQUIRED_SCOPES[name];
    const scopeText = scopes.length === 0
        ? "No additional fixed route scope; any challenge/grant scope remains exact."
        : `Potential fixed route scopes: ${scopes.join(", ")}.`;
    if (name === "receiz_v124_kai_now") {
        return "Read the current local KKSv1.0 coordinate candidate. It becomes temporal authority only after the unchanged KaiSigil proof binds it and canonical SDK admission verifies that proof and its causal context. No network, server, database, or createdAt field participates. Chronos is descriptive projection only; MCP is not authority.";
    }
    if (name === "receiz_v124_proof_authority_challenge_create") {
        return "Create the canonical whole-pulse V124 proof-authority challenge. The Receiz identity artifact remains authority; the challenge and later bearer are short-lived capability mechanics. MCP is not authority.";
    }
    if (name === "receiz_v124_runtime_authority_session_open" || name === "receiz_v124_runtime_authority_session_refresh") {
        return "Call the canonical Receiz V124 authority-session operation with a bound bearer, the exact signed challenge scopes, and each selected rail's write scope. The identity artifact remains authority; MCP is not authority and the session is not authority.";
    }
    if (name === "receiz_v124_execution_execute" || name === "receiz_v124_execution_cancel") {
        return "Execute against the exact MCP-custodied handle and an active authenticated authority session. The fixed route scope is receiz:domains.write; the complete stored session grant is re-authenticated, and settlement/reserve categories require that granted rail. Sealed proof objects remain authority; MCP, the bearer, and the session are not authority.";
    }
    if (name === "receiz_v124_domain_verified_private_additions") {
        return "Hydrate access-filtered private additions through receiz:world.private and an active authenticated session whose exact stored grant is re-authenticated. The exact encrypted viewer result remains host-custodied behind privateAdditionsRef; MCP output is not proof authority.";
    }
    if (name === "receiz_v124_identity_public_recipient_resolve") {
        return "Resolve a privacy-safe, rate-limited public recipient through receiz:subjects.read and an active authenticated session whose exact stored grant is re-authenticated. The recipient projection and session are not identity authority; the Receiz identity artifact remains stronger truth.";
    }
    if (name === "receiz_v124_source_publish_sealed") {
        return "Publish an already sealed source through the canonical SDK and bound bearer. Subject sources require receiz:subjects.write without a session; replay-segment and checkpoint sources require receiz:domains.write plus an active session whose exact stored grant is re-authenticated. Exact artifact bytes remain authority; MCP is not authority.";
    }
    if (name === "receiz_source_carried_replay_open") {
        return "Open exact sealed replay-segment sources as one deterministic held family and project every valid root-to-head branch without last-write-wins. Only stable coordinates and counts are returned; exact source bytes remain host-custodied. Sealed proof objects remain authority; the family digest, branch projection, and MCP are not authority.";
    }
    if (name === "receiz_conversation_source_family_open") {
        return "Open exact sealed conversation replay sources through the canonical SDK and preserve every lawful sibling branch. Only membership, epoch, message-digest, and head coordinates are returned; clear message bodies and source bytes remain in trusted host custody. Sealed proof objects remain authority; the projection and MCP are not authority.";
    }
    if (name === "receiz_conversation_epoch_grants_plan") {
        return "Plan one bounded encrypted epoch-grant window for invited Receiz IDs from host-custodied secret and recipient materials. The clear epoch secret is never returned; each call carries at most 128 recipients and reports the next offset without imposing a total membership cap. Receiz identity bindings and sealed proof objects remain authority; MCP is not authority.";
    }
    if (name === "receiz_material_source_parts_open") {
        return "Verify one complete host-custodied material source family through the canonical SDK and return a bounded segment-coordinate window. Exact material bytes and content-bearing locators never enter MCP output. The enclosing sealed material proof object remains authority; local custody, the manifest projection, and MCP are not authority.";
    }
    return `Call the canonical Receiz V124 SDK operation without reimplementing validation or authority. ${scopeText} Sealed proof objects and authenticated heads remain stronger truth; MCP is not authority.`;
}
const withMcpAuthorityBoundary = (description) => description.includes("MCP is not authority")
    ? description
    : `${description} MCP is not authority.`;
function operationInputSchema(name) {
    const digestValue = text("Exact lowercase SHA-256 digest.");
    const handleRef = text("Opaque process-local MCP execution-handle reference.");
    const sessionRef = text("Opaque non-authoritative MCP authority-session reference: locally held after open/refresh or resolved from trusted host persistence and reverified by the canonical SDK/server path. Raw session handles are forbidden.");
    let input;
    switch (name) {
        case "receiz_v124_kai_now":
            return object({});
        case "receiz_v124_proof_authority_challenge_create":
            input = object({
                artifactDigest: digestValue,
                scopes: stringArray("Exact canonical requested scopes."),
                consentStatementDigest: digestValue,
                ttlPulses: { type: "integer", minimum: 1, maximum: 600 },
                nonce: text("Optional canonical nonce; omitted to generate one cryptographically."),
            }, ["artifactDigest", "scopes", "consentStatementDigest", "ttlPulses"]);
            break;
        case "receiz_v124_execution_plan_atomic_operation":
            input = object({
                operations: { type: "array", minItems: 1, items: anyObject("Canonical registered V124 operation.") },
                participants: stringArray("Canonical participant IDs."),
                expectedParticipantHeads: anyObject("Exact participant-head CAS map."),
                semanticIdempotencyKey: text("Stable semantic idempotency key."),
                attemptId: text("Distinct attempt ID."),
            }, ["operations", "participants", "expectedParticipantHeads", "semanticIdempotencyKey", "attemptId"]);
            break;
        case "receiz_v124_execution_stage":
            input = object({ planRef: text("Opaque process-local MCP operation-plan reference returned by plan_atomic_operation.") }, ["planRef"]);
            break;
        case "receiz_v124_execution_stage_prepared":
            input = object({
                planRef: text("Opaque process-local MCP operation-plan reference returned by plan_atomic_operation."),
                transitionSetRef: text("Host-resolved reference to the exact portable execution transition set."),
            }, ["planRef", "transitionSetRef"]);
            break;
        case "receiz_v124_execution_execute":
        case "receiz_v124_execution_cancel":
            input = object({ handleRef, sessionRef }, ["handleRef", "sessionRef"]);
            break;
        case "receiz_v124_execution_resolve":
            input = object({ executionId: text("Durable execution ID.") }, ["executionId"]);
            break;
        case "receiz_v124_execution_resolve_by_idempotency":
            input = object({ domainId: text("Exact domain ID."), operationKind: text("Exact operation kind."), semanticIdempotencyKey: text("Stable semantic idempotency key.") }, ["domainId", "operationKind", "semanticIdempotencyKey"]);
            break;
        case "receiz_v124_runtime_authority_session_open":
            input = object({
                actorSubjectId: text("Exact actor subject ID."),
                identityArtifactRef: text("Host-resolved reference to the exact Receiz identity artifact."),
                subjectSourceArtifactRef: text("Host-resolved reference to the exact sealed subject-source artifact."),
                signedChallengeRef: text("Host-resolved reference to the locally signed canonical challenge."),
                requestedRails: stringArray("Exact selected runtime rails."),
                requiredNamespaces: stringArray("Exact required namespaces."),
            }, ["actorSubjectId", "identityArtifactRef", "subjectSourceArtifactRef", "signedChallengeRef", "requestedRails", "requiredNamespaces"]);
            break;
        case "receiz_v124_runtime_authority_session_refresh":
            input = object({
                sessionRef,
                identityArtifactRef: text("Host-resolved reference to the exact Receiz identity artifact."),
                signedChallengeRef: text("Host-resolved reference to the locally signed refresh challenge."),
                requestedRails: stringArray("Exact unchanged runtime rails."),
                requiredNamespaces: stringArray("Exact unchanged namespaces."),
            }, ["sessionRef", "identityArtifactRef", "signedChallengeRef", "requestedRails", "requiredNamespaces"]);
            break;
        case "receiz_v124_runtime_authority_session_close":
            input = object({ sessionRef }, ["sessionRef"]);
            break;
        case "receiz_v124_runtime_qualify":
            input = object({ operations: stringArray("Runtime operations to qualify exactly.") }, ["operations"]);
            break;
        case "receiz_v124_domain_verified_additions":
        case "receiz_v124_domain_verified_replay":
            input = object({
                domainId: text("Exact domain ID."),
                afterHead: nullableText("Verified predecessor head, or null only for genesis."),
                expectedRegistryDigest: digestValue,
                expectedReducerDigest: digestValue,
            }, ["domainId", "afterHead", "expectedRegistryDigest", "expectedReducerDigest"]);
            break;
        case "receiz_v124_domain_verified_checkpoint":
            input = object({ domainId: text("Exact domain ID."), throughHead: digestValue }, ["domainId", "throughHead"]);
            break;
        case "receiz_v124_domain_verified_private_additions":
            input = object({
                domainId: text("Exact private/invited domain ID."),
                afterHead: nullableText("Verified predecessor head, or null only for genesis."),
                sessionRef,
                accessGrantHandle: text("Existing access-grant capability handle."),
                expectedViewerSubjectId: text("Exact requesting viewer subject ID."),
                expectedViewerSubjectHead: digestValue,
                expectedGrantHead: digestValue,
            }, ["domainId", "afterHead", "sessionRef", "accessGrantHandle", "expectedViewerSubjectId", "expectedViewerSubjectHead", "expectedGrantHead"]);
            break;
        case "receiz_v124_domain_replay_proof_object_export":
            input = object({
                domainId: text("Exact domain ID."),
                expectedRegistryDigest: digestValue,
                expectedReducerDigest: digestValue,
                throughHead: digestValue,
                includeCheckpoint: { type: "boolean" },
                ownership: anyObject("Portable ownership projection."),
                provenance: anyObject("Portable provenance projection."),
                settlement: anyObject("Portable settlement projection."),
            }, ["domainId", "expectedRegistryDigest", "expectedReducerDigest", "throughHead", "ownership", "provenance", "settlement"]);
            break;
        case "receiz_v124_domain_replay_proof_object_restore":
            input = object({
                domainId: text("Exact domain ID."),
                expectedRegistryDigest: digestValue,
                expectedReducerDigest: digestValue,
                expectedHead: digestValue,
                expectedCursor: integer("Exact verified cursor."),
                expectedNamespace: anyObject("Exact namespace-head expectation."),
                sealedReplayProofObjectRef: text("Host-resolved reference to the exact sealed replay proof object."),
            }, ["domainId", "expectedRegistryDigest", "expectedReducerDigest", "expectedHead", "expectedCursor", "expectedNamespace", "sealedReplayProofObjectRef"]);
            break;
        case "receiz_source_carried_replay_open":
            input = object({
                sealedSourceArtifactRefs: {
                    type: "array",
                    minItems: 1,
                    items: { type: "string" },
                    description: "Host-resolved references to exact sealed replay-segment source artifacts. Exact bytes never enter MCP output.",
                },
                expected: object({
                    domainId: text("Optional exact domain identity expectation."),
                    expectedRegistryDigest: digestValue,
                    expectedReducerDigest: digestValue,
                    afterHead: nullableText("Optional exact predecessor head expectation."),
                    afterCursor: integer("Optional exact predecessor cursor."),
                }),
            }, ["sealedSourceArtifactRefs", "expected"]);
            break;
        case "receiz_conversation_source_family_open":
            input = object({
                sealedSourceArtifactRefs: {
                    type: "array",
                    minItems: 1,
                    items: { type: "string" },
                    description: "Host-resolved references to exact sealed conversation replay sources. No source bytes enter MCP output.",
                },
                expectedConversationId: text("Exact conversation proof-object identity."),
                expected: object({
                    domainId: text("Optional exact conversation-domain identity expectation."),
                    expectedRegistryDigest: digestValue,
                    expectedReducerDigest: digestValue,
                    afterHead: nullableText("Optional exact predecessor head expectation."),
                    afterCursor: integer("Optional exact predecessor cursor."),
                }),
            }, ["sealedSourceArtifactRefs", "expectedConversationId", "expected"]);
            break;
        case "receiz_conversation_epoch_grants_plan":
            input = object({
                epochSecretRef: text("Host-custodied reference to the exact epoch secret; clear key bytes never enter MCP output."),
                recipientSetRef: text("Host-custodied reference to the complete Receiz-ID participant and public-access binding set."),
                recipientOffset: integer("Stable offset in canonical Receiz-ID order."),
                recipientLimit: {
                    type: "integer",
                    minimum: 1,
                    maximum: 128,
                    description: "Bounded recipients for this call; repeat with nextRecipientOffset for any total membership size.",
                },
            }, ["epochSecretRef", "recipientSetRef", "recipientOffset", "recipientLimit"]);
            break;
        case "receiz_material_source_parts_open":
            input = object({
                materialSourceFamilyRef: text("Host-custodied reference to the complete head/source locator family. Content-bearing locators never enter MCP output."),
                segmentOffset: integer("Stable verified segment offset."),
                segmentLimit: {
                    type: "integer",
                    minimum: 1,
                    maximum: 256,
                    description: "Maximum verified segment coordinates returned by this call.",
                },
            }, ["materialSourceFamilyRef", "segmentOffset", "segmentLimit"]);
            break;
        case "receiz_v124_subject_namespaces_resolve":
            input = object({
                subjectId: text("Exact subject ID."),
                atHead: digestValue,
                names: stringArray("Canonical namespace names."),
                expectedAdmittedProofDigest: digestValue,
                expectedOwnershipHead: digestValue,
                expectedRegistryDigest: digestValue,
                expectedReducerDigest: digestValue,
            }, ["subjectId", "atHead", "names", "expectedAdmittedProofDigest", "expectedOwnershipHead", "expectedRegistryDigest", "expectedReducerDigest"]);
            break;
        case "receiz_v124_identity_public_recipient_resolve":
            input = object({
                sessionRef,
                expectedRequesterSubjectId: text("Exact requesting subject ID."),
                normalizedAlias: text("NFKC-normalized lowercase public alias."),
                purpose: text("Exact one-use resolution purpose."),
                operationNonce: text("Canonical operation nonce."),
            }, ["sessionRef", "expectedRequesterSubjectId", "normalizedAlias", "purpose", "operationNonce"]);
            break;
        case "receiz_v124_source_publish_sealed":
            input = object({
                sessionRef: text("Required for replay-segment/checkpoint sources; omit for subject sources."),
                sealedSourceArtifactRef: text("Host-resolved reference to the exact already sealed source artifact."),
            }, ["sealedSourceArtifactRef"]);
            break;
    }
    return object({
        input,
        ...(mutations.has(name) ? { confirmation: text("Exact SHA-256 confirmation digest returned by the preview call.") } : {}),
    }, ["input"]);
}
export const RECEIZ_V124_MCP_TOOLS = RECEIZ_V124_MCP_TOOL_NAMES.map((name) => ({
    name,
    description: withMcpAuthorityBoundary(operationDescription(name)),
    inputSchema: operationInputSchema(name),
    outputSchema: { type: "object", additionalProperties: true },
}));
export const RECEIZ_V124_MCP_MATERIAL_KINDS = Object.freeze([
    "operation-plan",
    "identity-artifact",
    "subject-source-artifact",
    "signed-challenge",
    "portable-transition-set",
    "sealed-source-artifact",
    "sealed-replay-proof-object",
    "persisted-authority-session",
    "private-additions",
    "conversation-epoch-secret",
    "conversation-recipient-set",
    "material-source-family",
    "verified-portable-transition-set",
    "prepared-portable-transition-commit-set",
    "committed-artifact-transitions",
    "portable-transition-recovery",
]);
const custodyByClient = new WeakMap();
function canonical(value) {
    if (value === null || typeof value === "string" || typeof value === "boolean")
        return JSON.stringify(value);
    if (typeof value === "number" && Number.isFinite(value))
        return JSON.stringify(value);
    if (typeof value === "bigint")
        return JSON.stringify(value.toString());
    if (value instanceof Uint8Array)
        return JSON.stringify(Buffer.from(value).toString("base64url"));
    if (value instanceof ArrayBuffer)
        return JSON.stringify(Buffer.from(value).toString("base64url"));
    if (Array.isArray(value))
        return `[${value.map(canonical).join(",")}]`;
    if (value && typeof value === "object") {
        return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;
    }
    return JSON.stringify(String(value));
}
async function canonicalMaterial(value, seen = new WeakSet()) {
    if (value === null || typeof value === "string" || typeof value === "boolean")
        return value;
    if (typeof value === "number") {
        if (!Number.isFinite(value))
            throw new TypeError("V124_MCP_MATERIAL_INVALID");
        return value;
    }
    if (typeof value === "bigint")
        return value.toString();
    if (value instanceof Uint8Array) {
        return { schema: "receiz.mcp.exact-bytes.v124", exactBytesB64u: Buffer.from(value).toString("base64url") };
    }
    if (value instanceof ArrayBuffer) {
        return { schema: "receiz.mcp.exact-bytes.v124", exactBytesB64u: Buffer.from(value).toString("base64url") };
    }
    if (typeof Blob !== "undefined" && value instanceof Blob) {
        return {
            schema: "receiz.mcp.exact-blob.v124",
            mimeType: value.type,
            size: value.size,
            exactBytesB64u: Buffer.from(await value.arrayBuffer()).toString("base64url"),
        };
    }
    if (Array.isArray(value))
        return Promise.all(value.map((entry) => canonicalMaterial(entry, seen)));
    if (typeof value === "object") {
        if (seen.has(value))
            throw new TypeError("V124_MCP_MATERIAL_INVALID");
        seen.add(value);
        const output = {};
        for (const key of Object.keys(value).sort()) {
            output[key] = await canonicalMaterial(value[key], seen);
        }
        seen.delete(value);
        return output;
    }
    throw new TypeError("V124_MCP_MATERIAL_INVALID");
}
function digest(value) {
    return createHash("sha256").update(canonical(value)).digest("hex");
}
async function materialDigest(value) {
    return digest(await canonicalMaterial(value));
}
/** Exact private-material fingerprint for later MCP custody composition. Not proof admission. */
export async function digestReceizV124McpMaterial(value) {
    return materialDigest(value);
}
function confirmationDigest(name, value) {
    return digest({ schema: "receiz.mcp.mutation-confirmation.v124", name, value });
}
function previewOrConfirm(name, args, input) {
    const expected = confirmationDigest(name, input);
    if (args.confirmation === undefined) {
        return {
            confirmationRequired: true,
            confirmationDigest: expected,
            writesPerformed: 0,
            secretMaterialReturned: false,
            authority: {
                mcpIsAuthority: false,
                strongerTruth: identityBoundMutations.has(name)
                    ? "receiz-identity-artifact"
                    : "sealed-receiz-proof-object",
            },
        };
    }
    if (args.confirmation !== expected)
        throw new TypeError("V124_MCP_CONFIRMATION_INVALID");
}
function inputObject(args) {
    const value = args.input ?? args;
    if (!value || typeof value !== "object" || Array.isArray(value))
        throw new TypeError("V124_MCP_INPUT_INVALID");
    return value;
}
function assertClosedInput(input, allowedKeys) {
    const allowed = new Set(allowedKeys);
    if (Object.keys(input).some((key) => !allowed.has(key))) {
        throw new TypeError("V124_MCP_INPUT_CLOSED_SHAPE_INVALID");
    }
}
function requiredMcpText(value, code) {
    if (typeof value !== "string" || value.length === 0 || value !== value.trim() || value.length > 2_048) {
        throw new TypeError(code);
    }
    return value;
}
function requiredHeldSourceLocator(value, code) {
    if (typeof value !== "string" || value.length === 0 || value !== value.trim())
        throw new TypeError(code);
    return value;
}
function boundedMcpInteger(value, minimum, maximum, code) {
    if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
        throw new TypeError(code);
    }
    return value;
}
function materialRecord(value, code) {
    if (!value || typeof value !== "object" || Array.isArray(value))
        throw new TypeError(code);
    return value;
}
function custody(client) {
    const key = client;
    const existing = custodyByClient.get(key);
    if (existing)
        return existing;
    const created = {
        handles: new Map(),
        sessions: new Map(),
        materials: new Map(),
    };
    custodyByClient.set(key, created);
    return created;
}
export function admitReceizV124McpMaterial(client, input) {
    if (!RECEIZ_V124_MCP_MATERIAL_KINDS.includes(input.kind))
        throw new TypeError("V124_MCP_MATERIAL_KIND_INVALID");
    if (typeof input.applicationId !== "string" || !input.applicationId)
        throw new TypeError("V124_MCP_APPLICATION_ID_REQUIRED");
    if (input.value === undefined || input.value === null)
        throw new TypeError("V124_MCP_MATERIAL_INVALID");
    const reference = `receiz:mcp:v124:material:${input.kind}:${randomBytes(32).toString("base64url")}`;
    custody(client).materials.set(reference, Object.freeze({ ...input }));
    return reference;
}
export function readReceizV124McpMaterial(client, input) {
    const held = custody(client).materials.get(input.reference);
    if (!held || held.kind !== input.kind || held.applicationId !== input.applicationId) {
        throw new TypeError("V124_MCP_MATERIAL_NOT_HELD");
    }
    return held.value;
}
function snapshotMaterial(value) {
    try {
        return structuredClone(value);
    }
    catch {
        throw new TypeError("V124_MCP_MATERIAL_INVALID");
    }
}
export async function resolveReceizV124McpMaterial(client, options, reference, kind) {
    if (typeof reference !== "string" || !reference)
        throw new TypeError("V124_MCP_MATERIAL_REF_REQUIRED");
    const applicationId = options.applicationId;
    if (!applicationId)
        throw new TypeError("V124_MCP_APPLICATION_ID_REQUIRED");
    const held = custody(client).materials.get(reference);
    if (held) {
        if (held.kind !== kind || held.applicationId !== applicationId)
            throw new TypeError("V124_MCP_MATERIAL_REFERENCE_MISMATCH");
        return held.value;
    }
    if (!options.resolveMaterial)
        throw new TypeError("V124_MCP_MATERIAL_RESOLVER_REQUIRED");
    const value = await options.resolveMaterial({ reference, kind, applicationId });
    if (value === undefined || value === null)
        throw new TypeError("V124_MCP_MATERIAL_NOT_FOUND");
    const snapshot = snapshotMaterial(value);
    custody(client).materials.set(reference, Object.freeze({ kind, applicationId, value: snapshot }));
    return snapshot;
}
export async function persistReceizV124McpMaterial(client, options, kind, value) {
    const applicationId = options.applicationId;
    if (!applicationId)
        throw new TypeError("V124_MCP_APPLICATION_ID_REQUIRED");
    if (!options.persistMaterial) {
        return admitReceizV124McpMaterial(client, { kind, applicationId, value });
    }
    const reference = await options.persistMaterial({ kind, applicationId, value });
    if (typeof reference !== "string" || !reference)
        throw new TypeError("V124_MCP_MATERIAL_PERSISTENCE_INVALID");
    custody(client).materials.set(reference, Object.freeze({ kind, applicationId, value }));
    return reference;
}
function storeCustodied(client, kind, value) {
    if (!value || typeof value !== "object" || Array.isArray(value))
        throw new TypeError(`V124_MCP_${kind.toUpperCase()}_INVALID`);
    const ref = `receiz:mcp:v124:${kind}:${digest({ kind, value })}`;
    const store = custody(client);
    (kind === "handle" ? store.handles : store.sessions).set(ref, value);
    return ref;
}
function readCustodied(client, kind, ref) {
    if (typeof ref !== "string" || !ref)
        throw new TypeError(`V124_MCP_${kind.toUpperCase()}_REF_REQUIRED`);
    const store = custody(client);
    const value = (kind === "handle" ? store.handles : store.sessions).get(ref);
    if (!value)
        throw new TypeError(`V124_MCP_${kind.toUpperCase()}_NOT_HELD`);
    return value;
}
async function readSession(client, options, ref) {
    if (typeof ref !== "string" || !ref)
        throw new TypeError("V124_MCP_SESSION_REF_REQUIRED");
    const held = custody(client).sessions.get(ref);
    if (held)
        return held;
    if (options.requireReferenceMaterials !== true)
        throw new TypeError("V124_MCP_SESSION_NOT_HELD");
    const persisted = await resolveReceizV124McpMaterial(client, options, ref, "persisted-authority-session");
    if (options.applicationId)
        assertApplicationValue(persisted, options.applicationId);
    authoritySessionHandle(persisted);
    return persisted;
}
function authoritySessionHandle(session) {
    if (!session || typeof session !== "object" || Array.isArray(session))
        throw new TypeError("V124_MCP_SESSION_INVALID");
    const handle = session.authoritySessionHandle;
    if (typeof handle !== "string" || !handle)
        throw new TypeError("V124_MCP_SESSION_INVALID");
    return handle;
}
async function inputWithHeldSession(client, input, required, options) {
    if (input.authoritySessionHandle !== undefined)
        throw new TypeError("V124_MCP_RAW_SESSION_HANDLE_FORBIDDEN");
    if (input.sessionRef === undefined) {
        if (required)
            throw new TypeError("V124_MCP_SESSION_REF_REQUIRED");
        return {
            input: { ...without(input, "sessionRef", "authoritySessionHandle"), authoritySessionHandle: null },
            session: null,
        };
    }
    const session = await readSession(client, options, input.sessionRef);
    return {
        input: {
            ...without(input, "sessionRef", "authoritySessionHandle"),
            authoritySessionHandle: authoritySessionHandle(session),
        },
        session,
    };
}
function redact(value) {
    if (Array.isArray(value))
        return value.map(redact);
    if (!value || typeof value !== "object")
        return value;
    if (value instanceof Uint8Array || value instanceof ArrayBuffer)
        return undefined;
    const output = {};
    for (const [key, child] of Object.entries(value)) {
        if (/^(accessToken|bearerToken|refreshToken|token|clientSecret|privateKey|privateKeyJwk|secret|passphrase|mnemonic|authoritySessionHandle)$/i.test(key))
            continue;
        const projected = redact(child);
        if (projected !== undefined)
            output[key] = projected;
    }
    return output;
}
function projectionWithRef(value, field, ref) {
    const projected = redact(value);
    return projected && typeof projected === "object" && !Array.isArray(projected)
        ? { ...projected, [field]: ref }
        : { [field]: ref, projection: projected };
}
async function sessionProjection(client, options, session) {
    const projected = projectionWithRef(session, "sessionRef", storeCustodied(client, "session", session));
    if (!options.persistMaterial)
        return projected;
    return {
        ...projected,
        persistedSessionRef: await persistReceizV124McpMaterial(client, options, "persisted-authority-session", session),
    };
}
function without(input, ...keys) {
    const output = {};
    for (const [key, value] of Object.entries(input))
        if (!keys.includes(key))
            output[key] = value;
    return output;
}
function withPinnedApplication(input, options) {
    return options.applicationId ? { ...input, applicationId: options.applicationId } : input;
}
function safePlanProjection(plan, planRef) {
    const record = plan && typeof plan === "object" && !Array.isArray(plan) ? plan : {};
    const allowed = [
        "schema", "applicationId", "domainId", "operationKind", "registryDigest",
        "reducerDigest", "exactPlanDigest", "expectedParticipantHeads",
        "semanticIdempotencyKey", "attemptId", "writesOnFailure",
    ];
    return {
        planRef,
        ...Object.fromEntries(allowed.filter((key) => record[key] !== undefined).map((key) => [key, redact(record[key])])),
        authority: { planRefIsAuthority: false, strongerTruth: "sealed-receiz-proof-object" },
    };
}
async function executionOutcomeProjection(client, options, value) {
    if (!value || typeof value !== "object" || Array.isArray(value))
        return redact(value);
    const record = value;
    if (record.status === "committed" && client.execution.exportCommittedRecovery) {
        try {
            const recovery = client.execution.exportCommittedRecovery(value);
            const recoveryRef = await persistReceizV124McpMaterial(client, options, "portable-transition-recovery", recovery);
            return {
                ...redact(value),
                recoveryRef,
                recoveryAuthority: {
                    recoveryRefIsAuthority: false,
                    transactionOccursAtEdge: true,
                    serverRole: "global-sync-only",
                    strongerTruth: "sealed-receiz-proof-object",
                },
            };
        }
        catch {
            // A committed coordinate without SDK-held transition custody remains a
            // valid report, but cannot be promoted into a portable edge recovery.
        }
    }
    if (record.status !== "unknown" || !record.plan || typeof record.plan !== "object" || Array.isArray(record.plan)) {
        return redact(value);
    }
    const applicationId = options.applicationId
        ?? record.plan.applicationId;
    if (typeof applicationId !== "string" || !applicationId)
        throw new TypeError("V124_MCP_APPLICATION_ID_REQUIRED");
    assertApplicationValue(record.plan, applicationId);
    const planRef = admitReceizV124McpMaterial(client, {
        kind: "operation-plan",
        applicationId,
        value: record.plan,
    });
    const { plan: _plan, ...coordinates } = record;
    return {
        ...redact(coordinates),
        planRef,
        plan: safePlanProjection(record.plan, planRef),
    };
}
function replayExportProjection(value) {
    if (!value || typeof value !== "object" || Array.isArray(value))
        throw new TypeError("V124_MCP_REPLAY_EXPORT_INVALID");
    const record = value;
    if (!record.proofObject || typeof record.proofObject !== "object" || Array.isArray(record.proofObject)) {
        throw new TypeError("V124_MCP_REPLAY_EXPORT_INVALID");
    }
    const proofObject = record.proofObject;
    if (!proofObject.payload || typeof proofObject.payload !== "object" || Array.isArray(proofObject.payload)) {
        throw new TypeError("V124_MCP_REPLAY_EXPORT_INVALID");
    }
    const payload = proofObject.payload;
    const bytes = payload.bytes;
    if (!(bytes instanceof Uint8Array) && !(bytes instanceof ArrayBuffer)) {
        throw new TypeError("V124_MCP_REPLAY_EXPORT_BYTES_INVALID");
    }
    const { proofObject: _proofObject, ...outer } = record;
    const { payload: _payload, ...proofCoordinates } = proofObject;
    const { bytes: _bytes, ...payloadCoordinates } = payload;
    return {
        ...redact(outer),
        proofObject: {
            ...redact(proofCoordinates),
            payload: {
                ...redact(payloadCoordinates),
                exactBytesB64u: Buffer.from(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)).toString("base64url"),
            },
        },
    };
}
async function privateAdditionsProjection(client, options, value) {
    if (!value || typeof value !== "object" || Array.isArray(value))
        return redact(value);
    const record = value;
    if (record.status !== "authenticated")
        return redact(value);
    const additions = Array.isArray(record.additions) ? record.additions : [];
    const additionDigests = additions.map((addition) => {
        if (!addition || typeof addition !== "object" || Array.isArray(addition))
            return null;
        const eventDigest = addition.eventDigest;
        return typeof eventDigest === "string" ? eventDigest : null;
    }).filter((entry) => entry !== null);
    const privateAdditionsRef = await persistReceizV124McpMaterial(client, options, "private-additions", value);
    return {
        schema: record.schema,
        status: record.status,
        applicationId: record.applicationId,
        domainId: record.domainId,
        afterHead: record.afterHead,
        afterCursor: record.afterCursor,
        cursor: record.cursor,
        priorHead: record.priorHead,
        head: record.head,
        additionCount: additions.length,
        additionDigests,
        privateAdditionsRef,
        authenticatedReceipt: redact(record.authenticatedReceipt),
        authority: {
            privateAdditionsRefIsProofAuthority: false,
            strongerTruth: "sealed-receiz-proof-object",
        },
    };
}
async function confirmationBasis(input, materials) {
    const entries = await Promise.all(Object.entries(materials).map(async ([name, value]) => [
        name,
        await materialDigest(value),
    ]));
    return {
        ...input,
        mcpMaterialDigests: Object.fromEntries(entries.sort(([left], [right]) => left.localeCompare(right))),
    };
}
function assertApplicationValue(value, expected) {
    if (!value || typeof value !== "object" || Array.isArray(value))
        return;
    const applicationId = value.applicationId;
    if (applicationId !== undefined && applicationId !== expected)
        throw new TypeError("V124_MCP_APPLICATION_MISMATCH");
}
function assertPinnedApplication(name, input, options) {
    if (name === "receiz_v124_kai_now")
        return;
    const expected = options.applicationId;
    if (options.requirePinnedApplicationId === true && !expected)
        throw new TypeError("V124_MCP_APPLICATION_ID_REQUIRED");
    if (!expected)
        return;
    assertApplicationValue(input, expected);
    if (input.plan)
        assertApplicationValue(input.plan, expected);
}
async function confirmed(name, args, confirmationInput, operation, project = redact) {
    const preview = previewOrConfirm(name, args, confirmationInput);
    if (preview)
        return preview;
    return project(await operation());
}
export async function callReceizV124McpOperation(client, name, args, options = {}) {
    if (!RECEIZ_V124_MCP_TOOL_NAMES.includes(name))
        throw new TypeError("V124_MCP_TOOL_UNKNOWN");
    const toolName = name;
    const input = inputObject(args);
    assertPinnedApplication(toolName, input, options);
    const pinnedInput = withPinnedApplication(input, options);
    const referenceMaterials = options.requireReferenceMaterials === true;
    switch (toolName) {
        case "receiz_v124_kai_now":
            {
                const coordinate = receizKaiNow();
                return {
                    schema: "receiz.kks-v1.coordinate-candidate.v1",
                    kksVersion: "KKSv1.0",
                    kaiPulse: String(coordinate.pulse),
                    kaiUpulse: String(coordinate.uPulse),
                    pulse: coordinate.pulse,
                    uPulse: coordinate.uPulse,
                    source: "live-monotonic-frequency-from-genesis",
                    authority: {
                        candidateIsTemporalAuthority: false,
                        requiresKaiSigilProof: true,
                        requiredAdmission: "admitReceizKksV1ProofCoordinate",
                        createdAtAuthority: false,
                        networkRequired: false,
                    },
                };
            }
        case "receiz_v124_proof_authority_challenge_create":
            {
                const preview = previewOrConfirm(toolName, args, pinnedInput);
                if (preview)
                    return preview;
                return createReceizProofAuthorityChallenge(pinnedInput);
            }
        case "receiz_v124_execution_plan_atomic_operation": {
            const plan = await client.execution.planAtomicOperationV124(pinnedInput);
            if (!referenceMaterials)
                return plan;
            const applicationId = options.applicationId;
            if (!applicationId)
                throw new TypeError("V124_MCP_APPLICATION_ID_REQUIRED");
            const planRef = admitReceizV124McpMaterial(client, { kind: "operation-plan", applicationId, value: plan });
            return safePlanProjection(plan, planRef);
        }
        case "receiz_v124_execution_stage": {
            const plan = referenceMaterials
                ? await resolveReceizV124McpMaterial(client, options, input.planRef, "operation-plan")
                : Object.prototype.hasOwnProperty.call(input, "plan") ? input.plan : input;
            const basis = referenceMaterials
                ? await confirmationBasis(pinnedInput, { plan })
                : pinnedInput;
            return confirmed(toolName, args, basis, async () => {
                const handle = await client.execution.stage(plan);
                return projectionWithRef(handle, "handleRef", storeCustodied(client, "handle", handle));
            });
        }
        case "receiz_v124_execution_stage_prepared": {
            const plan = referenceMaterials
                ? await resolveReceizV124McpMaterial(client, options, input.planRef, "operation-plan")
                : input.plan;
            const transitionSet = referenceMaterials
                ? await resolveReceizV124McpMaterial(client, options, input.transitionSetRef, "portable-transition-set")
                : input.transitionSet;
            const basis = referenceMaterials
                ? await confirmationBasis(pinnedInput, { plan, transitionSet })
                : pinnedInput;
            return confirmed(toolName, args, basis, async () => {
                const handle = await client.execution.stagePrepared(plan, transitionSet);
                return projectionWithRef(handle, "handleRef", storeCustodied(client, "handle", handle));
            });
        }
        case "receiz_v124_execution_execute": {
            const handle = readCustodied(client, "handle", input.handleRef);
            const session = await readSession(client, options, input.sessionRef);
            if (options.applicationId) {
                assertApplicationValue(handle, options.applicationId);
                assertApplicationValue(session, options.applicationId);
            }
            return confirmed(toolName, args, await confirmationBasis(pinnedInput, { handle, session }), () => client.execution.execute(handle, session), (value) => executionOutcomeProjection(client, options, value));
        }
        case "receiz_v124_execution_resolve":
            return executionOutcomeProjection(client, options, await client.execution.resolve(pinnedInput));
        case "receiz_v124_execution_resolve_by_idempotency":
            return executionOutcomeProjection(client, options, await client.execution.resolveByIdempotencyKey(pinnedInput));
        case "receiz_v124_execution_cancel": {
            const handle = readCustodied(client, "handle", input.handleRef);
            const session = await readSession(client, options, input.sessionRef);
            if (options.applicationId) {
                assertApplicationValue(handle, options.applicationId);
                assertApplicationValue(session, options.applicationId);
            }
            return confirmed(toolName, args, await confirmationBasis(pinnedInput, { handle, session }), () => client.execution.cancel(handle, session), (value) => executionOutcomeProjection(client, options, value));
        }
        case "receiz_v124_runtime_authority_session_open": {
            const proofArtifact = referenceMaterials
                ? await resolveReceizV124McpMaterial(client, options, input.identityArtifactRef, "identity-artifact")
                : input.proofArtifact;
            const subjectSourceArtifact = referenceMaterials
                ? await resolveReceizV124McpMaterial(client, options, input.subjectSourceArtifactRef, "subject-source-artifact")
                : input.subjectSourceArtifact;
            const signedChallenge = referenceMaterials
                ? await resolveReceizV124McpMaterial(client, options, input.signedChallengeRef, "signed-challenge")
                : input.signedChallenge;
            const basis = referenceMaterials
                ? await confirmationBasis(pinnedInput, { proofArtifact, subjectSourceArtifact, signedChallenge })
                : pinnedInput;
            const preview = previewOrConfirm(toolName, args, basis);
            if (preview)
                return preview;
            const openInput = referenceMaterials
                ? {
                    ...without(pinnedInput, "identityArtifactRef", "subjectSourceArtifactRef", "signedChallengeRef"),
                    proofArtifact,
                    subjectSourceArtifact,
                    signedChallenge,
                    audience: options.applicationId,
                }
                : input;
            const session = await client.runtime.openAuthoritySessionV124(openInput);
            return sessionProjection(client, options, session);
        }
        case "receiz_v124_runtime_authority_session_refresh": {
            const priorRef = typeof input.sessionRef === "string" ? input.sessionRef : null;
            const persistedSession = priorRef ? await readSession(client, options, priorRef) : input.persistedSession;
            if (!persistedSession)
                throw new TypeError("V124_MCP_SESSION_REF_REQUIRED");
            const heldHandle = authoritySessionHandle(persistedSession);
            const proofArtifact = referenceMaterials
                ? await resolveReceizV124McpMaterial(client, options, input.identityArtifactRef, "identity-artifact")
                : input.proofArtifact;
            const signedChallenge = referenceMaterials
                ? await resolveReceizV124McpMaterial(client, options, input.signedChallengeRef, "signed-challenge")
                : input.signedChallenge;
            const basis = referenceMaterials
                ? await confirmationBasis(pinnedInput, { persistedSession, proofArtifact, signedChallenge })
                : await confirmationBasis(pinnedInput, { persistedSession });
            const preview = previewOrConfirm(toolName, args, basis);
            if (preview)
                return preview;
            if (input.authoritySessionHandle !== undefined && input.authoritySessionHandle !== heldHandle)
                throw new TypeError("V124_MCP_SESSION_HANDLE_MISMATCH");
            const session = await client.runtime.refreshAuthoritySessionV124({
                ...without(pinnedInput, "sessionRef", "persistedSession", "authoritySessionHandle", "identityArtifactRef", "signedChallengeRef"),
                authoritySessionHandle: heldHandle,
                persistedSession,
                ...(referenceMaterials ? {
                    proofArtifact,
                    signedChallenge,
                    audience: options.applicationId,
                } : {}),
            });
            if (priorRef)
                custody(client).sessions.delete(priorRef);
            return sessionProjection(client, options, session);
        }
        case "receiz_v124_runtime_authority_session_close": {
            const priorRef = typeof input.sessionRef === "string" ? input.sessionRef : null;
            const persistedSession = priorRef ? await readSession(client, options, priorRef) : input.persistedSession;
            if (!persistedSession)
                throw new TypeError("V124_MCP_SESSION_REF_REQUIRED");
            const heldHandle = authoritySessionHandle(persistedSession);
            const preview = previewOrConfirm(toolName, args, await confirmationBasis(pinnedInput, { persistedSession }));
            if (preview)
                return preview;
            if (input.authoritySessionHandle !== undefined && input.authoritySessionHandle !== heldHandle)
                throw new TypeError("V124_MCP_SESSION_HANDLE_MISMATCH");
            const closed = await client.runtime.closeAuthoritySessionV124({
                ...without(pinnedInput, "sessionRef", "persistedSession", "authoritySessionHandle"),
                authoritySessionHandle: heldHandle,
                persistedSession,
            });
            if (priorRef)
                custody(client).sessions.delete(priorRef);
            return redact(closed);
        }
        case "receiz_v124_runtime_qualify":
            return redact(await client.runtime.qualifyV124(pinnedInput));
        case "receiz_v124_domain_verified_additions":
            return redact(await client.domains.verifiedAdditionsV124(pinnedInput));
        case "receiz_v124_domain_verified_replay":
            return redact(await client.domains.verifiedReplayV124(pinnedInput));
        case "receiz_v124_domain_verified_checkpoint":
            return redact(await client.domains.verifiedCheckpointV124(pinnedInput));
        case "receiz_v124_domain_verified_private_additions": {
            const held = await inputWithHeldSession(client, pinnedInput, true, options);
            return privateAdditionsProjection(client, options, await client.domains.verifiedPrivateAdditionsV124(held.input));
        }
        case "receiz_v124_domain_replay_proof_object_export":
            return replayExportProjection(await client.domains.exportVerifiedReplayProofObjectV124(pinnedInput));
        case "receiz_v124_domain_replay_proof_object_restore": {
            const restoreInput = referenceMaterials
                ? {
                    ...without(pinnedInput, "sealedReplayProofObjectRef"),
                    artifact: await resolveReceizV124McpMaterial(client, options, input.sealedReplayProofObjectRef, "sealed-replay-proof-object"),
                }
                : input;
            return redact(await client.domains.restoreVerifiedReplayProofObjectV124(restoreInput));
        }
        case "receiz_source_carried_replay_open": {
            const applicationId = options.applicationId;
            if (!applicationId)
                throw new TypeError("V124_MCP_APPLICATION_ID_REQUIRED");
            if (!Array.isArray(input.sealedSourceArtifactRefs) || input.sealedSourceArtifactRefs.length === 0) {
                throw new TypeError("V124_MCP_SOURCE_REFS_REQUIRED");
            }
            const references = input.sealedSourceArtifactRefs.map((reference) => {
                if (typeof reference !== "string" || reference.length === 0) {
                    throw new TypeError("V124_MCP_SOURCE_REF_INVALID");
                }
                return reference;
            });
            if (!input.expected || typeof input.expected !== "object" || Array.isArray(input.expected)) {
                throw new TypeError("V124_MCP_SOURCE_EXPECTATION_INVALID");
            }
            const artifacts = await Promise.all(references.map((reference) => resolveReceizV124McpMaterial(client, options, reference, "sealed-source-artifact")));
            const family = await openReceizSourceCarriedReplayFamilyV124({
                artifacts: artifacts,
                expected: {
                    ...input.expected,
                    applicationId,
                    audience: applicationId,
                },
            });
            const branches = projectReceizSourceCarriedReplayBranchesV124(family);
            return {
                schema: "receiz.mcp.source-carried-replay-open.v124",
                proofObjectId: family.proofObjectId,
                applicationId: family.applicationId,
                domainId: family.domainId,
                registryDigest: family.registryDigest,
                reducerDigest: family.reducerDigest,
                familySetDigest: family.familySetDigest,
                sourceCount: family.sources.length,
                headArtifactSha256s: family.headArtifactSha256s,
                branches: branches.map((branch) => ({
                    headArtifactSha256: branch.headArtifactSha256,
                    sourceCount: branch.sourceArtifactSha256s.length,
                    additionCount: branch.additions.length,
                })),
                writesPerformed: 0,
                authority: {
                    mcpIsProofAuthority: false,
                    familyIsProofAuthority: false,
                    setDigestIsProofAuthority: false,
                    projectionIsProofAuthority: false,
                    strongerTruth: "sealed-receiz-proof-object",
                },
            };
        }
        case "receiz_conversation_source_family_open": {
            assertClosedInput(input, ["sealedSourceArtifactRefs", "expectedConversationId", "expected"]);
            const applicationId = options.applicationId;
            if (!applicationId)
                throw new TypeError("V124_MCP_APPLICATION_ID_REQUIRED");
            if (!Array.isArray(input.sealedSourceArtifactRefs) || input.sealedSourceArtifactRefs.length === 0) {
                throw new TypeError("V124_MCP_SOURCE_REFS_REQUIRED");
            }
            const references = input.sealedSourceArtifactRefs.map((reference) => requiredMcpText(reference, "V124_MCP_SOURCE_REF_INVALID"));
            const expected = materialRecord(input.expected, "V124_MCP_SOURCE_EXPECTATION_INVALID");
            const expectedConversationId = requiredMcpText(input.expectedConversationId, "V124_MCP_CONVERSATION_ID_INVALID");
            const artifacts = await Promise.all(references.map((reference) => resolveReceizV124McpMaterial(client, options, reference, "sealed-source-artifact")));
            const family = await openReceizConversationSourceFamilyV1({
                artifacts: artifacts,
                expected: {
                    ...expected,
                    applicationId,
                    audience: applicationId,
                },
                expectedConversationId,
            });
            return {
                schema: "receiz.mcp.conversation-source-family-open.v1",
                proofObjectId: family.replayFamily.proofObjectId,
                applicationId: family.replayFamily.applicationId,
                domainId: family.replayFamily.domainId,
                familySetDigest: family.replayFamily.familySetDigest,
                sourceCount: family.replayFamily.sources.length,
                headArtifactSha256s: family.replayFamily.headArtifactSha256s,
                branches: family.branches.map((branch) => ({
                    headArtifactSha256: branch.headArtifactSha256,
                    sourceCount: branch.sourceArtifactSha256s.length,
                    conversationId: branch.projection.conversationId,
                    memberCount: branch.projection.members.length,
                    activeMemberCount: branch.projection.members.filter((member) => member.state === "active").length,
                    invitationCount: branch.projection.invitations.length,
                    messageCount: branch.projection.messages.length,
                    activeEpoch: branch.projection.activeEpoch,
                    projectionDigest: branch.projection.projectionDigest,
                    headEventIds: branch.projection.headEventIds,
                })),
                writesPerformed: 0,
                clearMessageBodiesReturned: false,
                authority: {
                    mcpIsProofAuthority: false,
                    familyIsProofAuthority: false,
                    projectionIsProofAuthority: false,
                    strongerTruth: "sealed-receiz-proof-object",
                },
            };
        }
        case "receiz_conversation_epoch_grants_plan": {
            assertClosedInput(input, ["epochSecretRef", "recipientSetRef", "recipientOffset", "recipientLimit"]);
            const secret = await resolveReceizV124McpMaterial(client, options, requiredMcpText(input.epochSecretRef, "V124_MCP_EPOCH_SECRET_REF_INVALID"), "conversation-epoch-secret");
            const recipientSet = materialRecord(await resolveReceizV124McpMaterial(client, options, requiredMcpText(input.recipientSetRef, "V124_MCP_RECIPIENT_SET_REF_INVALID"), "conversation-recipient-set"), "V124_MCP_RECIPIENT_SET_INVALID");
            assertClosedInput(recipientSet, ["recipients", "recipientBindings"]);
            if (!Array.isArray(recipientSet.recipients) || !Array.isArray(recipientSet.recipientBindings)
                || recipientSet.recipients.length === 0) {
                throw new TypeError("V124_MCP_RECIPIENT_SET_INVALID");
            }
            const orderedRecipients = [...recipientSet.recipients].sort((left, right) => {
                const leftReceizId = requiredMcpText(materialRecord(left, "V124_MCP_RECIPIENT_SET_INVALID").receizId, "V124_MCP_RECIPIENT_SET_INVALID");
                const rightReceizId = requiredMcpText(materialRecord(right, "V124_MCP_RECIPIENT_SET_INVALID").receizId, "V124_MCP_RECIPIENT_SET_INVALID");
                return leftReceizId.localeCompare(rightReceizId);
            });
            const recipientOffset = boundedMcpInteger(input.recipientOffset, 0, Number.MAX_SAFE_INTEGER, "V124_MCP_RECIPIENT_OFFSET_INVALID");
            const recipientLimit = boundedMcpInteger(input.recipientLimit, 1, 128, "V124_MCP_RECIPIENT_LIMIT_INVALID");
            if (recipientOffset >= orderedRecipients.length)
                throw new TypeError("V124_MCP_RECIPIENT_OFFSET_INVALID");
            const selectedRecipients = orderedRecipients.slice(recipientOffset, recipientOffset + recipientLimit);
            const selectedSubjectIds = new Set(selectedRecipients.map((recipient) => requiredMcpText(materialRecord(recipient, "V124_MCP_RECIPIENT_SET_INVALID").subjectId, "V124_MCP_RECIPIENT_SET_INVALID")));
            const selectedBindings = recipientSet.recipientBindings.filter((binding) => selectedSubjectIds.has(requiredMcpText(materialRecord(binding, "V124_MCP_RECIPIENT_SET_INVALID").subjectId, "V124_MCP_RECIPIENT_SET_INVALID")));
            const batches = await planReceizConversationEpochGrantBatchesV1({
                secret: secret,
                recipients: selectedRecipients,
                recipientBindings: selectedBindings,
                maxRecipientsPerBatch: selectedRecipients.length,
                batchIndexOffset: recipientOffset,
            });
            const batch = batches[0];
            if (!batch || batches.length !== 1)
                throw new TypeError("V124_MCP_EPOCH_GRANT_PLAN_INVALID");
            const nextRecipientOffset = recipientOffset + selectedRecipients.length;
            return {
                schema: "receiz.mcp.conversation-epoch-grants-plan.v1",
                conversationId: batch.conversationId,
                epoch: batch.epoch,
                batchIndex: batch.batchIndex,
                batchDigest: batch.batchDigest,
                recipientReceizIds: batch.recipientReceizIds,
                recipientOffset,
                recipientCount: batch.recipientReceizIds.length,
                totalRecipientCount: orderedRecipients.length,
                nextRecipientOffset: nextRecipientOffset < orderedRecipients.length ? nextRecipientOffset : null,
                envelope: batch.envelope,
                writesPerformed: 0,
                secretMaterialReturned: false,
                authority: {
                    mcpIsProofAuthority: false,
                    grantIsIdentityAuthority: false,
                    projectionIsProofAuthority: false,
                    strongerTruth: "sealed-receiz-proof-object",
                },
            };
        }
        case "receiz_material_source_parts_open": {
            assertClosedInput(input, ["materialSourceFamilyRef", "segmentOffset", "segmentLimit"]);
            const heldFamily = materialRecord(await resolveReceizV124McpMaterial(client, options, requiredMcpText(input.materialSourceFamilyRef, "V124_MCP_MATERIAL_SOURCE_FAMILY_REF_INVALID"), "material-source-family"), "V124_MCP_MATERIAL_SOURCE_FAMILY_INVALID");
            assertClosedInput(heldFamily, ["headUrl", "sourceUrls"]);
            const headUrl = requiredHeldSourceLocator(heldFamily.headUrl, "V124_MCP_MATERIAL_SOURCE_FAMILY_INVALID");
            if (!Array.isArray(heldFamily.sourceUrls))
                throw new TypeError("V124_MCP_MATERIAL_SOURCE_FAMILY_INVALID");
            const sourceUrls = heldFamily.sourceUrls.map((sourceUrl) => requiredHeldSourceLocator(sourceUrl, "V124_MCP_MATERIAL_SOURCE_FAMILY_INVALID"));
            const parts = await openReceizMaterialSourceParts({ headUrl, sourceUrls });
            const segmentOffset = boundedMcpInteger(input.segmentOffset, 0, Number.MAX_SAFE_INTEGER, "V124_MCP_MATERIAL_SEGMENT_OFFSET_INVALID");
            const segmentLimit = boundedMcpInteger(input.segmentLimit, 1, 256, "V124_MCP_MATERIAL_SEGMENT_LIMIT_INVALID");
            if (segmentOffset >= parts.manifest.segmentCount) {
                throw new TypeError("V124_MCP_MATERIAL_SEGMENT_OFFSET_INVALID");
            }
            const segments = parts.manifest.segments.slice(segmentOffset, segmentOffset + segmentLimit).map((segment) => ({
                index: segment.index,
                offset: segment.offset,
                byteLength: segment.byteLength,
                sha256: segment.sha256,
                leafDigest: segment.leafDigest,
            }));
            const nextSegmentOffset = segmentOffset + segments.length;
            return {
                schema: "receiz.mcp.material-source-parts-open.v1",
                packageDigest: parts.manifest.packageDigest,
                capsuleEncoding: parts.manifest.capsuleEncoding ?? "legacy-brotli-json",
                capsuleSha256: parts.manifest.capsuleSha256,
                capsuleByteLength: parts.manifest.capsuleByteLength,
                sealedArtifactSha256: parts.manifest.sealedArtifactSha256,
                sealedArtifactByteLength: parts.manifest.sealedArtifactByteLength,
                sealedFilename: parts.manifest.sealedFilename,
                sealedMimeType: parts.manifest.sealedMimeType,
                verifyPath: parts.manifest.verifyPath,
                segmentByteBoundary: parts.manifest.segmentByteBoundary,
                segmentCount: parts.manifest.segmentCount,
                merkleRoot: parts.manifest.merkle.root,
                progressive: parts.manifest.materialProgressiveLedger
                    ? createReceizMaterialProgressiveCommitment(parts.manifest.materialProgressiveLedger)
                    : null,
                segmentOffset,
                segmentCountReturned: segments.length,
                nextSegmentOffset: nextSegmentOffset < parts.manifest.segmentCount ? nextSegmentOffset : null,
                segments,
                writesPerformed: 0,
                exactBytesReturned: false,
                authority: {
                    mcpIsProofAuthority: false,
                    manifestIsProofAuthority: false,
                    storageIsProofAuthority: false,
                    projectionIsProofAuthority: false,
                    strongerTruth: "sealed-receiz-proof-object",
                },
            };
        }
        case "receiz_v124_subject_namespaces_resolve":
            return redact(await client.subjects.resolveNamespacesV124(input));
        case "receiz_v124_identity_public_recipient_resolve": {
            const held = await inputWithHeldSession(client, pinnedInput, true, options);
            return redact(await client.identity.resolvePublicRecipientV124(held.input));
        }
        case "receiz_v124_source_publish_sealed": {
            const sourceArtifact = referenceMaterials
                ? await resolveReceizV124McpMaterial(client, options, input.sealedSourceArtifactRef, "sealed-source-artifact")
                : input.sourceArtifact;
            const publicationInput = referenceMaterials
                ? { ...without(pinnedInput, "sealedSourceArtifactRef"), sourceArtifact }
                : input;
            const held = await inputWithHeldSession(client, publicationInput, false, options);
            const materials = { sourceArtifact };
            if (held.session)
                materials.session = held.session;
            return confirmed(toolName, args, await confirmationBasis(pinnedInput, materials), () => client.sources.publishSealedSourceV124(held.input));
        }
    }
}
//# sourceMappingURL=v124Operations.js.map