@ai-matrx/agents 0.40.0 → 0.41.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/dist/content-transfer/index.cjs.map +1 -1
- package/dist/content-transfer/index.js.map +1 -1
- package/dist/content-transfer/react/index.cjs.map +1 -1
- package/dist/content-transfer/react/index.js.map +1 -1
- package/dist/context/index.cjs +0 -5
- package/dist/context/index.cjs.map +1 -1
- package/dist/context/index.d.cts +2 -14
- package/dist/context/index.d.ts +2 -14
- package/dist/context/index.js +0 -7
- package/dist/context/index.js.map +1 -1
- package/dist/context/react/index.cjs +66 -8
- package/dist/context/react/index.cjs.map +1 -1
- package/dist/context/react/index.d.cts +9 -16
- package/dist/context/react/index.d.ts +9 -16
- package/dist/context/react/index.js +66 -8
- package/dist/context/react/index.js.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/{keys.generated-myjGAtI0.d.cts → keys.generated-B72Ds5EJ.d.cts} +4 -4
- package/dist/{keys.generated-myjGAtI0.d.ts → keys.generated-B72Ds5EJ.d.ts} +4 -4
- package/dist/mandates/index.cjs +2 -2
- package/dist/mandates/index.cjs.map +1 -1
- package/dist/mandates/index.d.cts +2 -2
- package/dist/mandates/index.d.ts +2 -2
- package/dist/mandates/index.js +2 -2
- package/dist/mandates/index.js.map +1 -1
- package/dist/matrx/index.d.cts +1 -1
- package/dist/matrx/index.d.ts +1 -1
- package/mandates/snapshots/keys.0.41.0.json +653 -0
- package/mandates/snapshots/keys.0.41.1.json +653 -0
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../content-transfer/react/index.tsx","../../../content-transfer/index.ts","../../../mandates/keys.generated.ts","../../../mandates/index.ts","../../../matrx/transport.ts","../../../stream/ndjson.ts","../../../matrx/conversation.ts","../../../matrx/internal.ts","../../../stream/sse.ts","../../../matrx/operations.ts","../../../matrx/run.ts"],"sourcesContent":["\"use client\";\n\nimport * as React from \"react\";\nimport type {\n AiPreparation,\n Draft,\n Snapshot,\n} from \"@ai-matrx/kit/content-transfer\";\nimport {\n ContentTransferCapabilitiesProvider,\n type ContentTransferCapabilities,\n} from \"@ai-matrx/design-system/content-transfer\";\nimport {\n createMatrxContentTransferAdapter,\n type MatrxContentTransferAdapterOptions,\n type MatrxContentTransferIdentity,\n type MatrxContentTransferProgress,\n} from \"..\";\n\nexport interface MatrxContentTransferProviderProps\n extends MatrxContentTransferAdapterOptions {\n children: React.ReactNode;\n capabilities?: Omit<ContentTransferCapabilities, \"ai\">;\n /** Persist identifiers in the host's canonical live-run window. Never persist draft content here. */\n onProgress?: (progress: MatrxContentTransferProgress) => void;\n}\nfunction createAiSession(\n options: MatrxContentTransferAdapterOptions,\n onProgress?: (progress: MatrxContentTransferProgress) => void,\n): AiPreparation {\n const adapter = createMatrxContentTransferAdapter(options);\n let retainedIdentity: MatrxContentTransferIdentity | null = null;\n let retainedSource: {\n snapshot: Snapshot;\n draft: Draft;\n } | null = null;\n let activeRequestId: string | null = null;\n let latestRun = 0;\n let pendingRequest: {\n promise: Promise<string | null>;\n resolve: (requestId: string | null) => void;\n } | null = null;\n\n const session: AiPreparation = {\n supports: (_snapshot: Snapshot) => true,\n fork: () => createAiSession(options, onProgress),\n async run({ snapshot, draft, instruction, signal }) {\n const run = ++latestRun;\n activeRequestId = null;\n retainedIdentity = null;\n retainedSource = Object.freeze({ snapshot, draft });\n let resolveRequest!: (requestId: string | null) => void;\n const request = {\n promise: new Promise<string | null>((resolve) => {\n resolveRequest = resolve;\n }),\n resolve: resolveRequest,\n };\n pendingRequest = request;\n try {\n const result = await adapter.launch({\n snapshot,\n draft,\n instruction,\n signal,\n onProgress: (progress) => {\n if (run !== latestRun) return;\n onProgress?.(progress);\n if (!progress.requestId) return;\n activeRequestId = progress.requestId;\n request.resolve(progress.requestId);\n retainedIdentity = Object.freeze({\n requestId: progress.requestId,\n conversationId: progress.conversationId,\n executionId: progress.executionId,\n snapshotId: snapshot.id,\n sourceId: draft.sourceId,\n sourceRevision: draft.sourceRevision,\n draftRevision: draft.revision,\n });\n },\n });\n if (run === latestRun) {\n retainedIdentity = result.identity ?? retainedIdentity;\n activeRequestId = result.identity?.requestId ?? activeRequestId;\n request.resolve(activeRequestId);\n }\n if (result.status !== \"completed\" || !result.draft)\n throw new Error(\n result.message || \"AI preparation did not return a draft.\",\n );\n return result.draft;\n } finally {\n request.resolve(null);\n if (run === latestRun && pendingRequest === request) {\n pendingRequest = null;\n }\n }\n },\n async recover({ snapshot, draft, signal }) {\n const recoveryRun = ++latestRun;\n if (!retainedIdentity)\n throw new Error(\n \"No recoverable AI preparation exists in this workspace session.\",\n );\n if (\n !retainedSource ||\n retainedIdentity.snapshotId !== snapshot.id ||\n retainedSource.snapshot.id !== snapshot.id ||\n retainedSource.draft.snapshotId !== draft.snapshotId ||\n retainedSource.draft.sourceId !== draft.sourceId ||\n retainedSource.draft.sourceRevision !== draft.sourceRevision ||\n retainedSource.draft.revision !== draft.revision\n ) {\n throw new Error(\n \"The recoverable AI preparation belongs to a different source draft.\",\n );\n }\n const result = await adapter.rejoin(\n retainedIdentity,\n retainedSource.draft,\n (progress) => {\n if (recoveryRun === latestRun) onProgress?.(progress);\n },\n signal,\n );\n if (recoveryRun !== latestRun)\n throw new Error(\"A newer AI preparation started before recovery settled.\");\n retainedIdentity = result.identity ?? retainedIdentity;\n activeRequestId = retainedIdentity.requestId;\n if (result.status !== \"completed\" || !result.draft)\n throw new Error(\n result.message || \"AI preparation recovery did not return a draft.\",\n );\n return result.draft;\n },\n async cancel() {\n const requestId =\n activeRequestId ??\n (pendingRequest ? await pendingRequest.promise : null);\n if (!requestId)\n throw new Error(\n \"The current AI preparation ended before the server returned a request ID; no server cancellation was reported.\",\n );\n await adapter.cancel(requestId);\n },\n };\n return session;\n}\n\n/**\n * Composes the package-owned durable Matrx adapter into the design-system's\n * nearest capability context. Surface identity remains the design-system's\n * explicit local handle; this provider never performs global surface lookup.\n */\nexport function MatrxContentTransferProvider({\n children,\n capabilities,\n onProgress,\n ...options\n}: MatrxContentTransferProviderProps) {\n const ai = React.useMemo<AiPreparation>(\n () => createAiSession(options, onProgress),\n [\n options.transport,\n options.supabase,\n options.organizationId,\n options.sourceApp,\n options.onStreamEvent,\n options.onRuntimeEvent,\n onProgress,\n ],\n );\n return (\n <ContentTransferCapabilitiesProvider value={{ ...capabilities, ai }}>\n {children}\n </ContentTransferCapabilitiesProvider>\n );\n}\n","/** Matrx's durable AI capability for Alchemy Content Transfer. */\nexport * from \"./destinations\";\nimport {\n editDraft,\n serialize,\n type Draft,\n type Snapshot,\n} from \"@ai-matrx/kit/content-transfer\";\nimport type { MatrxStreamEnvelope } from \"../stream/ndjson\";\nimport { MANDATE_KEYS } from \"../mandates\";\nimport {\n cancelAgentRun,\n followRuntimeOperationToEnd,\n getRuntimeOperationStatus,\n newStoredConversationStart,\n rejoinRuntimeOperation,\n startMandateRun,\n MatrxApiError,\n type MatrxRuntimeExecutionStatus,\n type MatrxRuntimeOperationEvent,\n type MatrxTransport,\n} from \"../matrx\";\n\nexport type MatrxContentTransferStatus =\n \"completed\" | \"failed\" | \"cancelled\" | \"detached\" | \"unavailable\";\nexport interface MatrxContentTransferIdentity {\n requestId: string;\n conversationId: string;\n executionId: string | null;\n snapshotId: string;\n sourceId: string;\n sourceRevision: string;\n draftRevision: number;\n}\nexport interface MatrxContentTransferProgress {\n requestId: string | null;\n conversationId: string;\n executionId: string | null;\n status: \"starting\" | \"streaming\" | MatrxRuntimeExecutionStatus | \"detached\";\n}\nexport interface MatrxContentTransferResult {\n status: MatrxContentTransferStatus;\n identity: MatrxContentTransferIdentity | null;\n /** A new draft only; the caller's original draft remains unchanged. */\n draft: Draft | null;\n /** Human-readable reason for an honest partial/failure/cancelled state. */\n message: string | null;\n}\nexport interface MatrxContentTransferDbRow {\n id: string;\n content?: unknown;\n metadata?: unknown;\n iteration?: number | null;\n}\nexport interface MatrxContentTransferDbResponse {\n data: MatrxContentTransferDbRow[] | null;\n error: { message?: string | null } | null;\n}\nexport interface MatrxContentTransferQuery extends PromiseLike<MatrxContentTransferDbResponse> {\n eq(column: string, value: unknown): this;\n is(column: string, value: null): this;\n not(column: string, operator: \"is\", value: null): this;\n order(column: string, options: { ascending: boolean }): this;\n limit(count: number): this;\n}\nexport interface MatrxContentTransferSupabase {\n schema(schema: \"chat\"): {\n from(table: \"request\" | \"message\"): {\n select(columns: string): MatrxContentTransferQuery;\n };\n };\n}\nexport interface MatrxContentTransferAdapterOptions {\n transport: MatrxTransport | (() => MatrxTransport);\n supabase: MatrxContentTransferSupabase;\n organizationId: string | (() => string);\n sourceApp: \"matrx-frontend\" | \"dashboard\";\n /**\n * Interactivity attestation for the preparation run. `launch()` is the\n * Alchemy door a person opens by hand, so \"user\" is the default and the\n * server classes the conversation `origin_class = 'human'`; an embedder that\n * fires a transfer from client code with no gesture behind it passes \"auto\".\n * Omitting the field entirely is what left these runs reading as unattested\n * API traffic (census 2026-09-20).\n */\n initiation?: \"user\" | \"auto\";\n /** The original NDJSON stream, exposed without consuming it twice. */\n onStreamEvent?: (event: MatrxStreamEnvelope) => void;\n /** Durable runtime lifecycle events emitted during recovery. */\n onRuntimeEvent?: (\n event: MatrxRuntimeOperationEvent,\n seq: number | null,\n ) => void;\n}\nexport interface MatrxContentTransferLaunchInput {\n snapshot: Snapshot;\n draft: Draft;\n instruction: string;\n signal?: AbortSignal;\n onProgress?: (progress: MatrxContentTransferProgress) => void;\n}\nclass SupersededRunError extends Error {\n constructor() {\n super(\"A newer AI preparation started before this result settled.\");\n }\n}\nfunction resolve<T>(value: T | (() => T)): T {\n return typeof value === \"function\" ? (value as () => T)() : value;\n}\nfunction deepFreeze<T>(value: T): T {\n if (ArrayBuffer.isView(value)) return value;\n if (value && typeof value === \"object\" && !Object.isFrozen(value)) {\n Object.freeze(value);\n for (const nested of Object.values(value)) deepFreeze(nested);\n }\n return value;\n}\nfunction isDeepFrozen(value: unknown, seen = new WeakSet<object>()): boolean {\n if (!value || typeof value !== \"object\" || ArrayBuffer.isView(value))\n return true;\n if (seen.has(value)) return true;\n seen.add(value);\n return (\n Object.isFrozen(value) &&\n Object.values(value).every((nested) => isDeepFrozen(nested, seen))\n );\n}\nfunction descriptionForCoverage(snapshot: Snapshot, draft: Draft): string {\n const { coverage } = snapshot;\n const total =\n coverage.total === null ? \"unknown total\" : `${coverage.total} total`;\n const offered =\n draft.payload.kind === \"rows\"\n ? `${draft.payload.rows.length} prepared rows`\n : \"one prepared document\";\n return `snapshot ${coverage.status}: ${coverage.included} included, ${total}; offered ${offered} from ${draft.sourceId}@${draft.sourceRevision}, draft revision ${draft.revision}${coverage.reason ? `; ${coverage.reason}` : \"\"}`;\n}\nfunction descriptionForOmissions(draft: Draft): string {\n if (draft.omissions.length === 0)\n return \"No pre-AI exclusions or reductions were recorded in this prepared draft.\";\n return draft.omissions\n .map(\n (o) =>\n `${o.path || \"document\"}: ${o.reason}${o.count === undefined ? \"\" : ` (${o.count})`}`,\n )\n .join(\"; \");\n}\n/**\n * The mapped-only offered values of `alchemy.prepared_content` (server\n * `client_mandates.py`), built from facts this launch already holds. Sent by\n * name beside the four by-name values; the mandate door drops them unless a\n * binding's consumption map names one, so no current Holder's payload changes.\n * Absent facts are omitted, never sent empty.\n */\nexport function preparedContentOfferedValues(\n snapshot: Snapshot,\n draft: Draft,\n): Record<string, string | number | boolean | string[]> {\n const { coverage } = snapshot;\n const values: Record<string, string | number | boolean | string[]> = {\n coverage_status: coverage.status,\n included_count: coverage.included,\n payload_kind: draft.payload.kind,\n omission_count: draft.omissions.length,\n has_unsaved_changes: snapshot.unsavedChanges,\n manually_edited: draft.manuallyEdited,\n };\n if (coverage.total !== null) values.total_count = coverage.total;\n if (coverage.unit) values.coverage_unit = coverage.unit;\n if (coverage.reason) values.coverage_reason = coverage.reason;\n if (draft.payload.kind === \"rows\") {\n values.row_count = draft.payload.rows.length;\n const labels = draft.payload.columns\n .filter((column) => column.visible)\n .map((column) => column.label);\n if (labels.length > 0) values.column_labels = labels;\n }\n if (draft.omissions.length > 0)\n values.omission_reasons = draft.omissions.map((o) => o.reason);\n const sections = snapshot.sections.map((section) => section.label);\n if (sections.length > 0) values.section_labels = sections;\n if (snapshot.capturedAt) values.captured_at = snapshot.capturedAt;\n return values;\n}\nfunction visibleAssistantText(content: unknown): string | null {\n if (typeof content === \"string\") return content.trim() || null;\n if (!Array.isArray(content)) return null;\n const parts = content.flatMap((part) => {\n if (!part || typeof part !== \"object\" || Array.isArray(part)) return [];\n const block = part as { type?: unknown; text?: unknown };\n return block.type === \"text\" && typeof block.text === \"string\"\n ? [block.text]\n : [];\n });\n return parts.join(\"\\n\\n\").trim() || null;\n}\nfunction responseMessageId(metadata: unknown): string | null {\n if (!metadata || typeof metadata !== \"object\" || Array.isArray(metadata))\n return null;\n const value = (metadata as { response_message_id?: unknown })\n .response_message_id;\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\nfunction draftFromAssistant(\n source: Draft,\n text: string,\n identity: MatrxContentTransferIdentity,\n): Draft {\n const edited = editDraft(source, { kind: \"markdown\", text });\n const reducedBy =\n serialize(source, \"markdown\").plainText.length - text.length;\n return deepFreeze({\n ...edited,\n manuallyEdited: source.manuallyEdited,\n omissions: [\n ...edited.omissions,\n ...(reducedBy > 0\n ? [\n {\n path: \"/ai/content\",\n reason: \"truncated\" as const,\n count: reducedBy,\n },\n ]\n : []),\n ],\n provenance: [\n ...edited.provenance.slice(0, -1),\n {\n kind: \"ai\" as const,\n operationId: identity.requestId,\n description: `AI preparation of ${source.sourceId}@${source.sourceRevision}; source omissions remain separately recorded.`,\n },\n ],\n });\n}\nfunction assertCoherent(snapshot: Snapshot, draft: Draft): void {\n if (!isDeepFrozen(snapshot) || !isDeepFrozen(draft))\n throw new Error(\n \"Alchemy requires the deeply frozen Snapshot and Draft produced by @ai-matrx/kit/content-transfer.\",\n );\n if (\n draft.snapshotId !== snapshot.id ||\n draft.sourceId !== snapshot.sourceId ||\n draft.sourceRevision !== snapshot.revision\n )\n throw new Error(\n \"The prepared draft does not belong to this captured snapshot.\",\n );\n}\nfunction assertIdentitySource(\n identity: MatrxContentTransferIdentity,\n source: Draft,\n): void {\n if (!isDeepFrozen(source))\n throw new Error(\n \"Alchemy recovery requires the deeply frozen Draft produced by @ai-matrx/kit/content-transfer.\",\n );\n if (\n identity.snapshotId !== source.snapshotId ||\n identity.sourceId !== source.sourceId ||\n identity.sourceRevision !== source.sourceRevision ||\n identity.draftRevision !== source.revision\n ) {\n throw new Error(\n \"The recovery identity does not belong to this frozen prepared draft.\",\n );\n }\n}\nfunction errorMessage(error: unknown): string {\n return error instanceof Error && error.message\n ? error.message\n : \"Unknown stream failure.\";\n}\nfunction detached(\n identity: MatrxContentTransferIdentity,\n message: string,\n): MatrxContentTransferResult {\n return { status: \"detached\", identity, draft: null, message };\n}\nasync function consume(\n handle: Awaited<ReturnType<typeof startMandateRun>>,\n afterAwait: () => void,\n onEvent?: (event: MatrxStreamEnvelope) => void,\n): Promise<void> {\n for await (const event of handle.events) {\n afterAwait();\n onEvent?.(event);\n }\n afterAwait();\n}\n\n/** One monotonic generation fences every public launch/recover/rejoin. */\nexport function createMatrxContentTransferAdapter(\n options: MatrxContentTransferAdapterOptions,\n) {\n let latestGeneration = 0;\n const transport = () => resolve(options.transport);\n const organizationId = () => resolve(options.organizationId);\n let activeGeneration: AbortController | null = null;\n const inGeneration = async <T>(\n outer: AbortSignal | undefined,\n run: (generation: number, signal: AbortSignal) => Promise<T>,\n ): Promise<T> => {\n activeGeneration?.abort();\n const controller = new AbortController();\n activeGeneration = controller;\n const generation = ++latestGeneration;\n const abort = () => controller.abort(outer?.reason);\n if (outer?.aborted) abort();\n else outer?.addEventListener(\"abort\", abort, { once: true });\n try {\n return await run(generation, controller.signal);\n } finally {\n outer?.removeEventListener(\"abort\", abort);\n if (activeGeneration === controller) activeGeneration = null;\n }\n };\n const check = (generation: number) => {\n if (generation !== latestGeneration) throw new SupersededRunError();\n activeGeneration?.signal.throwIfAborted();\n };\n\n const readVisibleAssistant = async (\n identity: MatrxContentTransferIdentity,\n generation: number,\n ): Promise<string | null> => {\n const requestResult = await options.supabase\n .schema(\"chat\")\n .from(\"request\")\n .select(\"id, metadata, iteration\")\n .eq(\"user_request_id\", identity.requestId)\n .eq(\"conversation_id\", identity.conversationId)\n .is(\"deleted_at\", null)\n .not(\"metadata->>response_message_id\", \"is\", null)\n .order(\"iteration\", { ascending: false })\n .limit(1);\n check(generation);\n if (requestResult.error)\n throw new Error(\n requestResult.error.message ||\n \"Could not read the persisted AI request.\",\n );\n const messageId = responseMessageId(requestResult.data?.[0]?.metadata);\n if (!messageId)\n throw new Error(\n \"The completed AI request has no persisted response message link yet.\",\n );\n const messageResult = await options.supabase\n .schema(\"chat\")\n .from(\"message\")\n .select(\"id, content\")\n .eq(\"id\", messageId)\n .eq(\"conversation_id\", identity.conversationId)\n .eq(\"role\", \"assistant\")\n .is(\"deleted_at\", null)\n .eq(\"is_visible_to_user\", true)\n .limit(1);\n check(generation);\n if (messageResult.error)\n throw new Error(\n messageResult.error.message || \"Could not read the prepared AI result.\",\n );\n const exact = messageResult.data?.find((row) => row.id === messageId);\n return exact ? visibleAssistantText(exact.content) : null;\n };\n\n const locate = async (\n identity: MatrxContentTransferIdentity,\n generation: number,\n signal?: AbortSignal,\n ) => {\n const result = await getRuntimeOperationStatus(\n transport(),\n identity.requestId,\n signal ? { signal } : {},\n );\n check(generation);\n const exact =\n result?.operations.find(\n (operation) =>\n operation.request_id === identity.requestId &&\n operation.link_kind === \"conversation\" &&\n operation.link_id === identity.conversationId,\n ) ?? null;\n if (!exact && result?.operation_count)\n throw new Error(\n \"The durable operation identity does not match this stored conversation.\",\n );\n return exact;\n };\n\n const recoverInGeneration = async (\n generation: number,\n identity: MatrxContentTransferIdentity,\n source: Draft,\n onProgress?: MatrxContentTransferLaunchInput[\"onProgress\"],\n signal?: AbortSignal,\n ): Promise<MatrxContentTransferResult> => {\n try {\n assertIdentitySource(identity, source);\n check(generation);\n let operation = await locate(identity, generation, signal);\n if (!operation)\n return {\n status: \"unavailable\",\n identity,\n draft: null,\n message:\n \"The durable operation is not available to this account yet.\",\n };\n let resolvedIdentity = deepFreeze({\n ...identity,\n executionId: operation.execution_id,\n });\n if (!operation.is_terminal) {\n onProgress?.({ ...resolvedIdentity, status: operation.status });\n const settled = await followRuntimeOperationToEnd(\n transport(),\n operation.execution_id,\n {\n ...(signal ? { signal } : {}),\n lastEventSeq: operation.last_event_seq,\n onEvent: (event, seq) => {\n // Supersession already aborts the local follower. Never throw\n // from this callback into the runtime reconnect retry policy.\n if (generation !== latestGeneration || signal?.aborted) return;\n options.onRuntimeEvent?.(event, seq);\n },\n },\n );\n check(generation);\n if (!settled.ended || settled.status === null)\n return detached(\n resolvedIdentity,\n \"The lifecycle stream detached; the operation remains recoverable from this request.\",\n );\n const refreshed = await locate(identity, generation, signal);\n if (!refreshed)\n return detached(\n resolvedIdentity,\n \"The settled operation is temporarily unavailable; retry recovery with this request.\",\n );\n operation = refreshed;\n resolvedIdentity = deepFreeze({\n ...identity,\n executionId: operation.execution_id,\n });\n }\n onProgress?.({ ...resolvedIdentity, status: operation.status });\n if (operation.status === \"cancelled\")\n return {\n status: \"cancelled\",\n identity: resolvedIdentity,\n draft: null,\n message:\n \"The AI preparation was cancelled. Any partial output was not applied.\",\n };\n if (operation.status !== \"completed\")\n return {\n status: \"failed\",\n identity: resolvedIdentity,\n draft: null,\n message:\n typeof operation.error?.message === \"string\"\n ? operation.error.message\n : \"The AI preparation did not complete.\",\n };\n const text = await readVisibleAssistant(resolvedIdentity, generation);\n check(generation);\n if (!text)\n return {\n status: \"unavailable\",\n identity: resolvedIdentity,\n draft: null,\n message: \"The exact persisted assistant result is not visible yet.\",\n };\n const draft = draftFromAssistant(source, text, resolvedIdentity);\n check(generation);\n return {\n status: \"completed\",\n identity: resolvedIdentity,\n draft,\n message: null,\n };\n } catch (error) {\n return detached(\n identity,\n error instanceof SupersededRunError\n ? error.message\n : `Recovery detached: ${errorMessage(error)} You can retry with this request.`,\n );\n }\n };\n\n return {\n async launch(\n input: MatrxContentTransferLaunchInput,\n ): Promise<MatrxContentTransferResult> {\n return inGeneration(input.signal, async (generation, signal) => {\n assertCoherent(input.snapshot, input.draft);\n const conversation = newStoredConversationStart();\n input.onProgress?.({\n requestId: null,\n conversationId: conversation.conversation_id,\n executionId: null,\n status: \"starting\",\n });\n const preparedContent = serialize(input.draft, \"markdown\").plainText;\n let identity: MatrxContentTransferIdentity | null = null;\n try {\n const handle = await startMandateRun(\n transport(),\n MANDATE_KEYS.alchemy__prepare_content,\n {\n ...conversation,\n organization_id: organizationId(),\n source_app: options.sourceApp,\n source_feature: `mandate:${MANDATE_KEYS.alchemy__prepare_content}`,\n initiation: options.initiation ?? \"user\",\n user_input: input.instruction,\n variables: {\n prepared_content: preparedContent,\n content_label: input.snapshot.label,\n coverage_description: descriptionForCoverage(\n input.snapshot,\n input.draft,\n ),\n omission_description: descriptionForOmissions(input.draft),\n ...preparedContentOfferedValues(input.snapshot, input.draft),\n },\n },\n { signal },\n );\n if (!handle.requestId)\n throw new Error(\n \"The Matrx server did not return X-Request-ID for the preparation run.\",\n );\n identity = deepFreeze({\n requestId: handle.requestId,\n conversationId:\n handle.conversationId ?? conversation.conversation_id,\n executionId: null,\n snapshotId: input.snapshot.id,\n sourceId: input.draft.sourceId,\n sourceRevision: input.draft.sourceRevision,\n draftRevision: input.draft.revision,\n });\n assertIdentitySource(identity, input.draft);\n check(generation);\n input.onProgress?.({ ...identity, status: \"streaming\" });\n await consume(handle, () => check(generation), options.onStreamEvent);\n check(generation);\n const result = await recoverInGeneration(\n generation,\n identity,\n input.draft,\n input.onProgress,\n signal,\n );\n check(generation);\n return result;\n } catch (error) {\n if (!identity) throw error;\n return detached(\n identity,\n error instanceof SupersededRunError\n ? error.message\n : `The local stream detached after the server accepted the request: ${errorMessage(error)} Server work was not cancelled; retry recovery with this request.`,\n );\n }\n });\n },\n async recover(\n identity: MatrxContentTransferIdentity,\n source: Draft,\n onProgress?: MatrxContentTransferLaunchInput[\"onProgress\"],\n signal?: AbortSignal,\n ) {\n return inGeneration(signal, async (generation, signal) => {\n assertIdentitySource(identity, source);\n const result = await recoverInGeneration(\n generation,\n identity,\n source,\n onProgress,\n signal,\n );\n return generation === latestGeneration\n ? result\n : detached(\n identity,\n \"A newer AI preparation started before this result settled.\",\n );\n });\n },\n async rejoin(\n identity: MatrxContentTransferIdentity,\n source: Draft,\n onProgress?: MatrxContentTransferLaunchInput[\"onProgress\"],\n signal?: AbortSignal,\n ) {\n return inGeneration(signal, async (generation, signal) => {\n assertIdentitySource(identity, source);\n try {\n const handle = await rejoinRuntimeOperation(\n transport(),\n identity.requestId,\n signal ? { signal } : {},\n );\n check(generation);\n await consume(handle, () => check(generation), options.onStreamEvent);\n check(generation);\n } catch (error) {\n if (!(error instanceof MatrxApiError && error.status === 409))\n return detached(\n identity,\n error instanceof SupersededRunError\n ? error.message\n : `Live rejoin detached: ${errorMessage(error)} You can retry durable recovery with this request.`,\n );\n }\n const result = await recoverInGeneration(\n generation,\n identity,\n source,\n onProgress,\n signal,\n );\n return generation === latestGeneration\n ? result\n : detached(\n identity,\n \"A newer AI preparation started before this result settled.\",\n );\n });\n },\n cancel(requestId: string) {\n return cancelAgentRun(transport(), requestId);\n },\n };\n}\nexport type MatrxContentTransferAdapter = ReturnType<\n typeof createMatrxContentTransferAdapter\n>;\n\nexport * from \"./destination-ports\";\n","/**\n * GENERATED — DO NOT EDIT. Regenerate with:\n * uv run python scripts/mandates_generate.py (aidream repo; --dry-run also writes this file)\n *\n * THE ONE GENERATOR (`aidream/scripts/mandates_generate.py`, stage (h)) emits this\n * from the IN-PROCESS mandate declarations — the same `declared_mandates()` the\n * boot sync writes to the database from. There is no hand list anywhere.\n *\n * aidream revision: a57cc41414e45aed65b336d0c3b829a4f7f49403\n * generator version: 1.0.0\n * package version: 0.40.0\n * active keys: 544\n * retiring keys: 0\n *\n * THE IDENTIFIER RULE: every `.` in a key becomes `__`, any character outside\n * [A-Za-z0-9_] becomes `_`, a leading digit gets an `_` prefix. So\n * `seo.keyword_classifier` is `MANDATE_KEYS.seo__keyword_classifier`. Collisions are a\n * fatal generator error, never a silently dropped key.\n */\n\n/** Where this module came from — surfaced so a report can name the exact build. */\nexport const MANDATE_KEYS_META = {\n aidreamRevision: \"a57cc41414e45aed65b336d0c3b829a4f7f49403\",\n generatorVersion: \"1.0.0\",\n packageVersion: \"0.40.0\",\n retireWindow: 3,\n} as const;\n\n/** Every declared mandate key, by THE IDENTIFIER RULE. */\nexport const MANDATE_KEYS = {\n agent_apps__auto_create: \"agent_apps.auto_create\",\n agent_apps__auto_create_lightning: \"agent_apps.auto_create_lightning\",\n agent_apps__metadata: \"agent_apps.metadata\",\n agent_apps__prompt_app_dev: \"agent_apps.prompt_app_dev\",\n agent_factory__structure_builder: \"agent_factory.structure_builder\",\n alchemy__prepare_content: \"alchemy.prepare_content\",\n ambient__page_guidance: \"ambient.page_guidance\",\n ambient__spoken_summary: \"ambient.spoken_summary\",\n audio__live_music: \"audio.live_music\",\n audio__speech: \"audio.speech\",\n brand__voice_rewrite: \"brand.voice_rewrite\",\n chat__cx_default: \"chat.cx_default\",\n chat__default_new_chat: \"chat.default_new_chat\",\n chat__quick_audio_plan: \"chat.quick_audio_plan\",\n chat__quick_fair_news: \"chat.quick_fair_news\",\n chat__quick_flashcards: \"chat.quick_flashcards\",\n chat__quick_image: \"chat.quick_image\",\n chat__quick_org_chart: \"chat.quick_org_chart\",\n chat__quick_research: \"chat.quick_research\",\n chat__quick_showcase: \"chat.quick_showcase\",\n chat__quick_writing_partner: \"chat.quick_writing_partner\",\n chat__response_mode_brainstorm: \"chat.response_mode_brainstorm\",\n chat__response_mode_data: \"chat.response_mode_data\",\n chat__response_mode_research: \"chat.response_mode_research\",\n chat__response_mode_video: \"chat.response_mode_video\",\n checks__cleanup_bakeoff__answer: \"checks.cleanup_bakeoff.answer\",\n checks__cleanup_bakeoff__judge: \"checks.cleanup_bakeoff.judge\",\n checks__finding_disposition: \"checks.finding_disposition\",\n checks__finding_disposition_review: \"checks.finding_disposition_review\",\n cms__content_writing: \"cms.content_writing\",\n cms__publish_review: \"cms.publish_review\",\n cms__seo_metadata: \"cms.seo_metadata\",\n cms__site_editing: \"cms.site_editing\",\n cms__theme_design: \"cms.theme_design\",\n code_editor__code_edit: \"code_editor.code_edit\",\n code_editor__dynamic_context_edit: \"code_editor.dynamic_context_edit\",\n code_editor__prompt_app_ui_edit: \"code_editor.prompt_app_ui_edit\",\n coding_session__conversation_responder: \"coding_session.conversation_responder\",\n coding_session__managed_translation_reference: \"coding_session.managed_translation_reference\",\n commerce_intake__assess_value: \"commerce_intake.assess_value\",\n commerce_intake__extract_vision: \"commerce_intake.extract_vision\",\n commerce_intake__grading: \"commerce_intake.grading\",\n commerce_intake__instant_analysis: \"commerce_intake.instant_analysis\",\n commerce_intake__refute_no_value: \"commerce_intake.refute_no_value\",\n commerce_intake__research_product: \"commerce_intake.research_product\",\n commerce_intake__segment_photos: \"commerce_intake.segment_photos\",\n commerce_intake__verify_enrichment: \"commerce_intake.verify_enrichment\",\n content_gate__section_relevance_decision: \"content_gate.section_relevance_decision\",\n content_ir__component_artisan: \"content_ir.component_artisan\",\n content_ir__kind_architect: \"content_ir.kind_architect\",\n content_ir__kind_component_builder: \"content_ir.kind_component_builder\",\n content_ir__kind_creator: \"content_ir.kind_creator\",\n content_plan__branch_purpose: \"content_plan.branch_purpose\",\n content_plan__brief_writer: \"content_plan.brief_writer\",\n content_plan__deepen_page: \"content_plan.deepen_page\",\n content_plan__entity_attacher: \"content_plan.entity_attacher\",\n content_plan__entity_curator: \"content_plan.entity_curator\",\n content_plan__family_namer: \"content_plan.family_namer\",\n content_plan__keyword_strategist: \"content_plan.keyword_strategist\",\n content_plan__merge_wave: \"content_plan.merge_wave\",\n content_plan__p3_family: \"content_plan.p3_family\",\n content_plan__p4_write: \"content_plan.p4_write\",\n content_plan__p5_review: \"content_plan.p5_review\",\n content_plan__p6_build: \"content_plan.p6_build\",\n content_plan__p6_build__about: \"content_plan.p6_build.about\",\n content_plan__p6_build__blog: \"content_plan.p6_build.blog\",\n content_plan__p6_build__comparison: \"content_plan.p6_build.comparison\",\n content_plan__p6_build__contact: \"content_plan.p6_build.contact\",\n content_plan__p6_build__faq: \"content_plan.p6_build.faq\",\n content_plan__p6_build__guide: \"content_plan.p6_build.guide\",\n content_plan__p6_build__home: \"content_plan.p6_build.home\",\n content_plan__p6_build__index: \"content_plan.p6_build.index\",\n content_plan__p6_build__location: \"content_plan.p6_build.location\",\n content_plan__p6_build__pillar: \"content_plan.p6_build.pillar\",\n content_plan__p6_build__pricing: \"content_plan.p6_build.pricing\",\n content_plan__p6_build__service: \"content_plan.p6_build.service\",\n content_plan__plan_reviewer: \"content_plan.plan_reviewer\",\n content_plan__research_wave__audience_journey: \"content_plan.research_wave.audience_journey\",\n content_plan__research_wave__competitor_coverage: \"content_plan.research_wave.competitor_coverage\",\n content_plan__research_wave__keyword_value: \"content_plan.research_wave.keyword_value\",\n content_plan__route_picker: \"content_plan.route_picker\",\n content_plan__shape_planner: \"content_plan.shape_planner\",\n conversation__action_auditor: \"conversation.action_auditor\",\n conversation__decision_ledger: \"conversation.decision_ledger\",\n conversation__drift_auditor: \"conversation.drift_auditor\",\n conversation__label_agent_run: \"conversation.label_agent_run\",\n conversation__label_chat: \"conversation.label_chat\",\n conversation__outcome_summarizer: \"conversation.outcome_summarizer\",\n conversation__vision_extractor: \"conversation.vision_extractor\",\n conversation__vision_interviewer: \"conversation.vision_interviewer\",\n crm__journalist_beat_analyst: \"crm.journalist_beat_analyst\",\n crm__media_list_ranker: \"crm.media_list_ranker\",\n crm__outreach_draft_reviewer: \"crm.outreach_draft_reviewer\",\n crm__outreach_fact_check: \"crm.outreach_fact_check\",\n crm__outreach_personalization_coach: \"crm.outreach_personalization_coach\",\n crm__outreach_personalization_writer: \"crm.outreach_personalization_writer\",\n crm__outreach_pitch_writer: \"crm.outreach_pitch_writer\",\n crm__outreach_recipient_shortlister: \"crm.outreach_recipient_shortlister\",\n crm__outreach_reply_drafter: \"crm.outreach_reply_drafter\",\n crm__outreach_strategy: \"crm.outreach_strategy\",\n crm__party_kind_judge: \"crm.party_kind_judge\",\n crm__save_contact: \"crm.save_contact\",\n data__formula_writing: \"data.formula_writing\",\n data__page_guidance: \"data.page_guidance\",\n data__row_action: \"data.row_action\",\n dictionary__workspace_guide: \"dictionary.workspace_guide\",\n distillation__timeline_distiller: \"distillation.timeline_distiller\",\n distillation__timeline_unfolder: \"distillation.timeline_unfolder\",\n docproc__content_structure: \"docproc.content_structure\",\n education__admin_guidance: \"education.admin_guidance\",\n education__analytics_narrate: \"education.analytics_narrate\",\n education__audio_study_guidance: \"education.audio_study_guidance\",\n education__card_image_generator: \"education.card_image_generator\",\n education__card_image_prompt_writer: \"education.card_image_prompt_writer\",\n education__card_image_qc_judge: \"education.card_image_qc_judge\",\n education__card_image_web_source: \"education.card_image_web_source\",\n education__classes_guidance: \"education.classes_guidance\",\n education__creator_guidance: \"education.creator_guidance\",\n education__data_guidance: \"education.data_guidance\",\n education__exam_prep_guidance: \"education.exam_prep_guidance\",\n education__family_guidance: \"education.family_guidance\",\n education__fastfire_guidance: \"education.fastfire_guidance\",\n education__features_guidance: \"education.features_guidance\",\n education__flashcards_guidance: \"education.flashcards_guidance\",\n education__game_guidance: \"education.game_guidance\",\n education__grade_handwritten: \"education.grade_handwritten\",\n education__grade_work_guidance: \"education.grade_work_guidance\",\n education__kit_title: \"education.kit_title\",\n education__learn_guidance: \"education.learn_guidance\",\n education__levels_guidance: \"education.levels_guidance\",\n education__library_guidance: \"education.library_guidance\",\n education__media_guidance: \"education.media_guidance\",\n education__memory_generate: \"education.memory_generate\",\n education__memory_guidance: \"education.memory_guidance\",\n education__memory_hint: \"education.memory_hint\",\n education__mind_maps_guidance: \"education.mind_maps_guidance\",\n education__mindmap_generate: \"education.mindmap_generate\",\n education__notes_generate: \"education.notes_generate\",\n education__notes_guidance: \"education.notes_guidance\",\n education__offline_guidance: \"education.offline_guidance\",\n education__page_guidance: \"education.page_guidance\",\n education__plan_generate: \"education.plan_generate\",\n education__planner_guidance: \"education.planner_guidance\",\n education__practice_oral_guidance: \"education.practice_oral_guidance\",\n education__practice_tests_guidance: \"education.practice_tests_guidance\",\n education__progress_guidance: \"education.progress_guidance\",\n education__quiz_deepen_item: \"education.quiz_deepen_item\",\n education__quiz_generate: \"education.quiz_generate\",\n education__quiz_generate_from_source: \"education.quiz_generate_from_source\",\n education__quizzes_guidance: \"education.quizzes_guidance\",\n education__spoken_practice_design: \"education.spoken_practice_design\",\n education__spoken_practice_design_language: \"education.spoken_practice_design_language\",\n education__spoken_practice_grade: \"education.spoken_practice_grade\",\n education__spoken_practice_grade_pronunciation: \"education.spoken_practice_grade_pronunciation\",\n education__spoken_practice_review: \"education.spoken_practice_review\",\n education__start_guidance: \"education.start_guidance\",\n education__study_aids_guidance: \"education.study_aids_guidance\",\n education__study_pack_flashcards: \"education.study_pack_flashcards\",\n education__study_pack_lessons: \"education.study_pack_lessons\",\n education__study_pack_notes: \"education.study_pack_notes\",\n education__study_pack_quiz: \"education.study_pack_quiz\",\n education__study_pack_v2_flashcards: \"education.study_pack_v2_flashcards\",\n education__study_pack_v2_lessons: \"education.study_pack_v2_lessons\",\n education__study_pack_v2_notes: \"education.study_pack_v2_notes\",\n education__study_pack_v2_quiz: \"education.study_pack_v2_quiz\",\n education__subjects_guidance: \"education.subjects_guidance\",\n education__summaries_guidance: \"education.summaries_guidance\",\n education__summarize: \"education.summarize\",\n education__tutor_guidance: \"education.tutor_guidance\",\n education__tutor_message: \"education.tutor_message\",\n education__voice_tutor: \"education.voice_tutor\",\n evaluators__comparative_judge: \"evaluators.comparative_judge\",\n evaluators__rubric_judge: \"evaluators.rubric_judge\",\n extend__browser_chat: \"extend.browser_chat\",\n extend__pattern_from_data: \"extend.pattern_from_data\",\n extend__structured_extractor: \"extend.structured_extractor\",\n feedback__item_triage_decision: \"feedback.item_triage_decision\",\n flashcards__enrich_card: \"flashcards.enrich_card\",\n flashcards__expand_card: \"flashcards.expand_card\",\n flashcards__fix_giveaway_cards: \"flashcards.fix_giveaway_cards\",\n flashcards__generate_cards: \"flashcards.generate_cards\",\n flashcards__generate_from_source: \"flashcards.generate_from_source\",\n flashcards__grade_spoken: \"flashcards.grade_spoken\",\n flashcards__grade_typed_answer: \"flashcards.grade_typed_answer\",\n flashcards__help_live: \"flashcards.help_live\",\n flashcards__helper_tts: \"flashcards.helper_tts\",\n flashcards__make_quiz_items: \"flashcards.make_quiz_items\",\n flashcards__micro_coach: \"flashcards.micro_coach\",\n flashcards__review_batch: \"flashcards.review_batch\",\n flashcards__spoken_front_tts: \"flashcards.spoken_front_tts\",\n flashcards__verify_against_source: \"flashcards.verify_against_source\",\n foundry__planner: \"foundry.planner\",\n google__channel_video_plan: \"google.channel_video_plan\",\n google__desk_work: \"google.desk_work\",\n google__traffic_change_explanation: \"google.traffic_change_explanation\",\n growth_loop__quality_analyze: \"growth_loop.quality_analyze\",\n growth_loop__quality_brief: \"growth_loop.quality_brief\",\n growth_loop__quality_crawl: \"growth_loop.quality_crawl\",\n growth_loop__quality_fill: \"growth_loop.quality_fill\",\n growth_loop__quality_measure: \"growth_loop.quality_measure\",\n growth_loop__quality_plan: \"growth_loop.quality_plan\",\n growth_loop__quality_publish: \"growth_loop.quality_publish\",\n growth_loop__quality_realize: \"growth_loop.quality_realize\",\n growth_loop__quality_research: \"growth_loop.quality_research\",\n growth_loop__quality_serve: \"growth_loop.quality_serve\",\n growth_loop__quality_suggest: \"growth_loop.quality_suggest\",\n growth_loop__quality_writeback: \"growth_loop.quality_writeback\",\n growth_loop__supervisor: \"growth_loop.supervisor\",\n hindsight__crystallizer: \"hindsight.crystallizer\",\n hindsight__replay_judge: \"hindsight.replay_judge\",\n hindsight__reviewer: \"hindsight.reviewer\",\n human_decisions__fallback_decider: \"human_decisions.fallback_decider\",\n image__generate: \"image.generate\",\n image_pipeline__concept: \"image_pipeline.concept\",\n image_pipeline__prompt_write: \"image_pipeline.prompt_write\",\n image_pipeline__qc_judge: \"image_pipeline.qc_judge\",\n iteration__architect: \"iteration.architect\",\n iteration__diagnostic: \"iteration.diagnostic\",\n iteration__root_cause: \"iteration.root_cause\",\n iteration__thinking_display: \"iteration.thinking_display\",\n kg__cluster_namer: \"kg.cluster_namer\",\n kg__ner_extractor: \"kg.ner_extractor\",\n knowledge__document_verifier: \"knowledge.document_verifier\",\n knowledge__qa_generator: \"knowledge.qa_generator\",\n knowledge__section_summarizer: \"knowledge.section_summarizer\",\n local__answer_question: \"local.answer_question\",\n local__chat_persona_brainstorm: \"local.chat_persona_brainstorm\",\n local__chat_persona_code_review: \"local.chat_persona_code_review\",\n local__chat_persona_explain_simply: \"local.chat_persona_explain_simply\",\n local__chat_persona_helpful: \"local.chat_persona_helpful\",\n local__chat_persona_spoken_replies: \"local.chat_persona_spoken_replies\",\n local__chat_persona_summarize: \"local.chat_persona_summarize\",\n local__chat_persona_transcript_polish: \"local.chat_persona_transcript_polish\",\n local__cloud_chat: \"local.cloud_chat\",\n local__cloud_chat_reply: \"local.cloud_chat_reply\",\n local__confidential_chat: \"local.confidential_chat\",\n local__explain_code: \"local.explain_code\",\n local__extract_action_items: \"local.extract_action_items\",\n local__improve_writing: \"local.improve_writing\",\n local__polish_style_action_items: \"local.polish_style_action_items\",\n local__polish_style_bullets: \"local.polish_style_bullets\",\n local__polish_style_custom: \"local.polish_style_custom\",\n local__polish_style_formal: \"local.polish_style_formal\",\n local__polish_style_light_cleanup: \"local.polish_style_light_cleanup\",\n local__polish_style_meeting_notes: \"local.polish_style_meeting_notes\",\n local__polish_style_standard: \"local.polish_style_standard\",\n local__polish_transcript: \"local.polish_transcript\",\n local__raw_completion: \"local.raw_completion\",\n local__summarize_text: \"local.summarize_text\",\n local__tool_calling_chat: \"local.tool_calling_chat\",\n mandate_outcome__goal_clause_extraction: \"mandate_outcome.goal_clause_extraction\",\n mandate_outcome__goal_fitness_decision: \"mandate_outcome.goal_fitness_decision\",\n mandates__holder_draft: \"mandates.holder_draft\",\n marketing__endowment_analysis: \"marketing.endowment_analysis\",\n marketing__endowment_portfolio: \"marketing.endowment_portfolio\",\n marketing__image_prompt: \"marketing.image_prompt\",\n marketing__page_image: \"marketing.page_image\",\n marketing__page_image_all_in_one: \"marketing.page_image_all_in_one\",\n marketing__video_metadata: \"marketing.video_metadata\",\n masterwork__approach_selector: \"masterwork.approach_selector\",\n masterwork__audition_judge: \"masterwork.audition_judge\",\n masterwork__bad_draft: \"masterwork.bad_draft\",\n masterwork__bad_example_probe: \"masterwork.bad_example_probe\",\n masterwork__case_oracle: \"masterwork.case_oracle\",\n masterwork__checkup_auditor: \"masterwork.checkup_auditor\",\n masterwork__coherence_partner: \"masterwork.coherence_partner\",\n masterwork__conductor: \"masterwork.conductor\",\n masterwork__corpus_cleaner: \"masterwork.corpus_cleaner\",\n masterwork__corpus_synthesizer: \"masterwork.corpus_synthesizer\",\n masterwork__counterparty: \"masterwork.counterparty\",\n masterwork__critique_distiller: \"masterwork.critique_distiller\",\n masterwork__draft_triage: \"masterwork.draft_triage\",\n masterwork__drip_distiller: \"masterwork.drip_distiller\",\n masterwork__drip_question: \"masterwork.drip_question\",\n masterwork__elicitation_judge: \"masterwork.elicitation_judge\",\n masterwork__exception_hunter: \"masterwork.exception_hunter\",\n masterwork__exemplar_distiller: \"masterwork.exemplar_distiller\",\n masterwork__faithfulness_judge: \"masterwork.faithfulness_judge\",\n masterwork__intake_designer: \"masterwork.intake_designer\",\n masterwork__markup_distiller: \"masterwork.markup_distiller\",\n masterwork__meeting_scavenger: \"masterwork.meeting_scavenger\",\n masterwork__monologue_distiller: \"masterwork.monologue_distiller\",\n masterwork__outcome_judge: \"masterwork.outcome_judge\",\n masterwork__pairwise_judge: \"masterwork.pairwise_judge\",\n masterwork__prediction_boundary: \"masterwork.prediction_boundary\",\n masterwork__prediction_distiller: \"masterwork.prediction_distiller\",\n masterwork__relationship_auditor: \"masterwork.relationship_auditor\",\n masterwork__rule_improver: \"masterwork.rule_improver\",\n masterwork__rulebook_auditor: \"masterwork.rulebook_auditor\",\n masterwork__scout: \"masterwork.scout\",\n masterwork__sealed_case_oracle: \"masterwork.sealed_case_oracle\",\n masterwork__sort_case_writer: \"masterwork.sort_case_writer\",\n masterwork__sort_distiller: \"masterwork.sort_distiller\",\n masterwork__source_distiller: \"masterwork.source_distiller\",\n masterwork__teach_back_distiller: \"masterwork.teach_back_distiller\",\n masterwork__teach_back_explainer: \"masterwork.teach_back_explainer\",\n masterwork__template__chief_edit: \"masterwork.template.chief_edit\",\n masterwork__template__chief_generate: \"masterwork.template.chief_generate\",\n masterwork__template__editor: \"masterwork.template.editor\",\n masterwork__template__maker: \"masterwork.template.maker\",\n masterwork__timeline_distiller: \"masterwork.timeline_distiller\",\n masterwork__timeline_segmenter: \"masterwork.timeline_segmenter\",\n masterwork__transcript_distiller: \"masterwork.transcript_distiller\",\n masterwork__transcript_shortlister: \"masterwork.transcript_shortlister\",\n masterwork__triad_distiller: \"masterwork.triad_distiller\",\n masterwork__triad_generator: \"masterwork.triad_generator\",\n masterwork__understudy: \"masterwork.understudy\",\n masterwork__unfolding_judge: \"masterwork.unfolding_judge\",\n masterworks__bench__a2_loop: \"masterworks.bench.a2_loop\",\n masterworks__bench__calibration_decoy: \"masterworks.bench.calibration_decoy\",\n masterworks__bench__consensus: \"masterworks.bench.consensus\",\n masterworks__bench__extract: \"masterworks.bench.extract\",\n masterworks__bench__judge: \"masterworks.bench.judge\",\n masterworks__bench__panel: \"masterworks.bench.panel\",\n masterworks__bench__raw_arm: \"masterworks.bench.raw_arm\",\n masterworks__vanilla_arm__answer_from_facts: \"masterworks.vanilla_arm.answer_from_facts\",\n masterworks__vanilla_arm__best_work: \"masterworks.vanilla_arm.best_work\",\n masterworks__vanilla_arm__outcome_case: \"masterworks.vanilla_arm.outcome_case\",\n masterworks__vanilla_arm__professional_help: \"masterworks.vanilla_arm.professional_help\",\n media__youtube_analyzer: \"media.youtube_analyzer\",\n media_catalog__item_vetting_decision: \"media_catalog.item_vetting_decision\",\n meet__agenda_draft: \"meet.agenda_draft\",\n meet__live_intelligence: \"meet.live_intelligence\",\n meet__live_notes: \"meet.live_notes\",\n meet__pre_meeting_brief: \"meet.pre_meeting_brief\",\n meet__transcription: \"meet.transcription\",\n meet__wrap_up: \"meet.wrap_up\",\n memory__observer: \"memory.observer\",\n memory__reflector: \"memory.reflector\",\n mermaid__diagram_editing: \"mermaid.diagram_editing\",\n messaging__action_item_extraction: \"messaging.action_item_extraction\",\n messaging__conversation_catch_up: \"messaging.conversation_catch_up\",\n messaging__conversation_summary: \"messaging.conversation_summary\",\n messaging__reply_drafting: \"messaging.reply_drafting\",\n ner__deep_chunk_extractor: \"ner.deep_chunk_extractor\",\n ner__document_orienter: \"ner.document_orienter\",\n ner__entity_canonicalizer: \"ner.entity_canonicalizer\",\n ner__finisher: \"ner.finisher\",\n ner__item_proposer: \"ner.item_proposer\",\n ner__magic_moment_detector: \"ner.magic_moment_detector\",\n ner__scope_proposer: \"ner.scope_proposer\",\n ner__scope_slot_filler: \"ner.scope_slot_filler\",\n ner__suggestion_reviewer: \"ner.suggestion_reviewer\",\n ner__sweep_scope_discoverer: \"ner.sweep_scope_discoverer\",\n ner__sweep_scope_reference_finder: \"ner.sweep_scope_reference_finder\",\n ner__sweep_value_miner: \"ner.sweep_value_miner\",\n news__angles: \"news.angles\",\n news__coarse_relevance: \"news.coarse_relevance\",\n news__monitor_setup_proposer: \"news.monitor_setup_proposer\",\n news__report: \"news.report\",\n news__story_origin: \"news.story_origin\",\n news__triage: \"news.triage\",\n notes__organizer: \"notes.organizer\",\n notes__page_guidance: \"notes.page_guidance\",\n observability__tool_trace_pattern_detection: \"observability.tool_trace_pattern_detection\",\n observability__tool_trace_triage: \"observability.tool_trace_triage\",\n orchestras__role_describer: \"orchestras.role_describer\",\n orchestration__tool_failure_standoff_decision: \"orchestration.tool_failure_standoff_decision\",\n pdf__chunk_clean_ocr_text: \"pdf.chunk_clean_ocr_text\",\n pdf__chunk_flashcards_json: \"pdf.chunk_flashcards_json\",\n pdf__chunk_flashcards_typescript: \"pdf.chunk_flashcards_typescript\",\n pdf__content_cleaner: \"pdf.content_cleaner\",\n personal_staff__escalation: \"personal_staff.escalation\",\n personal_staff__front_line: \"personal_staff.front_line\",\n podcast__audience_adapter: \"podcast.audience_adapter\",\n podcast__audio_dialogue: \"podcast.audio_dialogue\",\n podcast__audio_english: \"podcast.audio_english\",\n podcast__audio_persian: \"podcast.audio_persian\",\n podcast__chapter_marker: \"podcast.chapter_marker\",\n podcast__content_extractor: \"podcast.content_extractor\",\n podcast__deep_research: \"podcast.deep_research\",\n podcast__image_v1: \"podcast.image_v1\",\n podcast__image_v2: \"podcast.image_v2\",\n podcast__image_v3: \"podcast.image_v3\",\n podcast__image_v4: \"podcast.image_v4\",\n podcast__image_v5: \"podcast.image_v5\",\n podcast__image_v6_feature: \"podcast.image_v6_feature\",\n podcast__image_v6_feature_prompt: \"podcast.image_v6_feature_prompt\",\n podcast__live_rewrite: \"podcast.live_rewrite\",\n podcast__metadata: \"podcast.metadata\",\n podcast__multihost_script: \"podcast.multihost_script\",\n podcast__post_prep_expansion: \"podcast.post_prep_expansion\",\n podcast__post_prep_fact_checking: \"podcast.post_prep_fact_checking\",\n podcast__post_prep_summarization: \"podcast.post_prep_summarization\",\n podcast__post_prep_translation: \"podcast.post_prep_translation\",\n podcast__race_frontier: \"podcast.race_frontier\",\n podcast__relevance_gate: \"podcast.relevance_gate\",\n podcast__roundtable_script: \"podcast.roundtable_script\",\n podcast__script_educational: \"podcast.script_educational\",\n podcast__script_news: \"podcast.script_news\",\n podcast__script_persian: \"podcast.script_persian\",\n podcast__solo_script: \"podcast.solo_script\",\n podcast__title_optimizer: \"podcast.title_optimizer\",\n podcast__video_v1: \"podcast.video_v1\",\n podcast__video_v2: \"podcast.video_v2\",\n podcast_client__blog_writer: \"podcast_client.blog_writer\",\n podcast_client__show_notes: \"podcast_client.show_notes\",\n podcast_client__topic_ideas: \"podcast_client.topic_ideas\",\n podcast_client__web_content_extractor: \"podcast_client.web_content_extractor\",\n podcast_client__youtube_research: \"podcast_client.youtube_research\",\n product_capture__instant_analysis: \"product_capture.instant_analysis\",\n projects__creation_guide: \"projects.creation_guide\",\n proof_runs__judge: \"proof_runs.judge\",\n purpose__writer: \"purpose.writer\",\n rag__chunk_contextualizer: \"rag.chunk_contextualizer\",\n rag__grounded_synthesis: \"rag.grounded_synthesis\",\n rag__grounding_claim_extract: \"rag.grounding_claim_extract\",\n rag__grounding_judge: \"rag.grounding_judge\",\n rag__hyde_generator: \"rag.hyde_generator\",\n rag__image_caption: \"rag.image_caption\",\n rag__pdf_page_cleaner: \"rag.pdf_page_cleaner\",\n rag__query_expander: \"rag.query_expander\",\n rag_kinds__grounded_synthesis: \"rag_kinds.grounded_synthesis\",\n records__enrichment: \"records.enrichment\",\n research__auto_tagger: \"research.auto_tagger\",\n research__condenser_1: \"research.condenser_1\",\n research__condenser_2: \"research.condenser_2\",\n research__coverage_audit: \"research.coverage_audit\",\n research__cross_cutting_tags: \"research.cross_cutting_tags\",\n research__document_assembly: \"research.document_assembly\",\n research__keyword_synthesis: \"research.keyword_synthesis\",\n research__report: \"research.report\",\n research__report_updater: \"research.report_updater\",\n research__source_authority: \"research.source_authority\",\n research__source_triage_decision: \"research.source_triage_decision\",\n research__structured_page_summary: \"research.structured_page_summary\",\n research__suggest_setup: \"research.suggest_setup\",\n research__tag_consolidation: \"research.tag_consolidation\",\n research__topic_deep_research: \"research.topic_deep_research\",\n research_client__output_blog: \"research_client.output_blog\",\n research_client__output_brand_profile: \"research_client.output_brand_profile\",\n research_client__output_competitive_landscape: \"research_client.output_competitive_landscape\",\n research_client__output_gap_analysis: \"research_client.output_gap_analysis\",\n research_client__output_literature_review: \"research_client.output_literature_review\",\n research_client__output_reputation_business: \"research_client.output_reputation_business\",\n research_client__output_reputation_personal: \"research_client.output_reputation_personal\",\n research_client__output_seo: \"research_client.output_seo\",\n research_client__output_slides: \"research_client.output_slides\",\n scraper__fact_check: \"scraper.fact_check\",\n scraper__keyword_analysis: \"scraper.keyword_analysis\",\n scraper__page_fetch_verdict: \"scraper.page_fetch_verdict\",\n seo__ai_visibility_blind_question_writer: \"seo.ai_visibility_blind_question_writer\",\n seo__ai_visibility_buyer_jobs: \"seo.ai_visibility_buyer_jobs\",\n seo__ai_visibility_decision_analyst: \"seo.ai_visibility_decision_analyst\",\n seo__ai_visibility_evidence_icp: \"seo.ai_visibility_evidence_icp\",\n seo__ai_visibility_panel_designer: \"seo.ai_visibility_panel_designer\",\n seo__ai_visibility_panel_report: \"seo.ai_visibility_panel_report\",\n seo__ai_visibility_question_architect: \"seo.ai_visibility_question_architect\",\n seo__ai_visibility_question_qa: \"seo.ai_visibility_question_qa\",\n seo__ai_visibility_writing_audit: \"seo.ai_visibility_writing_audit\",\n seo__backlink_analysis: \"seo.backlink_analysis\",\n seo__backlink_context_assessor: \"seo.backlink_context_assessor\",\n seo__backlink_work_planner: \"seo.backlink_work_planner\",\n seo__business_model_verdict: \"seo.business_model_verdict\",\n seo__competitor_classifier: \"seo.competitor_classifier\",\n seo__competitor_opportunity_autopsy: \"seo.competitor_opportunity_autopsy\",\n seo__competitor_page_autopsy: \"seo.competitor_page_autopsy\",\n seo__coverage_analyst: \"seo.coverage_analyst\",\n seo__digital_pr_reputation_adjudicator: \"seo.digital_pr_reputation_adjudicator\",\n seo__evidence_workbench: \"seo.evidence_workbench\",\n seo__finding_fixer: \"seo.finding_fixer\",\n seo__guidelines_drafter: \"seo.guidelines_drafter\",\n seo__ideal_customer_profile: \"seo.ideal_customer_profile\",\n seo__keyword_classifier: \"seo.keyword_classifier\",\n seo__keyword_expander: \"seo.keyword_expander\",\n seo__keyword_researcher: \"seo.keyword_researcher\",\n seo__keyword_serp_intent_analyst: \"seo.keyword_serp_intent_analyst\",\n seo__landscape_brief: \"seo.landscape_brief\",\n seo__map_author: \"seo.map_author\",\n seo__map_curation: \"seo.map_curation\",\n seo__money_map: \"seo.money_map\",\n seo__offering_extraction: \"seo.offering_extraction\",\n seo__offering_valuation: \"seo.offering_valuation\",\n seo__page_analyzer: \"seo.page_analyzer\",\n seo__page_intent_proposer: \"seo.page_intent_proposer\",\n seo__page_keyword_mapper: \"seo.page_keyword_mapper\",\n seo__page_mapper: \"seo.page_mapper\",\n seo__press_calendar_planner: \"seo.press_calendar_planner\",\n seo__press_clip_reviewer: \"seo.press_clip_reviewer\",\n seo__press_headlines: \"seo.press_headlines\",\n seo__press_moment_researcher: \"seo.press_moment_researcher\",\n seo__press_newsworthiness_check: \"seo.press_newsworthiness_check\",\n seo__press_source_request_responder: \"seo.press_source_request_responder\",\n seo__press_story_analyst: \"seo.press_story_analyst\",\n seo__press_strategist: \"seo.press_strategist\",\n seo__reputation_crisis_holding: \"seo.reputation_crisis_holding\",\n seo__session_rule_writer: \"seo.session_rule_writer\",\n seo__session_stamp_proposer: \"seo.session_stamp_proposer\",\n seo__site_intake: \"seo.site_intake\",\n seo__site_link_authority_router: \"seo.site_link_authority_router\",\n seo__site_strategist: \"seo.site_strategist\",\n seo__starter_pack_proposer: \"seo.starter_pack_proposer\",\n seo__strategy__site_brief__generate: \"seo.strategy.site_brief.generate\",\n seo__topic_assigner: \"seo.topic_assigner\",\n seo__topic_curation: \"seo.topic_curation\",\n sms__owner_beta: \"sms.owner_beta\",\n surfaces_client__binding_mapper: \"surfaces_client.binding_mapper\",\n tasks__triage: \"tasks.triage\",\n tool_viz__component_generator: \"tool_viz.component_generator\",\n tools__summarize_content: \"tools.summarize_content\",\n transcript_studio__document_edit: \"transcript_studio.document_edit\",\n transcript_studio__scribe_live: \"transcript_studio.scribe_live\",\n transcripts__clean_with_context: \"transcripts.clean_with_context\",\n transcripts__clean_with_context_variable: \"transcripts.clean_with_context_variable\",\n transcripts__clean_without_context: \"transcripts.clean_without_context\",\n vision_interview__adversary: \"vision_interview.adversary\",\n vision_interview__amplifier: \"vision_interview.amplifier\",\n vision_interview__answer_tracker: \"vision_interview.answer_tracker\",\n vision_interview__archaeologist: \"vision_interview.archaeologist\",\n vision_interview__architect: \"vision_interview.architect\",\n vision_interview__cartographer: \"vision_interview.cartographer\",\n vision_interview__requirements_author: \"vision_interview.requirements_author\",\n vision_interview__scribe: \"vision_interview.scribe\",\n vision_interview__sounding_board: \"vision_interview.sounding_board\",\n vision_interview__transcript_cleaner: \"vision_interview.transcript_cleaner\",\n vision_interview__vision_author: \"vision_interview.vision_author\",\n voice__communicator: \"voice.communicator\",\n voice__gemini_live: \"voice.gemini_live\",\n voice__intro: \"voice.intro\",\n voice__owner_beta: \"voice.owner_beta\",\n war_room__master: \"war_room.master\",\n war_room__room: \"war_room.room\",\n war_room__thread: \"war_room.thread\",\n web__endpoint_family_judge: \"web.endpoint_family_judge\",\n workflow__complex_research__keyword_synthesis: \"workflow.complex_research.keyword_synthesis\",\n workflow__complex_research__page_summary: \"workflow.complex_research.page_summary\",\n workflow__complex_research__report: \"workflow.complex_research.report\",\n workflow__conductor: \"workflow.conductor\",\n workflow__deep_research__keyword_synthesis: \"workflow.deep_research.keyword_synthesis\",\n workflow__extract_namer: \"workflow.extract_namer\",\n workflow__plan_design: \"workflow.plan_design\",\n workflow__plan_input_kind_authoring: \"workflow.plan_input_kind_authoring\",\n workflow__plan_node_type_recommender: \"workflow.plan_node_type_recommender\",\n workflow__plan_notes_writer: \"workflow.plan_notes_writer\",\n workflow__plan_output_kind_authoring: \"workflow.plan_output_kind_authoring\",\n workflow__recovery_advisor: \"workflow.recovery_advisor\",\n workflow__run_assist_suggester: \"workflow.run_assist_suggester\",\n workflow__step_intelligence: \"workflow.step_intelligence\",\n workflow__steward: \"workflow.steward\",\n workflow__steward__agent_run: \"workflow.steward.agent_run\",\n workflow__steward__data: \"workflow.steward.data\",\n workflow__steward__decision: \"workflow.steward.decision\",\n workflow__steward__user_input: \"workflow.steward.user_input\",\n workflow__wizard__agent_run: \"workflow.wizard.agent_run\",\n} as const;\n\n/** Every key this package version accepts — active plus retiring. */\nexport type MandateKey = (typeof MANDATE_KEYS)[keyof typeof MANDATE_KEYS];\n\n/** The key set as a runtime array, in generated order. */\nexport const ALL_MANDATE_KEYS: readonly MandateKey[] = Object.values(MANDATE_KEYS) as readonly MandateKey[];\n\n/** Keys still in the union but no longer declared (two-phase retire, phase 1). */\nexport const RETIRING_MANDATE_KEYS = {\n} as const;\n\n/**\n * Declared FAMILIES — a prefix the feature's own roster owns, and its members.\n * Emitted from `declared_families()` (aidream `services/mandates/carriers.py`).\n */\nexport const MANDATE_FAMILIES = {\n \"ambient.page_guidance_overrides\": [\n \"data.page_guidance\",\n \"education.admin_guidance\",\n \"education.audio_study_guidance\",\n \"education.classes_guidance\",\n \"education.creator_guidance\",\n \"education.data_guidance\",\n \"education.exam_prep_guidance\",\n \"education.family_guidance\",\n \"education.fastfire_guidance\",\n \"education.features_guidance\",\n \"education.flashcards_guidance\",\n \"education.game_guidance\",\n \"education.grade_work_guidance\",\n \"education.learn_guidance\",\n \"education.levels_guidance\",\n \"education.library_guidance\",\n \"education.media_guidance\",\n \"education.memory_guidance\",\n \"education.mind_maps_guidance\",\n \"education.notes_guidance\",\n \"education.offline_guidance\",\n \"education.page_guidance\",\n \"education.planner_guidance\",\n \"education.practice_oral_guidance\",\n \"education.practice_tests_guidance\",\n \"education.progress_guidance\",\n \"education.quizzes_guidance\",\n \"education.start_guidance\",\n \"education.study_aids_guidance\",\n \"education.subjects_guidance\",\n \"education.summaries_guidance\",\n \"education.tutor_guidance\",\n \"notes.page_guidance\",\n ],\n \"checks.cleanup_bakeoff\": [\n \"checks.cleanup_bakeoff.answer\",\n \"checks.cleanup_bakeoff.judge\",\n ],\n \"content_plan.p6_build\": [\n \"content_plan.p6_build.about\",\n \"content_plan.p6_build.blog\",\n \"content_plan.p6_build.comparison\",\n \"content_plan.p6_build.contact\",\n \"content_plan.p6_build.faq\",\n \"content_plan.p6_build.guide\",\n \"content_plan.p6_build.home\",\n \"content_plan.p6_build.index\",\n \"content_plan.p6_build.location\",\n \"content_plan.p6_build.pillar\",\n \"content_plan.p6_build.pricing\",\n \"content_plan.p6_build.service\",\n ],\n \"content_plan.research_wave\": [\n \"content_plan.research_wave.audience_journey\",\n \"content_plan.research_wave.competitor_coverage\",\n \"content_plan.research_wave.keyword_value\",\n ],\n \"conversation\": [\n \"conversation.action_auditor\",\n \"conversation.decision_ledger\",\n \"conversation.drift_auditor\",\n \"conversation.outcome_summarizer\",\n \"conversation.vision_extractor\",\n \"conversation.vision_interviewer\",\n ],\n \"masterworks.bench\": [\n \"masterworks.bench.a2_loop\",\n \"masterworks.bench.calibration_decoy\",\n \"masterworks.bench.consensus\",\n \"masterworks.bench.extract\",\n \"masterworks.bench.judge\",\n \"masterworks.bench.panel\",\n \"masterworks.bench.raw_arm\",\n ],\n \"masterworks.vanilla_arm\": [\n \"masterworks.vanilla_arm.answer_from_facts\",\n \"masterworks.vanilla_arm.best_work\",\n \"masterworks.vanilla_arm.outcome_case\",\n \"masterworks.vanilla_arm.professional_help\",\n ],\n \"vision_interview\": [\n \"vision_interview.adversary\",\n \"vision_interview.amplifier\",\n \"vision_interview.answer_tracker\",\n \"vision_interview.archaeologist\",\n \"vision_interview.architect\",\n \"vision_interview.cartographer\",\n \"vision_interview.requirements_author\",\n \"vision_interview.scribe\",\n \"vision_interview.sounding_board\",\n \"vision_interview.transcript_cleaner\",\n \"vision_interview.vision_author\",\n ],\n} as const;\n\nexport type MandateFamilyPrefix = keyof typeof MANDATE_FAMILIES;\n\n/** Members of a declared family, typed as real keys. */\nexport type MandateFamilyMember<P extends MandateFamilyPrefix> =\n (typeof MANDATE_FAMILIES)[P][number];\n\n/**\n * THE DYNAMIC FAMILIES — DB-authored (`mandate.definition` origin='user'). No\n * generated union can contain them, so their accessors return a BRANDED\n * `DynamicMandateKey`, deliberately NOT assignable to `MandateKey`: a carrier that\n * demands a declared key still refuses one, and a carrier that accepts either\n * says so in its own signature (`MandateKey | DynamicMandateKey`).\n */\ndeclare const dynamicMandateKeyBrand: unique symbol;\n\nexport type DynamicMandateKey = string & {\n readonly [dynamicMandateKeyBrand]: true;\n};\n\nexport const DYNAMIC_MANDATE_FAMILIES = {\n \"app\": { prefix: \"app\", note: \"One mandate per user-built app (`mandate.definition` origin='user').\" },\n \"shortcut\": { prefix: \"shortcut\", note: \"One mandate per user-authored shortcut (origin='user').\" },\n} as const;\n\nexport type DynamicMandateFamilyPrefix = keyof typeof DYNAMIC_MANDATE_FAMILIES;\n\nconst DYNAMIC_SLUG = /^[a-z0-9]+(?:_[a-z0-9]+)*$/;\n\nfunction dynamicKey(\n prefix: DynamicMandateFamilyPrefix,\n ...slugs: readonly (string | undefined)[]\n): DynamicMandateKey {\n const parts = slugs.filter((slug): slug is string => slug !== undefined);\n if (parts.length === 0) {\n throw new Error(\n `mandate family \"${prefix}\" needs at least a member slug — it was given none.`,\n );\n }\n for (const slug of parts) {\n if (!DYNAMIC_SLUG.test(slug)) {\n throw new Error(\n `mandate family \"${prefix}\" cannot name a member from ` +\n `${JSON.stringify(slug)}: a segment is lowercase words joined by single ` +\n \"underscores. Pass the slug the row carries, never a display name.\",\n );\n }\n }\n return [prefix, ...parts].join(\".\") as DynamicMandateKey;\n}\n\n/**\n * The mandate key of a user-built app. DB-authored — never a declared key.\n * `surfaceSlug` names the per-surface row a few apps carry\n * (`app.<app>.<surface>`); omit it for the app's own mandate.\n */\nexport function mandateKeyOfApp(\n appSlug: string,\n surfaceSlug?: string,\n): DynamicMandateKey {\n return dynamicKey(\"app\", appSlug, surfaceSlug);\n}\n\n/**\n * The mandate key of a user-authored shortcut. DB-authored. `surfaceSlug` names\n * the per-surface row (`shortcut.<shortcut>.<surface>`), which is how most live\n * shortcut rows are keyed; omit it for the shortcut's own mandate.\n */\nexport function mandateKeyOfShortcut(\n shortcutSlug: string,\n surfaceSlug?: string,\n): DynamicMandateKey {\n return dynamicKey(\"shortcut\", shortcutSlug, surfaceSlug);\n}\n","/**\n * `@ai-matrx/agents/mandates` — the ONE place a TypeScript client learns a\n * mandate key.\n *\n * 🚨 **Clients never declare a mandate.** aidream's `declare_mandate` is the\n * only declaration path in the system; this subpath publishes the key set that\n * declaration produced, so a hand-typed `\"seo.keyword_cluster\"` literal, a local\n * `mandates.ts` mirror, or an `as MandateKey` cast is a defect with a real\n * replacement — not a style preference. Every carrier that takes a key should\n * type it `MandateKey` (or `MandateKey | DynamicMandateKey` when it genuinely\n * accepts a DB-authored one) so a wrong key fails type-check instead of failing\n * at run time as a 404 nobody sees.\n *\n * The key data lives in `keys.generated.ts`, emitted by THE ONE GENERATOR\n * (`aidream/scripts/mandates_generate.py`, stage (h)) from the in-process\n * declarations — never edit it. The per-version key set that shipped with each\n * published version is committed beside it under `snapshots/`, so a scan can\n * resolve a client's references against the key set of the version it actually\n * ships (Mandate Declaration & Usage Reporting, DESIGN § 4.5 step 2).\n */\n\nexport {\n ALL_MANDATE_KEYS,\n DYNAMIC_MANDATE_FAMILIES,\n MANDATE_FAMILIES,\n MANDATE_KEYS,\n MANDATE_KEYS_META,\n RETIRING_MANDATE_KEYS,\n mandateKeyOfApp,\n mandateKeyOfShortcut,\n type DynamicMandateFamilyPrefix,\n type DynamicMandateKey,\n type MandateFamilyMember,\n type MandateFamilyPrefix,\n type MandateKey,\n} from \"./keys.generated\";\n\nimport {\n ALL_MANDATE_KEYS,\n MANDATE_KEYS_META,\n type DynamicMandateKey,\n type MandateKey,\n} from \"./keys.generated\";\n\n/**\n * What a carrier accepts when the key may be a declared one OR a DB-authored\n * one (`app.*` / `shortcut.*`, a `mandate.definition` row with origin='user').\n * Carriers that only ever run a declared job stay `MandateKey`.\n *\n * The mandate reference scanner reads a binding of this type as a proven key in\n * flight (`passthrough`), never an `UNRESOLVED_KEY` — so this is THE one\n * definition every client imports, never a local copy.\n */\nexport type AnyMandateKey = MandateKey | DynamicMandateKey;\n\n/**\n * A KEY THE CODE DID NOT CHOOSE, entering the typed world named for what it is:\n * a `mandate_key` column the platform wrote (an agent app's own mandate, a\n * shortcut's, a stored binding row), a stored `mandate:` ref, a saved config.\n *\n * It TYPES and never rejects. The server is the authority on whether the key\n * exists — a key declared after this package version shipped is real there and\n * absent from this build's key set — so narrowing here would send such a key\n * through the wrong door. The server answers an unknown key with a 404 that\n * names it.\n *\n * Never use it on a key your code picks: that key belongs to\n * `MANDATE_KEYS.<id>`, and routing it through here hides a rename from the\n * compiler. For a value that must be PROVEN declared (a URL segment a person\n * could have edited), use `isMandateKey` / `assertMandateKey` instead.\n */\nexport function storedMandateKey(value: string): AnyMandateKey {\n return value as AnyMandateKey;\n}\n\nconst KEY_SET: ReadonlySet<string> = new Set<string>(ALL_MANDATE_KEYS);\n\n/**\n * Narrow an unknown string to a declared `MandateKey`.\n *\n * Use it on anything that crossed a wire — a URL segment, a stored preference,\n * a row's `mandate_key` column. It answers only for the key set THIS package\n * version ships; a key declared after this version was published is correctly\n * `false` here, which is the point of the per-version snapshots.\n */\nexport function isMandateKey(value: unknown): value is MandateKey {\n return typeof value === \"string\" && KEY_SET.has(value);\n}\n\n/**\n * Assert an unknown value is a declared `MandateKey`, or throw with a remedy.\n *\n * Nothing fails silently: the message names the value, the package version its\n * key set came from, and what to do — never a bare \"invalid key\".\n */\nexport function assertMandateKey(\n value: unknown,\n context?: string,\n): asserts value is MandateKey {\n if (isMandateKey(value)) return;\n const where = context ? ` at ${context}` : \"\";\n throw new Error(\n `${JSON.stringify(value)} is not a declared mandate key${where}. ` +\n `@ai-matrx/agents@${MANDATE_KEYS_META.packageVersion} ships ` +\n `${ALL_MANDATE_KEYS.length} keys (aidream ${MANDATE_KEYS_META.aidreamRevision.slice(0, 12)}). ` +\n \"If the key is real, this package is behind — take `latest` and re-check. \" +\n \"If it is a user-built app or shortcut, it is DB-authored: build it with \" +\n \"mandateKeyOfApp() / mandateKeyOfShortcut(), which return DynamicMandateKey.\",\n );\n}\n\n/**\n * A DB-AUTHORED KEY THE GENERATED UNION CANNOT CARRY — the ONE typed door for\n * a literal a client's mandate-key allowlist already governs.\n *\n * Two honest cases: an `origin='user'` mandate somebody created in the console\n * (no generator built from code declarations can ever contain it), and a key\n * aidream has declared but the installed `@ai-matrx/agents` predates. Because\n * the parameter is a literal type, the key still appears verbatim at the call\n * site for a hand-typed-key scanner and for a human reading the diff.\n *\n * 🚨 NOT an escape hatch for a declared key. A key in `MANDATE_KEYS` goes\n * through `MANDATE_KEYS.<id>`; using this for one hides a real rename from the\n * compiler. When the package publishes a key routed through here, delete the call.\n */\nexport function dbAuthoredMandateKey<K extends string>(\n key: K,\n): DynamicMandateKey {\n return key as unknown as DynamicMandateKey;\n}\n\nexport interface MandateKeyParts {\n /** The feature/domain namespace before the first dot. */\n feature: string;\n /** The complete step name after the first dot; later dots are preserved. */\n mandate: string;\n}\n\n/** Split canonical `<feature>.<mandate>` identity without losing information. */\nexport function splitMandateKey(mandateKey: string): MandateKeyParts {\n const separator = mandateKey.indexOf(\".\");\n if (separator <= 0 || separator === mandateKey.length - 1) {\n return { feature: \"(unscoped)\", mandate: mandateKey };\n }\n return {\n feature: mandateKey.slice(0, separator),\n mandate: mandateKey.slice(separator + 1),\n };\n}\n\nexport {\n EMPTY_MANDATE_CONTRACT,\n missingRequiredVariables,\n missingVariablesMessage,\n parseMandateContract,\n type MandateContract,\n} from \"./contract\";\n","/**\n * `@ai-matrx/agents/matrx` — the Matrx transport port.\n *\n * The ONE seam between this package's wire semantics and a host's connection\n * policy. This package owns WHAT is said to the AI Matrx server — paths,\n * methods, JSON bodies, streaming Accept headers, the `Last-Event-ID` cursor\n * header — and the host owns HOW the connection is made:\n *\n * - base-URL / backend-channel resolution (global, sandbox override, local\n * engine, EC2-dedicated — whatever ladder the host runs);\n * - credentials (Supabase JWT `Authorization: Bearer`, guest\n * `X-Fingerprint-ID`, or the API-key lane) — NEVER implemented here;\n * - the `X-Organization-Id` context header;\n * - retry policy, network-level timeouts, and diagnostics capture.\n *\n * A host implements the port in a few lines:\n *\n * ```ts\n * const transport: MatrxTransport = {\n * fetch: (path, init) =>\n * fetch(`${baseUrl}${path}`, {\n * ...init,\n * headers: { ...init.headers, ...authHeaders() },\n * }),\n * };\n * ```\n *\n * The port is deliberately structural and `fetch`-shaped so `@ai-matrx/data`'s\n * `/api` transport can implement it without importing this package.\n */\n\n/**\n * The request this package hands the port. A strict subset of `RequestInit`,\n * so a host can spread it straight into `fetch`.\n */\nexport interface MatrxTransportRequest {\n method: \"GET\" | \"POST\";\n /**\n * Wire-semantic headers the CALL requires (`Content-Type`, `Accept`,\n * `Last-Event-ID`). The host merges its policy headers (auth, org) on top;\n * it must not drop these.\n */\n headers: Record<string, string>;\n /** Pre-serialized JSON body, present on POST calls that carry one. */\n body?: string;\n /** Caller cancellation. The host must wire it to the underlying fetch. */\n signal?: AbortSignal;\n}\n\n/**\n * The transport port. `path` is server-relative and always starts with `/`\n * (`/ai/...`, `/runtime/...`); the host prepends its resolved base URL.\n */\nexport interface MatrxTransport {\n fetch(path: string, init: MatrxTransportRequest): Promise<Response>;\n}\n\n/**\n * A non-2xx response from the Matrx API, with the server's structured error\n * body preserved and its richest human-readable message extracted.\n */\nexport class MatrxApiError extends Error {\n override readonly name = \"MatrxApiError\";\n /** HTTP status of the failed response. */\n readonly status: number;\n /** Machine code from the server body (`code`, or `detail.code`), when present. */\n readonly code: string | null;\n /** The parsed server error body, verbatim (undefined when unparsable). */\n readonly serverDetail: unknown;\n /** The request path the failure came from (server-relative). */\n readonly path: string;\n\n constructor(args: {\n status: number;\n path: string;\n serverDetail?: unknown;\n message?: string;\n }) {\n super(\n args.message ??\n extractMatrxErrorMessage(args.serverDetail) ??\n `HTTP ${args.status}`,\n );\n this.status = args.status;\n this.path = args.path;\n this.serverDetail = args.serverDetail;\n this.code = extractMatrxErrorCode(args.serverDetail);\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction nonBlankString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim() ? value : undefined;\n}\n\n/**\n * Extract the richest human-readable message from a Matrx/FastAPI error body.\n *\n * aidream 4xx validation errors look like\n * `{ error, user_message, details: [{ field, message, help }] }`; hand-raised\n * HTTPExceptions carry `{ detail: { code, message } }`; FastAPI's defaults are\n * `{ detail: string | [{ msg }] }`. Preference order: `user_message` →\n * `message` → joined `details[].message` → `detail.message` →\n * `detail` string → joined `detail[].msg`. Returns undefined for\n * unrecognized bodies so callers fall back to the bare status line.\n */\nexport function extractMatrxErrorMessage(\n serverDetail: unknown,\n): string | undefined {\n if (!isRecord(serverDetail)) return undefined;\n\n const userMessage = nonBlankString(serverDetail.user_message);\n if (userMessage) return userMessage;\n const message = nonBlankString(serverDetail.message);\n if (message) return message;\n\n if (Array.isArray(serverDetail.details)) {\n const messages = serverDetail.details\n .map((entry: unknown) => {\n if (!isRecord(entry)) return undefined;\n const detailMessage = nonBlankString(entry.message);\n if (!detailMessage) return undefined;\n const field = nonBlankString(entry.field);\n return field ? `${field}: ${detailMessage}` : detailMessage;\n })\n .filter((m): m is string => typeof m === \"string\");\n if (messages.length > 0) return messages.join(\"; \");\n }\n\n const detail = serverDetail.detail;\n if (isRecord(detail)) {\n const detailMessage =\n nonBlankString(detail.message) ?? nonBlankString(detail.user_message);\n if (detailMessage) return detailMessage;\n }\n if (typeof detail === \"string\" && detail.trim()) return detail;\n if (Array.isArray(detail)) {\n const messages = detail\n .map((entry: unknown) =>\n isRecord(entry) ? nonBlankString(entry.msg) : undefined,\n )\n .filter((m): m is string => typeof m === \"string\");\n if (messages.length > 0) return messages.join(\"; \");\n }\n return undefined;\n}\n\n/**\n * Extract the machine error code from a Matrx error body: top-level `code`,\n * else `detail.code` (the hand-raised HTTPException shape). Null when absent.\n */\nexport function extractMatrxErrorCode(serverDetail: unknown): string | null {\n if (!isRecord(serverDetail)) return null;\n const topLevel = nonBlankString(serverDetail.code);\n if (topLevel) return topLevel;\n const detail = serverDetail.detail;\n if (isRecord(detail)) {\n const nested = nonBlankString(detail.code);\n if (nested) return nested;\n }\n return null;\n}\n","/**\n * Canonical AI Matrx NDJSON wire kernel.\n *\n * This module is deliberately independent of React, Redux, Next.js, Supabase,\n * and generated application types. Every Matrx client uses it to turn the\n * backend's byte stream into the same normalized `{ event, data }` envelopes.\n * Host runtimes remain responsible for HTTP/auth errors and for deciding what\n * each event means in their state model.\n */\n\nexport interface MatrxStreamEnvelope<TData = unknown> {\n event: string;\n /** Immutable emitter segment; transport sequence is scoped to this id. */\n stream_id?: string;\n data: TData;\n /** Monotonic transport sequence from full envelopes, when supplied. */\n stream_seq?: number;\n}\n\nexport interface MatrxNdjsonIssue {\n line: string;\n error: unknown;\n /** One-based physical NDJSON line number. */\n lineNumber: number;\n /** True when an unterminated trailing fragment was parsed by `finish()`. */\n atCompletion: boolean;\n}\n\nexport interface MatrxStreamEnvelopeObservation {\n /** Exact parsed JSON value before compact/full normalization. */\n raw: unknown;\n envelope: MatrxStreamEnvelope;\n line: string;\n lineNumber: number;\n atCompletion: boolean;\n}\n\nexport interface MatrxNdjsonFramerOptions {\n /** Malformed JSON is non-fatal, but it must never disappear silently. */\n onMalformedLine?: (issue: MatrxNdjsonIssue) => void;\n /** Valid JSON with no recognized Matrx event envelope is also non-fatal. */\n onUnknownEnvelope?: (value: unknown) => void;\n /** Observe every valid envelope without changing or consuming it. */\n onValidEnvelope?: (observation: MatrxStreamEnvelopeObservation) => void;\n}\n\nexport interface ReadMatrxNdjsonOptions extends MatrxNdjsonFramerOptions {\n signal?: AbortSignal;\n /** Maximum normalized events read ahead of the iterator consumer. */\n maxReadAhead?: number;\n}\n\nexport interface MatrxNdjsonFramer {\n /** Push a text fragment. Fragments may split JSON tokens or line endings. */\n pushText(fragment: string): MatrxStreamEnvelope[];\n /** Push a byte fragment. UTF-8 code points may span calls. */\n pushBytes(fragment: Uint8Array): MatrxStreamEnvelope[];\n /** Parse the final unterminated line and flush any pending UTF-8 bytes. */\n finish(): MatrxStreamEnvelope[];\n}\n\ntype QueueItem =\n | { kind: \"event\"; value: MatrxStreamEnvelope }\n | { kind: \"error\"; error: unknown }\n | { kind: \"done\" };\n\nexport const DEFAULT_MATRX_NDJSON_READ_AHEAD = 64;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Normalize both supported Matrx wire shapes:\n *\n * - full: `{ \"event\": \"chunk\", \"data\": { \"text\": \"...\" } }`\n * - compact chunk: `{ \"e\": \"c\", \"t\": \"...\" }`\n * - compact reasoning: `{ \"e\": \"r\", \"t\": \"...\" }`\n */\nexport function normalizeMatrxStreamEnvelope(\n value: unknown,\n): MatrxStreamEnvelope | null {\n if (!isRecord(value)) return null;\n\n if (typeof value.event === \"string\") {\n const streamSeq =\n typeof value.stream_seq === \"number\" && Number.isFinite(value.stream_seq)\n ? value.stream_seq\n : undefined;\n const streamId = typeof value.stream_id === \"string\" ? value.stream_id : undefined;\n return {\n event: value.event,\n data: value.data,\n ...(streamId === undefined ? {} : { stream_id: streamId }),\n ...(streamSeq === undefined ? {} : { stream_seq: streamSeq }),\n };\n }\n if (value.e === \"c\" && typeof value.t === \"string\") {\n const streamId = typeof value.stream_id === \"string\" ? value.stream_id : undefined;\n const streamSeq =\n typeof value.stream_seq === \"number\" && Number.isFinite(value.stream_seq)\n ? value.stream_seq\n : undefined;\n return {\n event: \"chunk\",\n data: { text: value.t },\n ...(streamId === undefined ? {} : { stream_id: streamId }),\n ...(streamSeq === undefined ? {} : { stream_seq: streamSeq }),\n };\n }\n if (value.e === \"r\" && typeof value.t === \"string\") {\n const streamId = typeof value.stream_id === \"string\" ? value.stream_id : undefined;\n const streamSeq =\n typeof value.stream_seq === \"number\" && Number.isFinite(value.stream_seq)\n ? value.stream_seq\n : undefined;\n return {\n event: \"reasoning_chunk\",\n data: { text: value.t },\n ...(streamId === undefined ? {} : { stream_id: streamId }),\n ...(streamSeq === undefined ? {} : { stream_seq: streamSeq }),\n };\n }\n return null;\n}\n\n/**\n * Create the transport-independent NDJSON framer used by the stream reader.\n * Browser extensions, desktop bridges, WebSockets, and tests can feed it\n * fragmented strings or bytes without constructing a `ReadableStream`.\n */\nexport function createMatrxNdjsonFramer(\n options: MatrxNdjsonFramerOptions = {},\n): MatrxNdjsonFramer {\n const decoder = new TextDecoder();\n let buffer = \"\";\n let lineNumber = 0;\n let finished = false;\n\n const assertOpen = (): void => {\n if (finished) throw new Error(\"Matrx NDJSON framer is already finished\");\n };\n\n const parseLine = (\n line: string,\n atCompletion: boolean,\n ): MatrxStreamEnvelope | null => {\n const currentLineNumber = ++lineNumber;\n const trimmed = line.trim();\n if (!trimmed) return null;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(trimmed) as unknown;\n } catch (error) {\n options.onMalformedLine?.({\n line: trimmed,\n error,\n lineNumber: currentLineNumber,\n atCompletion,\n });\n return null;\n }\n\n const envelope = normalizeMatrxStreamEnvelope(parsed);\n if (!envelope) {\n options.onUnknownEnvelope?.(parsed);\n return null;\n }\n options.onValidEnvelope?.({\n raw: parsed,\n envelope,\n line: trimmed,\n lineNumber: currentLineNumber,\n atCompletion,\n });\n return envelope;\n };\n\n const pushDecodedText = (fragment: string): MatrxStreamEnvelope[] => {\n buffer += fragment;\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() ?? \"\";\n const envelopes: MatrxStreamEnvelope[] = [];\n for (const line of lines) {\n const envelope = parseLine(line, false);\n if (envelope) envelopes.push(envelope);\n }\n return envelopes;\n };\n\n return {\n pushText(fragment) {\n assertOpen();\n // Flush any pending byte fragment before switching to explicit text.\n return pushDecodedText(decoder.decode() + fragment);\n },\n pushBytes(fragment) {\n assertOpen();\n return pushDecodedText(decoder.decode(fragment, { stream: true }));\n },\n finish() {\n assertOpen();\n finished = true;\n const envelopes = pushDecodedText(decoder.decode());\n if (buffer.length > 0) {\n const envelope = parseLine(buffer, true);\n buffer = \"\";\n if (envelope) envelopes.push(envelope);\n }\n return envelopes;\n },\n };\n}\n\nfunction readAheadLimit(value: number | undefined): number {\n const limit = value ?? DEFAULT_MATRX_NDJSON_READ_AHEAD;\n if (!Number.isSafeInteger(limit) || limit < 1) {\n throw new RangeError(\"maxReadAhead must be a positive safe integer\");\n }\n return limit;\n}\n\n/**\n * Read and normalize a Matrx NDJSON response body with bounded background\n * read-ahead. Consumer work does not stall the network until `maxReadAhead`\n * complete events are waiting; the bound prevents an abandoned or blocked\n * consumer from growing memory without limit.\n */\nexport async function* readMatrxNdjsonStream(\n body: ReadableStream<Uint8Array>,\n options: ReadMatrxNdjsonOptions = {},\n): AsyncGenerator<MatrxStreamEnvelope, void, undefined> {\n const maxReadAhead = readAheadLimit(options.maxReadAhead);\n const queue: QueueItem[] = [];\n let queuedEventCount = 0;\n let wakeConsumer: (() => void) | null = null;\n let wakeProducer: (() => void) | null = null;\n let readerFinished = false;\n let consumerClosed = false;\n\n const wakeWaitingConsumer = (): void => {\n const wake = wakeConsumer;\n wakeConsumer = null;\n wake?.();\n };\n const wakeWaitingProducer = (): void => {\n const wake = wakeProducer;\n wakeProducer = null;\n wake?.();\n };\n const enqueueTerminal = (item: QueueItem): void => {\n if (consumerClosed) return;\n queue.push(item);\n wakeWaitingConsumer();\n };\n const enqueueEvent = async (value: MatrxStreamEnvelope): Promise<boolean> => {\n while (\n queuedEventCount >= maxReadAhead &&\n !consumerClosed &&\n !options.signal?.aborted\n ) {\n await new Promise<void>((resolve) => {\n wakeProducer = resolve;\n });\n }\n if (consumerClosed || options.signal?.aborted) return false;\n queue.push({ kind: \"event\", value });\n queuedEventCount += 1;\n wakeWaitingConsumer();\n return true;\n };\n const waitForReadCapacity = async (): Promise<boolean> => {\n while (\n queuedEventCount >= maxReadAhead &&\n !consumerClosed &&\n !options.signal?.aborted\n ) {\n await new Promise<void>((resolve) => {\n wakeProducer = resolve;\n });\n }\n return !consumerClosed && !options.signal?.aborted;\n };\n\n const reader = body.getReader();\n const framer = createMatrxNdjsonFramer(options);\n\n const onAbort = (): void => {\n wakeWaitingProducer();\n wakeWaitingConsumer();\n void reader.cancel(options.signal?.reason).catch(() => undefined);\n };\n options.signal?.addEventListener(\"abort\", onAbort, { once: true });\n if (options.signal?.aborted) onAbort();\n\n const readerPromise = (async (): Promise<void> => {\n try {\n while (!options.signal?.aborted && !consumerClosed) {\n if (!(await waitForReadCapacity())) return;\n const { value, done } = await reader.read();\n if (done) break;\n for (const envelope of framer.pushBytes(value)) {\n if (!(await enqueueEvent(envelope))) return;\n }\n }\n\n if (!options.signal?.aborted && !consumerClosed) {\n for (const envelope of framer.finish()) {\n if (!(await enqueueEvent(envelope))) return;\n }\n }\n } catch (error) {\n const aborted =\n options.signal?.aborted ||\n consumerClosed ||\n (error instanceof Error && error.name === \"AbortError\");\n if (!aborted) enqueueTerminal({ kind: \"error\", error });\n } finally {\n readerFinished = true;\n reader.releaseLock();\n enqueueTerminal({ kind: \"done\" });\n }\n })();\n\n try {\n while (true) {\n if (queue.length === 0) {\n if (options.signal?.aborted || readerFinished) return;\n await new Promise<void>((resolve) => {\n wakeConsumer = resolve;\n });\n }\n\n const item = queue.shift();\n if (item?.kind === \"event\") queuedEventCount -= 1;\n wakeWaitingProducer();\n if (!item || item.kind === \"done\") return;\n if (item.kind === \"error\") throw item.error;\n yield item.value;\n }\n } finally {\n consumerClosed = true;\n wakeWaitingProducer();\n wakeWaitingConsumer();\n options.signal?.removeEventListener(\"abort\", onAbort);\n if (!readerFinished) {\n await reader.cancel().catch(() => undefined);\n }\n await readerPromise;\n }\n}\n","/**\n * The conversation-start contract — client-minted `conversation_id`, `is_new`,\n * `store` — typed exactly per the cross-repo System of Record\n * (`common-docs/systems/agents/conversation-start-contract/FEATURE.md`;\n * server truth `aidream/services/conversation_context/scope.py::\n * ConversationStartRequest`).\n *\n * Every request that STARTS a conversation sends all three fields, no\n * defaults:\n *\n * | `is_new` | `store` | Result |\n * |----------|---------|----------------------------------------------------------|\n * | true | true | Create the row with the caller's id — 409 if it exists |\n * | true | false | No row. The id is correlation only (ephemeral run) |\n * | false | true | Continue it — 404 if the caller doesn't own it |\n * | false | false | Ephemeral run on a known id; nothing read, nothing written |\n *\n * `store` is the ONLY ephemeral signal; `is_new` is the caller's assertion\n * about the id, never a persistence switch. `prior_messages` (the client-owned\n * transcript of an ephemeral multi-turn run) is only valid with\n * `store: false` — the union below makes the invalid combination\n * unrepresentable, mirroring the server's 422.\n *\n * Continue routes (`POST /ai/conversations/{id}`) take the id from the path\n * and do not carry this triple.\n */\n\n/** Recursive JSON value — the package's honest type for free-form wire bags. */\nexport type MatrxJsonValue =\n | string\n | number\n | boolean\n | null\n | MatrxJsonValue[]\n | { [key: string]: MatrxJsonValue };\n\n/** A JSON object on the wire. */\nexport type MatrxJsonObject = { [key: string]: MatrxJsonValue };\n\n/**\n * One LLM message on the request wire — `prior_messages` entries for\n * stateless multi-turn runs. Mirrors aidream's `ChatMessageInput`\n * (`aidream/schemas/messages.py`, `extra=\"allow\"` — additional provider\n * fields round-trip untouched).\n */\nexport interface MatrxChatMessage {\n role: string;\n content?: string | MatrxJsonValue[] | null;\n name?: string | null;\n tool_call_id?: string | null;\n tool_calls?: MatrxJsonObject[] | null;\n [extra: string]: MatrxJsonValue | undefined;\n}\n\n/** `is_new: true, store: true` — create the row with the caller's id. */\nexport interface MatrxStoredConversationCreate {\n conversation_id: string;\n is_new: true;\n store: true;\n}\n\n/** `is_new: false, store: true` — continue an owned stored conversation via a start route. */\nexport interface MatrxStoredConversationContinue {\n conversation_id: string;\n is_new: false;\n store: true;\n}\n\n/**\n * `store: false` — ephemeral: nothing read, nothing written; the id is the\n * caller's correlation handle. This is the ONLY member that may carry\n * `prior_messages` (the server 422s a client transcript on a stored run).\n */\nexport interface MatrxEphemeralConversation {\n conversation_id: string;\n is_new: boolean;\n store: false;\n prior_messages?: MatrxChatMessage[];\n}\n\n/** The full conversation-start triple, one member per contract cell. */\nexport type MatrxConversationStart =\n | MatrxStoredConversationCreate\n | MatrxStoredConversationContinue\n | MatrxEphemeralConversation;\n\n/** Mint a fresh client-side conversation id (the contract requires the CLIENT to mint it). */\nexport function mintMatrxConversationId(): string {\n return crypto.randomUUID();\n}\n\n/** Start a NEW stored conversation (`is_new: true, store: true`). */\nexport function newStoredConversationStart(\n conversationId?: string,\n): MatrxStoredConversationCreate {\n return {\n conversation_id: conversationId ?? mintMatrxConversationId(),\n is_new: true,\n store: true,\n };\n}\n\n/**\n * Continue an EXISTING stored conversation through a start route\n * (`is_new: false, store: true` — 404 when the caller doesn't own the id).\n * Prefer `continueAgentConversation` (the dedicated continue route) for\n * ordinary follow-up turns.\n */\nexport function continueStoredConversationStart(\n conversationId: string,\n): MatrxStoredConversationContinue {\n return { conversation_id: conversationId, is_new: false, store: true };\n}\n\n/**\n * Start a NEW ephemeral run (`is_new: true, store: false`) — a freshly minted\n * correlation id, nothing persisted.\n */\nexport function newEphemeralConversationStart(\n conversationId?: string,\n): MatrxEphemeralConversation {\n return {\n conversation_id: conversationId ?? mintMatrxConversationId(),\n is_new: true,\n store: false,\n };\n}\n\n/**\n * Continue an ephemeral multi-turn run (`is_new: false, store: false`): the\n * CLIENT owns the transcript and replays it as `prior_messages` (ordered\n * oldest-first) because the server wrote no rows to rebuild from. The server\n * still owns the agent definition, model, tools, and system prompt.\n */\nexport function continueEphemeralConversationStart(\n conversationId: string,\n priorMessages: MatrxChatMessage[],\n): MatrxEphemeralConversation {\n return {\n conversation_id: conversationId,\n is_new: false,\n store: false,\n prior_messages: priorMessages,\n };\n}\n","/**\n * Internal request plumbing for `@ai-matrx/agents/matrx`. Not part of the\n * public surface — `matrx/index.ts` deliberately does not re-export this\n * module. Everything here is pure: no globals, no work at import time.\n */\n\nimport {\n readMatrxNdjsonStream,\n type MatrxNdjsonIssue,\n type MatrxStreamEnvelope,\n type MatrxStreamEnvelopeObservation,\n} from \"../stream/ndjson\";\nimport { MatrxApiError, type MatrxTransport } from \"./transport\";\n\n/** Encode one path segment (an id) safely into a server-relative path. */\nexport function encodePathSegment(value: string): string {\n return encodeURIComponent(value);\n}\n\nexport type QueryValue =\n | string\n | number\n | boolean\n | readonly string[]\n | undefined;\n\n/**\n * Build a query string. Array values repeat the key (`kind=a&kind=b` — the\n * FastAPI repeatable-parameter convention); undefined values are omitted.\n * Returns \"\" or a string starting with \"?\".\n */\nexport function buildQuery(params: Record<string, QueryValue>): string {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined) continue;\n if (Array.isArray(value)) {\n for (const entry of value) search.append(key, entry);\n } else {\n search.append(key, String(value));\n }\n }\n const encoded = search.toString();\n return encoded ? `?${encoded}` : \"\";\n}\n\nasync function readServerDetail(response: Response): Promise<unknown> {\n try {\n return (await response.json()) as unknown;\n } catch {\n return undefined;\n }\n}\n\nasync function throwApiError(path: string, response: Response): Promise<never> {\n throw new MatrxApiError({\n status: response.status,\n path,\n serverDetail: await readServerDetail(response),\n });\n}\n\nexport interface JsonRequestOptions {\n method: \"GET\" | \"POST\";\n body?: unknown;\n signal?: AbortSignal;\n}\n\n/**\n * Execute a JSON request through the transport. Throws `MatrxApiError` on a\n * non-2xx response; resolves with the parsed JSON body otherwise.\n */\nexport async function requestJson<T>(\n transport: MatrxTransport,\n path: string,\n options: JsonRequestOptions,\n): Promise<T> {\n const hasBody = options.method !== \"GET\" && options.body !== undefined;\n const response = await transport.fetch(path, {\n method: options.method,\n headers: hasBody ? { \"Content-Type\": \"application/json\" } : {},\n ...(hasBody ? { body: JSON.stringify(options.body) } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n });\n if (!response.ok) return throwApiError(path, response);\n return (await response.json()) as T;\n}\n\n/**\n * Options for every streaming call, riding the NDJSON kernel's contract.\n * Public via `./run`'s re-export.\n */\nexport interface MatrxStreamCallOptions {\n /** Abort the fetch and end the events iterator. */\n signal?: AbortSignal;\n /** Bounded background read-ahead (see `stream/ndjson`). */\n maxReadAhead?: number;\n /** Malformed NDJSON is non-fatal but must never disappear silently. */\n onMalformedLine?: (issue: MatrxNdjsonIssue) => void;\n /** Valid JSON with no recognized Matrx envelope. */\n onUnknownEnvelope?: (value: unknown) => void;\n /** Observe every valid envelope in its exact wire form. */\n onValidEnvelope?: (observation: MatrxStreamEnvelopeObservation) => void;\n}\n\n/**\n * A live agent run: the server-assigned ids (from response headers, available\n * BEFORE any event) and the normalized event stream. Public via `./run`.\n */\nexport interface MatrxRunHandle {\n /** `X-Request-ID` — the ONLY id `POST /ai/cancel/{request_id}` accepts. */\n requestId: string | null;\n /** `X-Conversation-ID` — the server's conversation identity. */\n conversationId: string | null;\n /** Normalized `{event, data}` envelopes through the ONE wire kernel. */\n events: AsyncGenerator<MatrxStreamEnvelope, void, undefined>;\n /** The raw response, for hosts that need headers/status beyond the ids. */\n response: Response;\n}\n\n/**\n * Wrap a validated streaming Response into the run handle — the ONE place\n * the id headers are read and the NDJSON kernel is attached (`./run` and\n * `./operations`' rejoin share it).\n */\nexport function toRunHandle(\n response: Response,\n options: MatrxStreamCallOptions,\n): MatrxRunHandle {\n return {\n requestId: response.headers.get(\"X-Request-ID\"),\n conversationId: response.headers.get(\"X-Conversation-ID\"),\n events: readMatrxNdjsonStream(response.body as ReadableStream<Uint8Array>, {\n ...(options.signal ? { signal: options.signal } : {}),\n ...(options.maxReadAhead !== undefined\n ? { maxReadAhead: options.maxReadAhead }\n : {}),\n ...(options.onMalformedLine\n ? { onMalformedLine: options.onMalformedLine }\n : {}),\n ...(options.onUnknownEnvelope\n ? { onUnknownEnvelope: options.onUnknownEnvelope }\n : {}),\n ...(options.onValidEnvelope\n ? { onValidEnvelope: options.onValidEnvelope }\n : {}),\n }),\n response,\n };\n}\n\nexport interface StreamRequestOptions {\n method: \"GET\" | \"POST\";\n body?: unknown;\n /** Extra wire-semantic headers (`Accept`, `Last-Event-ID`). */\n headers?: Record<string, string>;\n signal?: AbortSignal;\n}\n\n/**\n * Execute a streaming request. Throws `MatrxApiError` on a non-2xx response\n * (reading the error body as JSON when possible) or when a 2xx response\n * carries no body; resolves with the validated `Response` otherwise.\n */\nexport async function requestStream(\n transport: MatrxTransport,\n path: string,\n options: StreamRequestOptions,\n): Promise<Response> {\n const hasBody = options.method !== \"GET\" && options.body !== undefined;\n const response = await transport.fetch(path, {\n method: options.method,\n headers: {\n ...(hasBody ? { \"Content-Type\": \"application/json\" } : {}),\n ...options.headers,\n },\n ...(hasBody ? { body: JSON.stringify(options.body) } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n });\n if (!response.ok) return throwApiError(path, response);\n if (!response.body) {\n throw new MatrxApiError({\n status: response.status,\n path,\n serverDetail: { code: \"missing_response_body\" },\n message: \"The streaming response carried no body.\",\n });\n }\n return response;\n}\n","/**\n * `@ai-matrx/agents/stream/sse` — the Matrx SSE frame kernel.\n *\n * Two Matrx clients hand-rolled the identical `text/event-stream` framing —\n * the same separator regex, the same field parsing, the same CRLF incident —\n * for the durable rejoin endpoints (`/runtime/.../events/stream`,\n * `/runs/.../events/stream`). This module is that framing extracted ONCE, as a\n * pure incremental parser, so a host keeps only what is genuinely host policy:\n * the fetch, the stall timer, the retry budget, and what each event MEANS.\n *\n * Contract, mirroring `stream/ndjson`:\n * - Pure and effect-free: no fetch, no timers, no globals. Importing this\n * module performs no work.\n * - Incremental across arbitrary chunk boundaries: a frame split anywhere —\n * mid-line, mid-separator, mid-UTF-8 when using the byte reader — parses\n * identically to one delivered whole.\n * - All three SSE line terminators (`\\r\\n`, `\\n`, `\\r`) and all three frame\n * separators are handled — the CRLF-vs-LF divergence that bit production is\n * covered by construction and by test.\n * - Comment-only frames (heartbeats, `:` lines) ARE emitted (with\n * `data === null`) because hosts use any parsed frame as liveness proof to\n * reset stall timers and retry budgets. Frames with data join multi-line\n * `data:` fields with `\\n` per the SSE spec.\n * - `id:` is surfaced raw AND, when it is a safe integer, as `seq` — the\n * `Last-Event-ID` cursor both Matrx rejoin endpoints use for durable replay.\n * Cursor ADVANCEMENT (`seq > cursor`) stays host-side, next to the retry.\n */\n\nexport interface MatrxSseFrame {\n /** `event:` field; the SSE default \"message\" when absent. */\n event: string;\n /** `id:` field, raw, when present. */\n id: string | null;\n /**\n * `id:` parsed as a non-negative safe integer, else null. Matrx rejoin\n * streams use integer ids as the `Last-Event-ID` replay cursor.\n */\n seq: number | null;\n /**\n * Joined `data:` lines (`\\n`-separated per spec), or null for a frame with\n * no data field at all (e.g. a comment-only heartbeat). An empty-string\n * data field is `\"\"`, not null.\n */\n data: string | null;\n}\n\nconst FRAME_SEPARATOR = /\\r\\n\\r\\n|\\n\\n|\\r\\r/;\nconst LINE_SEPARATOR = /\\r\\n|\\n|\\r/;\n\n/** Parse ONE complete frame's text (no trailing separator). */\nexport function parseMatrxSseFrame(frame: string): MatrxSseFrame {\n let event = \"message\";\n let id: string | null = null;\n const dataLines: string[] = [];\n let sawData = false;\n\n for (const line of frame.split(LINE_SEPARATOR)) {\n if (line.startsWith(\":\")) continue;\n if (line.startsWith(\"event:\")) event = line.slice(6).trim();\n else if (line.startsWith(\"data:\")) {\n sawData = true;\n dataLines.push(line.slice(5).replace(/^ /, \"\"));\n } else if (line.startsWith(\"id:\")) id = line.slice(3).trim();\n }\n\n const seqCandidate = id !== null && id !== \"\" ? Number(id) : NaN;\n const seq =\n Number.isSafeInteger(seqCandidate) && seqCandidate >= 0\n ? seqCandidate\n : null;\n\n return { event, id, seq, data: sawData ? dataLines.join(\"\\n\") : null };\n}\n\nexport interface MatrxSseFramer {\n /** Feed a decoded text chunk; returns every frame it completed. */\n push(chunk: string): MatrxSseFrame[];\n /**\n * Signal end of input. A non-empty trailing buffer is an UNTERMINATED frame:\n * per the SSE spec it was never dispatched, so it is returned separately for\n * the host to treat as diagnostic, never as a delivered event.\n */\n flush(): { incomplete: string | null };\n}\n\n/** Incremental SSE framer over already-decoded text. */\nexport function createMatrxSseFramer(): MatrxSseFramer {\n let buffer = \"\";\n return {\n push(chunk: string): MatrxSseFrame[] {\n buffer += chunk;\n const frames: MatrxSseFrame[] = [];\n for (;;) {\n const sep = FRAME_SEPARATOR.exec(buffer);\n if (sep === null) break;\n // A lone trailing `\\r` could be the first half of `\\r\\n\\r\\n`'s final\n // newline — but the separator regex only matched what is already\n // complete, so the slice below is always safe.\n const frame = buffer.slice(0, sep.index);\n buffer = buffer.slice(sep.index + sep[0].length);\n frames.push(parseMatrxSseFrame(frame));\n }\n return frames;\n },\n flush() {\n const rest = buffer;\n buffer = \"\";\n return { incomplete: rest.length > 0 ? rest : null };\n },\n };\n}\n\nexport interface ReadMatrxSseOptions {\n /**\n * Called with any unterminated trailing text at stream end (a frame the\n * server never finished — diagnostic, not a delivered event).\n */\n onIncomplete?: (text: string) => void;\n}\n\n/**\n * Async-iterate the frames of a byte stream (e.g. `response.body`), handling\n * split UTF-8 across chunk boundaries. Cancellation follows the reader: abort\n * the fetch and the iterator ends; a transport error after complete frames\n * were yielded surfaces AFTER those frames, with its original cause.\n */\nexport async function* readMatrxSseStream(\n stream: ReadableStream<Uint8Array>,\n options: ReadMatrxSseOptions = {},\n): AsyncGenerator<MatrxSseFrame, void, undefined> {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n const framer = createMatrxSseFramer();\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n const frames = framer.push(decoder.decode(value, { stream: true }));\n for (const frame of frames) yield frame;\n }\n const tail = framer.push(decoder.decode());\n for (const frame of tail) yield frame;\n const { incomplete } = framer.flush();\n if (incomplete !== null) options.onIncomplete?.(incomplete);\n } finally {\n reader.releaseLock();\n }\n}\n","/**\n * Runtime operations — the canonical reconnect & resume read surface of the\n * execution spine, over the `MatrxTransport` port.\n *\n * Server truth (verified against aidream source,\n * `aidream/api/routers/runtime_operations.py` + `aidream/services/runtime/\n * reconnect.py`; mounted at bare `/runtime`):\n * - `GET /runtime/operations/{request_id}` — identify by `X-Request-ID`\n * - `GET /runtime/operations/by-link/{kind}/{id}` — identify by feature record\n * - `GET /runtime/executions/{id}/events` — durable seq-cursored page\n * - `GET /runtime/executions/{id}/events/stream` — SSE replay-then-follow,\n * `id:` = per-tree seq, reconnect with `Last-Event-ID`\n * - `POST /runtime/operations/{request_id}/rejoin` — replay + follow the\n * ORIGINAL NDJSON response while its detached task is alive (409 when live\n * delivery is unavailable — fall back to the durable lifecycle stream)\n *\n * The contract: identify → recover durable progress → follow live → re-query\n * the final result from the feature's own record. Token text is deliberately\n * never replayed on the lifecycle stream — that is what `/rejoin` is for.\n *\n * The SSE wire rides the package's own `stream/sse` kernel. This module owns\n * ONE connection's semantics (frames → typed events, cursor advancement,\n * terminal `end`); stall timers, retry budgets, and reconnect loops stay host\n * policy — every yielded item carries the cursor the next attempt resumes from.\n */\n\nimport { readMatrxSseStream, type MatrxSseFrame } from \"../stream/sse\";\nimport type { MatrxJsonObject } from \"./conversation\";\nimport {\n encodePathSegment,\n buildQuery,\n requestJson,\n requestStream,\n toRunHandle,\n type MatrxRunHandle,\n type MatrxStreamCallOptions,\n} from \"./internal\";\nimport { MatrxApiError, type MatrxTransport } from \"./transport\";\n\n// ─── Wire types (mirroring `aidream/services/runtime/reconnect.py`) ─────────\n\n/** `matrx_runtime.models.ExecutionStatus` — the only progress column. */\nexport type MatrxRuntimeExecutionStatus =\n | \"pending\"\n | \"running\"\n | \"paused\"\n | \"waiting_input\"\n | \"completed\"\n | \"failed\"\n | \"cancelled\";\n\nexport const TERMINAL_MATRX_RUNTIME_STATUSES: ReadonlySet<MatrxRuntimeExecutionStatus> =\n new Set([\"completed\", \"failed\", \"cancelled\"]);\n\nconst RUNTIME_STATUSES: ReadonlySet<string> = new Set([\n \"pending\",\n \"running\",\n \"paused\",\n \"waiting_input\",\n \"completed\",\n \"failed\",\n \"cancelled\",\n]);\n\n/** One durable spine event on the wire (`OperationEvent`) — `seq` is the reconnect cursor. */\nexport interface MatrxRuntimeOperationEvent {\n seq: number | null;\n /** Lifecycle vocabulary: created | started | paused | resumed | waiting_input | completed | failed | cancelled | checkpoint_saved | note. */\n kind: string;\n execution_id: string;\n root_execution_id: string | null;\n detail: MatrxJsonObject | null;\n created_at: string | null;\n}\n\n/** One root execution as a reconnecting client sees it (`OperationView`). */\nexport interface MatrxRuntimeOperationView {\n execution_id: string;\n /** Durable request identity — feeds `/rejoin` and no-prompt resume recovery. */\n request_id: string | null;\n type: string;\n status: MatrxRuntimeExecutionStatus;\n is_terminal: boolean;\n waiting_input: boolean;\n /** Decimal on the wire — may arrive as number or string; display-only. */\n cost: number | string;\n meters: Record<string, number | string>;\n link_kind: string | null;\n link_id: string | null;\n error: MatrxJsonObject | null;\n created_at: string | null;\n started_at: string | null;\n ended_at: string | null;\n last_event_seq: number;\n events_path: string;\n stream_path: string;\n}\n\nexport interface MatrxOperationStatusResponse {\n request_id: string;\n operation_count: number;\n operations: MatrxRuntimeOperationView[];\n}\n\nexport interface MatrxOperationsByLinkResponse {\n link_kind: string;\n link_id: string;\n operation_count: number;\n operations: MatrxRuntimeOperationView[];\n}\n\nexport interface MatrxOperationEventsPage {\n execution_id: string;\n root_execution_id: string;\n events: MatrxRuntimeOperationEvent[];\n /** Feeds the next page or the SSE `Last-Event-ID` — polling and push share ONE cursor. */\n next_after_seq: number;\n has_more: boolean;\n root_status: MatrxRuntimeExecutionStatus;\n root_is_terminal: boolean;\n}\n\n// ─── Identify + durable progress ────────────────────────────────────────────\n\n/**\n * Where is my operation? Resolves an `X-Request-ID` to its root execution(s).\n * Returns null on 404 — missing and unowned share one shape by design\n * (existence is never leaked).\n */\nexport async function getRuntimeOperationStatus(\n transport: MatrxTransport,\n requestId: string,\n options: { signal?: AbortSignal } = {},\n): Promise<MatrxOperationStatusResponse | null> {\n try {\n return await requestJson<MatrxOperationStatusResponse>(\n transport,\n `/runtime/operations/${encodePathSegment(requestId)}`,\n { method: \"GET\", ...(options.signal ? { signal: options.signal } : {}) },\n );\n } catch (error) {\n if (error instanceof MatrxApiError && error.status === 404) return null;\n throw error;\n }\n}\n\n/**\n * Operations for a feature record — e.g. `(\"conversation\", conversationId)`,\n * `(\"workflow\", runId)`, `(\"agent_run\", runId)`. Newest first; unowned trees\n * omitted. Returns null on 404 (surface absent, or the caller owns nothing —\n * one shape by design).\n */\nexport async function getRuntimeOperationsByLink(\n transport: MatrxTransport,\n linkKind: string,\n linkId: string,\n options: { limit?: number; signal?: AbortSignal } = {},\n): Promise<MatrxOperationsByLinkResponse | null> {\n const query = buildQuery(\n options.limit !== undefined ? { limit: options.limit } : {},\n );\n try {\n return await requestJson<MatrxOperationsByLinkResponse>(\n transport,\n `/runtime/operations/by-link/${encodePathSegment(linkKind)}/${encodePathSegment(linkId)}${query}`,\n { method: \"GET\", ...(options.signal ? { signal: options.signal } : {}) },\n );\n } catch (error) {\n if (error instanceof MatrxApiError && error.status === 404) return null;\n throw error;\n }\n}\n\n/**\n * Durable progress page for the whole operation TREE:\n * `GET /runtime/executions/{id}/events?after_seq=…`. Pass any node id — it\n * resolves to the root.\n */\nexport function listRuntimeOperationEvents(\n transport: MatrxTransport,\n executionId: string,\n options: {\n afterSeq?: number;\n limit?: number;\n /** Repeatable event-kind filter. */\n kinds?: readonly string[];\n signal?: AbortSignal;\n } = {},\n): Promise<MatrxOperationEventsPage> {\n const query = buildQuery({\n ...(options.afterSeq !== undefined ? { after_seq: options.afterSeq } : {}),\n ...(options.limit !== undefined ? { limit: options.limit } : {}),\n ...(options.kinds !== undefined ? { kind: options.kinds } : {}),\n });\n return requestJson<MatrxOperationEventsPage>(\n transport,\n `/runtime/executions/${encodePathSegment(executionId)}/events${query}`,\n { method: \"GET\", ...(options.signal ? { signal: options.signal } : {}) },\n );\n}\n\n// ─── SSE follow (replay-then-follow with Last-Event-ID) ─────────────────────\n\n/**\n * One item from the follow stream. Every item carries `cursor` — the highest\n * event seq seen so far, which is exactly the `Last-Event-ID` a reconnect\n * resumes from (host retry policy owns the reconnect loop).\n */\nexport type MatrxOperationFollowEvent =\n | {\n /** A parsed durable spine event. */\n type: \"event\";\n event: MatrxRuntimeOperationEvent;\n /** The frame's SSE `id:` as an integer, when it carried one. */\n seq: number | null;\n cursor: number;\n }\n | {\n /**\n * A frame that carried no deliverable event — a comment heartbeat, an\n * unknown event name, or a malformed payload (also surfaced through\n * `onMalformedFrame`). ANY parsed frame proves the wire is alive: hosts\n * reset stall timers and retry budgets on it.\n */\n type: \"liveness\";\n cursor: number;\n }\n | {\n /** The server's terminal frame — the root settled; the stream is over. */\n type: \"end\";\n status: MatrxRuntimeExecutionStatus | null;\n cursor: number;\n };\n\nexport interface FollowRuntimeOperationOptions {\n /** Resume cursor — the operation view's `last_event_seq` (0 = from start). */\n lastEventSeq?: number;\n /** Abort the follow — the generator simply ends. */\n signal?: AbortSignal;\n /** A frame whose payload failed to parse — never silently dropped. */\n onMalformedFrame?: (frame: MatrxSseFrame, error: unknown) => void;\n /** Unterminated trailing SSE text at stream end (diagnostic, never an event). */\n onIncomplete?: (text: string) => void;\n}\n\nfunction parseEndStatus(data: string | null): MatrxRuntimeExecutionStatus | null {\n if (data === null) return null;\n try {\n const parsed = JSON.parse(data) as unknown;\n if (\n typeof parsed === \"object\" &&\n parsed !== null &&\n typeof (parsed as { status?: unknown }).status === \"string\"\n ) {\n const status = (parsed as { status: string }).status;\n return RUNTIME_STATUSES.has(status)\n ? (status as MatrxRuntimeExecutionStatus)\n : null;\n }\n } catch {\n // malformed end payload — still terminal\n }\n return null;\n}\n\n/**\n * Follow ONE SSE connection of an operation's lifecycle stream:\n * `GET /runtime/executions/{id}/events/stream` with `Last-Event-ID` when\n * resuming past 0. Replays from the cursor, then follows live; a\n * WAITING_INPUT park keeps it open (a resume re-attaches to the same\n * execution and its events continue here). Ends after yielding\n * `{type: \"end\"}` when the root settles; a server close WITHOUT an end frame\n * simply ends the generator — reconnect from the last yielded `cursor` (host\n * retry policy).\n */\nexport async function* followRuntimeOperationEvents(\n transport: MatrxTransport,\n executionId: string,\n options: FollowRuntimeOperationOptions = {},\n): AsyncGenerator<MatrxOperationFollowEvent, void, undefined> {\n let cursor = options.lastEventSeq ?? 0;\n\n const headers: Record<string, string> = { Accept: \"text/event-stream\" };\n if (cursor > 0) headers[\"Last-Event-ID\"] = String(cursor);\n\n const response = await requestStream(\n transport,\n `/runtime/executions/${encodePathSegment(executionId)}/events/stream`,\n {\n method: \"GET\",\n headers,\n ...(options.signal ? { signal: options.signal } : {}),\n },\n );\n\n const frames = readMatrxSseStream(\n response.body as ReadableStream<Uint8Array>,\n options.onIncomplete ? { onIncomplete: options.onIncomplete } : {},\n );\n\n for await (const frame of frames) {\n if (frame.event === \"end\") {\n yield { type: \"end\", status: parseEndStatus(frame.data), cursor };\n return;\n }\n if (frame.event === \"execution_event\" && frame.data !== null) {\n let event: MatrxRuntimeOperationEvent;\n try {\n event = JSON.parse(frame.data) as MatrxRuntimeOperationEvent;\n } catch (error) {\n options.onMalformedFrame?.(frame, error);\n yield { type: \"liveness\", cursor };\n continue;\n }\n if (frame.seq !== null && frame.seq > cursor) cursor = frame.seq;\n yield { type: \"event\", event, seq: frame.seq, cursor };\n continue;\n }\n // Comment heartbeats, unknown event names, data-less frames: liveness.\n yield { type: \"liveness\", cursor };\n }\n}\n\n// ─── Follow to end (the production reconnect policy) ────────────────────────\n\nexport interface FollowRuntimeOperationToEndOptions {\n /** Resume cursor — the operation view's `last_event_seq` (0 = from start). */\n lastEventSeq?: number;\n /** Caller teardown — aborting resolves with `ended: false`. */\n signal?: AbortSignal;\n /**\n * The server pings every ~15s, so a wire that is open but silent past this\n * is dead (buffering proxy, idle-killed connection) — abort the attempt and\n * retry rather than hanging forever. Default 45_000.\n */\n stallTimeoutMs?: number;\n /**\n * Consecutive failed attempts before giving up. A single-server deployment\n * deliberately drains for 60s, then starts a new container — the default\n * budget (60 × 2s) keeps following for ~three minutes so the runtime ledger\n * can bridge that handoff. ANY parsed frame resets the budget. Default 60.\n */\n reconnectLimit?: number;\n /** Delay between attempts. Default 2_000. */\n reconnectDelayMs?: number;\n /** Fired per durable spine event (lifecycle transitions + notes). */\n onEvent: (event: MatrxRuntimeOperationEvent, seq: number | null) => void;\n /** A failed attempt (never silently swallowed when provided). */\n onAttemptError?: (error: unknown) => void;\n /** A frame whose payload failed to parse (the ledger heals gaps on reconnect). */\n onMalformedFrame?: (frame: MatrxSseFrame, error: unknown) => void;\n}\n\nexport interface FollowRuntimeOperationToEndResult {\n /** True when the server sent the terminal `end` frame. */\n ended: boolean;\n /** The root status carried on the `end` frame (when `ended`). */\n status: MatrxRuntimeExecutionStatus | null;\n}\n\n/**\n * Follow an operation's lifecycle stream TO ITS END — the full production\n * reconnect policy over `followRuntimeOperationEvents`: replay-then-follow\n * with bounded reconnects, a stall watchdog, and durable `Last-Event-ID`\n * cursor advancement across attempts.\n *\n * Resolves `{ended: true, status}` on the server's `end` frame (the operation\n * settled); `{ended: false}` when the caller aborted or every reconnect\n * attempt failed. A WAITING_INPUT park keeps the stream open by design — a\n * resume re-attaches to the same execution and its events continue arriving\n * on the same cursor. Any parsed frame — comment heartbeats included —\n * proves the wire is alive and resets both the stall timer and the retry\n * budget.\n */\nexport async function followRuntimeOperationToEnd(\n transport: MatrxTransport,\n executionId: string,\n options: FollowRuntimeOperationToEndOptions,\n): Promise<FollowRuntimeOperationToEndResult> {\n const stallTimeoutMs = options.stallTimeoutMs ?? 45_000;\n const reconnectLimit = options.reconnectLimit ?? 60;\n const reconnectDelayMs = options.reconnectDelayMs ?? 2_000;\n const outer = options.signal;\n\n let cursor = options.lastEventSeq ?? 0;\n let failures = 0;\n\n while (!outer?.aborted && failures < reconnectLimit) {\n const attempt = new AbortController();\n const onOuterAbort = () => attempt.abort();\n outer?.addEventListener(\"abort\", onOuterAbort, { once: true });\n\n let stallTimer: ReturnType<typeof setTimeout> | null = null;\n const armStall = () => {\n if (stallTimer !== null) clearTimeout(stallTimer);\n stallTimer = setTimeout(() => attempt.abort(), stallTimeoutMs);\n };\n\n try {\n const items = followRuntimeOperationEvents(transport, executionId, {\n lastEventSeq: cursor,\n signal: attempt.signal,\n ...(options.onMalformedFrame\n ? { onMalformedFrame: options.onMalformedFrame }\n : {}),\n });\n\n armStall();\n for await (const item of items) {\n armStall();\n failures = 0;\n cursor = item.cursor;\n if (item.type === \"end\") {\n return { ended: true, status: item.status };\n }\n if (item.type === \"event\") {\n options.onEvent(item.event, item.seq);\n }\n }\n // Server closed without an `end` frame (e.g. process restart). Retry —\n // `Last-Event-ID` replays anything missed from the durable ledger.\n failures += 1;\n } catch (error) {\n if (outer?.aborted) break;\n failures += 1;\n options.onAttemptError?.(error);\n } finally {\n if (stallTimer !== null) clearTimeout(stallTimer);\n outer?.removeEventListener(\"abort\", onOuterAbort);\n }\n\n if (!outer?.aborted && failures < reconnectLimit) {\n await new Promise((r) => setTimeout(r, reconnectDelayMs));\n }\n }\n\n return { ended: false, status: null };\n}\n\n// ─── NDJSON rejoin (replay the original response) ───────────────────────────\n\n/**\n * Rejoin the ORIGINAL NDJSON response while its detached task is still alive:\n * `POST /runtime/operations/{request_id}/rejoin`. Replays the response from\n * frame one, then continues live — every frame is sequence-stamped\n * (`stream_seq`), so a same-page reconnect can drop frames it already\n * rendered. Throws `MatrxApiError` with status 409 when live delivery is\n * unavailable — fall back to `followRuntimeOperationEvents` + a final record\n * re-query. The `requestId` must be the server's `X-Request-ID`.\n */\nexport async function rejoinRuntimeOperation(\n transport: MatrxTransport,\n requestId: string,\n options: MatrxStreamCallOptions = {},\n): Promise<MatrxRunHandle> {\n const response = await requestStream(\n transport,\n `/runtime/operations/${encodePathSegment(requestId)}/rejoin`,\n {\n method: \"POST\",\n // The route takes no body model; the reference client posts an empty\n // JSON object. Match it so proxies see an ordinary JSON POST.\n body: {},\n ...(options.signal ? { signal: options.signal } : {}),\n },\n );\n return toRunHandle(response, options);\n}\n","/**\n * Agent run lifecycle against the AI Matrx API — start, continue, resume,\n * cancel — over the `MatrxTransport` port, with every streaming response\n * parsed through the package's ONE NDJSON wire kernel (`stream/ndjson`).\n *\n * Server truth (verified against aidream source):\n * - `POST /ai/agents/{agent_id}` — start (`aidream/api/routers/agents.py`)\n * - `POST /ai/conversations/{conversation_id}` — continue (`aidream/api/routers/conversations.py`)\n * - `POST /ai/conversations/{conversation_id}/resume` — resume after\n * client-delegated tool suspension (same router)\n * - `POST /ai/cancel/{request_id}?mode=interrupt` — cancel (`aidream/api/routers/cancel.py`)\n *\n * Response headers arrive before the body: `X-Conversation-ID` and\n * `X-Request-ID` are surfaced on the run handle immediately. `X-Request-ID`\n * is the ONLY id the server accepts for cancel — a client-local id means\n * nothing to it.\n *\n * Host policy stays out: no retry, no store, no timeouts, no persistence\n * (C10: no-persistence). Cancellation is the caller's `AbortSignal`; a client\n * disconnect never stops server work (`detach_on_disconnect`).\n */\n\nimport type { MatrxStreamEnvelope } from \"../stream/ndjson\";\nimport type {\n MatrxConversationStart,\n MatrxJsonObject,\n MatrxJsonValue,\n} from \"./conversation\";\nimport {\n encodePathSegment,\n buildQuery,\n requestJson,\n requestStream,\n toRunHandle,\n type MatrxRunHandle,\n type MatrxStreamCallOptions,\n} from \"./internal\";\nimport type { MatrxTransport } from \"./transport\";\nimport { streamErrorText } from \"./rejoin\";\n\nexport type { MatrxRunHandle, MatrxStreamCallOptions } from \"./internal\";\n\n// ─── Request shapes (mirroring the server's Pydantic models) ────────────────\n\n/**\n * Stable identity of the durable entity whose saved context owns a run —\n * the server reloads the row and uses ITS scope (`ContextAnchor`,\n * `aidream/services/conversation_context/scope.py`).\n */\nexport interface MatrxContextAnchor {\n resource_type: string;\n resource_id: string;\n}\n\n/**\n * Scope and source fields shared by every scoped request\n * (`ScopedRequest` / `AcceptsInjectedScope` server-side). All optional here;\n * the start request narrows `organization_id` to required.\n */\nexport interface MatrxRequestScope {\n organization_id?: string;\n project_id?: string | null;\n task_id?: string | null;\n /** Active context-scope ids from the client's global picker (membership-validated server-side). */\n scope_ids?: string[] | null;\n /** Active scope-TYPE ids — a type-level selection with no specific scope chosen. */\n active_scope_type_ids?: string[] | null;\n context_anchor?: MatrxContextAnchor | null;\n /** Stable application slug that initiated the request. */\n source_app?: string | null;\n /** Stable feature slug within the source application. */\n source_feature?: string | null;\n /** \"user\" = a person directly triggered this; \"auto\" = client automation; omit for API callers. */\n initiation?: \"user\" | \"auto\" | null;\n /** Specific connected desktop instance allowed to claim delegated local tools. */\n target_instance_id?: string | null;\n}\n\n/**\n * Fields shared by start/continue turn requests (tool injection, client\n * capability envelope, context object). The complex bags (`tools`, `client`,\n * `user`, `config_overrides`) are typed as JSON objects — their authoritative\n * schemas are the server's Pydantic models and the generated API types;\n * this package stays payload-agnostic about them by design.\n */\nexport interface MatrxTurnFields {\n /** What the human typed (string), or structured input parts. Never smuggle machine content here. */\n user_input?: string | MatrxJsonValue[] | null;\n /** Per-run model/config overrides (LLMParams shape). */\n config_overrides?: MatrxJsonObject | null;\n debug?: boolean;\n /** Additive tool specs merged into the agent's resolved tool set. */\n tools?: MatrxJsonObject[];\n /** When set, becomes the agent's ENTIRE tool set for the turn. */\n tools_replace?: MatrxJsonObject[] | null;\n /** Client capability envelope (`ClientContext`). */\n client?: MatrxJsonObject | null;\n /** Per-request user-level tool inclusion/exclusion overrides. */\n user?: MatrxJsonObject | null;\n /** Per-route context object, free-form by design. */\n context?: MatrxJsonObject;\n writable_variables?: string[];\n allow_context_create?: boolean;\n /** Request-snapshot capture override (tri-state; omit for the platform default). */\n snapshot?: boolean | null;\n}\n\n/**\n * `POST /ai/agents/{agent_id}` body (`AgentStartRequest` server-side).\n * The conversation-start triple is required by construction; `organization_id`\n * is required (the server 422s a blank one — it never manufactures an org).\n * `stream` is not accepted here: this client is the streaming path and always\n * sends `stream: true`.\n */\nexport type MatrxAgentStartRequest = MatrxConversationStart &\n Omit<MatrxRequestScope, \"organization_id\"> &\n MatrxTurnFields & {\n organization_id: string;\n /** Variable name → value map filling the agent's declared variables. */\n variables?: MatrxJsonObject | null;\n /** Run the versions table row instead of the live agent row. */\n is_version?: boolean;\n max_iterations?: number;\n max_retries_per_iteration?: number;\n };\n\n/**\n * `POST /ai/mandates/{mandate_key}` uses the exact saved-agent start body.\n * The server resolves the mandate's holder, binding, and configuration; a\n * client must offer only the declared variables and human input here.\n */\nexport type MatrxMandateStartRequest = MatrxAgentStartRequest;\n\n/** `POST /ai/conversations/{id}` body (`ConversationContinueRequest` server-side). */\nexport type MatrxConversationContinueRequest = MatrxRequestScope &\n MatrxTurnFields & {\n /** Re-run the conversation's current persisted state (recovery after a failed turn); omit `user_input`. */\n retry?: boolean;\n };\n\n/**\n * `POST /ai/conversations/{id}/resume` body (`ResumeRequest` server-side) —\n * the shipped durable continuation after client-delegated tool calls were\n * answered via `POST /tool_results` while the original stream was gone.\n * `user_request_id` is optional: when omitted the server resolves the turn\n * from the conversation's newest answered client-delegated tool call.\n * Re-send fresh `context` here — a resumed loop is otherwise context-blind.\n */\nexport type MatrxConversationResumeRequest = MatrxRequestScope & {\n user_request_id?: string | null;\n config_overrides?: MatrxJsonObject | null;\n debug?: boolean;\n tools?: MatrxJsonObject[];\n tools_replace?: MatrxJsonObject[] | null;\n client?: MatrxJsonObject | null;\n user?: MatrxJsonObject | null;\n context?: MatrxJsonObject;\n writable_variables?: string[];\n allow_context_create?: boolean;\n};\n\n/** `POST /ai/cancel/{request_id}` response (`CancelResponse` server-side). */\nexport interface MatrxCancelResponse {\n status: string;\n request_id: string;\n spine_executions_signalled: string[];\n}\n\n// ─── The run handle ─────────────────────────────────────────────────────────\n// `MatrxStreamCallOptions`, `MatrxRunHandle`, and the handle constructor live\n// in ./internal so `./operations`' rejoin shares the exact same construction.\n\nasync function streamCall(\n transport: MatrxTransport,\n path: string,\n body: object,\n options: MatrxStreamCallOptions,\n): Promise<MatrxRunHandle> {\n const response = await requestStream(transport, path, {\n method: \"POST\",\n // This client IS the streaming path — `stream: true` always, last so a\n // caller-supplied value can never flip the response off NDJSON.\n body: { ...body, stream: true },\n ...(options.signal ? { signal: options.signal } : {}),\n });\n return toRunHandle(response, options);\n}\n\n// ─── Lifecycle calls ────────────────────────────────────────────────────────\n\n/** Start an agent run: `POST /ai/agents/{agent_id}` (NDJSON stream). */\nexport function startAgentRun(\n transport: MatrxTransport,\n agentId: string,\n request: MatrxAgentStartRequest,\n options: MatrxStreamCallOptions = {},\n): Promise<MatrxRunHandle> {\n return streamCall(\n transport,\n `/ai/agents/${encodePathSegment(agentId)}`,\n request,\n options,\n );\n}\n\n/**\n * Start a declared mandate: `POST /ai/mandates/{mandate_key}` (NDJSON\n * stream). This is deliberately separate from `startAgentRun`: callers name\n * the mandate and never resolve or echo its holder/configuration themselves.\n */\nexport function startMandateRun(\n transport: MatrxTransport,\n mandateKey: string,\n request: MatrxMandateStartRequest,\n options: MatrxStreamCallOptions = {},\n): Promise<MatrxRunHandle> {\n return streamCall(\n transport,\n `/ai/mandates/${encodePathSegment(mandateKey)}`,\n request,\n options,\n );\n}\n\n/** Continue a stored conversation: `POST /ai/conversations/{id}` (NDJSON stream). */\nexport function continueAgentConversation(\n transport: MatrxTransport,\n conversationId: string,\n request: MatrxConversationContinueRequest,\n options: MatrxStreamCallOptions = {},\n): Promise<MatrxRunHandle> {\n return streamCall(\n transport,\n `/ai/conversations/${encodePathSegment(conversationId)}`,\n request,\n options,\n );\n}\n\n/**\n * Resume a suspended loop after delegated tool answers landed:\n * `POST /ai/conversations/{id}/resume` (NDJSON stream). A 409\n * (`resume_conflict`) means another resume holds the run claim — retrying is\n * host policy.\n */\nexport function resumeAgentConversation(\n transport: MatrxTransport,\n conversationId: string,\n request: MatrxConversationResumeRequest = {},\n options: MatrxStreamCallOptions = {},\n): Promise<MatrxRunHandle> {\n return streamCall(\n transport,\n `/ai/conversations/${encodePathSegment(conversationId)}/resume`,\n request,\n options,\n );\n}\n\n/**\n * Stop a running request at its next iteration boundary:\n * `POST /ai/cancel/{request_id}`. Cooperative and best-effort — the in-flight\n * provider call finishes by design, and everything already streamed persists.\n * `mode: \"interrupt\"` = stop-and-fork: the tail after the last clean boundary\n * persists hidden so the user's follow-up replies to what they actually saw.\n * The id must be the server's `X-Request-ID`.\n */\nexport function cancelAgentRun(\n transport: MatrxTransport,\n requestId: string,\n options: { mode?: \"cancel\" | \"interrupt\"; signal?: AbortSignal } = {},\n): Promise<MatrxCancelResponse> {\n const query = buildQuery(\n options.mode === \"interrupt\" ? { mode: \"interrupt\" } : {},\n );\n return requestJson<MatrxCancelResponse>(\n transport,\n `/ai/cancel/${encodePathSegment(requestId)}${query}`,\n {\n method: \"POST\",\n ...(options.signal ? { signal: options.signal } : {}),\n },\n );\n}\n\n// ─── End-to-end convenience: run to completion ──────────────────────────────\n\n/**\n * A run that terminated unsuccessfully: the server emitted a fatal `error`\n * event, or the `user_request` completion settled `failed`/`cancelled`.\n */\nexport class MatrxRunError extends Error {\n override readonly name = \"MatrxRunError\";\n /** The verbatim `error` event payload, when one fired. */\n readonly errorPayload: Record<string, unknown> | null;\n /** The `user_request` completion status (`\"failed\"` | `\"cancelled\"`), when that was the trigger. */\n readonly completionStatus: string | null;\n /** Text streamed before the failure — partial content never vanishes. */\n readonly partialText: string;\n\n constructor(args: {\n message: string;\n errorPayload?: Record<string, unknown> | null;\n completionStatus?: string | null;\n partialText?: string;\n }) {\n super(args.message);\n this.errorPayload = args.errorPayload ?? null;\n this.completionStatus = args.completionStatus ?? null;\n this.partialText = args.partialText ?? \"\";\n }\n}\n\nexport interface MatrxCompletedRun {\n /** Accumulated `chunk` text (falls back to the completion's `result.output`). */\n text: string;\n requestId: string | null;\n conversationId: string | null;\n /** The `user_request` completion payload, verbatim, when one arrived. */\n completion: Record<string, unknown> | null;\n}\n\nexport interface RunAgentToCompletionOptions extends MatrxStreamCallOptions {\n /** Live progress: the full accumulated text after each chunk. */\n onChunk?: (fullText: string) => void;\n /** Every normalized envelope, before this helper interprets it. */\n onEvent?: (envelope: MatrxStreamEnvelope) => void;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction stringField(value: unknown, key: string): string | null {\n if (!isRecord(value)) return null;\n const field = value[key];\n return typeof field === \"string\" && field ? field : null;\n}\n\n/**\n * Run an agent end-to-end and resolve with its full text output — the\n * package-level equivalent of the simplest existing host path\n * (`useRunAgent`): accumulate `chunk` text, treat a fatal `error` event or a\n * `failed`/`cancelled` `user_request` completion as a thrown `MatrxRunError`,\n * and fall back to the completion's `result.output` when no text streamed.\n *\n * The caller still owns the conversation-start triple on `request` — a\n * one-shot run typically uses `newEphemeralConversationStart()`.\n */\nexport async function runAgentToCompletion(\n transport: MatrxTransport,\n agentId: string,\n request: MatrxAgentStartRequest,\n options: RunAgentToCompletionOptions = {},\n): Promise<MatrxCompletedRun> {\n const handle = await startAgentRun(transport, agentId, request, options);\n\n let text = \"\";\n let completion: Record<string, unknown> | null = null;\n let failure: MatrxRunError | null = null;\n\n for await (const envelope of handle.events) {\n options.onEvent?.(envelope);\n\n if (envelope.event === \"chunk\") {\n const chunk = stringField(envelope.data, \"text\");\n if (chunk !== null) {\n text += chunk;\n options.onChunk?.(text);\n }\n continue;\n }\n\n if (envelope.event === \"error\" && failure === null) {\n const payload = isRecord(envelope.data) ? envelope.data : null;\n failure = new MatrxRunError({\n message: streamErrorText(payload) ?? \"The agent run failed\",\n errorPayload: payload,\n partialText: text,\n });\n continue;\n }\n\n if (envelope.event !== \"completion\" || !isRecord(envelope.data)) continue;\n // `init`/`completion` pairs exist for five operations; the terminal\n // outcome of the run is the `user_request` completion (STREAM-CONTRACT\n // §3.2 — always present, always last).\n if (envelope.data.operation !== \"user_request\") continue;\n\n completion = envelope.data;\n const status = envelope.data.status;\n if ((status === \"failed\" || status === \"cancelled\") && failure === null) {\n const result = isRecord(envelope.data.result) ? envelope.data.result : null;\n failure = new MatrxRunError({\n message:\n stringField(result, \"error\") ??\n stringField(result, \"user_message\") ??\n `The agent run ${status}`,\n completionStatus: status,\n partialText: text,\n });\n }\n }\n\n if (failure) throw failure;\n\n if (!text && completion) {\n const result = completion.result;\n const output = stringField(result, \"output\");\n if (output !== null) text = output;\n }\n\n return {\n text,\n requestId: handle.requestId,\n conversationId: handle.conversationId,\n completion,\n };\n}\n"],"mappings":";;;;AAEA,YAAY,WAAW;AAMvB;AAAA,EACE;AAAA,OAEK;;;ACTP;AAAA,EACE;AAAA,EACA;AAAA,OAGK;;;ACsBA,IAAM,eAAe;AAAA,EAC1B,y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M,QAAQ;AAAA,QAC3B;AAAA,QACA,eAAe;AAAA,QACf,CAAC,aAAa;AACZ,cAAI,gBAAgB,UAAW,cAAa,QAAQ;AAAA,QACtD;AAAA,QACA;AAAA,MACF;AACA,UAAI,gBAAgB;AAClB,cAAM,IAAI,MAAM,yDAAyD;AAC3E,yBAAmB,OAAO,YAAY;AACtC,wBAAkB,iBAAiB;AACnC,UAAI,OAAO,WAAW,eAAe,CAAC,OAAO;AAC3C,cAAM,IAAI;AAAA,UACR,OAAO,WAAW;AAAA,QACpB;AACF,aAAO,OAAO;AAAA,IAChB;AAAA,IACA,MAAM,SAAS;AACb,YAAM,YACJ,oBACC,iBAAiB,MAAM,eAAe,UAAU;AACnD,UAAI,CAAC;AACH,cAAM,IAAI;AAAA,UACR;AAAA,QACF;AACF,YAAM,QAAQ,OAAO,SAAS;AAAA,IAChC;AAAA,EACF;AACA,SAAO;AACT;AAOO,SAAS,6BAA6B;AAAA,EAC3C;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAG;AACL,GAAsC;AACpC,QAAM,KAAW;AAAA,IACf,MAAM,gBAAgB,SAAS,UAAU;AAAA,IACzC;AAAA,MACE,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SACE,oBAAC,uCAAoC,OAAO,EAAE,GAAG,cAAc,GAAG,GAC/D,UACH;AAEJ;","names":["isRecord","resolve","signal","resolve"]}
|
|
1
|
+
{"version":3,"sources":["../../../content-transfer/react/index.tsx","../../../content-transfer/index.ts","../../../mandates/keys.generated.ts","../../../mandates/index.ts","../../../matrx/transport.ts","../../../stream/ndjson.ts","../../../matrx/conversation.ts","../../../matrx/internal.ts","../../../stream/sse.ts","../../../matrx/operations.ts","../../../matrx/run.ts"],"sourcesContent":["\"use client\";\n\nimport * as React from \"react\";\nimport type {\n AiPreparation,\n Draft,\n Snapshot,\n} from \"@ai-matrx/kit/content-transfer\";\nimport {\n ContentTransferCapabilitiesProvider,\n type ContentTransferCapabilities,\n} from \"@ai-matrx/design-system/content-transfer\";\nimport {\n createMatrxContentTransferAdapter,\n type MatrxContentTransferAdapterOptions,\n type MatrxContentTransferIdentity,\n type MatrxContentTransferProgress,\n} from \"..\";\n\nexport interface MatrxContentTransferProviderProps\n extends MatrxContentTransferAdapterOptions {\n children: React.ReactNode;\n capabilities?: Omit<ContentTransferCapabilities, \"ai\">;\n /** Persist identifiers in the host's canonical live-run window. Never persist draft content here. */\n onProgress?: (progress: MatrxContentTransferProgress) => void;\n}\nfunction createAiSession(\n options: MatrxContentTransferAdapterOptions,\n onProgress?: (progress: MatrxContentTransferProgress) => void,\n): AiPreparation {\n const adapter = createMatrxContentTransferAdapter(options);\n let retainedIdentity: MatrxContentTransferIdentity | null = null;\n let retainedSource: {\n snapshot: Snapshot;\n draft: Draft;\n } | null = null;\n let activeRequestId: string | null = null;\n let latestRun = 0;\n let pendingRequest: {\n promise: Promise<string | null>;\n resolve: (requestId: string | null) => void;\n } | null = null;\n\n const session: AiPreparation = {\n supports: (_snapshot: Snapshot) => true,\n fork: () => createAiSession(options, onProgress),\n async run({ snapshot, draft, instruction, signal }) {\n const run = ++latestRun;\n activeRequestId = null;\n retainedIdentity = null;\n retainedSource = Object.freeze({ snapshot, draft });\n let resolveRequest!: (requestId: string | null) => void;\n const request = {\n promise: new Promise<string | null>((resolve) => {\n resolveRequest = resolve;\n }),\n resolve: resolveRequest,\n };\n pendingRequest = request;\n try {\n const result = await adapter.launch({\n snapshot,\n draft,\n instruction,\n signal,\n onProgress: (progress) => {\n if (run !== latestRun) return;\n onProgress?.(progress);\n if (!progress.requestId) return;\n activeRequestId = progress.requestId;\n request.resolve(progress.requestId);\n retainedIdentity = Object.freeze({\n requestId: progress.requestId,\n conversationId: progress.conversationId,\n executionId: progress.executionId,\n snapshotId: snapshot.id,\n sourceId: draft.sourceId,\n sourceRevision: draft.sourceRevision,\n draftRevision: draft.revision,\n });\n },\n });\n if (run === latestRun) {\n retainedIdentity = result.identity ?? retainedIdentity;\n activeRequestId = result.identity?.requestId ?? activeRequestId;\n request.resolve(activeRequestId);\n }\n if (result.status !== \"completed\" || !result.draft)\n throw new Error(\n result.message || \"AI preparation did not return a draft.\",\n );\n return result.draft;\n } finally {\n request.resolve(null);\n if (run === latestRun && pendingRequest === request) {\n pendingRequest = null;\n }\n }\n },\n async recover({ snapshot, draft, signal }) {\n const recoveryRun = ++latestRun;\n if (!retainedIdentity)\n throw new Error(\n \"No recoverable AI preparation exists in this workspace session.\",\n );\n if (\n !retainedSource ||\n retainedIdentity.snapshotId !== snapshot.id ||\n retainedSource.snapshot.id !== snapshot.id ||\n retainedSource.draft.snapshotId !== draft.snapshotId ||\n retainedSource.draft.sourceId !== draft.sourceId ||\n retainedSource.draft.sourceRevision !== draft.sourceRevision ||\n retainedSource.draft.revision !== draft.revision\n ) {\n throw new Error(\n \"The recoverable AI preparation belongs to a different source draft.\",\n );\n }\n const result = await adapter.rejoin(\n retainedIdentity,\n retainedSource.draft,\n (progress) => {\n if (recoveryRun === latestRun) onProgress?.(progress);\n },\n signal,\n );\n if (recoveryRun !== latestRun)\n throw new Error(\"A newer AI preparation started before recovery settled.\");\n retainedIdentity = result.identity ?? retainedIdentity;\n activeRequestId = retainedIdentity.requestId;\n if (result.status !== \"completed\" || !result.draft)\n throw new Error(\n result.message || \"AI preparation recovery did not return a draft.\",\n );\n return result.draft;\n },\n async cancel() {\n const requestId =\n activeRequestId ??\n (pendingRequest ? await pendingRequest.promise : null);\n if (!requestId)\n throw new Error(\n \"The current AI preparation ended before the server returned a request ID; no server cancellation was reported.\",\n );\n await adapter.cancel(requestId);\n },\n };\n return session;\n}\n\n/**\n * Composes the package-owned durable Matrx adapter into the design-system's\n * nearest capability context. Surface identity remains the design-system's\n * explicit local handle; this provider never performs global surface lookup.\n */\nexport function MatrxContentTransferProvider({\n children,\n capabilities,\n onProgress,\n ...options\n}: MatrxContentTransferProviderProps) {\n const ai = React.useMemo<AiPreparation>(\n () => createAiSession(options, onProgress),\n [\n options.transport,\n options.supabase,\n options.organizationId,\n options.sourceApp,\n options.onStreamEvent,\n options.onRuntimeEvent,\n onProgress,\n ],\n );\n return (\n <ContentTransferCapabilitiesProvider value={{ ...capabilities, ai }}>\n {children}\n </ContentTransferCapabilitiesProvider>\n );\n}\n","/** Matrx's durable AI capability for Alchemy Content Transfer. */\nexport * from \"./destinations\";\nimport {\n editDraft,\n serialize,\n type Draft,\n type Snapshot,\n} from \"@ai-matrx/kit/content-transfer\";\nimport type { MatrxStreamEnvelope } from \"../stream/ndjson\";\nimport { MANDATE_KEYS } from \"../mandates\";\nimport {\n cancelAgentRun,\n followRuntimeOperationToEnd,\n getRuntimeOperationStatus,\n newStoredConversationStart,\n rejoinRuntimeOperation,\n startMandateRun,\n MatrxApiError,\n type MatrxRuntimeExecutionStatus,\n type MatrxRuntimeOperationEvent,\n type MatrxTransport,\n} from \"../matrx\";\n\nexport type MatrxContentTransferStatus =\n \"completed\" | \"failed\" | \"cancelled\" | \"detached\" | \"unavailable\";\nexport interface MatrxContentTransferIdentity {\n requestId: string;\n conversationId: string;\n executionId: string | null;\n snapshotId: string;\n sourceId: string;\n sourceRevision: string;\n draftRevision: number;\n}\nexport interface MatrxContentTransferProgress {\n requestId: string | null;\n conversationId: string;\n executionId: string | null;\n status: \"starting\" | \"streaming\" | MatrxRuntimeExecutionStatus | \"detached\";\n}\nexport interface MatrxContentTransferResult {\n status: MatrxContentTransferStatus;\n identity: MatrxContentTransferIdentity | null;\n /** A new draft only; the caller's original draft remains unchanged. */\n draft: Draft | null;\n /** Human-readable reason for an honest partial/failure/cancelled state. */\n message: string | null;\n}\nexport interface MatrxContentTransferDbRow {\n id: string;\n content?: unknown;\n metadata?: unknown;\n iteration?: number | null;\n}\nexport interface MatrxContentTransferDbResponse {\n data: MatrxContentTransferDbRow[] | null;\n error: { message?: string | null } | null;\n}\nexport interface MatrxContentTransferQuery extends PromiseLike<MatrxContentTransferDbResponse> {\n eq(column: string, value: unknown): this;\n is(column: string, value: null): this;\n not(column: string, operator: \"is\", value: null): this;\n order(column: string, options: { ascending: boolean }): this;\n limit(count: number): this;\n}\nexport interface MatrxContentTransferSupabase {\n schema(schema: \"chat\"): {\n from(table: \"request\" | \"message\"): {\n select(columns: string): MatrxContentTransferQuery;\n };\n };\n}\nexport interface MatrxContentTransferAdapterOptions {\n transport: MatrxTransport | (() => MatrxTransport);\n supabase: MatrxContentTransferSupabase;\n organizationId: string | (() => string);\n sourceApp: \"matrx-frontend\" | \"dashboard\";\n /**\n * Interactivity attestation for the preparation run. `launch()` is the\n * Alchemy door a person opens by hand, so \"user\" is the default and the\n * server classes the conversation `origin_class = 'human'`; an embedder that\n * fires a transfer from client code with no gesture behind it passes \"auto\".\n * Omitting the field entirely is what left these runs reading as unattested\n * API traffic (census 2026-09-20).\n */\n initiation?: \"user\" | \"auto\";\n /** The original NDJSON stream, exposed without consuming it twice. */\n onStreamEvent?: (event: MatrxStreamEnvelope) => void;\n /** Durable runtime lifecycle events emitted during recovery. */\n onRuntimeEvent?: (\n event: MatrxRuntimeOperationEvent,\n seq: number | null,\n ) => void;\n}\nexport interface MatrxContentTransferLaunchInput {\n snapshot: Snapshot;\n draft: Draft;\n instruction: string;\n signal?: AbortSignal;\n onProgress?: (progress: MatrxContentTransferProgress) => void;\n}\nclass SupersededRunError extends Error {\n constructor() {\n super(\"A newer AI preparation started before this result settled.\");\n }\n}\nfunction resolve<T>(value: T | (() => T)): T {\n return typeof value === \"function\" ? (value as () => T)() : value;\n}\nfunction deepFreeze<T>(value: T): T {\n if (ArrayBuffer.isView(value)) return value;\n if (value && typeof value === \"object\" && !Object.isFrozen(value)) {\n Object.freeze(value);\n for (const nested of Object.values(value)) deepFreeze(nested);\n }\n return value;\n}\nfunction isDeepFrozen(value: unknown, seen = new WeakSet<object>()): boolean {\n if (!value || typeof value !== \"object\" || ArrayBuffer.isView(value))\n return true;\n if (seen.has(value)) return true;\n seen.add(value);\n return (\n Object.isFrozen(value) &&\n Object.values(value).every((nested) => isDeepFrozen(nested, seen))\n );\n}\nfunction descriptionForCoverage(snapshot: Snapshot, draft: Draft): string {\n const { coverage } = snapshot;\n const total =\n coverage.total === null ? \"unknown total\" : `${coverage.total} total`;\n const offered =\n draft.payload.kind === \"rows\"\n ? `${draft.payload.rows.length} prepared rows`\n : \"one prepared document\";\n return `snapshot ${coverage.status}: ${coverage.included} included, ${total}; offered ${offered} from ${draft.sourceId}@${draft.sourceRevision}, draft revision ${draft.revision}${coverage.reason ? `; ${coverage.reason}` : \"\"}`;\n}\nfunction descriptionForOmissions(draft: Draft): string {\n if (draft.omissions.length === 0)\n return \"No pre-AI exclusions or reductions were recorded in this prepared draft.\";\n return draft.omissions\n .map(\n (o) =>\n `${o.path || \"document\"}: ${o.reason}${o.count === undefined ? \"\" : ` (${o.count})`}`,\n )\n .join(\"; \");\n}\n/**\n * The mapped-only offered values of `alchemy.prepared_content` (server\n * `client_mandates.py`), built from facts this launch already holds. Sent by\n * name beside the four by-name values; the mandate door drops them unless a\n * binding's consumption map names one, so no current Holder's payload changes.\n * Absent facts are omitted, never sent empty.\n */\nexport function preparedContentOfferedValues(\n snapshot: Snapshot,\n draft: Draft,\n): Record<string, string | number | boolean | string[]> {\n const { coverage } = snapshot;\n const values: Record<string, string | number | boolean | string[]> = {\n coverage_status: coverage.status,\n included_count: coverage.included,\n payload_kind: draft.payload.kind,\n omission_count: draft.omissions.length,\n has_unsaved_changes: snapshot.unsavedChanges,\n manually_edited: draft.manuallyEdited,\n };\n if (coverage.total !== null) values.total_count = coverage.total;\n if (coverage.unit) values.coverage_unit = coverage.unit;\n if (coverage.reason) values.coverage_reason = coverage.reason;\n if (draft.payload.kind === \"rows\") {\n values.row_count = draft.payload.rows.length;\n const labels = draft.payload.columns\n .filter((column) => column.visible)\n .map((column) => column.label);\n if (labels.length > 0) values.column_labels = labels;\n }\n if (draft.omissions.length > 0)\n values.omission_reasons = draft.omissions.map((o) => o.reason);\n const sections = snapshot.sections.map((section) => section.label);\n if (sections.length > 0) values.section_labels = sections;\n if (snapshot.capturedAt) values.captured_at = snapshot.capturedAt;\n return values;\n}\nfunction visibleAssistantText(content: unknown): string | null {\n if (typeof content === \"string\") return content.trim() || null;\n if (!Array.isArray(content)) return null;\n const parts = content.flatMap((part) => {\n if (!part || typeof part !== \"object\" || Array.isArray(part)) return [];\n const block = part as { type?: unknown; text?: unknown };\n return block.type === \"text\" && typeof block.text === \"string\"\n ? [block.text]\n : [];\n });\n return parts.join(\"\\n\\n\").trim() || null;\n}\nfunction responseMessageId(metadata: unknown): string | null {\n if (!metadata || typeof metadata !== \"object\" || Array.isArray(metadata))\n return null;\n const value = (metadata as { response_message_id?: unknown })\n .response_message_id;\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\nfunction draftFromAssistant(\n source: Draft,\n text: string,\n identity: MatrxContentTransferIdentity,\n): Draft {\n const edited = editDraft(source, { kind: \"markdown\", text });\n const reducedBy =\n serialize(source, \"markdown\").plainText.length - text.length;\n return deepFreeze({\n ...edited,\n manuallyEdited: source.manuallyEdited,\n omissions: [\n ...edited.omissions,\n ...(reducedBy > 0\n ? [\n {\n path: \"/ai/content\",\n reason: \"truncated\" as const,\n count: reducedBy,\n },\n ]\n : []),\n ],\n provenance: [\n ...edited.provenance.slice(0, -1),\n {\n kind: \"ai\" as const,\n operationId: identity.requestId,\n description: `AI preparation of ${source.sourceId}@${source.sourceRevision}; source omissions remain separately recorded.`,\n },\n ],\n });\n}\nfunction assertCoherent(snapshot: Snapshot, draft: Draft): void {\n if (!isDeepFrozen(snapshot) || !isDeepFrozen(draft))\n throw new Error(\n \"Alchemy requires the deeply frozen Snapshot and Draft produced by @ai-matrx/kit/content-transfer.\",\n );\n if (\n draft.snapshotId !== snapshot.id ||\n draft.sourceId !== snapshot.sourceId ||\n draft.sourceRevision !== snapshot.revision\n )\n throw new Error(\n \"The prepared draft does not belong to this captured snapshot.\",\n );\n}\nfunction assertIdentitySource(\n identity: MatrxContentTransferIdentity,\n source: Draft,\n): void {\n if (!isDeepFrozen(source))\n throw new Error(\n \"Alchemy recovery requires the deeply frozen Draft produced by @ai-matrx/kit/content-transfer.\",\n );\n if (\n identity.snapshotId !== source.snapshotId ||\n identity.sourceId !== source.sourceId ||\n identity.sourceRevision !== source.sourceRevision ||\n identity.draftRevision !== source.revision\n ) {\n throw new Error(\n \"The recovery identity does not belong to this frozen prepared draft.\",\n );\n }\n}\nfunction errorMessage(error: unknown): string {\n return error instanceof Error && error.message\n ? error.message\n : \"Unknown stream failure.\";\n}\nfunction detached(\n identity: MatrxContentTransferIdentity,\n message: string,\n): MatrxContentTransferResult {\n return { status: \"detached\", identity, draft: null, message };\n}\nasync function consume(\n handle: Awaited<ReturnType<typeof startMandateRun>>,\n afterAwait: () => void,\n onEvent?: (event: MatrxStreamEnvelope) => void,\n): Promise<void> {\n for await (const event of handle.events) {\n afterAwait();\n onEvent?.(event);\n }\n afterAwait();\n}\n\n/** One monotonic generation fences every public launch/recover/rejoin. */\nexport function createMatrxContentTransferAdapter(\n options: MatrxContentTransferAdapterOptions,\n) {\n let latestGeneration = 0;\n const transport = () => resolve(options.transport);\n const organizationId = () => resolve(options.organizationId);\n let activeGeneration: AbortController | null = null;\n const inGeneration = async <T>(\n outer: AbortSignal | undefined,\n run: (generation: number, signal: AbortSignal) => Promise<T>,\n ): Promise<T> => {\n activeGeneration?.abort();\n const controller = new AbortController();\n activeGeneration = controller;\n const generation = ++latestGeneration;\n const abort = () => controller.abort(outer?.reason);\n if (outer?.aborted) abort();\n else outer?.addEventListener(\"abort\", abort, { once: true });\n try {\n return await run(generation, controller.signal);\n } finally {\n outer?.removeEventListener(\"abort\", abort);\n if (activeGeneration === controller) activeGeneration = null;\n }\n };\n const check = (generation: number) => {\n if (generation !== latestGeneration) throw new SupersededRunError();\n activeGeneration?.signal.throwIfAborted();\n };\n\n const readVisibleAssistant = async (\n identity: MatrxContentTransferIdentity,\n generation: number,\n ): Promise<string | null> => {\n const requestResult = await options.supabase\n .schema(\"chat\")\n .from(\"request\")\n .select(\"id, metadata, iteration\")\n .eq(\"user_request_id\", identity.requestId)\n .eq(\"conversation_id\", identity.conversationId)\n .is(\"deleted_at\", null)\n .not(\"metadata->>response_message_id\", \"is\", null)\n .order(\"iteration\", { ascending: false })\n .limit(1);\n check(generation);\n if (requestResult.error)\n throw new Error(\n requestResult.error.message ||\n \"Could not read the persisted AI request.\",\n );\n const messageId = responseMessageId(requestResult.data?.[0]?.metadata);\n if (!messageId)\n throw new Error(\n \"The completed AI request has no persisted response message link yet.\",\n );\n const messageResult = await options.supabase\n .schema(\"chat\")\n .from(\"message\")\n .select(\"id, content\")\n .eq(\"id\", messageId)\n .eq(\"conversation_id\", identity.conversationId)\n .eq(\"role\", \"assistant\")\n .is(\"deleted_at\", null)\n .eq(\"is_visible_to_user\", true)\n .limit(1);\n check(generation);\n if (messageResult.error)\n throw new Error(\n messageResult.error.message || \"Could not read the prepared AI result.\",\n );\n const exact = messageResult.data?.find((row) => row.id === messageId);\n return exact ? visibleAssistantText(exact.content) : null;\n };\n\n const locate = async (\n identity: MatrxContentTransferIdentity,\n generation: number,\n signal?: AbortSignal,\n ) => {\n const result = await getRuntimeOperationStatus(\n transport(),\n identity.requestId,\n signal ? { signal } : {},\n );\n check(generation);\n const exact =\n result?.operations.find(\n (operation) =>\n operation.request_id === identity.requestId &&\n operation.link_kind === \"conversation\" &&\n operation.link_id === identity.conversationId,\n ) ?? null;\n if (!exact && result?.operation_count)\n throw new Error(\n \"The durable operation identity does not match this stored conversation.\",\n );\n return exact;\n };\n\n const recoverInGeneration = async (\n generation: number,\n identity: MatrxContentTransferIdentity,\n source: Draft,\n onProgress?: MatrxContentTransferLaunchInput[\"onProgress\"],\n signal?: AbortSignal,\n ): Promise<MatrxContentTransferResult> => {\n try {\n assertIdentitySource(identity, source);\n check(generation);\n let operation = await locate(identity, generation, signal);\n if (!operation)\n return {\n status: \"unavailable\",\n identity,\n draft: null,\n message:\n \"The durable operation is not available to this account yet.\",\n };\n let resolvedIdentity = deepFreeze({\n ...identity,\n executionId: operation.execution_id,\n });\n if (!operation.is_terminal) {\n onProgress?.({ ...resolvedIdentity, status: operation.status });\n const settled = await followRuntimeOperationToEnd(\n transport(),\n operation.execution_id,\n {\n ...(signal ? { signal } : {}),\n lastEventSeq: operation.last_event_seq,\n onEvent: (event, seq) => {\n // Supersession already aborts the local follower. Never throw\n // from this callback into the runtime reconnect retry policy.\n if (generation !== latestGeneration || signal?.aborted) return;\n options.onRuntimeEvent?.(event, seq);\n },\n },\n );\n check(generation);\n if (!settled.ended || settled.status === null)\n return detached(\n resolvedIdentity,\n \"The lifecycle stream detached; the operation remains recoverable from this request.\",\n );\n const refreshed = await locate(identity, generation, signal);\n if (!refreshed)\n return detached(\n resolvedIdentity,\n \"The settled operation is temporarily unavailable; retry recovery with this request.\",\n );\n operation = refreshed;\n resolvedIdentity = deepFreeze({\n ...identity,\n executionId: operation.execution_id,\n });\n }\n onProgress?.({ ...resolvedIdentity, status: operation.status });\n if (operation.status === \"cancelled\")\n return {\n status: \"cancelled\",\n identity: resolvedIdentity,\n draft: null,\n message:\n \"The AI preparation was cancelled. Any partial output was not applied.\",\n };\n if (operation.status !== \"completed\")\n return {\n status: \"failed\",\n identity: resolvedIdentity,\n draft: null,\n message:\n typeof operation.error?.message === \"string\"\n ? operation.error.message\n : \"The AI preparation did not complete.\",\n };\n const text = await readVisibleAssistant(resolvedIdentity, generation);\n check(generation);\n if (!text)\n return {\n status: \"unavailable\",\n identity: resolvedIdentity,\n draft: null,\n message: \"The exact persisted assistant result is not visible yet.\",\n };\n const draft = draftFromAssistant(source, text, resolvedIdentity);\n check(generation);\n return {\n status: \"completed\",\n identity: resolvedIdentity,\n draft,\n message: null,\n };\n } catch (error) {\n return detached(\n identity,\n error instanceof SupersededRunError\n ? error.message\n : `Recovery detached: ${errorMessage(error)} You can retry with this request.`,\n );\n }\n };\n\n return {\n async launch(\n input: MatrxContentTransferLaunchInput,\n ): Promise<MatrxContentTransferResult> {\n return inGeneration(input.signal, async (generation, signal) => {\n assertCoherent(input.snapshot, input.draft);\n const conversation = newStoredConversationStart();\n input.onProgress?.({\n requestId: null,\n conversationId: conversation.conversation_id,\n executionId: null,\n status: \"starting\",\n });\n const preparedContent = serialize(input.draft, \"markdown\").plainText;\n let identity: MatrxContentTransferIdentity | null = null;\n try {\n const handle = await startMandateRun(\n transport(),\n MANDATE_KEYS.alchemy__prepare_content,\n {\n ...conversation,\n organization_id: organizationId(),\n source_app: options.sourceApp,\n source_feature: `mandate:${MANDATE_KEYS.alchemy__prepare_content}`,\n initiation: options.initiation ?? \"user\",\n user_input: input.instruction,\n variables: {\n prepared_content: preparedContent,\n content_label: input.snapshot.label,\n coverage_description: descriptionForCoverage(\n input.snapshot,\n input.draft,\n ),\n omission_description: descriptionForOmissions(input.draft),\n ...preparedContentOfferedValues(input.snapshot, input.draft),\n },\n },\n { signal },\n );\n if (!handle.requestId)\n throw new Error(\n \"The Matrx server did not return X-Request-ID for the preparation run.\",\n );\n identity = deepFreeze({\n requestId: handle.requestId,\n conversationId:\n handle.conversationId ?? conversation.conversation_id,\n executionId: null,\n snapshotId: input.snapshot.id,\n sourceId: input.draft.sourceId,\n sourceRevision: input.draft.sourceRevision,\n draftRevision: input.draft.revision,\n });\n assertIdentitySource(identity, input.draft);\n check(generation);\n input.onProgress?.({ ...identity, status: \"streaming\" });\n await consume(handle, () => check(generation), options.onStreamEvent);\n check(generation);\n const result = await recoverInGeneration(\n generation,\n identity,\n input.draft,\n input.onProgress,\n signal,\n );\n check(generation);\n return result;\n } catch (error) {\n if (!identity) throw error;\n return detached(\n identity,\n error instanceof SupersededRunError\n ? error.message\n : `The local stream detached after the server accepted the request: ${errorMessage(error)} Server work was not cancelled; retry recovery with this request.`,\n );\n }\n });\n },\n async recover(\n identity: MatrxContentTransferIdentity,\n source: Draft,\n onProgress?: MatrxContentTransferLaunchInput[\"onProgress\"],\n signal?: AbortSignal,\n ) {\n return inGeneration(signal, async (generation, signal) => {\n assertIdentitySource(identity, source);\n const result = await recoverInGeneration(\n generation,\n identity,\n source,\n onProgress,\n signal,\n );\n return generation === latestGeneration\n ? result\n : detached(\n identity,\n \"A newer AI preparation started before this result settled.\",\n );\n });\n },\n async rejoin(\n identity: MatrxContentTransferIdentity,\n source: Draft,\n onProgress?: MatrxContentTransferLaunchInput[\"onProgress\"],\n signal?: AbortSignal,\n ) {\n return inGeneration(signal, async (generation, signal) => {\n assertIdentitySource(identity, source);\n try {\n const handle = await rejoinRuntimeOperation(\n transport(),\n identity.requestId,\n signal ? { signal } : {},\n );\n check(generation);\n await consume(handle, () => check(generation), options.onStreamEvent);\n check(generation);\n } catch (error) {\n if (!(error instanceof MatrxApiError && error.status === 409))\n return detached(\n identity,\n error instanceof SupersededRunError\n ? error.message\n : `Live rejoin detached: ${errorMessage(error)} You can retry durable recovery with this request.`,\n );\n }\n const result = await recoverInGeneration(\n generation,\n identity,\n source,\n onProgress,\n signal,\n );\n return generation === latestGeneration\n ? result\n : detached(\n identity,\n \"A newer AI preparation started before this result settled.\",\n );\n });\n },\n cancel(requestId: string) {\n return cancelAgentRun(transport(), requestId);\n },\n };\n}\nexport type MatrxContentTransferAdapter = ReturnType<\n typeof createMatrxContentTransferAdapter\n>;\n\nexport * from \"./destination-ports\";\n","/**\n * GENERATED — DO NOT EDIT. Regenerate with:\n * uv run python scripts/mandates_generate.py (aidream repo; --dry-run also writes this file)\n *\n * THE ONE GENERATOR (`aidream/scripts/mandates_generate.py`, stage (h)) emits this\n * from the IN-PROCESS mandate declarations — the same `declared_mandates()` the\n * boot sync writes to the database from. There is no hand list anywhere.\n *\n * aidream revision: 175728de96b6149b94e048a4968ae36f3d87ee65\n * generator version: 1.0.0\n * package version: 0.41.1\n * active keys: 544\n * retiring keys: 0\n *\n * THE IDENTIFIER RULE: every `.` in a key becomes `__`, any character outside\n * [A-Za-z0-9_] becomes `_`, a leading digit gets an `_` prefix. So\n * `seo.keyword_classifier` is `MANDATE_KEYS.seo__keyword_classifier`. Collisions are a\n * fatal generator error, never a silently dropped key.\n */\n\n/** Where this module came from — surfaced so a report can name the exact build. */\nexport const MANDATE_KEYS_META = {\n aidreamRevision: \"175728de96b6149b94e048a4968ae36f3d87ee65\",\n generatorVersion: \"1.0.0\",\n packageVersion: \"0.41.1\",\n retireWindow: 3,\n} as const;\n\n/** Every declared mandate key, by THE IDENTIFIER RULE. */\nexport const MANDATE_KEYS = {\n agent_apps__auto_create: \"agent_apps.auto_create\",\n agent_apps__auto_create_lightning: \"agent_apps.auto_create_lightning\",\n agent_apps__metadata: \"agent_apps.metadata\",\n agent_apps__prompt_app_dev: \"agent_apps.prompt_app_dev\",\n agent_factory__structure_builder: \"agent_factory.structure_builder\",\n alchemy__prepare_content: \"alchemy.prepare_content\",\n ambient__page_guidance: \"ambient.page_guidance\",\n ambient__spoken_summary: \"ambient.spoken_summary\",\n audio__live_music: \"audio.live_music\",\n audio__speech: \"audio.speech\",\n brand__voice_rewrite: \"brand.voice_rewrite\",\n chat__cx_default: \"chat.cx_default\",\n chat__default_new_chat: \"chat.default_new_chat\",\n chat__quick_audio_plan: \"chat.quick_audio_plan\",\n chat__quick_fair_news: \"chat.quick_fair_news\",\n chat__quick_flashcards: \"chat.quick_flashcards\",\n chat__quick_image: \"chat.quick_image\",\n chat__quick_org_chart: \"chat.quick_org_chart\",\n chat__quick_research: \"chat.quick_research\",\n chat__quick_showcase: \"chat.quick_showcase\",\n chat__quick_writing_partner: \"chat.quick_writing_partner\",\n chat__response_mode_brainstorm: \"chat.response_mode_brainstorm\",\n chat__response_mode_data: \"chat.response_mode_data\",\n chat__response_mode_research: \"chat.response_mode_research\",\n chat__response_mode_video: \"chat.response_mode_video\",\n checks__cleanup_bakeoff__answer: \"checks.cleanup_bakeoff.answer\",\n checks__cleanup_bakeoff__judge: \"checks.cleanup_bakeoff.judge\",\n checks__finding_disposition: \"checks.finding_disposition\",\n checks__finding_disposition_review: \"checks.finding_disposition_review\",\n cms__content_writing: \"cms.content_writing\",\n cms__publish_review: \"cms.publish_review\",\n cms__seo_metadata: \"cms.seo_metadata\",\n cms__site_editing: \"cms.site_editing\",\n cms__theme_design: \"cms.theme_design\",\n code_editor__code_edit: \"code_editor.code_edit\",\n code_editor__dynamic_context_edit: \"code_editor.dynamic_context_edit\",\n code_editor__prompt_app_ui_edit: \"code_editor.prompt_app_ui_edit\",\n coding_session__conversation_responder: \"coding_session.conversation_responder\",\n coding_session__managed_translation_reference: \"coding_session.managed_translation_reference\",\n commerce_intake__assess_value: \"commerce_intake.assess_value\",\n commerce_intake__extract_vision: \"commerce_intake.extract_vision\",\n commerce_intake__grading: \"commerce_intake.grading\",\n commerce_intake__instant_analysis: \"commerce_intake.instant_analysis\",\n commerce_intake__refute_no_value: \"commerce_intake.refute_no_value\",\n commerce_intake__research_product: \"commerce_intake.research_product\",\n commerce_intake__segment_photos: \"commerce_intake.segment_photos\",\n commerce_intake__verify_enrichment: \"commerce_intake.verify_enrichment\",\n content_gate__section_relevance_decision: \"content_gate.section_relevance_decision\",\n content_ir__component_artisan: \"content_ir.component_artisan\",\n content_ir__kind_architect: \"content_ir.kind_architect\",\n content_ir__kind_component_builder: \"content_ir.kind_component_builder\",\n content_ir__kind_creator: \"content_ir.kind_creator\",\n content_plan__branch_purpose: \"content_plan.branch_purpose\",\n content_plan__brief_writer: \"content_plan.brief_writer\",\n content_plan__deepen_page: \"content_plan.deepen_page\",\n content_plan__entity_attacher: \"content_plan.entity_attacher\",\n content_plan__entity_curator: \"content_plan.entity_curator\",\n content_plan__family_namer: \"content_plan.family_namer\",\n content_plan__keyword_strategist: \"content_plan.keyword_strategist\",\n content_plan__merge_wave: \"content_plan.merge_wave\",\n content_plan__p3_family: \"content_plan.p3_family\",\n content_plan__p4_write: \"content_plan.p4_write\",\n content_plan__p5_review: \"content_plan.p5_review\",\n content_plan__p6_build: \"content_plan.p6_build\",\n content_plan__p6_build__about: \"content_plan.p6_build.about\",\n content_plan__p6_build__blog: \"content_plan.p6_build.blog\",\n content_plan__p6_build__comparison: \"content_plan.p6_build.comparison\",\n content_plan__p6_build__contact: \"content_plan.p6_build.contact\",\n content_plan__p6_build__faq: \"content_plan.p6_build.faq\",\n content_plan__p6_build__guide: \"content_plan.p6_build.guide\",\n content_plan__p6_build__home: \"content_plan.p6_build.home\",\n content_plan__p6_build__index: \"content_plan.p6_build.index\",\n content_plan__p6_build__location: \"content_plan.p6_build.location\",\n content_plan__p6_build__pillar: \"content_plan.p6_build.pillar\",\n content_plan__p6_build__pricing: \"content_plan.p6_build.pricing\",\n content_plan__p6_build__service: \"content_plan.p6_build.service\",\n content_plan__plan_reviewer: \"content_plan.plan_reviewer\",\n content_plan__research_wave__audience_journey: \"content_plan.research_wave.audience_journey\",\n content_plan__research_wave__competitor_coverage: \"content_plan.research_wave.competitor_coverage\",\n content_plan__research_wave__keyword_value: \"content_plan.research_wave.keyword_value\",\n content_plan__route_picker: \"content_plan.route_picker\",\n content_plan__shape_planner: \"content_plan.shape_planner\",\n conversation__action_auditor: \"conversation.action_auditor\",\n conversation__decision_ledger: \"conversation.decision_ledger\",\n conversation__drift_auditor: \"conversation.drift_auditor\",\n conversation__label_agent_run: \"conversation.label_agent_run\",\n conversation__label_chat: \"conversation.label_chat\",\n conversation__outcome_summarizer: \"conversation.outcome_summarizer\",\n conversation__vision_extractor: \"conversation.vision_extractor\",\n conversation__vision_interviewer: \"conversation.vision_interviewer\",\n crm__journalist_beat_analyst: \"crm.journalist_beat_analyst\",\n crm__media_list_ranker: \"crm.media_list_ranker\",\n crm__outreach_draft_reviewer: \"crm.outreach_draft_reviewer\",\n crm__outreach_fact_check: \"crm.outreach_fact_check\",\n crm__outreach_personalization_coach: \"crm.outreach_personalization_coach\",\n crm__outreach_personalization_writer: \"crm.outreach_personalization_writer\",\n crm__outreach_pitch_writer: \"crm.outreach_pitch_writer\",\n crm__outreach_recipient_shortlister: \"crm.outreach_recipient_shortlister\",\n crm__outreach_reply_drafter: \"crm.outreach_reply_drafter\",\n crm__outreach_strategy: \"crm.outreach_strategy\",\n crm__party_kind_judge: \"crm.party_kind_judge\",\n crm__save_contact: \"crm.save_contact\",\n data__formula_writing: \"data.formula_writing\",\n data__page_guidance: \"data.page_guidance\",\n data__row_action: \"data.row_action\",\n dictionary__workspace_guide: \"dictionary.workspace_guide\",\n distillation__timeline_distiller: \"distillation.timeline_distiller\",\n distillation__timeline_unfolder: \"distillation.timeline_unfolder\",\n docproc__content_structure: \"docproc.content_structure\",\n education__admin_guidance: \"education.admin_guidance\",\n education__analytics_narrate: \"education.analytics_narrate\",\n education__audio_study_guidance: \"education.audio_study_guidance\",\n education__card_image_generator: \"education.card_image_generator\",\n education__card_image_prompt_writer: \"education.card_image_prompt_writer\",\n education__card_image_qc_judge: \"education.card_image_qc_judge\",\n education__card_image_web_source: \"education.card_image_web_source\",\n education__classes_guidance: \"education.classes_guidance\",\n education__creator_guidance: \"education.creator_guidance\",\n education__data_guidance: \"education.data_guidance\",\n education__exam_prep_guidance: \"education.exam_prep_guidance\",\n education__family_guidance: \"education.family_guidance\",\n education__fastfire_guidance: \"education.fastfire_guidance\",\n education__features_guidance: \"education.features_guidance\",\n education__flashcards_guidance: \"education.flashcards_guidance\",\n education__game_guidance: \"education.game_guidance\",\n education__grade_handwritten: \"education.grade_handwritten\",\n education__grade_work_guidance: \"education.grade_work_guidance\",\n education__kit_title: \"education.kit_title\",\n education__learn_guidance: \"education.learn_guidance\",\n education__levels_guidance: \"education.levels_guidance\",\n education__library_guidance: \"education.library_guidance\",\n education__media_guidance: \"education.media_guidance\",\n education__memory_generate: \"education.memory_generate\",\n education__memory_guidance: \"education.memory_guidance\",\n education__memory_hint: \"education.memory_hint\",\n education__mind_maps_guidance: \"education.mind_maps_guidance\",\n education__mindmap_generate: \"education.mindmap_generate\",\n education__notes_generate: \"education.notes_generate\",\n education__notes_guidance: \"education.notes_guidance\",\n education__offline_guidance: \"education.offline_guidance\",\n education__page_guidance: \"education.page_guidance\",\n education__plan_generate: \"education.plan_generate\",\n education__planner_guidance: \"education.planner_guidance\",\n education__practice_oral_guidance: \"education.practice_oral_guidance\",\n education__practice_tests_guidance: \"education.practice_tests_guidance\",\n education__progress_guidance: \"education.progress_guidance\",\n education__quiz_deepen_item: \"education.quiz_deepen_item\",\n education__quiz_generate: \"education.quiz_generate\",\n education__quiz_generate_from_source: \"education.quiz_generate_from_source\",\n education__quizzes_guidance: \"education.quizzes_guidance\",\n education__spoken_practice_design: \"education.spoken_practice_design\",\n education__spoken_practice_design_language: \"education.spoken_practice_design_language\",\n education__spoken_practice_grade: \"education.spoken_practice_grade\",\n education__spoken_practice_grade_pronunciation: \"education.spoken_practice_grade_pronunciation\",\n education__spoken_practice_review: \"education.spoken_practice_review\",\n education__start_guidance: \"education.start_guidance\",\n education__study_aids_guidance: \"education.study_aids_guidance\",\n education__study_pack_flashcards: \"education.study_pack_flashcards\",\n education__study_pack_lessons: \"education.study_pack_lessons\",\n education__study_pack_notes: \"education.study_pack_notes\",\n education__study_pack_quiz: \"education.study_pack_quiz\",\n education__study_pack_v2_flashcards: \"education.study_pack_v2_flashcards\",\n education__study_pack_v2_lessons: \"education.study_pack_v2_lessons\",\n education__study_pack_v2_notes: \"education.study_pack_v2_notes\",\n education__study_pack_v2_quiz: \"education.study_pack_v2_quiz\",\n education__subjects_guidance: \"education.subjects_guidance\",\n education__summaries_guidance: \"education.summaries_guidance\",\n education__summarize: \"education.summarize\",\n education__tutor_guidance: \"education.tutor_guidance\",\n education__tutor_message: \"education.tutor_message\",\n education__voice_tutor: \"education.voice_tutor\",\n evaluators__comparative_judge: \"evaluators.comparative_judge\",\n evaluators__rubric_judge: \"evaluators.rubric_judge\",\n extend__browser_chat: \"extend.browser_chat\",\n extend__pattern_from_data: \"extend.pattern_from_data\",\n extend__structured_extractor: \"extend.structured_extractor\",\n feedback__item_triage_decision: \"feedback.item_triage_decision\",\n flashcards__enrich_card: \"flashcards.enrich_card\",\n flashcards__expand_card: \"flashcards.expand_card\",\n flashcards__fix_giveaway_cards: \"flashcards.fix_giveaway_cards\",\n flashcards__generate_cards: \"flashcards.generate_cards\",\n flashcards__generate_from_source: \"flashcards.generate_from_source\",\n flashcards__grade_spoken: \"flashcards.grade_spoken\",\n flashcards__grade_typed_answer: \"flashcards.grade_typed_answer\",\n flashcards__help_live: \"flashcards.help_live\",\n flashcards__helper_tts: \"flashcards.helper_tts\",\n flashcards__make_quiz_items: \"flashcards.make_quiz_items\",\n flashcards__micro_coach: \"flashcards.micro_coach\",\n flashcards__review_batch: \"flashcards.review_batch\",\n flashcards__spoken_front_tts: \"flashcards.spoken_front_tts\",\n flashcards__verify_against_source: \"flashcards.verify_against_source\",\n foundry__planner: \"foundry.planner\",\n google__channel_video_plan: \"google.channel_video_plan\",\n google__desk_work: \"google.desk_work\",\n google__traffic_change_explanation: \"google.traffic_change_explanation\",\n growth_loop__quality_analyze: \"growth_loop.quality_analyze\",\n growth_loop__quality_brief: \"growth_loop.quality_brief\",\n growth_loop__quality_crawl: \"growth_loop.quality_crawl\",\n growth_loop__quality_fill: \"growth_loop.quality_fill\",\n growth_loop__quality_measure: \"growth_loop.quality_measure\",\n growth_loop__quality_plan: \"growth_loop.quality_plan\",\n growth_loop__quality_publish: \"growth_loop.quality_publish\",\n growth_loop__quality_realize: \"growth_loop.quality_realize\",\n growth_loop__quality_research: \"growth_loop.quality_research\",\n growth_loop__quality_serve: \"growth_loop.quality_serve\",\n growth_loop__quality_suggest: \"growth_loop.quality_suggest\",\n growth_loop__quality_writeback: \"growth_loop.quality_writeback\",\n growth_loop__supervisor: \"growth_loop.supervisor\",\n hindsight__crystallizer: \"hindsight.crystallizer\",\n hindsight__replay_judge: \"hindsight.replay_judge\",\n hindsight__reviewer: \"hindsight.reviewer\",\n human_decisions__fallback_decider: \"human_decisions.fallback_decider\",\n image__generate: \"image.generate\",\n image_pipeline__concept: \"image_pipeline.concept\",\n image_pipeline__prompt_write: \"image_pipeline.prompt_write\",\n image_pipeline__qc_judge: \"image_pipeline.qc_judge\",\n iteration__architect: \"iteration.architect\",\n iteration__diagnostic: \"iteration.diagnostic\",\n iteration__root_cause: \"iteration.root_cause\",\n iteration__thinking_display: \"iteration.thinking_display\",\n kg__cluster_namer: \"kg.cluster_namer\",\n kg__ner_extractor: \"kg.ner_extractor\",\n knowledge__document_verifier: \"knowledge.document_verifier\",\n knowledge__qa_generator: \"knowledge.qa_generator\",\n knowledge__section_summarizer: \"knowledge.section_summarizer\",\n local__answer_question: \"local.answer_question\",\n local__chat_persona_brainstorm: \"local.chat_persona_brainstorm\",\n local__chat_persona_code_review: \"local.chat_persona_code_review\",\n local__chat_persona_explain_simply: \"local.chat_persona_explain_simply\",\n local__chat_persona_helpful: \"local.chat_persona_helpful\",\n local__chat_persona_spoken_replies: \"local.chat_persona_spoken_replies\",\n local__chat_persona_summarize: \"local.chat_persona_summarize\",\n local__chat_persona_transcript_polish: \"local.chat_persona_transcript_polish\",\n local__cloud_chat: \"local.cloud_chat\",\n local__cloud_chat_reply: \"local.cloud_chat_reply\",\n local__confidential_chat: \"local.confidential_chat\",\n local__explain_code: \"local.explain_code\",\n local__extract_action_items: \"local.extract_action_items\",\n local__improve_writing: \"local.improve_writing\",\n local__polish_style_action_items: \"local.polish_style_action_items\",\n local__polish_style_bullets: \"local.polish_style_bullets\",\n local__polish_style_custom: \"local.polish_style_custom\",\n local__polish_style_formal: \"local.polish_style_formal\",\n local__polish_style_light_cleanup: \"local.polish_style_light_cleanup\",\n local__polish_style_meeting_notes: \"local.polish_style_meeting_notes\",\n local__polish_style_standard: \"local.polish_style_standard\",\n local__polish_transcript: \"local.polish_transcript\",\n local__raw_completion: \"local.raw_completion\",\n local__summarize_text: \"local.summarize_text\",\n local__tool_calling_chat: \"local.tool_calling_chat\",\n mandate_outcome__goal_clause_extraction: \"mandate_outcome.goal_clause_extraction\",\n mandate_outcome__goal_fitness_decision: \"mandate_outcome.goal_fitness_decision\",\n mandates__holder_draft: \"mandates.holder_draft\",\n marketing__endowment_analysis: \"marketing.endowment_analysis\",\n marketing__endowment_portfolio: \"marketing.endowment_portfolio\",\n marketing__image_prompt: \"marketing.image_prompt\",\n marketing__page_image: \"marketing.page_image\",\n marketing__page_image_all_in_one: \"marketing.page_image_all_in_one\",\n marketing__video_metadata: \"marketing.video_metadata\",\n masterwork__approach_selector: \"masterwork.approach_selector\",\n masterwork__audition_judge: \"masterwork.audition_judge\",\n masterwork__bad_draft: \"masterwork.bad_draft\",\n masterwork__bad_example_probe: \"masterwork.bad_example_probe\",\n masterwork__case_oracle: \"masterwork.case_oracle\",\n masterwork__checkup_auditor: \"masterwork.checkup_auditor\",\n masterwork__coherence_partner: \"masterwork.coherence_partner\",\n masterwork__conductor: \"masterwork.conductor\",\n masterwork__corpus_cleaner: \"masterwork.corpus_cleaner\",\n masterwork__corpus_synthesizer: \"masterwork.corpus_synthesizer\",\n masterwork__counterparty: \"masterwork.counterparty\",\n masterwork__critique_distiller: \"masterwork.critique_distiller\",\n masterwork__draft_triage: \"masterwork.draft_triage\",\n masterwork__drip_distiller: \"masterwork.drip_distiller\",\n masterwork__drip_question: \"masterwork.drip_question\",\n masterwork__elicitation_judge: \"masterwork.elicitation_judge\",\n masterwork__exception_hunter: \"masterwork.exception_hunter\",\n masterwork__exemplar_distiller: \"masterwork.exemplar_distiller\",\n masterwork__faithfulness_judge: \"masterwork.faithfulness_judge\",\n masterwork__intake_designer: \"masterwork.intake_designer\",\n masterwork__markup_distiller: \"masterwork.markup_distiller\",\n masterwork__meeting_scavenger: \"masterwork.meeting_scavenger\",\n masterwork__monologue_distiller: \"masterwork.monologue_distiller\",\n masterwork__outcome_judge: \"masterwork.outcome_judge\",\n masterwork__pairwise_judge: \"masterwork.pairwise_judge\",\n masterwork__prediction_boundary: \"masterwork.prediction_boundary\",\n masterwork__prediction_distiller: \"masterwork.prediction_distiller\",\n masterwork__relationship_auditor: \"masterwork.relationship_auditor\",\n masterwork__rule_improver: \"masterwork.rule_improver\",\n masterwork__rulebook_auditor: \"masterwork.rulebook_auditor\",\n masterwork__scout: \"masterwork.scout\",\n masterwork__sealed_case_oracle: \"masterwork.sealed_case_oracle\",\n masterwork__sort_case_writer: \"masterwork.sort_case_writer\",\n masterwork__sort_distiller: \"masterwork.sort_distiller\",\n masterwork__source_distiller: \"masterwork.source_distiller\",\n masterwork__teach_back_distiller: \"masterwork.teach_back_distiller\",\n masterwork__teach_back_explainer: \"masterwork.teach_back_explainer\",\n masterwork__template__chief_edit: \"masterwork.template.chief_edit\",\n masterwork__template__chief_generate: \"masterwork.template.chief_generate\",\n masterwork__template__editor: \"masterwork.template.editor\",\n masterwork__template__maker: \"masterwork.template.maker\",\n masterwork__timeline_distiller: \"masterwork.timeline_distiller\",\n masterwork__timeline_segmenter: \"masterwork.timeline_segmenter\",\n masterwork__transcript_distiller: \"masterwork.transcript_distiller\",\n masterwork__transcript_shortlister: \"masterwork.transcript_shortlister\",\n masterwork__triad_distiller: \"masterwork.triad_distiller\",\n masterwork__triad_generator: \"masterwork.triad_generator\",\n masterwork__understudy: \"masterwork.understudy\",\n masterwork__unfolding_judge: \"masterwork.unfolding_judge\",\n masterworks__bench__a2_loop: \"masterworks.bench.a2_loop\",\n masterworks__bench__calibration_decoy: \"masterworks.bench.calibration_decoy\",\n masterworks__bench__consensus: \"masterworks.bench.consensus\",\n masterworks__bench__extract: \"masterworks.bench.extract\",\n masterworks__bench__judge: \"masterworks.bench.judge\",\n masterworks__bench__panel: \"masterworks.bench.panel\",\n masterworks__bench__raw_arm: \"masterworks.bench.raw_arm\",\n masterworks__vanilla_arm__answer_from_facts: \"masterworks.vanilla_arm.answer_from_facts\",\n masterworks__vanilla_arm__best_work: \"masterworks.vanilla_arm.best_work\",\n masterworks__vanilla_arm__outcome_case: \"masterworks.vanilla_arm.outcome_case\",\n masterworks__vanilla_arm__professional_help: \"masterworks.vanilla_arm.professional_help\",\n media__youtube_analyzer: \"media.youtube_analyzer\",\n media_catalog__item_vetting_decision: \"media_catalog.item_vetting_decision\",\n meet__agenda_draft: \"meet.agenda_draft\",\n meet__live_intelligence: \"meet.live_intelligence\",\n meet__live_notes: \"meet.live_notes\",\n meet__pre_meeting_brief: \"meet.pre_meeting_brief\",\n meet__transcription: \"meet.transcription\",\n meet__wrap_up: \"meet.wrap_up\",\n memory__observer: \"memory.observer\",\n memory__reflector: \"memory.reflector\",\n mermaid__diagram_editing: \"mermaid.diagram_editing\",\n messaging__action_item_extraction: \"messaging.action_item_extraction\",\n messaging__conversation_catch_up: \"messaging.conversation_catch_up\",\n messaging__conversation_summary: \"messaging.conversation_summary\",\n messaging__reply_drafting: \"messaging.reply_drafting\",\n ner__deep_chunk_extractor: \"ner.deep_chunk_extractor\",\n ner__document_orienter: \"ner.document_orienter\",\n ner__entity_canonicalizer: \"ner.entity_canonicalizer\",\n ner__finisher: \"ner.finisher\",\n ner__item_proposer: \"ner.item_proposer\",\n ner__magic_moment_detector: \"ner.magic_moment_detector\",\n ner__scope_proposer: \"ner.scope_proposer\",\n ner__scope_slot_filler: \"ner.scope_slot_filler\",\n ner__suggestion_reviewer: \"ner.suggestion_reviewer\",\n ner__sweep_scope_discoverer: \"ner.sweep_scope_discoverer\",\n ner__sweep_scope_reference_finder: \"ner.sweep_scope_reference_finder\",\n ner__sweep_value_miner: \"ner.sweep_value_miner\",\n news__angles: \"news.angles\",\n news__coarse_relevance: \"news.coarse_relevance\",\n news__monitor_setup_proposer: \"news.monitor_setup_proposer\",\n news__report: \"news.report\",\n news__story_origin: \"news.story_origin\",\n news__triage: \"news.triage\",\n notes__organizer: \"notes.organizer\",\n notes__page_guidance: \"notes.page_guidance\",\n observability__tool_trace_pattern_detection: \"observability.tool_trace_pattern_detection\",\n observability__tool_trace_triage: \"observability.tool_trace_triage\",\n orchestras__role_describer: \"orchestras.role_describer\",\n orchestration__tool_failure_standoff_decision: \"orchestration.tool_failure_standoff_decision\",\n pdf__chunk_clean_ocr_text: \"pdf.chunk_clean_ocr_text\",\n pdf__chunk_flashcards_json: \"pdf.chunk_flashcards_json\",\n pdf__chunk_flashcards_typescript: \"pdf.chunk_flashcards_typescript\",\n pdf__content_cleaner: \"pdf.content_cleaner\",\n personal_staff__escalation: \"personal_staff.escalation\",\n personal_staff__front_line: \"personal_staff.front_line\",\n podcast__audience_adapter: \"podcast.audience_adapter\",\n podcast__audio_dialogue: \"podcast.audio_dialogue\",\n podcast__audio_english: \"podcast.audio_english\",\n podcast__audio_persian: \"podcast.audio_persian\",\n podcast__chapter_marker: \"podcast.chapter_marker\",\n podcast__content_extractor: \"podcast.content_extractor\",\n podcast__deep_research: \"podcast.deep_research\",\n podcast__image_v1: \"podcast.image_v1\",\n podcast__image_v2: \"podcast.image_v2\",\n podcast__image_v3: \"podcast.image_v3\",\n podcast__image_v4: \"podcast.image_v4\",\n podcast__image_v5: \"podcast.image_v5\",\n podcast__image_v6_feature: \"podcast.image_v6_feature\",\n podcast__image_v6_feature_prompt: \"podcast.image_v6_feature_prompt\",\n podcast__live_rewrite: \"podcast.live_rewrite\",\n podcast__metadata: \"podcast.metadata\",\n podcast__multihost_script: \"podcast.multihost_script\",\n podcast__post_prep_expansion: \"podcast.post_prep_expansion\",\n podcast__post_prep_fact_checking: \"podcast.post_prep_fact_checking\",\n podcast__post_prep_summarization: \"podcast.post_prep_summarization\",\n podcast__post_prep_translation: \"podcast.post_prep_translation\",\n podcast__race_frontier: \"podcast.race_frontier\",\n podcast__relevance_gate: \"podcast.relevance_gate\",\n podcast__roundtable_script: \"podcast.roundtable_script\",\n podcast__script_educational: \"podcast.script_educational\",\n podcast__script_news: \"podcast.script_news\",\n podcast__script_persian: \"podcast.script_persian\",\n podcast__solo_script: \"podcast.solo_script\",\n podcast__title_optimizer: \"podcast.title_optimizer\",\n podcast__video_v1: \"podcast.video_v1\",\n podcast__video_v2: \"podcast.video_v2\",\n podcast_client__blog_writer: \"podcast_client.blog_writer\",\n podcast_client__show_notes: \"podcast_client.show_notes\",\n podcast_client__topic_ideas: \"podcast_client.topic_ideas\",\n podcast_client__web_content_extractor: \"podcast_client.web_content_extractor\",\n podcast_client__youtube_research: \"podcast_client.youtube_research\",\n product_capture__instant_analysis: \"product_capture.instant_analysis\",\n projects__creation_guide: \"projects.creation_guide\",\n proof_runs__judge: \"proof_runs.judge\",\n purpose__writer: \"purpose.writer\",\n rag__chunk_contextualizer: \"rag.chunk_contextualizer\",\n rag__grounded_synthesis: \"rag.grounded_synthesis\",\n rag__grounding_claim_extract: \"rag.grounding_claim_extract\",\n rag__grounding_judge: \"rag.grounding_judge\",\n rag__hyde_generator: \"rag.hyde_generator\",\n rag__image_caption: \"rag.image_caption\",\n rag__pdf_page_cleaner: \"rag.pdf_page_cleaner\",\n rag__query_expander: \"rag.query_expander\",\n rag_kinds__grounded_synthesis: \"rag_kinds.grounded_synthesis\",\n records__enrichment: \"records.enrichment\",\n research__auto_tagger: \"research.auto_tagger\",\n research__condenser_1: \"research.condenser_1\",\n research__condenser_2: \"research.condenser_2\",\n research__coverage_audit: \"research.coverage_audit\",\n research__cross_cutting_tags: \"research.cross_cutting_tags\",\n research__document_assembly: \"research.document_assembly\",\n research__keyword_synthesis: \"research.keyword_synthesis\",\n research__report: \"research.report\",\n research__report_updater: \"research.report_updater\",\n research__source_authority: \"research.source_authority\",\n research__source_triage_decision: \"research.source_triage_decision\",\n research__structured_page_summary: \"research.structured_page_summary\",\n research__suggest_setup: \"research.suggest_setup\",\n research__tag_consolidation: \"research.tag_consolidation\",\n research__topic_deep_research: \"research.topic_deep_research\",\n research_client__output_blog: \"research_client.output_blog\",\n research_client__output_brand_profile: \"research_client.output_brand_profile\",\n research_client__output_competitive_landscape: \"research_client.output_competitive_landscape\",\n research_client__output_gap_analysis: \"research_client.output_gap_analysis\",\n research_client__output_literature_review: \"research_client.output_literature_review\",\n research_client__output_reputation_business: \"research_client.output_reputation_business\",\n research_client__output_reputation_personal: \"research_client.output_reputation_personal\",\n research_client__output_seo: \"research_client.output_seo\",\n research_client__output_slides: \"research_client.output_slides\",\n scraper__fact_check: \"scraper.fact_check\",\n scraper__keyword_analysis: \"scraper.keyword_analysis\",\n scraper__page_fetch_verdict: \"scraper.page_fetch_verdict\",\n seo__ai_visibility_blind_question_writer: \"seo.ai_visibility_blind_question_writer\",\n seo__ai_visibility_buyer_jobs: \"seo.ai_visibility_buyer_jobs\",\n seo__ai_visibility_decision_analyst: \"seo.ai_visibility_decision_analyst\",\n seo__ai_visibility_evidence_icp: \"seo.ai_visibility_evidence_icp\",\n seo__ai_visibility_panel_designer: \"seo.ai_visibility_panel_designer\",\n seo__ai_visibility_panel_report: \"seo.ai_visibility_panel_report\",\n seo__ai_visibility_question_architect: \"seo.ai_visibility_question_architect\",\n seo__ai_visibility_question_qa: \"seo.ai_visibility_question_qa\",\n seo__ai_visibility_writing_audit: \"seo.ai_visibility_writing_audit\",\n seo__backlink_analysis: \"seo.backlink_analysis\",\n seo__backlink_context_assessor: \"seo.backlink_context_assessor\",\n seo__backlink_work_planner: \"seo.backlink_work_planner\",\n seo__business_model_verdict: \"seo.business_model_verdict\",\n seo__competitor_classifier: \"seo.competitor_classifier\",\n seo__competitor_opportunity_autopsy: \"seo.competitor_opportunity_autopsy\",\n seo__competitor_page_autopsy: \"seo.competitor_page_autopsy\",\n seo__coverage_analyst: \"seo.coverage_analyst\",\n seo__digital_pr_reputation_adjudicator: \"seo.digital_pr_reputation_adjudicator\",\n seo__evidence_workbench: \"seo.evidence_workbench\",\n seo__finding_fixer: \"seo.finding_fixer\",\n seo__guidelines_drafter: \"seo.guidelines_drafter\",\n seo__ideal_customer_profile: \"seo.ideal_customer_profile\",\n seo__keyword_classifier: \"seo.keyword_classifier\",\n seo__keyword_expander: \"seo.keyword_expander\",\n seo__keyword_researcher: \"seo.keyword_researcher\",\n seo__keyword_serp_intent_analyst: \"seo.keyword_serp_intent_analyst\",\n seo__landscape_brief: \"seo.landscape_brief\",\n seo__map_author: \"seo.map_author\",\n seo__map_curation: \"seo.map_curation\",\n seo__money_map: \"seo.money_map\",\n seo__offering_extraction: \"seo.offering_extraction\",\n seo__offering_valuation: \"seo.offering_valuation\",\n seo__page_analyzer: \"seo.page_analyzer\",\n seo__page_intent_proposer: \"seo.page_intent_proposer\",\n seo__page_keyword_mapper: \"seo.page_keyword_mapper\",\n seo__page_mapper: \"seo.page_mapper\",\n seo__press_calendar_planner: \"seo.press_calendar_planner\",\n seo__press_clip_reviewer: \"seo.press_clip_reviewer\",\n seo__press_headlines: \"seo.press_headlines\",\n seo__press_moment_researcher: \"seo.press_moment_researcher\",\n seo__press_newsworthiness_check: \"seo.press_newsworthiness_check\",\n seo__press_source_request_responder: \"seo.press_source_request_responder\",\n seo__press_story_analyst: \"seo.press_story_analyst\",\n seo__press_strategist: \"seo.press_strategist\",\n seo__reputation_crisis_holding: \"seo.reputation_crisis_holding\",\n seo__session_rule_writer: \"seo.session_rule_writer\",\n seo__session_stamp_proposer: \"seo.session_stamp_proposer\",\n seo__site_intake: \"seo.site_intake\",\n seo__site_link_authority_router: \"seo.site_link_authority_router\",\n seo__site_strategist: \"seo.site_strategist\",\n seo__starter_pack_proposer: \"seo.starter_pack_proposer\",\n seo__strategy__site_brief__generate: \"seo.strategy.site_brief.generate\",\n seo__topic_assigner: \"seo.topic_assigner\",\n seo__topic_curation: \"seo.topic_curation\",\n sms__owner_beta: \"sms.owner_beta\",\n surfaces_client__binding_mapper: \"surfaces_client.binding_mapper\",\n tasks__triage: \"tasks.triage\",\n tool_viz__component_generator: \"tool_viz.component_generator\",\n tools__summarize_content: \"tools.summarize_content\",\n transcript_studio__document_edit: \"transcript_studio.document_edit\",\n transcript_studio__scribe_live: \"transcript_studio.scribe_live\",\n transcripts__clean_with_context: \"transcripts.clean_with_context\",\n transcripts__clean_with_context_variable: \"transcripts.clean_with_context_variable\",\n transcripts__clean_without_context: \"transcripts.clean_without_context\",\n vision_interview__adversary: \"vision_interview.adversary\",\n vision_interview__amplifier: \"vision_interview.amplifier\",\n vision_interview__answer_tracker: \"vision_interview.answer_tracker\",\n vision_interview__archaeologist: \"vision_interview.archaeologist\",\n vision_interview__architect: \"vision_interview.architect\",\n vision_interview__cartographer: \"vision_interview.cartographer\",\n vision_interview__requirements_author: \"vision_interview.requirements_author\",\n vision_interview__scribe: \"vision_interview.scribe\",\n vision_interview__sounding_board: \"vision_interview.sounding_board\",\n vision_interview__transcript_cleaner: \"vision_interview.transcript_cleaner\",\n vision_interview__vision_author: \"vision_interview.vision_author\",\n voice__communicator: \"voice.communicator\",\n voice__gemini_live: \"voice.gemini_live\",\n voice__intro: \"voice.intro\",\n voice__owner_beta: \"voice.owner_beta\",\n war_room__master: \"war_room.master\",\n war_room__room: \"war_room.room\",\n war_room__thread: \"war_room.thread\",\n web__endpoint_family_judge: \"web.endpoint_family_judge\",\n workflow__complex_research__keyword_synthesis: \"workflow.complex_research.keyword_synthesis\",\n workflow__complex_research__page_summary: \"workflow.complex_research.page_summary\",\n workflow__complex_research__report: \"workflow.complex_research.report\",\n workflow__conductor: \"workflow.conductor\",\n workflow__deep_research__keyword_synthesis: \"workflow.deep_research.keyword_synthesis\",\n workflow__extract_namer: \"workflow.extract_namer\",\n workflow__plan_design: \"workflow.plan_design\",\n workflow__plan_input_kind_authoring: \"workflow.plan_input_kind_authoring\",\n workflow__plan_node_type_recommender: \"workflow.plan_node_type_recommender\",\n workflow__plan_notes_writer: \"workflow.plan_notes_writer\",\n workflow__plan_output_kind_authoring: \"workflow.plan_output_kind_authoring\",\n workflow__recovery_advisor: \"workflow.recovery_advisor\",\n workflow__run_assist_suggester: \"workflow.run_assist_suggester\",\n workflow__step_intelligence: \"workflow.step_intelligence\",\n workflow__steward: \"workflow.steward\",\n workflow__steward__agent_run: \"workflow.steward.agent_run\",\n workflow__steward__data: \"workflow.steward.data\",\n workflow__steward__decision: \"workflow.steward.decision\",\n workflow__steward__user_input: \"workflow.steward.user_input\",\n workflow__wizard__agent_run: \"workflow.wizard.agent_run\",\n} as const;\n\n/** Every key this package version accepts — active plus retiring. */\nexport type MandateKey = (typeof MANDATE_KEYS)[keyof typeof MANDATE_KEYS];\n\n/** The key set as a runtime array, in generated order. */\nexport const ALL_MANDATE_KEYS: readonly MandateKey[] = Object.values(MANDATE_KEYS) as readonly MandateKey[];\n\n/** Keys still in the union but no longer declared (two-phase retire, phase 1). */\nexport const RETIRING_MANDATE_KEYS = {\n} as const;\n\n/**\n * Declared FAMILIES — a prefix the feature's own roster owns, and its members.\n * Emitted from `declared_families()` (aidream `services/mandates/carriers.py`).\n */\nexport const MANDATE_FAMILIES = {\n \"ambient.page_guidance_overrides\": [\n \"data.page_guidance\",\n \"education.admin_guidance\",\n \"education.audio_study_guidance\",\n \"education.classes_guidance\",\n \"education.creator_guidance\",\n \"education.data_guidance\",\n \"education.exam_prep_guidance\",\n \"education.family_guidance\",\n \"education.fastfire_guidance\",\n \"education.features_guidance\",\n \"education.flashcards_guidance\",\n \"education.game_guidance\",\n \"education.grade_work_guidance\",\n \"education.learn_guidance\",\n \"education.levels_guidance\",\n \"education.library_guidance\",\n \"education.media_guidance\",\n \"education.memory_guidance\",\n \"education.mind_maps_guidance\",\n \"education.notes_guidance\",\n \"education.offline_guidance\",\n \"education.page_guidance\",\n \"education.planner_guidance\",\n \"education.practice_oral_guidance\",\n \"education.practice_tests_guidance\",\n \"education.progress_guidance\",\n \"education.quizzes_guidance\",\n \"education.start_guidance\",\n \"education.study_aids_guidance\",\n \"education.subjects_guidance\",\n \"education.summaries_guidance\",\n \"education.tutor_guidance\",\n \"notes.page_guidance\",\n ],\n \"checks.cleanup_bakeoff\": [\n \"checks.cleanup_bakeoff.answer\",\n \"checks.cleanup_bakeoff.judge\",\n ],\n \"content_plan.p6_build\": [\n \"content_plan.p6_build.about\",\n \"content_plan.p6_build.blog\",\n \"content_plan.p6_build.comparison\",\n \"content_plan.p6_build.contact\",\n \"content_plan.p6_build.faq\",\n \"content_plan.p6_build.guide\",\n \"content_plan.p6_build.home\",\n \"content_plan.p6_build.index\",\n \"content_plan.p6_build.location\",\n \"content_plan.p6_build.pillar\",\n \"content_plan.p6_build.pricing\",\n \"content_plan.p6_build.service\",\n ],\n \"content_plan.research_wave\": [\n \"content_plan.research_wave.audience_journey\",\n \"content_plan.research_wave.competitor_coverage\",\n \"content_plan.research_wave.keyword_value\",\n ],\n \"conversation\": [\n \"conversation.action_auditor\",\n \"conversation.decision_ledger\",\n \"conversation.drift_auditor\",\n \"conversation.outcome_summarizer\",\n \"conversation.vision_extractor\",\n \"conversation.vision_interviewer\",\n ],\n \"masterworks.bench\": [\n \"masterworks.bench.a2_loop\",\n \"masterworks.bench.calibration_decoy\",\n \"masterworks.bench.consensus\",\n \"masterworks.bench.extract\",\n \"masterworks.bench.judge\",\n \"masterworks.bench.panel\",\n \"masterworks.bench.raw_arm\",\n ],\n \"masterworks.vanilla_arm\": [\n \"masterworks.vanilla_arm.answer_from_facts\",\n \"masterworks.vanilla_arm.best_work\",\n \"masterworks.vanilla_arm.outcome_case\",\n \"masterworks.vanilla_arm.professional_help\",\n ],\n \"vision_interview\": [\n \"vision_interview.adversary\",\n \"vision_interview.amplifier\",\n \"vision_interview.answer_tracker\",\n \"vision_interview.archaeologist\",\n \"vision_interview.architect\",\n \"vision_interview.cartographer\",\n \"vision_interview.requirements_author\",\n \"vision_interview.scribe\",\n \"vision_interview.sounding_board\",\n \"vision_interview.transcript_cleaner\",\n \"vision_interview.vision_author\",\n ],\n} as const;\n\nexport type MandateFamilyPrefix = keyof typeof MANDATE_FAMILIES;\n\n/** Members of a declared family, typed as real keys. */\nexport type MandateFamilyMember<P extends MandateFamilyPrefix> =\n (typeof MANDATE_FAMILIES)[P][number];\n\n/**\n * THE DYNAMIC FAMILIES — DB-authored (`mandate.definition` origin='user'). No\n * generated union can contain them, so their accessors return a BRANDED\n * `DynamicMandateKey`, deliberately NOT assignable to `MandateKey`: a carrier that\n * demands a declared key still refuses one, and a carrier that accepts either\n * says so in its own signature (`MandateKey | DynamicMandateKey`).\n */\ndeclare const dynamicMandateKeyBrand: unique symbol;\n\nexport type DynamicMandateKey = string & {\n readonly [dynamicMandateKeyBrand]: true;\n};\n\nexport const DYNAMIC_MANDATE_FAMILIES = {\n \"app\": { prefix: \"app\", note: \"One mandate per user-built app (`mandate.definition` origin='user').\" },\n \"shortcut\": { prefix: \"shortcut\", note: \"One mandate per user-authored shortcut (origin='user').\" },\n} as const;\n\nexport type DynamicMandateFamilyPrefix = keyof typeof DYNAMIC_MANDATE_FAMILIES;\n\nconst DYNAMIC_SLUG = /^[a-z0-9]+(?:_[a-z0-9]+)*$/;\n\nfunction dynamicKey(\n prefix: DynamicMandateFamilyPrefix,\n ...slugs: readonly (string | undefined)[]\n): DynamicMandateKey {\n const parts = slugs.filter((slug): slug is string => slug !== undefined);\n if (parts.length === 0) {\n throw new Error(\n `mandate family \"${prefix}\" needs at least a member slug — it was given none.`,\n );\n }\n for (const slug of parts) {\n if (!DYNAMIC_SLUG.test(slug)) {\n throw new Error(\n `mandate family \"${prefix}\" cannot name a member from ` +\n `${JSON.stringify(slug)}: a segment is lowercase words joined by single ` +\n \"underscores. Pass the slug the row carries, never a display name.\",\n );\n }\n }\n return [prefix, ...parts].join(\".\") as DynamicMandateKey;\n}\n\n/**\n * The mandate key of a user-built app. DB-authored — never a declared key.\n * `surfaceSlug` names the per-surface row a few apps carry\n * (`app.<app>.<surface>`); omit it for the app's own mandate.\n */\nexport function mandateKeyOfApp(\n appSlug: string,\n surfaceSlug?: string,\n): DynamicMandateKey {\n return dynamicKey(\"app\", appSlug, surfaceSlug);\n}\n\n/**\n * The mandate key of a user-authored shortcut. DB-authored. `surfaceSlug` names\n * the per-surface row (`shortcut.<shortcut>.<surface>`), which is how most live\n * shortcut rows are keyed; omit it for the shortcut's own mandate.\n */\nexport function mandateKeyOfShortcut(\n shortcutSlug: string,\n surfaceSlug?: string,\n): DynamicMandateKey {\n return dynamicKey(\"shortcut\", shortcutSlug, surfaceSlug);\n}\n","/**\n * `@ai-matrx/agents/mandates` — the ONE place a TypeScript client learns a\n * mandate key.\n *\n * 🚨 **Clients never declare a mandate.** aidream's `declare_mandate` is the\n * only declaration path in the system; this subpath publishes the key set that\n * declaration produced, so a hand-typed `\"seo.keyword_cluster\"` literal, a local\n * `mandates.ts` mirror, or an `as MandateKey` cast is a defect with a real\n * replacement — not a style preference. Every carrier that takes a key should\n * type it `MandateKey` (or `MandateKey | DynamicMandateKey` when it genuinely\n * accepts a DB-authored one) so a wrong key fails type-check instead of failing\n * at run time as a 404 nobody sees.\n *\n * The key data lives in `keys.generated.ts`, emitted by THE ONE GENERATOR\n * (`aidream/scripts/mandates_generate.py`, stage (h)) from the in-process\n * declarations — never edit it. The per-version key set that shipped with each\n * published version is committed beside it under `snapshots/`, so a scan can\n * resolve a client's references against the key set of the version it actually\n * ships (Mandate Declaration & Usage Reporting, DESIGN § 4.5 step 2).\n */\n\nexport {\n ALL_MANDATE_KEYS,\n DYNAMIC_MANDATE_FAMILIES,\n MANDATE_FAMILIES,\n MANDATE_KEYS,\n MANDATE_KEYS_META,\n RETIRING_MANDATE_KEYS,\n mandateKeyOfApp,\n mandateKeyOfShortcut,\n type DynamicMandateFamilyPrefix,\n type DynamicMandateKey,\n type MandateFamilyMember,\n type MandateFamilyPrefix,\n type MandateKey,\n} from \"./keys.generated\";\n\nimport {\n ALL_MANDATE_KEYS,\n MANDATE_KEYS_META,\n type DynamicMandateKey,\n type MandateKey,\n} from \"./keys.generated\";\n\n/**\n * What a carrier accepts when the key may be a declared one OR a DB-authored\n * one (`app.*` / `shortcut.*`, a `mandate.definition` row with origin='user').\n * Carriers that only ever run a declared job stay `MandateKey`.\n *\n * The mandate reference scanner reads a binding of this type as a proven key in\n * flight (`passthrough`), never an `UNRESOLVED_KEY` — so this is THE one\n * definition every client imports, never a local copy.\n */\nexport type AnyMandateKey = MandateKey | DynamicMandateKey;\n\n/**\n * A KEY THE CODE DID NOT CHOOSE, entering the typed world named for what it is:\n * a `mandate_key` column the platform wrote (an agent app's own mandate, a\n * shortcut's, a stored binding row), a stored `mandate:` ref, a saved config.\n *\n * It TYPES and never rejects. The server is the authority on whether the key\n * exists — a key declared after this package version shipped is real there and\n * absent from this build's key set — so narrowing here would send such a key\n * through the wrong door. The server answers an unknown key with a 404 that\n * names it.\n *\n * Never use it on a key your code picks: that key belongs to\n * `MANDATE_KEYS.<id>`, and routing it through here hides a rename from the\n * compiler. For a value that must be PROVEN declared (a URL segment a person\n * could have edited), use `isMandateKey` / `assertMandateKey` instead.\n */\nexport function storedMandateKey(value: string): AnyMandateKey {\n return value as AnyMandateKey;\n}\n\nconst KEY_SET: ReadonlySet<string> = new Set<string>(ALL_MANDATE_KEYS);\n\n/**\n * Narrow an unknown string to a declared `MandateKey`.\n *\n * Use it on anything that crossed a wire — a URL segment, a stored preference,\n * a row's `mandate_key` column. It answers only for the key set THIS package\n * version ships; a key declared after this version was published is correctly\n * `false` here, which is the point of the per-version snapshots.\n */\nexport function isMandateKey(value: unknown): value is MandateKey {\n return typeof value === \"string\" && KEY_SET.has(value);\n}\n\n/**\n * Assert an unknown value is a declared `MandateKey`, or throw with a remedy.\n *\n * Nothing fails silently: the message names the value, the package version its\n * key set came from, and what to do — never a bare \"invalid key\".\n */\nexport function assertMandateKey(\n value: unknown,\n context?: string,\n): asserts value is MandateKey {\n if (isMandateKey(value)) return;\n const where = context ? ` at ${context}` : \"\";\n throw new Error(\n `${JSON.stringify(value)} is not a declared mandate key${where}. ` +\n `@ai-matrx/agents@${MANDATE_KEYS_META.packageVersion} ships ` +\n `${ALL_MANDATE_KEYS.length} keys (aidream ${MANDATE_KEYS_META.aidreamRevision.slice(0, 12)}). ` +\n \"If the key is real, this package is behind — take `latest` and re-check. \" +\n \"If it is a user-built app or shortcut, it is DB-authored: build it with \" +\n \"mandateKeyOfApp() / mandateKeyOfShortcut(), which return DynamicMandateKey.\",\n );\n}\n\n/**\n * A DB-AUTHORED KEY THE GENERATED UNION CANNOT CARRY — the ONE typed door for\n * a literal a client's mandate-key allowlist already governs.\n *\n * Two honest cases: an `origin='user'` mandate somebody created in the console\n * (no generator built from code declarations can ever contain it), and a key\n * aidream has declared but the installed `@ai-matrx/agents` predates. Because\n * the parameter is a literal type, the key still appears verbatim at the call\n * site for a hand-typed-key scanner and for a human reading the diff.\n *\n * 🚨 NOT an escape hatch for a declared key. A key in `MANDATE_KEYS` goes\n * through `MANDATE_KEYS.<id>`; using this for one hides a real rename from the\n * compiler. When the package publishes a key routed through here, delete the call.\n */\nexport function dbAuthoredMandateKey<K extends string>(\n key: K,\n): DynamicMandateKey {\n return key as unknown as DynamicMandateKey;\n}\n\nexport interface MandateKeyParts {\n /** The feature/domain namespace before the first dot. */\n feature: string;\n /** The complete step name after the first dot; later dots are preserved. */\n mandate: string;\n}\n\n/** Split canonical `<feature>.<mandate>` identity without losing information. */\nexport function splitMandateKey(mandateKey: string): MandateKeyParts {\n const separator = mandateKey.indexOf(\".\");\n if (separator <= 0 || separator === mandateKey.length - 1) {\n return { feature: \"(unscoped)\", mandate: mandateKey };\n }\n return {\n feature: mandateKey.slice(0, separator),\n mandate: mandateKey.slice(separator + 1),\n };\n}\n\nexport {\n EMPTY_MANDATE_CONTRACT,\n missingRequiredVariables,\n missingVariablesMessage,\n parseMandateContract,\n type MandateContract,\n} from \"./contract\";\n","/**\n * `@ai-matrx/agents/matrx` — the Matrx transport port.\n *\n * The ONE seam between this package's wire semantics and a host's connection\n * policy. This package owns WHAT is said to the AI Matrx server — paths,\n * methods, JSON bodies, streaming Accept headers, the `Last-Event-ID` cursor\n * header — and the host owns HOW the connection is made:\n *\n * - base-URL / backend-channel resolution (global, sandbox override, local\n * engine, EC2-dedicated — whatever ladder the host runs);\n * - credentials (Supabase JWT `Authorization: Bearer`, guest\n * `X-Fingerprint-ID`, or the API-key lane) — NEVER implemented here;\n * - the `X-Organization-Id` context header;\n * - retry policy, network-level timeouts, and diagnostics capture.\n *\n * A host implements the port in a few lines:\n *\n * ```ts\n * const transport: MatrxTransport = {\n * fetch: (path, init) =>\n * fetch(`${baseUrl}${path}`, {\n * ...init,\n * headers: { ...init.headers, ...authHeaders() },\n * }),\n * };\n * ```\n *\n * The port is deliberately structural and `fetch`-shaped so `@ai-matrx/data`'s\n * `/api` transport can implement it without importing this package.\n */\n\n/**\n * The request this package hands the port. A strict subset of `RequestInit`,\n * so a host can spread it straight into `fetch`.\n */\nexport interface MatrxTransportRequest {\n method: \"GET\" | \"POST\";\n /**\n * Wire-semantic headers the CALL requires (`Content-Type`, `Accept`,\n * `Last-Event-ID`). The host merges its policy headers (auth, org) on top;\n * it must not drop these.\n */\n headers: Record<string, string>;\n /** Pre-serialized JSON body, present on POST calls that carry one. */\n body?: string;\n /** Caller cancellation. The host must wire it to the underlying fetch. */\n signal?: AbortSignal;\n}\n\n/**\n * The transport port. `path` is server-relative and always starts with `/`\n * (`/ai/...`, `/runtime/...`); the host prepends its resolved base URL.\n */\nexport interface MatrxTransport {\n fetch(path: string, init: MatrxTransportRequest): Promise<Response>;\n}\n\n/**\n * A non-2xx response from the Matrx API, with the server's structured error\n * body preserved and its richest human-readable message extracted.\n */\nexport class MatrxApiError extends Error {\n override readonly name = \"MatrxApiError\";\n /** HTTP status of the failed response. */\n readonly status: number;\n /** Machine code from the server body (`code`, or `detail.code`), when present. */\n readonly code: string | null;\n /** The parsed server error body, verbatim (undefined when unparsable). */\n readonly serverDetail: unknown;\n /** The request path the failure came from (server-relative). */\n readonly path: string;\n\n constructor(args: {\n status: number;\n path: string;\n serverDetail?: unknown;\n message?: string;\n }) {\n super(\n args.message ??\n extractMatrxErrorMessage(args.serverDetail) ??\n `HTTP ${args.status}`,\n );\n this.status = args.status;\n this.path = args.path;\n this.serverDetail = args.serverDetail;\n this.code = extractMatrxErrorCode(args.serverDetail);\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction nonBlankString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim() ? value : undefined;\n}\n\n/**\n * Extract the richest human-readable message from a Matrx/FastAPI error body.\n *\n * aidream 4xx validation errors look like\n * `{ error, user_message, details: [{ field, message, help }] }`; hand-raised\n * HTTPExceptions carry `{ detail: { code, message } }`; FastAPI's defaults are\n * `{ detail: string | [{ msg }] }`. Preference order: `user_message` →\n * `message` → joined `details[].message` → `detail.message` →\n * `detail` string → joined `detail[].msg`. Returns undefined for\n * unrecognized bodies so callers fall back to the bare status line.\n */\nexport function extractMatrxErrorMessage(\n serverDetail: unknown,\n): string | undefined {\n if (!isRecord(serverDetail)) return undefined;\n\n const userMessage = nonBlankString(serverDetail.user_message);\n if (userMessage) return userMessage;\n const message = nonBlankString(serverDetail.message);\n if (message) return message;\n\n if (Array.isArray(serverDetail.details)) {\n const messages = serverDetail.details\n .map((entry: unknown) => {\n if (!isRecord(entry)) return undefined;\n const detailMessage = nonBlankString(entry.message);\n if (!detailMessage) return undefined;\n const field = nonBlankString(entry.field);\n return field ? `${field}: ${detailMessage}` : detailMessage;\n })\n .filter((m): m is string => typeof m === \"string\");\n if (messages.length > 0) return messages.join(\"; \");\n }\n\n const detail = serverDetail.detail;\n if (isRecord(detail)) {\n const detailMessage =\n nonBlankString(detail.message) ?? nonBlankString(detail.user_message);\n if (detailMessage) return detailMessage;\n }\n if (typeof detail === \"string\" && detail.trim()) return detail;\n if (Array.isArray(detail)) {\n const messages = detail\n .map((entry: unknown) =>\n isRecord(entry) ? nonBlankString(entry.msg) : undefined,\n )\n .filter((m): m is string => typeof m === \"string\");\n if (messages.length > 0) return messages.join(\"; \");\n }\n return undefined;\n}\n\n/**\n * Extract the machine error code from a Matrx error body: top-level `code`,\n * else `detail.code` (the hand-raised HTTPException shape). Null when absent.\n */\nexport function extractMatrxErrorCode(serverDetail: unknown): string | null {\n if (!isRecord(serverDetail)) return null;\n const topLevel = nonBlankString(serverDetail.code);\n if (topLevel) return topLevel;\n const detail = serverDetail.detail;\n if (isRecord(detail)) {\n const nested = nonBlankString(detail.code);\n if (nested) return nested;\n }\n return null;\n}\n","/**\n * Canonical AI Matrx NDJSON wire kernel.\n *\n * This module is deliberately independent of React, Redux, Next.js, Supabase,\n * and generated application types. Every Matrx client uses it to turn the\n * backend's byte stream into the same normalized `{ event, data }` envelopes.\n * Host runtimes remain responsible for HTTP/auth errors and for deciding what\n * each event means in their state model.\n */\n\nexport interface MatrxStreamEnvelope<TData = unknown> {\n event: string;\n /** Immutable emitter segment; transport sequence is scoped to this id. */\n stream_id?: string;\n data: TData;\n /** Monotonic transport sequence from full envelopes, when supplied. */\n stream_seq?: number;\n}\n\nexport interface MatrxNdjsonIssue {\n line: string;\n error: unknown;\n /** One-based physical NDJSON line number. */\n lineNumber: number;\n /** True when an unterminated trailing fragment was parsed by `finish()`. */\n atCompletion: boolean;\n}\n\nexport interface MatrxStreamEnvelopeObservation {\n /** Exact parsed JSON value before compact/full normalization. */\n raw: unknown;\n envelope: MatrxStreamEnvelope;\n line: string;\n lineNumber: number;\n atCompletion: boolean;\n}\n\nexport interface MatrxNdjsonFramerOptions {\n /** Malformed JSON is non-fatal, but it must never disappear silently. */\n onMalformedLine?: (issue: MatrxNdjsonIssue) => void;\n /** Valid JSON with no recognized Matrx event envelope is also non-fatal. */\n onUnknownEnvelope?: (value: unknown) => void;\n /** Observe every valid envelope without changing or consuming it. */\n onValidEnvelope?: (observation: MatrxStreamEnvelopeObservation) => void;\n}\n\nexport interface ReadMatrxNdjsonOptions extends MatrxNdjsonFramerOptions {\n signal?: AbortSignal;\n /** Maximum normalized events read ahead of the iterator consumer. */\n maxReadAhead?: number;\n}\n\nexport interface MatrxNdjsonFramer {\n /** Push a text fragment. Fragments may split JSON tokens or line endings. */\n pushText(fragment: string): MatrxStreamEnvelope[];\n /** Push a byte fragment. UTF-8 code points may span calls. */\n pushBytes(fragment: Uint8Array): MatrxStreamEnvelope[];\n /** Parse the final unterminated line and flush any pending UTF-8 bytes. */\n finish(): MatrxStreamEnvelope[];\n}\n\ntype QueueItem =\n | { kind: \"event\"; value: MatrxStreamEnvelope }\n | { kind: \"error\"; error: unknown }\n | { kind: \"done\" };\n\nexport const DEFAULT_MATRX_NDJSON_READ_AHEAD = 64;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Normalize both supported Matrx wire shapes:\n *\n * - full: `{ \"event\": \"chunk\", \"data\": { \"text\": \"...\" } }`\n * - compact chunk: `{ \"e\": \"c\", \"t\": \"...\" }`\n * - compact reasoning: `{ \"e\": \"r\", \"t\": \"...\" }`\n */\nexport function normalizeMatrxStreamEnvelope(\n value: unknown,\n): MatrxStreamEnvelope | null {\n if (!isRecord(value)) return null;\n\n if (typeof value.event === \"string\") {\n const streamSeq =\n typeof value.stream_seq === \"number\" && Number.isFinite(value.stream_seq)\n ? value.stream_seq\n : undefined;\n const streamId = typeof value.stream_id === \"string\" ? value.stream_id : undefined;\n return {\n event: value.event,\n data: value.data,\n ...(streamId === undefined ? {} : { stream_id: streamId }),\n ...(streamSeq === undefined ? {} : { stream_seq: streamSeq }),\n };\n }\n if (value.e === \"c\" && typeof value.t === \"string\") {\n const streamId = typeof value.stream_id === \"string\" ? value.stream_id : undefined;\n const streamSeq =\n typeof value.stream_seq === \"number\" && Number.isFinite(value.stream_seq)\n ? value.stream_seq\n : undefined;\n return {\n event: \"chunk\",\n data: { text: value.t },\n ...(streamId === undefined ? {} : { stream_id: streamId }),\n ...(streamSeq === undefined ? {} : { stream_seq: streamSeq }),\n };\n }\n if (value.e === \"r\" && typeof value.t === \"string\") {\n const streamId = typeof value.stream_id === \"string\" ? value.stream_id : undefined;\n const streamSeq =\n typeof value.stream_seq === \"number\" && Number.isFinite(value.stream_seq)\n ? value.stream_seq\n : undefined;\n return {\n event: \"reasoning_chunk\",\n data: { text: value.t },\n ...(streamId === undefined ? {} : { stream_id: streamId }),\n ...(streamSeq === undefined ? {} : { stream_seq: streamSeq }),\n };\n }\n return null;\n}\n\n/**\n * Create the transport-independent NDJSON framer used by the stream reader.\n * Browser extensions, desktop bridges, WebSockets, and tests can feed it\n * fragmented strings or bytes without constructing a `ReadableStream`.\n */\nexport function createMatrxNdjsonFramer(\n options: MatrxNdjsonFramerOptions = {},\n): MatrxNdjsonFramer {\n const decoder = new TextDecoder();\n let buffer = \"\";\n let lineNumber = 0;\n let finished = false;\n\n const assertOpen = (): void => {\n if (finished) throw new Error(\"Matrx NDJSON framer is already finished\");\n };\n\n const parseLine = (\n line: string,\n atCompletion: boolean,\n ): MatrxStreamEnvelope | null => {\n const currentLineNumber = ++lineNumber;\n const trimmed = line.trim();\n if (!trimmed) return null;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(trimmed) as unknown;\n } catch (error) {\n options.onMalformedLine?.({\n line: trimmed,\n error,\n lineNumber: currentLineNumber,\n atCompletion,\n });\n return null;\n }\n\n const envelope = normalizeMatrxStreamEnvelope(parsed);\n if (!envelope) {\n options.onUnknownEnvelope?.(parsed);\n return null;\n }\n options.onValidEnvelope?.({\n raw: parsed,\n envelope,\n line: trimmed,\n lineNumber: currentLineNumber,\n atCompletion,\n });\n return envelope;\n };\n\n const pushDecodedText = (fragment: string): MatrxStreamEnvelope[] => {\n buffer += fragment;\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() ?? \"\";\n const envelopes: MatrxStreamEnvelope[] = [];\n for (const line of lines) {\n const envelope = parseLine(line, false);\n if (envelope) envelopes.push(envelope);\n }\n return envelopes;\n };\n\n return {\n pushText(fragment) {\n assertOpen();\n // Flush any pending byte fragment before switching to explicit text.\n return pushDecodedText(decoder.decode() + fragment);\n },\n pushBytes(fragment) {\n assertOpen();\n return pushDecodedText(decoder.decode(fragment, { stream: true }));\n },\n finish() {\n assertOpen();\n finished = true;\n const envelopes = pushDecodedText(decoder.decode());\n if (buffer.length > 0) {\n const envelope = parseLine(buffer, true);\n buffer = \"\";\n if (envelope) envelopes.push(envelope);\n }\n return envelopes;\n },\n };\n}\n\nfunction readAheadLimit(value: number | undefined): number {\n const limit = value ?? DEFAULT_MATRX_NDJSON_READ_AHEAD;\n if (!Number.isSafeInteger(limit) || limit < 1) {\n throw new RangeError(\"maxReadAhead must be a positive safe integer\");\n }\n return limit;\n}\n\n/**\n * Read and normalize a Matrx NDJSON response body with bounded background\n * read-ahead. Consumer work does not stall the network until `maxReadAhead`\n * complete events are waiting; the bound prevents an abandoned or blocked\n * consumer from growing memory without limit.\n */\nexport async function* readMatrxNdjsonStream(\n body: ReadableStream<Uint8Array>,\n options: ReadMatrxNdjsonOptions = {},\n): AsyncGenerator<MatrxStreamEnvelope, void, undefined> {\n const maxReadAhead = readAheadLimit(options.maxReadAhead);\n const queue: QueueItem[] = [];\n let queuedEventCount = 0;\n let wakeConsumer: (() => void) | null = null;\n let wakeProducer: (() => void) | null = null;\n let readerFinished = false;\n let consumerClosed = false;\n\n const wakeWaitingConsumer = (): void => {\n const wake = wakeConsumer;\n wakeConsumer = null;\n wake?.();\n };\n const wakeWaitingProducer = (): void => {\n const wake = wakeProducer;\n wakeProducer = null;\n wake?.();\n };\n const enqueueTerminal = (item: QueueItem): void => {\n if (consumerClosed) return;\n queue.push(item);\n wakeWaitingConsumer();\n };\n const enqueueEvent = async (value: MatrxStreamEnvelope): Promise<boolean> => {\n while (\n queuedEventCount >= maxReadAhead &&\n !consumerClosed &&\n !options.signal?.aborted\n ) {\n await new Promise<void>((resolve) => {\n wakeProducer = resolve;\n });\n }\n if (consumerClosed || options.signal?.aborted) return false;\n queue.push({ kind: \"event\", value });\n queuedEventCount += 1;\n wakeWaitingConsumer();\n return true;\n };\n const waitForReadCapacity = async (): Promise<boolean> => {\n while (\n queuedEventCount >= maxReadAhead &&\n !consumerClosed &&\n !options.signal?.aborted\n ) {\n await new Promise<void>((resolve) => {\n wakeProducer = resolve;\n });\n }\n return !consumerClosed && !options.signal?.aborted;\n };\n\n const reader = body.getReader();\n const framer = createMatrxNdjsonFramer(options);\n\n const onAbort = (): void => {\n wakeWaitingProducer();\n wakeWaitingConsumer();\n void reader.cancel(options.signal?.reason).catch(() => undefined);\n };\n options.signal?.addEventListener(\"abort\", onAbort, { once: true });\n if (options.signal?.aborted) onAbort();\n\n const readerPromise = (async (): Promise<void> => {\n try {\n while (!options.signal?.aborted && !consumerClosed) {\n if (!(await waitForReadCapacity())) return;\n const { value, done } = await reader.read();\n if (done) break;\n for (const envelope of framer.pushBytes(value)) {\n if (!(await enqueueEvent(envelope))) return;\n }\n }\n\n if (!options.signal?.aborted && !consumerClosed) {\n for (const envelope of framer.finish()) {\n if (!(await enqueueEvent(envelope))) return;\n }\n }\n } catch (error) {\n const aborted =\n options.signal?.aborted ||\n consumerClosed ||\n (error instanceof Error && error.name === \"AbortError\");\n if (!aborted) enqueueTerminal({ kind: \"error\", error });\n } finally {\n readerFinished = true;\n reader.releaseLock();\n enqueueTerminal({ kind: \"done\" });\n }\n })();\n\n try {\n while (true) {\n if (queue.length === 0) {\n if (options.signal?.aborted || readerFinished) return;\n await new Promise<void>((resolve) => {\n wakeConsumer = resolve;\n });\n }\n\n const item = queue.shift();\n if (item?.kind === \"event\") queuedEventCount -= 1;\n wakeWaitingProducer();\n if (!item || item.kind === \"done\") return;\n if (item.kind === \"error\") throw item.error;\n yield item.value;\n }\n } finally {\n consumerClosed = true;\n wakeWaitingProducer();\n wakeWaitingConsumer();\n options.signal?.removeEventListener(\"abort\", onAbort);\n if (!readerFinished) {\n await reader.cancel().catch(() => undefined);\n }\n await readerPromise;\n }\n}\n","/**\n * The conversation-start contract — client-minted `conversation_id`, `is_new`,\n * `store` — typed exactly per the cross-repo System of Record\n * (`common-docs/systems/agents/conversation-start-contract/FEATURE.md`;\n * server truth `aidream/services/conversation_context/scope.py::\n * ConversationStartRequest`).\n *\n * Every request that STARTS a conversation sends all three fields, no\n * defaults:\n *\n * | `is_new` | `store` | Result |\n * |----------|---------|----------------------------------------------------------|\n * | true | true | Create the row with the caller's id — 409 if it exists |\n * | true | false | No row. The id is correlation only (ephemeral run) |\n * | false | true | Continue it — 404 if the caller doesn't own it |\n * | false | false | Ephemeral run on a known id; nothing read, nothing written |\n *\n * `store` is the ONLY ephemeral signal; `is_new` is the caller's assertion\n * about the id, never a persistence switch. `prior_messages` (the client-owned\n * transcript of an ephemeral multi-turn run) is only valid with\n * `store: false` — the union below makes the invalid combination\n * unrepresentable, mirroring the server's 422.\n *\n * Continue routes (`POST /ai/conversations/{id}`) take the id from the path\n * and do not carry this triple.\n */\n\n/** Recursive JSON value — the package's honest type for free-form wire bags. */\nexport type MatrxJsonValue =\n | string\n | number\n | boolean\n | null\n | MatrxJsonValue[]\n | { [key: string]: MatrxJsonValue };\n\n/** A JSON object on the wire. */\nexport type MatrxJsonObject = { [key: string]: MatrxJsonValue };\n\n/**\n * One LLM message on the request wire — `prior_messages` entries for\n * stateless multi-turn runs. Mirrors aidream's `ChatMessageInput`\n * (`aidream/schemas/messages.py`, `extra=\"allow\"` — additional provider\n * fields round-trip untouched).\n */\nexport interface MatrxChatMessage {\n role: string;\n content?: string | MatrxJsonValue[] | null;\n name?: string | null;\n tool_call_id?: string | null;\n tool_calls?: MatrxJsonObject[] | null;\n [extra: string]: MatrxJsonValue | undefined;\n}\n\n/** `is_new: true, store: true` — create the row with the caller's id. */\nexport interface MatrxStoredConversationCreate {\n conversation_id: string;\n is_new: true;\n store: true;\n}\n\n/** `is_new: false, store: true` — continue an owned stored conversation via a start route. */\nexport interface MatrxStoredConversationContinue {\n conversation_id: string;\n is_new: false;\n store: true;\n}\n\n/**\n * `store: false` — ephemeral: nothing read, nothing written; the id is the\n * caller's correlation handle. This is the ONLY member that may carry\n * `prior_messages` (the server 422s a client transcript on a stored run).\n */\nexport interface MatrxEphemeralConversation {\n conversation_id: string;\n is_new: boolean;\n store: false;\n prior_messages?: MatrxChatMessage[];\n}\n\n/** The full conversation-start triple, one member per contract cell. */\nexport type MatrxConversationStart =\n | MatrxStoredConversationCreate\n | MatrxStoredConversationContinue\n | MatrxEphemeralConversation;\n\n/** Mint a fresh client-side conversation id (the contract requires the CLIENT to mint it). */\nexport function mintMatrxConversationId(): string {\n return crypto.randomUUID();\n}\n\n/** Start a NEW stored conversation (`is_new: true, store: true`). */\nexport function newStoredConversationStart(\n conversationId?: string,\n): MatrxStoredConversationCreate {\n return {\n conversation_id: conversationId ?? mintMatrxConversationId(),\n is_new: true,\n store: true,\n };\n}\n\n/**\n * Continue an EXISTING stored conversation through a start route\n * (`is_new: false, store: true` — 404 when the caller doesn't own the id).\n * Prefer `continueAgentConversation` (the dedicated continue route) for\n * ordinary follow-up turns.\n */\nexport function continueStoredConversationStart(\n conversationId: string,\n): MatrxStoredConversationContinue {\n return { conversation_id: conversationId, is_new: false, store: true };\n}\n\n/**\n * Start a NEW ephemeral run (`is_new: true, store: false`) — a freshly minted\n * correlation id, nothing persisted.\n */\nexport function newEphemeralConversationStart(\n conversationId?: string,\n): MatrxEphemeralConversation {\n return {\n conversation_id: conversationId ?? mintMatrxConversationId(),\n is_new: true,\n store: false,\n };\n}\n\n/**\n * Continue an ephemeral multi-turn run (`is_new: false, store: false`): the\n * CLIENT owns the transcript and replays it as `prior_messages` (ordered\n * oldest-first) because the server wrote no rows to rebuild from. The server\n * still owns the agent definition, model, tools, and system prompt.\n */\nexport function continueEphemeralConversationStart(\n conversationId: string,\n priorMessages: MatrxChatMessage[],\n): MatrxEphemeralConversation {\n return {\n conversation_id: conversationId,\n is_new: false,\n store: false,\n prior_messages: priorMessages,\n };\n}\n","/**\n * Internal request plumbing for `@ai-matrx/agents/matrx`. Not part of the\n * public surface — `matrx/index.ts` deliberately does not re-export this\n * module. Everything here is pure: no globals, no work at import time.\n */\n\nimport {\n readMatrxNdjsonStream,\n type MatrxNdjsonIssue,\n type MatrxStreamEnvelope,\n type MatrxStreamEnvelopeObservation,\n} from \"../stream/ndjson\";\nimport { MatrxApiError, type MatrxTransport } from \"./transport\";\n\n/** Encode one path segment (an id) safely into a server-relative path. */\nexport function encodePathSegment(value: string): string {\n return encodeURIComponent(value);\n}\n\nexport type QueryValue =\n | string\n | number\n | boolean\n | readonly string[]\n | undefined;\n\n/**\n * Build a query string. Array values repeat the key (`kind=a&kind=b` — the\n * FastAPI repeatable-parameter convention); undefined values are omitted.\n * Returns \"\" or a string starting with \"?\".\n */\nexport function buildQuery(params: Record<string, QueryValue>): string {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined) continue;\n if (Array.isArray(value)) {\n for (const entry of value) search.append(key, entry);\n } else {\n search.append(key, String(value));\n }\n }\n const encoded = search.toString();\n return encoded ? `?${encoded}` : \"\";\n}\n\nasync function readServerDetail(response: Response): Promise<unknown> {\n try {\n return (await response.json()) as unknown;\n } catch {\n return undefined;\n }\n}\n\nasync function throwApiError(path: string, response: Response): Promise<never> {\n throw new MatrxApiError({\n status: response.status,\n path,\n serverDetail: await readServerDetail(response),\n });\n}\n\nexport interface JsonRequestOptions {\n method: \"GET\" | \"POST\";\n body?: unknown;\n signal?: AbortSignal;\n}\n\n/**\n * Execute a JSON request through the transport. Throws `MatrxApiError` on a\n * non-2xx response; resolves with the parsed JSON body otherwise.\n */\nexport async function requestJson<T>(\n transport: MatrxTransport,\n path: string,\n options: JsonRequestOptions,\n): Promise<T> {\n const hasBody = options.method !== \"GET\" && options.body !== undefined;\n const response = await transport.fetch(path, {\n method: options.method,\n headers: hasBody ? { \"Content-Type\": \"application/json\" } : {},\n ...(hasBody ? { body: JSON.stringify(options.body) } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n });\n if (!response.ok) return throwApiError(path, response);\n return (await response.json()) as T;\n}\n\n/**\n * Options for every streaming call, riding the NDJSON kernel's contract.\n * Public via `./run`'s re-export.\n */\nexport interface MatrxStreamCallOptions {\n /** Abort the fetch and end the events iterator. */\n signal?: AbortSignal;\n /** Bounded background read-ahead (see `stream/ndjson`). */\n maxReadAhead?: number;\n /** Malformed NDJSON is non-fatal but must never disappear silently. */\n onMalformedLine?: (issue: MatrxNdjsonIssue) => void;\n /** Valid JSON with no recognized Matrx envelope. */\n onUnknownEnvelope?: (value: unknown) => void;\n /** Observe every valid envelope in its exact wire form. */\n onValidEnvelope?: (observation: MatrxStreamEnvelopeObservation) => void;\n}\n\n/**\n * A live agent run: the server-assigned ids (from response headers, available\n * BEFORE any event) and the normalized event stream. Public via `./run`.\n */\nexport interface MatrxRunHandle {\n /** `X-Request-ID` — the ONLY id `POST /ai/cancel/{request_id}` accepts. */\n requestId: string | null;\n /** `X-Conversation-ID` — the server's conversation identity. */\n conversationId: string | null;\n /** Normalized `{event, data}` envelopes through the ONE wire kernel. */\n events: AsyncGenerator<MatrxStreamEnvelope, void, undefined>;\n /** The raw response, for hosts that need headers/status beyond the ids. */\n response: Response;\n}\n\n/**\n * Wrap a validated streaming Response into the run handle — the ONE place\n * the id headers are read and the NDJSON kernel is attached (`./run` and\n * `./operations`' rejoin share it).\n */\nexport function toRunHandle(\n response: Response,\n options: MatrxStreamCallOptions,\n): MatrxRunHandle {\n return {\n requestId: response.headers.get(\"X-Request-ID\"),\n conversationId: response.headers.get(\"X-Conversation-ID\"),\n events: readMatrxNdjsonStream(response.body as ReadableStream<Uint8Array>, {\n ...(options.signal ? { signal: options.signal } : {}),\n ...(options.maxReadAhead !== undefined\n ? { maxReadAhead: options.maxReadAhead }\n : {}),\n ...(options.onMalformedLine\n ? { onMalformedLine: options.onMalformedLine }\n : {}),\n ...(options.onUnknownEnvelope\n ? { onUnknownEnvelope: options.onUnknownEnvelope }\n : {}),\n ...(options.onValidEnvelope\n ? { onValidEnvelope: options.onValidEnvelope }\n : {}),\n }),\n response,\n };\n}\n\nexport interface StreamRequestOptions {\n method: \"GET\" | \"POST\";\n body?: unknown;\n /** Extra wire-semantic headers (`Accept`, `Last-Event-ID`). */\n headers?: Record<string, string>;\n signal?: AbortSignal;\n}\n\n/**\n * Execute a streaming request. Throws `MatrxApiError` on a non-2xx response\n * (reading the error body as JSON when possible) or when a 2xx response\n * carries no body; resolves with the validated `Response` otherwise.\n */\nexport async function requestStream(\n transport: MatrxTransport,\n path: string,\n options: StreamRequestOptions,\n): Promise<Response> {\n const hasBody = options.method !== \"GET\" && options.body !== undefined;\n const response = await transport.fetch(path, {\n method: options.method,\n headers: {\n ...(hasBody ? { \"Content-Type\": \"application/json\" } : {}),\n ...options.headers,\n },\n ...(hasBody ? { body: JSON.stringify(options.body) } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n });\n if (!response.ok) return throwApiError(path, response);\n if (!response.body) {\n throw new MatrxApiError({\n status: response.status,\n path,\n serverDetail: { code: \"missing_response_body\" },\n message: \"The streaming response carried no body.\",\n });\n }\n return response;\n}\n","/**\n * `@ai-matrx/agents/stream/sse` — the Matrx SSE frame kernel.\n *\n * Two Matrx clients hand-rolled the identical `text/event-stream` framing —\n * the same separator regex, the same field parsing, the same CRLF incident —\n * for the durable rejoin endpoints (`/runtime/.../events/stream`,\n * `/runs/.../events/stream`). This module is that framing extracted ONCE, as a\n * pure incremental parser, so a host keeps only what is genuinely host policy:\n * the fetch, the stall timer, the retry budget, and what each event MEANS.\n *\n * Contract, mirroring `stream/ndjson`:\n * - Pure and effect-free: no fetch, no timers, no globals. Importing this\n * module performs no work.\n * - Incremental across arbitrary chunk boundaries: a frame split anywhere —\n * mid-line, mid-separator, mid-UTF-8 when using the byte reader — parses\n * identically to one delivered whole.\n * - All three SSE line terminators (`\\r\\n`, `\\n`, `\\r`) and all three frame\n * separators are handled — the CRLF-vs-LF divergence that bit production is\n * covered by construction and by test.\n * - Comment-only frames (heartbeats, `:` lines) ARE emitted (with\n * `data === null`) because hosts use any parsed frame as liveness proof to\n * reset stall timers and retry budgets. Frames with data join multi-line\n * `data:` fields with `\\n` per the SSE spec.\n * - `id:` is surfaced raw AND, when it is a safe integer, as `seq` — the\n * `Last-Event-ID` cursor both Matrx rejoin endpoints use for durable replay.\n * Cursor ADVANCEMENT (`seq > cursor`) stays host-side, next to the retry.\n */\n\nexport interface MatrxSseFrame {\n /** `event:` field; the SSE default \"message\" when absent. */\n event: string;\n /** `id:` field, raw, when present. */\n id: string | null;\n /**\n * `id:` parsed as a non-negative safe integer, else null. Matrx rejoin\n * streams use integer ids as the `Last-Event-ID` replay cursor.\n */\n seq: number | null;\n /**\n * Joined `data:` lines (`\\n`-separated per spec), or null for a frame with\n * no data field at all (e.g. a comment-only heartbeat). An empty-string\n * data field is `\"\"`, not null.\n */\n data: string | null;\n}\n\nconst FRAME_SEPARATOR = /\\r\\n\\r\\n|\\n\\n|\\r\\r/;\nconst LINE_SEPARATOR = /\\r\\n|\\n|\\r/;\n\n/** Parse ONE complete frame's text (no trailing separator). */\nexport function parseMatrxSseFrame(frame: string): MatrxSseFrame {\n let event = \"message\";\n let id: string | null = null;\n const dataLines: string[] = [];\n let sawData = false;\n\n for (const line of frame.split(LINE_SEPARATOR)) {\n if (line.startsWith(\":\")) continue;\n if (line.startsWith(\"event:\")) event = line.slice(6).trim();\n else if (line.startsWith(\"data:\")) {\n sawData = true;\n dataLines.push(line.slice(5).replace(/^ /, \"\"));\n } else if (line.startsWith(\"id:\")) id = line.slice(3).trim();\n }\n\n const seqCandidate = id !== null && id !== \"\" ? Number(id) : NaN;\n const seq =\n Number.isSafeInteger(seqCandidate) && seqCandidate >= 0\n ? seqCandidate\n : null;\n\n return { event, id, seq, data: sawData ? dataLines.join(\"\\n\") : null };\n}\n\nexport interface MatrxSseFramer {\n /** Feed a decoded text chunk; returns every frame it completed. */\n push(chunk: string): MatrxSseFrame[];\n /**\n * Signal end of input. A non-empty trailing buffer is an UNTERMINATED frame:\n * per the SSE spec it was never dispatched, so it is returned separately for\n * the host to treat as diagnostic, never as a delivered event.\n */\n flush(): { incomplete: string | null };\n}\n\n/** Incremental SSE framer over already-decoded text. */\nexport function createMatrxSseFramer(): MatrxSseFramer {\n let buffer = \"\";\n return {\n push(chunk: string): MatrxSseFrame[] {\n buffer += chunk;\n const frames: MatrxSseFrame[] = [];\n for (;;) {\n const sep = FRAME_SEPARATOR.exec(buffer);\n if (sep === null) break;\n // A lone trailing `\\r` could be the first half of `\\r\\n\\r\\n`'s final\n // newline — but the separator regex only matched what is already\n // complete, so the slice below is always safe.\n const frame = buffer.slice(0, sep.index);\n buffer = buffer.slice(sep.index + sep[0].length);\n frames.push(parseMatrxSseFrame(frame));\n }\n return frames;\n },\n flush() {\n const rest = buffer;\n buffer = \"\";\n return { incomplete: rest.length > 0 ? rest : null };\n },\n };\n}\n\nexport interface ReadMatrxSseOptions {\n /**\n * Called with any unterminated trailing text at stream end (a frame the\n * server never finished — diagnostic, not a delivered event).\n */\n onIncomplete?: (text: string) => void;\n}\n\n/**\n * Async-iterate the frames of a byte stream (e.g. `response.body`), handling\n * split UTF-8 across chunk boundaries. Cancellation follows the reader: abort\n * the fetch and the iterator ends; a transport error after complete frames\n * were yielded surfaces AFTER those frames, with its original cause.\n */\nexport async function* readMatrxSseStream(\n stream: ReadableStream<Uint8Array>,\n options: ReadMatrxSseOptions = {},\n): AsyncGenerator<MatrxSseFrame, void, undefined> {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n const framer = createMatrxSseFramer();\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n const frames = framer.push(decoder.decode(value, { stream: true }));\n for (const frame of frames) yield frame;\n }\n const tail = framer.push(decoder.decode());\n for (const frame of tail) yield frame;\n const { incomplete } = framer.flush();\n if (incomplete !== null) options.onIncomplete?.(incomplete);\n } finally {\n reader.releaseLock();\n }\n}\n","/**\n * Runtime operations — the canonical reconnect & resume read surface of the\n * execution spine, over the `MatrxTransport` port.\n *\n * Server truth (verified against aidream source,\n * `aidream/api/routers/runtime_operations.py` + `aidream/services/runtime/\n * reconnect.py`; mounted at bare `/runtime`):\n * - `GET /runtime/operations/{request_id}` — identify by `X-Request-ID`\n * - `GET /runtime/operations/by-link/{kind}/{id}` — identify by feature record\n * - `GET /runtime/executions/{id}/events` — durable seq-cursored page\n * - `GET /runtime/executions/{id}/events/stream` — SSE replay-then-follow,\n * `id:` = per-tree seq, reconnect with `Last-Event-ID`\n * - `POST /runtime/operations/{request_id}/rejoin` — replay + follow the\n * ORIGINAL NDJSON response while its detached task is alive (409 when live\n * delivery is unavailable — fall back to the durable lifecycle stream)\n *\n * The contract: identify → recover durable progress → follow live → re-query\n * the final result from the feature's own record. Token text is deliberately\n * never replayed on the lifecycle stream — that is what `/rejoin` is for.\n *\n * The SSE wire rides the package's own `stream/sse` kernel. This module owns\n * ONE connection's semantics (frames → typed events, cursor advancement,\n * terminal `end`); stall timers, retry budgets, and reconnect loops stay host\n * policy — every yielded item carries the cursor the next attempt resumes from.\n */\n\nimport { readMatrxSseStream, type MatrxSseFrame } from \"../stream/sse\";\nimport type { MatrxJsonObject } from \"./conversation\";\nimport {\n encodePathSegment,\n buildQuery,\n requestJson,\n requestStream,\n toRunHandle,\n type MatrxRunHandle,\n type MatrxStreamCallOptions,\n} from \"./internal\";\nimport { MatrxApiError, type MatrxTransport } from \"./transport\";\n\n// ─── Wire types (mirroring `aidream/services/runtime/reconnect.py`) ─────────\n\n/** `matrx_runtime.models.ExecutionStatus` — the only progress column. */\nexport type MatrxRuntimeExecutionStatus =\n | \"pending\"\n | \"running\"\n | \"paused\"\n | \"waiting_input\"\n | \"completed\"\n | \"failed\"\n | \"cancelled\";\n\nexport const TERMINAL_MATRX_RUNTIME_STATUSES: ReadonlySet<MatrxRuntimeExecutionStatus> =\n new Set([\"completed\", \"failed\", \"cancelled\"]);\n\nconst RUNTIME_STATUSES: ReadonlySet<string> = new Set([\n \"pending\",\n \"running\",\n \"paused\",\n \"waiting_input\",\n \"completed\",\n \"failed\",\n \"cancelled\",\n]);\n\n/** One durable spine event on the wire (`OperationEvent`) — `seq` is the reconnect cursor. */\nexport interface MatrxRuntimeOperationEvent {\n seq: number | null;\n /** Lifecycle vocabulary: created | started | paused | resumed | waiting_input | completed | failed | cancelled | checkpoint_saved | note. */\n kind: string;\n execution_id: string;\n root_execution_id: string | null;\n detail: MatrxJsonObject | null;\n created_at: string | null;\n}\n\n/** One root execution as a reconnecting client sees it (`OperationView`). */\nexport interface MatrxRuntimeOperationView {\n execution_id: string;\n /** Durable request identity — feeds `/rejoin` and no-prompt resume recovery. */\n request_id: string | null;\n type: string;\n status: MatrxRuntimeExecutionStatus;\n is_terminal: boolean;\n waiting_input: boolean;\n /** Decimal on the wire — may arrive as number or string; display-only. */\n cost: number | string;\n meters: Record<string, number | string>;\n link_kind: string | null;\n link_id: string | null;\n error: MatrxJsonObject | null;\n created_at: string | null;\n started_at: string | null;\n ended_at: string | null;\n last_event_seq: number;\n events_path: string;\n stream_path: string;\n}\n\nexport interface MatrxOperationStatusResponse {\n request_id: string;\n operation_count: number;\n operations: MatrxRuntimeOperationView[];\n}\n\nexport interface MatrxOperationsByLinkResponse {\n link_kind: string;\n link_id: string;\n operation_count: number;\n operations: MatrxRuntimeOperationView[];\n}\n\nexport interface MatrxOperationEventsPage {\n execution_id: string;\n root_execution_id: string;\n events: MatrxRuntimeOperationEvent[];\n /** Feeds the next page or the SSE `Last-Event-ID` — polling and push share ONE cursor. */\n next_after_seq: number;\n has_more: boolean;\n root_status: MatrxRuntimeExecutionStatus;\n root_is_terminal: boolean;\n}\n\n// ─── Identify + durable progress ────────────────────────────────────────────\n\n/**\n * Where is my operation? Resolves an `X-Request-ID` to its root execution(s).\n * Returns null on 404 — missing and unowned share one shape by design\n * (existence is never leaked).\n */\nexport async function getRuntimeOperationStatus(\n transport: MatrxTransport,\n requestId: string,\n options: { signal?: AbortSignal } = {},\n): Promise<MatrxOperationStatusResponse | null> {\n try {\n return await requestJson<MatrxOperationStatusResponse>(\n transport,\n `/runtime/operations/${encodePathSegment(requestId)}`,\n { method: \"GET\", ...(options.signal ? { signal: options.signal } : {}) },\n );\n } catch (error) {\n if (error instanceof MatrxApiError && error.status === 404) return null;\n throw error;\n }\n}\n\n/**\n * Operations for a feature record — e.g. `(\"conversation\", conversationId)`,\n * `(\"workflow\", runId)`, `(\"agent_run\", runId)`. Newest first; unowned trees\n * omitted. Returns null on 404 (surface absent, or the caller owns nothing —\n * one shape by design).\n */\nexport async function getRuntimeOperationsByLink(\n transport: MatrxTransport,\n linkKind: string,\n linkId: string,\n options: { limit?: number; signal?: AbortSignal } = {},\n): Promise<MatrxOperationsByLinkResponse | null> {\n const query = buildQuery(\n options.limit !== undefined ? { limit: options.limit } : {},\n );\n try {\n return await requestJson<MatrxOperationsByLinkResponse>(\n transport,\n `/runtime/operations/by-link/${encodePathSegment(linkKind)}/${encodePathSegment(linkId)}${query}`,\n { method: \"GET\", ...(options.signal ? { signal: options.signal } : {}) },\n );\n } catch (error) {\n if (error instanceof MatrxApiError && error.status === 404) return null;\n throw error;\n }\n}\n\n/**\n * Durable progress page for the whole operation TREE:\n * `GET /runtime/executions/{id}/events?after_seq=…`. Pass any node id — it\n * resolves to the root.\n */\nexport function listRuntimeOperationEvents(\n transport: MatrxTransport,\n executionId: string,\n options: {\n afterSeq?: number;\n limit?: number;\n /** Repeatable event-kind filter. */\n kinds?: readonly string[];\n signal?: AbortSignal;\n } = {},\n): Promise<MatrxOperationEventsPage> {\n const query = buildQuery({\n ...(options.afterSeq !== undefined ? { after_seq: options.afterSeq } : {}),\n ...(options.limit !== undefined ? { limit: options.limit } : {}),\n ...(options.kinds !== undefined ? { kind: options.kinds } : {}),\n });\n return requestJson<MatrxOperationEventsPage>(\n transport,\n `/runtime/executions/${encodePathSegment(executionId)}/events${query}`,\n { method: \"GET\", ...(options.signal ? { signal: options.signal } : {}) },\n );\n}\n\n// ─── SSE follow (replay-then-follow with Last-Event-ID) ─────────────────────\n\n/**\n * One item from the follow stream. Every item carries `cursor` — the highest\n * event seq seen so far, which is exactly the `Last-Event-ID` a reconnect\n * resumes from (host retry policy owns the reconnect loop).\n */\nexport type MatrxOperationFollowEvent =\n | {\n /** A parsed durable spine event. */\n type: \"event\";\n event: MatrxRuntimeOperationEvent;\n /** The frame's SSE `id:` as an integer, when it carried one. */\n seq: number | null;\n cursor: number;\n }\n | {\n /**\n * A frame that carried no deliverable event — a comment heartbeat, an\n * unknown event name, or a malformed payload (also surfaced through\n * `onMalformedFrame`). ANY parsed frame proves the wire is alive: hosts\n * reset stall timers and retry budgets on it.\n */\n type: \"liveness\";\n cursor: number;\n }\n | {\n /** The server's terminal frame — the root settled; the stream is over. */\n type: \"end\";\n status: MatrxRuntimeExecutionStatus | null;\n cursor: number;\n };\n\nexport interface FollowRuntimeOperationOptions {\n /** Resume cursor — the operation view's `last_event_seq` (0 = from start). */\n lastEventSeq?: number;\n /** Abort the follow — the generator simply ends. */\n signal?: AbortSignal;\n /** A frame whose payload failed to parse — never silently dropped. */\n onMalformedFrame?: (frame: MatrxSseFrame, error: unknown) => void;\n /** Unterminated trailing SSE text at stream end (diagnostic, never an event). */\n onIncomplete?: (text: string) => void;\n}\n\nfunction parseEndStatus(data: string | null): MatrxRuntimeExecutionStatus | null {\n if (data === null) return null;\n try {\n const parsed = JSON.parse(data) as unknown;\n if (\n typeof parsed === \"object\" &&\n parsed !== null &&\n typeof (parsed as { status?: unknown }).status === \"string\"\n ) {\n const status = (parsed as { status: string }).status;\n return RUNTIME_STATUSES.has(status)\n ? (status as MatrxRuntimeExecutionStatus)\n : null;\n }\n } catch {\n // malformed end payload — still terminal\n }\n return null;\n}\n\n/**\n * Follow ONE SSE connection of an operation's lifecycle stream:\n * `GET /runtime/executions/{id}/events/stream` with `Last-Event-ID` when\n * resuming past 0. Replays from the cursor, then follows live; a\n * WAITING_INPUT park keeps it open (a resume re-attaches to the same\n * execution and its events continue here). Ends after yielding\n * `{type: \"end\"}` when the root settles; a server close WITHOUT an end frame\n * simply ends the generator — reconnect from the last yielded `cursor` (host\n * retry policy).\n */\nexport async function* followRuntimeOperationEvents(\n transport: MatrxTransport,\n executionId: string,\n options: FollowRuntimeOperationOptions = {},\n): AsyncGenerator<MatrxOperationFollowEvent, void, undefined> {\n let cursor = options.lastEventSeq ?? 0;\n\n const headers: Record<string, string> = { Accept: \"text/event-stream\" };\n if (cursor > 0) headers[\"Last-Event-ID\"] = String(cursor);\n\n const response = await requestStream(\n transport,\n `/runtime/executions/${encodePathSegment(executionId)}/events/stream`,\n {\n method: \"GET\",\n headers,\n ...(options.signal ? { signal: options.signal } : {}),\n },\n );\n\n const frames = readMatrxSseStream(\n response.body as ReadableStream<Uint8Array>,\n options.onIncomplete ? { onIncomplete: options.onIncomplete } : {},\n );\n\n for await (const frame of frames) {\n if (frame.event === \"end\") {\n yield { type: \"end\", status: parseEndStatus(frame.data), cursor };\n return;\n }\n if (frame.event === \"execution_event\" && frame.data !== null) {\n let event: MatrxRuntimeOperationEvent;\n try {\n event = JSON.parse(frame.data) as MatrxRuntimeOperationEvent;\n } catch (error) {\n options.onMalformedFrame?.(frame, error);\n yield { type: \"liveness\", cursor };\n continue;\n }\n if (frame.seq !== null && frame.seq > cursor) cursor = frame.seq;\n yield { type: \"event\", event, seq: frame.seq, cursor };\n continue;\n }\n // Comment heartbeats, unknown event names, data-less frames: liveness.\n yield { type: \"liveness\", cursor };\n }\n}\n\n// ─── Follow to end (the production reconnect policy) ────────────────────────\n\nexport interface FollowRuntimeOperationToEndOptions {\n /** Resume cursor — the operation view's `last_event_seq` (0 = from start). */\n lastEventSeq?: number;\n /** Caller teardown — aborting resolves with `ended: false`. */\n signal?: AbortSignal;\n /**\n * The server pings every ~15s, so a wire that is open but silent past this\n * is dead (buffering proxy, idle-killed connection) — abort the attempt and\n * retry rather than hanging forever. Default 45_000.\n */\n stallTimeoutMs?: number;\n /**\n * Consecutive failed attempts before giving up. A single-server deployment\n * deliberately drains for 60s, then starts a new container — the default\n * budget (60 × 2s) keeps following for ~three minutes so the runtime ledger\n * can bridge that handoff. ANY parsed frame resets the budget. Default 60.\n */\n reconnectLimit?: number;\n /** Delay between attempts. Default 2_000. */\n reconnectDelayMs?: number;\n /** Fired per durable spine event (lifecycle transitions + notes). */\n onEvent: (event: MatrxRuntimeOperationEvent, seq: number | null) => void;\n /** A failed attempt (never silently swallowed when provided). */\n onAttemptError?: (error: unknown) => void;\n /** A frame whose payload failed to parse (the ledger heals gaps on reconnect). */\n onMalformedFrame?: (frame: MatrxSseFrame, error: unknown) => void;\n}\n\nexport interface FollowRuntimeOperationToEndResult {\n /** True when the server sent the terminal `end` frame. */\n ended: boolean;\n /** The root status carried on the `end` frame (when `ended`). */\n status: MatrxRuntimeExecutionStatus | null;\n}\n\n/**\n * Follow an operation's lifecycle stream TO ITS END — the full production\n * reconnect policy over `followRuntimeOperationEvents`: replay-then-follow\n * with bounded reconnects, a stall watchdog, and durable `Last-Event-ID`\n * cursor advancement across attempts.\n *\n * Resolves `{ended: true, status}` on the server's `end` frame (the operation\n * settled); `{ended: false}` when the caller aborted or every reconnect\n * attempt failed. A WAITING_INPUT park keeps the stream open by design — a\n * resume re-attaches to the same execution and its events continue arriving\n * on the same cursor. Any parsed frame — comment heartbeats included —\n * proves the wire is alive and resets both the stall timer and the retry\n * budget.\n */\nexport async function followRuntimeOperationToEnd(\n transport: MatrxTransport,\n executionId: string,\n options: FollowRuntimeOperationToEndOptions,\n): Promise<FollowRuntimeOperationToEndResult> {\n const stallTimeoutMs = options.stallTimeoutMs ?? 45_000;\n const reconnectLimit = options.reconnectLimit ?? 60;\n const reconnectDelayMs = options.reconnectDelayMs ?? 2_000;\n const outer = options.signal;\n\n let cursor = options.lastEventSeq ?? 0;\n let failures = 0;\n\n while (!outer?.aborted && failures < reconnectLimit) {\n const attempt = new AbortController();\n const onOuterAbort = () => attempt.abort();\n outer?.addEventListener(\"abort\", onOuterAbort, { once: true });\n\n let stallTimer: ReturnType<typeof setTimeout> | null = null;\n const armStall = () => {\n if (stallTimer !== null) clearTimeout(stallTimer);\n stallTimer = setTimeout(() => attempt.abort(), stallTimeoutMs);\n };\n\n try {\n const items = followRuntimeOperationEvents(transport, executionId, {\n lastEventSeq: cursor,\n signal: attempt.signal,\n ...(options.onMalformedFrame\n ? { onMalformedFrame: options.onMalformedFrame }\n : {}),\n });\n\n armStall();\n for await (const item of items) {\n armStall();\n failures = 0;\n cursor = item.cursor;\n if (item.type === \"end\") {\n return { ended: true, status: item.status };\n }\n if (item.type === \"event\") {\n options.onEvent(item.event, item.seq);\n }\n }\n // Server closed without an `end` frame (e.g. process restart). Retry —\n // `Last-Event-ID` replays anything missed from the durable ledger.\n failures += 1;\n } catch (error) {\n if (outer?.aborted) break;\n failures += 1;\n options.onAttemptError?.(error);\n } finally {\n if (stallTimer !== null) clearTimeout(stallTimer);\n outer?.removeEventListener(\"abort\", onOuterAbort);\n }\n\n if (!outer?.aborted && failures < reconnectLimit) {\n await new Promise((r) => setTimeout(r, reconnectDelayMs));\n }\n }\n\n return { ended: false, status: null };\n}\n\n// ─── NDJSON rejoin (replay the original response) ───────────────────────────\n\n/**\n * Rejoin the ORIGINAL NDJSON response while its detached task is still alive:\n * `POST /runtime/operations/{request_id}/rejoin`. Replays the response from\n * frame one, then continues live — every frame is sequence-stamped\n * (`stream_seq`), so a same-page reconnect can drop frames it already\n * rendered. Throws `MatrxApiError` with status 409 when live delivery is\n * unavailable — fall back to `followRuntimeOperationEvents` + a final record\n * re-query. The `requestId` must be the server's `X-Request-ID`.\n */\nexport async function rejoinRuntimeOperation(\n transport: MatrxTransport,\n requestId: string,\n options: MatrxStreamCallOptions = {},\n): Promise<MatrxRunHandle> {\n const response = await requestStream(\n transport,\n `/runtime/operations/${encodePathSegment(requestId)}/rejoin`,\n {\n method: \"POST\",\n // The route takes no body model; the reference client posts an empty\n // JSON object. Match it so proxies see an ordinary JSON POST.\n body: {},\n ...(options.signal ? { signal: options.signal } : {}),\n },\n );\n return toRunHandle(response, options);\n}\n","/**\n * Agent run lifecycle against the AI Matrx API — start, continue, resume,\n * cancel — over the `MatrxTransport` port, with every streaming response\n * parsed through the package's ONE NDJSON wire kernel (`stream/ndjson`).\n *\n * Server truth (verified against aidream source):\n * - `POST /ai/agents/{agent_id}` — start (`aidream/api/routers/agents.py`)\n * - `POST /ai/conversations/{conversation_id}` — continue (`aidream/api/routers/conversations.py`)\n * - `POST /ai/conversations/{conversation_id}/resume` — resume after\n * client-delegated tool suspension (same router)\n * - `POST /ai/cancel/{request_id}?mode=interrupt` — cancel (`aidream/api/routers/cancel.py`)\n *\n * Response headers arrive before the body: `X-Conversation-ID` and\n * `X-Request-ID` are surfaced on the run handle immediately. `X-Request-ID`\n * is the ONLY id the server accepts for cancel — a client-local id means\n * nothing to it.\n *\n * Host policy stays out: no retry, no store, no timeouts, no persistence\n * (C10: no-persistence). Cancellation is the caller's `AbortSignal`; a client\n * disconnect never stops server work (`detach_on_disconnect`).\n */\n\nimport type { MatrxStreamEnvelope } from \"../stream/ndjson\";\nimport type {\n MatrxConversationStart,\n MatrxJsonObject,\n MatrxJsonValue,\n} from \"./conversation\";\nimport {\n encodePathSegment,\n buildQuery,\n requestJson,\n requestStream,\n toRunHandle,\n type MatrxRunHandle,\n type MatrxStreamCallOptions,\n} from \"./internal\";\nimport type { MatrxTransport } from \"./transport\";\nimport { streamErrorText } from \"./rejoin\";\n\nexport type { MatrxRunHandle, MatrxStreamCallOptions } from \"./internal\";\n\n// ─── Request shapes (mirroring the server's Pydantic models) ────────────────\n\n/**\n * Stable identity of the durable entity whose saved context owns a run —\n * the server reloads the row and uses ITS scope (`ContextAnchor`,\n * `aidream/services/conversation_context/scope.py`).\n */\nexport interface MatrxContextAnchor {\n resource_type: string;\n resource_id: string;\n}\n\n/**\n * Scope and source fields shared by every scoped request\n * (`ScopedRequest` / `AcceptsInjectedScope` server-side). All optional here;\n * the start request narrows `organization_id` to required.\n */\nexport interface MatrxRequestScope {\n organization_id?: string;\n project_id?: string | null;\n task_id?: string | null;\n /** Active context-scope ids from the client's global picker (membership-validated server-side). */\n scope_ids?: string[] | null;\n /** Active scope-TYPE ids — a type-level selection with no specific scope chosen. */\n active_scope_type_ids?: string[] | null;\n context_anchor?: MatrxContextAnchor | null;\n /** Stable application slug that initiated the request. */\n source_app?: string | null;\n /** Stable feature slug within the source application. */\n source_feature?: string | null;\n /** \"user\" = a person directly triggered this; \"auto\" = client automation; omit for API callers. */\n initiation?: \"user\" | \"auto\" | null;\n /** Specific connected desktop instance allowed to claim delegated local tools. */\n target_instance_id?: string | null;\n}\n\n/**\n * Fields shared by start/continue turn requests (tool injection, client\n * capability envelope, context object). The complex bags (`tools`, `client`,\n * `user`, `config_overrides`) are typed as JSON objects — their authoritative\n * schemas are the server's Pydantic models and the generated API types;\n * this package stays payload-agnostic about them by design.\n */\nexport interface MatrxTurnFields {\n /** What the human typed (string), or structured input parts. Never smuggle machine content here. */\n user_input?: string | MatrxJsonValue[] | null;\n /** Per-run model/config overrides (LLMParams shape). */\n config_overrides?: MatrxJsonObject | null;\n debug?: boolean;\n /** Additive tool specs merged into the agent's resolved tool set. */\n tools?: MatrxJsonObject[];\n /** When set, becomes the agent's ENTIRE tool set for the turn. */\n tools_replace?: MatrxJsonObject[] | null;\n /** Client capability envelope (`ClientContext`). */\n client?: MatrxJsonObject | null;\n /** Per-request user-level tool inclusion/exclusion overrides. */\n user?: MatrxJsonObject | null;\n /** Per-route context object, free-form by design. */\n context?: MatrxJsonObject;\n writable_variables?: string[];\n allow_context_create?: boolean;\n /** Request-snapshot capture override (tri-state; omit for the platform default). */\n snapshot?: boolean | null;\n}\n\n/**\n * `POST /ai/agents/{agent_id}` body (`AgentStartRequest` server-side).\n * The conversation-start triple is required by construction; `organization_id`\n * is required (the server 422s a blank one — it never manufactures an org).\n * `stream` is not accepted here: this client is the streaming path and always\n * sends `stream: true`.\n */\nexport type MatrxAgentStartRequest = MatrxConversationStart &\n Omit<MatrxRequestScope, \"organization_id\"> &\n MatrxTurnFields & {\n organization_id: string;\n /** Variable name → value map filling the agent's declared variables. */\n variables?: MatrxJsonObject | null;\n /** Run the versions table row instead of the live agent row. */\n is_version?: boolean;\n max_iterations?: number;\n max_retries_per_iteration?: number;\n };\n\n/**\n * `POST /ai/mandates/{mandate_key}` uses the exact saved-agent start body.\n * The server resolves the mandate's holder, binding, and configuration; a\n * client must offer only the declared variables and human input here.\n */\nexport type MatrxMandateStartRequest = MatrxAgentStartRequest;\n\n/** `POST /ai/conversations/{id}` body (`ConversationContinueRequest` server-side). */\nexport type MatrxConversationContinueRequest = MatrxRequestScope &\n MatrxTurnFields & {\n /** Re-run the conversation's current persisted state (recovery after a failed turn); omit `user_input`. */\n retry?: boolean;\n };\n\n/**\n * `POST /ai/conversations/{id}/resume` body (`ResumeRequest` server-side) —\n * the shipped durable continuation after client-delegated tool calls were\n * answered via `POST /tool_results` while the original stream was gone.\n * `user_request_id` is optional: when omitted the server resolves the turn\n * from the conversation's newest answered client-delegated tool call.\n * Re-send fresh `context` here — a resumed loop is otherwise context-blind.\n */\nexport type MatrxConversationResumeRequest = MatrxRequestScope & {\n user_request_id?: string | null;\n config_overrides?: MatrxJsonObject | null;\n debug?: boolean;\n tools?: MatrxJsonObject[];\n tools_replace?: MatrxJsonObject[] | null;\n client?: MatrxJsonObject | null;\n user?: MatrxJsonObject | null;\n context?: MatrxJsonObject;\n writable_variables?: string[];\n allow_context_create?: boolean;\n};\n\n/** `POST /ai/cancel/{request_id}` response (`CancelResponse` server-side). */\nexport interface MatrxCancelResponse {\n status: string;\n request_id: string;\n spine_executions_signalled: string[];\n}\n\n// ─── The run handle ─────────────────────────────────────────────────────────\n// `MatrxStreamCallOptions`, `MatrxRunHandle`, and the handle constructor live\n// in ./internal so `./operations`' rejoin shares the exact same construction.\n\nasync function streamCall(\n transport: MatrxTransport,\n path: string,\n body: object,\n options: MatrxStreamCallOptions,\n): Promise<MatrxRunHandle> {\n const response = await requestStream(transport, path, {\n method: \"POST\",\n // This client IS the streaming path — `stream: true` always, last so a\n // caller-supplied value can never flip the response off NDJSON.\n body: { ...body, stream: true },\n ...(options.signal ? { signal: options.signal } : {}),\n });\n return toRunHandle(response, options);\n}\n\n// ─── Lifecycle calls ────────────────────────────────────────────────────────\n\n/** Start an agent run: `POST /ai/agents/{agent_id}` (NDJSON stream). */\nexport function startAgentRun(\n transport: MatrxTransport,\n agentId: string,\n request: MatrxAgentStartRequest,\n options: MatrxStreamCallOptions = {},\n): Promise<MatrxRunHandle> {\n return streamCall(\n transport,\n `/ai/agents/${encodePathSegment(agentId)}`,\n request,\n options,\n );\n}\n\n/**\n * Start a declared mandate: `POST /ai/mandates/{mandate_key}` (NDJSON\n * stream). This is deliberately separate from `startAgentRun`: callers name\n * the mandate and never resolve or echo its holder/configuration themselves.\n */\nexport function startMandateRun(\n transport: MatrxTransport,\n mandateKey: string,\n request: MatrxMandateStartRequest,\n options: MatrxStreamCallOptions = {},\n): Promise<MatrxRunHandle> {\n return streamCall(\n transport,\n `/ai/mandates/${encodePathSegment(mandateKey)}`,\n request,\n options,\n );\n}\n\n/** Continue a stored conversation: `POST /ai/conversations/{id}` (NDJSON stream). */\nexport function continueAgentConversation(\n transport: MatrxTransport,\n conversationId: string,\n request: MatrxConversationContinueRequest,\n options: MatrxStreamCallOptions = {},\n): Promise<MatrxRunHandle> {\n return streamCall(\n transport,\n `/ai/conversations/${encodePathSegment(conversationId)}`,\n request,\n options,\n );\n}\n\n/**\n * Resume a suspended loop after delegated tool answers landed:\n * `POST /ai/conversations/{id}/resume` (NDJSON stream). A 409\n * (`resume_conflict`) means another resume holds the run claim — retrying is\n * host policy.\n */\nexport function resumeAgentConversation(\n transport: MatrxTransport,\n conversationId: string,\n request: MatrxConversationResumeRequest = {},\n options: MatrxStreamCallOptions = {},\n): Promise<MatrxRunHandle> {\n return streamCall(\n transport,\n `/ai/conversations/${encodePathSegment(conversationId)}/resume`,\n request,\n options,\n );\n}\n\n/**\n * Stop a running request at its next iteration boundary:\n * `POST /ai/cancel/{request_id}`. Cooperative and best-effort — the in-flight\n * provider call finishes by design, and everything already streamed persists.\n * `mode: \"interrupt\"` = stop-and-fork: the tail after the last clean boundary\n * persists hidden so the user's follow-up replies to what they actually saw.\n * The id must be the server's `X-Request-ID`.\n */\nexport function cancelAgentRun(\n transport: MatrxTransport,\n requestId: string,\n options: { mode?: \"cancel\" | \"interrupt\"; signal?: AbortSignal } = {},\n): Promise<MatrxCancelResponse> {\n const query = buildQuery(\n options.mode === \"interrupt\" ? { mode: \"interrupt\" } : {},\n );\n return requestJson<MatrxCancelResponse>(\n transport,\n `/ai/cancel/${encodePathSegment(requestId)}${query}`,\n {\n method: \"POST\",\n ...(options.signal ? { signal: options.signal } : {}),\n },\n );\n}\n\n// ─── End-to-end convenience: run to completion ──────────────────────────────\n\n/**\n * A run that terminated unsuccessfully: the server emitted a fatal `error`\n * event, or the `user_request` completion settled `failed`/`cancelled`.\n */\nexport class MatrxRunError extends Error {\n override readonly name = \"MatrxRunError\";\n /** The verbatim `error` event payload, when one fired. */\n readonly errorPayload: Record<string, unknown> | null;\n /** The `user_request` completion status (`\"failed\"` | `\"cancelled\"`), when that was the trigger. */\n readonly completionStatus: string | null;\n /** Text streamed before the failure — partial content never vanishes. */\n readonly partialText: string;\n\n constructor(args: {\n message: string;\n errorPayload?: Record<string, unknown> | null;\n completionStatus?: string | null;\n partialText?: string;\n }) {\n super(args.message);\n this.errorPayload = args.errorPayload ?? null;\n this.completionStatus = args.completionStatus ?? null;\n this.partialText = args.partialText ?? \"\";\n }\n}\n\nexport interface MatrxCompletedRun {\n /** Accumulated `chunk` text (falls back to the completion's `result.output`). */\n text: string;\n requestId: string | null;\n conversationId: string | null;\n /** The `user_request` completion payload, verbatim, when one arrived. */\n completion: Record<string, unknown> | null;\n}\n\nexport interface RunAgentToCompletionOptions extends MatrxStreamCallOptions {\n /** Live progress: the full accumulated text after each chunk. */\n onChunk?: (fullText: string) => void;\n /** Every normalized envelope, before this helper interprets it. */\n onEvent?: (envelope: MatrxStreamEnvelope) => void;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction stringField(value: unknown, key: string): string | null {\n if (!isRecord(value)) return null;\n const field = value[key];\n return typeof field === \"string\" && field ? field : null;\n}\n\n/**\n * Run an agent end-to-end and resolve with its full text output — the\n * package-level equivalent of the simplest existing host path\n * (`useRunAgent`): accumulate `chunk` text, treat a fatal `error` event or a\n * `failed`/`cancelled` `user_request` completion as a thrown `MatrxRunError`,\n * and fall back to the completion's `result.output` when no text streamed.\n *\n * The caller still owns the conversation-start triple on `request` — a\n * one-shot run typically uses `newEphemeralConversationStart()`.\n */\nexport async function runAgentToCompletion(\n transport: MatrxTransport,\n agentId: string,\n request: MatrxAgentStartRequest,\n options: RunAgentToCompletionOptions = {},\n): Promise<MatrxCompletedRun> {\n const handle = await startAgentRun(transport, agentId, request, options);\n\n let text = \"\";\n let completion: Record<string, unknown> | null = null;\n let failure: MatrxRunError | null = null;\n\n for await (const envelope of handle.events) {\n options.onEvent?.(envelope);\n\n if (envelope.event === \"chunk\") {\n const chunk = stringField(envelope.data, \"text\");\n if (chunk !== null) {\n text += chunk;\n options.onChunk?.(text);\n }\n continue;\n }\n\n if (envelope.event === \"error\" && failure === null) {\n const payload = isRecord(envelope.data) ? envelope.data : null;\n failure = new MatrxRunError({\n message: streamErrorText(payload) ?? \"The agent run failed\",\n errorPayload: payload,\n partialText: text,\n });\n continue;\n }\n\n if (envelope.event !== \"completion\" || !isRecord(envelope.data)) continue;\n // `init`/`completion` pairs exist for five operations; the terminal\n // outcome of the run is the `user_request` completion (STREAM-CONTRACT\n // §3.2 — always present, always last).\n if (envelope.data.operation !== \"user_request\") continue;\n\n completion = envelope.data;\n const status = envelope.data.status;\n if ((status === \"failed\" || status === \"cancelled\") && failure === null) {\n const result = isRecord(envelope.data.result) ? envelope.data.result : null;\n failure = new MatrxRunError({\n message:\n stringField(result, \"error\") ??\n stringField(result, \"user_message\") ??\n `The agent run ${status}`,\n completionStatus: status,\n partialText: text,\n });\n }\n }\n\n if (failure) throw failure;\n\n if (!text && completion) {\n const result = completion.result;\n const output = stringField(result, \"output\");\n if (output !== null) text = output;\n }\n\n return {\n text,\n requestId: handle.requestId,\n conversationId: handle.conversationId,\n completion,\n };\n}\n"],"mappings":";;;;AAEA,YAAY,WAAW;AAMvB;AAAA,EACE;AAAA,OAEK;;;ACTP;AAAA,EACE;AAAA,EACA;AAAA,OAGK;;;ACsBA,IAAM,eAAe;AAAA,EAC1B,yBAAyB;AAAA,EACzB,mCAAmC;AAAA,EACnC,sBAAsB;AAAA,EACtB,4BAA4B;AAAA,E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