@mengine/medeo-tool 1.4.1-alpha.0 → 1.4.1-alpha.2
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/README.md +29 -5
- package/dist/{entity-contract-DHasvrhq.d.mts → entity-contract-Cpf3P69H.d.mts} +7 -2
- package/dist/index.d.mts +13 -2
- package/dist/index.mjs +51 -10
- package/dist/index.mjs.map +1 -1
- package/dist/sandbox-api.d.mts +24 -6
- package/dist/{script-session-DTq_VPEA.mjs → script-session-lXpqmupK.mjs} +7 -5
- package/dist/script-session-lXpqmupK.mjs.map +1 -0
- package/dist/worker-entry.d.mts +1 -1
- package/dist/worker-entry.mjs +125 -3
- package/dist/worker-entry.mjs.map +1 -1
- package/package.json +2 -2
- package/dist/script-session-DTq_VPEA.mjs.map +0 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["stableId","isRecord","isRecord"],"sources":["../src/sandbox/node-host.ts","../src/entity/caption-asset-assembly.ts","../src/entity/entity-contract.ts","../src/entity/entity-http-client.ts","../src/entity/generation-sync.ts","../src/sandbox/generated/entity-edit-sandbox-model-context.ts","../src/prompt.ts","../src/schema.ts","../src/session/commit-plan.ts","../src/host-tool.ts","../src/entity/materialize-resources.ts"],"sourcesContent":["/// <reference types=\"node\" />\n\nimport { Worker } from 'node:worker_threads';\n\nimport type { JournalEntry, VideoDocument } from '@mengine/medeo-client';\n\nimport type { EntityCommand, EntityStoreSnapshot } from '../entity/entity-contract.ts';\nimport type { ChangePlan } from './script-session.ts';\n\n/**\n * Host API for running an agent edit script in an isolated Node worker.\n *\n * Requires Node.js >= 24.15 (engines) so the worker can load TypeScript via\n * `--experimental-transform-types`. Do not inherit `process.execArgv` — vitest\n * injects loaders that break worker boot.\n */\n\nexport interface RunEditScriptOptions {\n document: VideoDocument;\n baseVersion: string;\n script: string;\n inputs?: Record<string, unknown>;\n /** Authoritative entity/relation rows and revision fetched for this document. */\n entityState?: EntityStoreSnapshot;\n /** Deterministic id mint label for tests; omit to use the default ULID factory. */\n idLabel?: string;\n /** @internal Select the graph-native Entity session used by the production host. */\n entityOnly?: boolean;\n /** Hard wall-clock timeout; default 2000 ms. */\n timeoutMs?: number;\n /** V8 old-generation ceiling for the worker; default 256 MB. */\n memoryLimitMb?: number;\n /** Override worker module URL (defaults to sibling `worker-entry.ts`). */\n workerEntryUrl?: URL;\n}\n\nexport type EditScriptResult =\n | {\n ok: true;\n plan: ChangePlan;\n /** Script execution time after worker readiness; excludes cold start. */\n durationMs: number;\n }\n | {\n ok: false;\n phase: 'parse' | 'runtime' | 'timeout' | 'memory';\n error: { message: string; line?: number; column?: number; stack?: string };\n partial: {\n ops: readonly JournalEntry[];\n entityCommands: readonly EntityCommand[];\n logs: string[];\n };\n };\n\ntype WorkerMessage =\n | { t: 'ready' }\n | { t: 'entry'; entry: JournalEntry }\n | { t: 'entity-entry'; command: EntityCommand }\n | { t: 'log'; line: string }\n | { t: 'truncate'; index: number }\n | { t: 'entity-truncate'; index: number }\n | {\n t: 'done';\n preview: string;\n opsCount: number;\n entityCommandsCount: number;\n loroUpdate?: string;\n entityBaseRevision: number;\n entityRows?: EntityStoreSnapshot;\n deletedEntityIds: readonly string[];\n deletedRelationIds: readonly string[];\n planKind: 'timeline' | 'entities';\n }\n | {\n t: 'fail';\n phase: 'parse' | 'runtime';\n error: { message: string; line?: number; column?: number; stack?: string };\n };\n\nconst DEFAULT_TIMEOUT_MS = 2000;\nconst DEFAULT_MEMORY_MB = 256;\n\n/**\n * Source runs load the checked-in TypeScript worker; packed runs load the\n * sibling JavaScript chunk emitted as a second package entry. Keeping this\n * branch explicit avoids shipping a `dist/*.ts` URL in the npm artifact.\n */\nfunction sourceSibling(fileName: string): URL {\n const selfUrl = new URL(import.meta.url);\n const extension = selfUrl.pathname.endsWith('.ts') ? 'ts' : 'mjs';\n return new URL(`./${fileName}.${extension}`, selfUrl);\n}\n\n/** Run `script` against a forked document snapshot; always resolves (never rejects). */\nexport function runEditScript(options: RunEditScriptOptions): Promise<EditScriptResult> {\n // Set when the worker has loaded its bundle and is about to invoke the script.\n // Keep this clock separate from worker boot so success timing matches the\n // timeout boundary and excludes cold-start/module-loading cost.\n let scriptStartedAt = performance.now();\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const memoryLimitMb = options.memoryLimitMb ?? DEFAULT_MEMORY_MB;\n const workerEntryUrl = options.workerEntryUrl ?? sourceSibling('worker-entry');\n const resolveRegisterUrl = sourceSibling('node-esm-resolve-register');\n\n const ops: JournalEntry[] = [];\n const entityCommands: EntityCommand[] = [];\n const logs: string[] = [];\n\n return new Promise<EditScriptResult>((resolve) => {\n let settled = false;\n let timedOut = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const worker = new Worker(workerEntryUrl, {\n workerData: {\n document: options.document,\n script: options.script,\n inputs: options.inputs,\n entityState: options.entityState,\n idLabel: options.idLabel,\n entityOnly: options.entityOnly,\n },\n // Explicit argv only — never inherit process.execArgv (vitest loaders).\n // Source workers need TypeScript transform plus the resolver hook for\n // workspace packages that still use extensionless directory imports.\n // Packed JavaScript workers already contain those dependencies.\n execArgv: resolveRegisterUrl.pathname.endsWith('.ts')\n ? [\n '--experimental-transform-types',\n '--disable-warning=ExperimentalWarning',\n `--import=${resolveRegisterUrl.href}`,\n ]\n : [],\n resourceLimits: { maxOldGenerationSizeMb: memoryLimitMb },\n });\n\n /** Start wall-clock timeout only after worker signals script is about to run. */\n const armTimeout = (): void => {\n if (settled || timer != null) return;\n timer = setTimeout(() => {\n timedOut = true;\n void worker.terminate();\n finish({\n ok: false,\n phase: 'timeout',\n error: { message: `edit script exceeded timeout of ${timeoutMs}ms` },\n partial: {\n ops: ops.slice(),\n entityCommands: entityCommands.slice(),\n logs: logs.slice(),\n },\n });\n }, timeoutMs);\n };\n\n const finish = (result: EditScriptResult): void => {\n if (settled) return;\n settled = true;\n if (timer != null) clearTimeout(timer);\n void worker.terminate();\n if (result.ok) {\n resolve({ ...result, durationMs: performance.now() - scriptStartedAt });\n } else {\n resolve(result);\n }\n };\n\n worker.on('message', (message: WorkerMessage) => {\n if (settled) return;\n if (message.t === 'ready') {\n scriptStartedAt = performance.now();\n armTimeout();\n return;\n }\n if (message.t === 'entry') {\n ops.push(message.entry);\n return;\n }\n if (message.t === 'entity-entry') {\n entityCommands.push(message.command);\n return;\n }\n if (message.t === 'log') {\n logs.push(message.line);\n return;\n }\n if (message.t === 'truncate') {\n ops.length = Math.max(0, Math.min(message.index, ops.length));\n return;\n }\n if (message.t === 'entity-truncate') {\n entityCommands.length = Math.max(0, Math.min(message.index, entityCommands.length));\n return;\n }\n if (message.t === 'done') {\n if (message.opsCount !== ops.length || message.entityCommandsCount !== entityCommands.length) {\n finish({\n ok: false,\n phase: 'runtime',\n error: {\n message:\n `journal count mismatch: worker reported timeline=${message.opsCount}, entities=${message.entityCommandsCount}; ` +\n `host collected timeline=${ops.length}, entities=${entityCommands.length}`,\n },\n partial: {\n ops: ops.slice(),\n entityCommands: entityCommands.slice(),\n logs: logs.slice(),\n },\n });\n return;\n }\n finish({\n ok: true,\n plan: {\n plan_kind: message.planKind,\n doc_id: options.document.meta.draft_id ?? '',\n base_version: options.baseVersion,\n ops: ops.slice(),\n ...(message.loroUpdate ? { loro_update: message.loroUpdate } : {}),\n entity_base_revision: message.entityBaseRevision,\n entity_commands: entityCommands.slice(),\n ...(message.entityRows !== undefined ? { entity_rows: message.entityRows } : {}),\n deleted_entity_ids: message.deletedEntityIds,\n deleted_relation_ids: message.deletedRelationIds,\n preview: message.preview,\n logs: logs.slice(),\n },\n durationMs: 0,\n });\n return;\n }\n if (message.t === 'fail') {\n finish({\n ok: false,\n phase: message.phase,\n error: message.error,\n partial: {\n ops: ops.slice(),\n entityCommands: entityCommands.slice(),\n logs: logs.slice(),\n },\n });\n }\n });\n\n worker.on('error', (error: Error) => {\n if (settled) return;\n const text = error.message ?? String(error);\n const phase = /memory limit/i.test(text) ? 'memory' : 'runtime';\n finish({\n ok: false,\n phase,\n error: { message: text, stack: error.stack },\n partial: {\n ops: ops.slice(),\n entityCommands: entityCommands.slice(),\n logs: logs.slice(),\n },\n });\n });\n\n worker.on('exit', (code: number) => {\n if (settled) return;\n if (timedOut) return;\n finish({\n ok: false,\n phase: 'runtime',\n error: { message: `worker exited with code ${code ?? 'null'} before completion` },\n partial: {\n ops: ops.slice(),\n entityCommands: entityCommands.slice(),\n logs: logs.slice(),\n },\n });\n });\n });\n}\n","import { createHash } from 'node:crypto';\n\nimport type { SandboxEntity, SandboxRelation } from './entity-contract.ts';\nimport type { EntityHttpClient } from './entity-http-client.ts';\n\n/** Optional physical artifact registered for one immutable Caption identity. */\nexport interface CaptionAssetFact {\n readonly captionEntityId: string;\n readonly assetId: string;\n readonly storageKey: string;\n}\n\n/** Host-only lookup. Missing facts mean the Caption has no physical artifact. */\nexport type CaptionAssetsLoader = (\n docId: string,\n captionEntityIds: readonly string[],\n) => Promise<readonly CaptionAssetFact[]>;\n\nexport interface CaptionAssetAssemblyOutcome {\n readonly status: 'applied' | 'current' | 'failed';\n readonly message?: string;\n}\n\n/** Assemble optional infrastructure after business execution, using exact entity identity. */\nexport async function assembleCaptionAssets(input: {\n client: EntityHttpClient;\n docId: string;\n loadAssets: CaptionAssetsLoader;\n}): Promise<CaptionAssetAssemblyOutcome> {\n try {\n const state = await input.client.fetchState();\n const candidates = state.entities.filter(\n (entity) =>\n entity.entity_kind === 'caption' &&\n !state.relations.some(\n (relation) =>\n relation.relation_kind === 'physical-asset' &&\n (relation.endpoint_0_entity_id === entity.entity_id || relation.endpoint_1_entity_id === entity.entity_id),\n ),\n );\n if (!candidates.length) return { status: 'current' };\n const ids = new Set(candidates.map((entity) => entity.entity_id));\n const facts = await input.loadAssets(input.docId, [...ids]);\n const entities: SandboxEntity[] = [...state.entities];\n const relations: SandboxRelation[] = [...state.relations];\n const bound = new Map<string, string>();\n for (const fact of facts) {\n if (!ids.has(fact.captionEntityId) || !trimmed(fact.assetId) || !trimmed(fact.storageKey))\n throw new Error('Caption Asset fact must identify a requested Caption and a real Asset locator');\n const previous = bound.get(fact.captionEntityId);\n if (previous !== undefined) {\n if (previous !== fact.assetId) throw new Error(`Conflicting Assets for Caption ${fact.captionEntityId}`);\n continue;\n }\n bound.set(fact.captionEntityId, fact.assetId);\n const matches = entities.filter((entity) => {\n const external = entity.payload.external;\n return (\n external !== null &&\n typeof external === 'object' &&\n !Array.isArray(external) &&\n external.system === 'memota' &&\n external.key === fact.assetId\n );\n });\n if (matches.length > 1 || (matches[0] && matches[0].entity_kind !== 'asset'))\n throw new Error(`Conflicting resource identity for Caption Asset ${fact.assetId}`);\n let asset = matches[0];\n if (asset && asset.payload.storageKey !== fact.storageKey)\n throw new Error(`Conflicting storage key for Caption Asset ${fact.assetId}`);\n if (!asset) {\n asset = {\n entity_id: stableId('asset', fact.assetId),\n entity_kind: 'asset',\n payload: { external: { system: 'memota', key: fact.assetId }, storageKey: fact.storageKey },\n };\n if (entities.some((entity) => entity.entity_id === asset!.entity_id))\n throw new Error('Caption Asset identity collision');\n entities.push(asset);\n }\n relations.push({\n relation_id: stableId('relation', fact.captionEntityId, asset.entity_id),\n relation_kind: 'physical-asset',\n endpoint_0_entity_id: fact.captionEntityId,\n endpoint_1_entity_id: asset.entity_id,\n metadata: {},\n trace: {},\n });\n }\n if (!bound.size) return { status: 'current' };\n await input.client.commit(state.revision, { ...state, entities, relations });\n return { status: 'applied' };\n } catch (error) {\n return { status: 'failed', message: error instanceof Error ? error.message : String(error) };\n }\n}\n\nfunction stableId(prefix: string, ...parts: string[]): string {\n return `${prefix}_${createHash('sha256').update(JSON.stringify(parts)).digest('hex')}`;\n}\nfunction trimmed(value: string): boolean {\n return typeof value === 'string' && value.length > 0 && value.trim() === value;\n}\n","import type { MediaAssetFact } from '@mengine/medeo-client';\n\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue = JsonPrimitive | JsonObject | JsonValue[];\nexport interface JsonObject {\n [key: string]: JsonValue;\n}\n\nexport type KnownEntityKind =\n | 'axvideo'\n | 'timeline'\n | 'track'\n | 'clip'\n | 'asset'\n | 'video'\n | 'audio'\n | 'voice'\n | 'image'\n | 'sequence-marker'\n | 'viewport'\n | 'audio-script'\n | 'phonetic-script'\n | 'caption';\n\n/** Asset identity, either an old physical-only row or a directly composed media variant. */\nexport type ResourceEntityKind = 'image' | 'video' | 'audio' | 'voice';\n\nexport const KNOWN_ENTITY_KINDS: readonly KnownEntityKind[] = [\n 'axvideo',\n 'timeline',\n 'track',\n 'clip',\n 'asset',\n 'video',\n 'audio',\n 'voice',\n 'image',\n 'sequence-marker',\n 'viewport',\n 'audio-script',\n 'phonetic-script',\n 'caption',\n];\n\nexport type KnownRelationKind =\n | 'timeline-track'\n | 'track-clip'\n | 'clip-marker'\n | 'marker-content'\n | 'axvideo-marker'\n | 'marker-timeline'\n | 'physical-asset'\n | 'generated'\n | 'caption-alignment'\n | 'clip-anchor'\n | 'phonetic-script-render'\n | 'audio-script-source'\n | 'audio-script-marker';\n\nexport const KNOWN_RELATION_KINDS: readonly KnownRelationKind[] = [\n 'timeline-track',\n 'track-clip',\n 'clip-marker',\n 'marker-content',\n 'axvideo-marker',\n 'marker-timeline',\n 'physical-asset',\n 'generated',\n 'caption-alignment',\n 'clip-anchor',\n 'phonetic-script-render',\n 'audio-script-source',\n 'audio-script-marker',\n];\n\nexport type AuthorableRelationKind = Exclude<KnownRelationKind, 'generated'>;\n\nexport interface BoundedNativeSequencePayload extends JsonObject {\n /** Factual coordinates from recalled media metadata; never invent an end/duration. */\n extent: { kind: 'bounded'; start: number; end: number };\n sampling: 'native';\n coordinateSpace: JsonValue;\n}\n\nexport interface UnboundedConstantSequencePayload extends JsonObject {\n extent: { kind: 'unbounded'; start: number };\n sampling: 'constant';\n coordinateSpace: JsonValue;\n}\n\nexport interface BoundedDerivedSequencePayload extends JsonObject {\n extent: { kind: 'bounded'; start: number; end: number };\n sampling: 'derived';\n coordinateSpace: JsonValue;\n}\n\nexport type ScriptTextSegment = JsonObject & {\n segmentId: string;\n text: string;\n language?: string;\n};\n\nexport type MediaAssetPayload = JsonObject & {\n external: { system: 'memota' | 'memota-speech'; key: string };\n storageKey?: string;\n};\n\nexport type CaptionTextSelection = JsonObject & {\n segmentId: string;\n /** Half-open Unicode code-point range within the selected source segment. */\n textRange?: { start: number; end: number };\n};\n\n/** Read result only: base text is assembled from the real AudioScript row. */\nexport interface ComposedScriptContent {\n audio_script_entity_id: string;\n text: string;\n segments: ScriptTextSegment[];\n}\n\nexport interface ComposedPhoneticContent extends ComposedScriptContent {\n phonemeScript?: string;\n prosody?: JsonObject;\n}\n\nexport interface EntityPayloadByKind {\n axvideo: BoundedDerivedSequencePayload;\n timeline: JsonObject;\n track: JsonObject & { hidden?: boolean; role?: string };\n clip: JsonObject;\n /** Physical resource fields; never a copy of Caption content. */\n asset: JsonObject;\n video: BoundedNativeSequencePayload & MediaAssetPayload;\n audio: BoundedNativeSequencePayload & MediaAssetPayload;\n voice: BoundedNativeSequencePayload & MediaAssetPayload;\n image: UnboundedConstantSequencePayload & MediaAssetPayload;\n 'sequence-marker': JsonObject & {\n sourceRange: { start: number; end: number };\n targetRange?: { start: number; end: number };\n duration: { mode: 'from-source' } | { mode: 'fixed'; value: number };\n timeRemapping?: JsonValue;\n anchorOffset?: number;\n durationPolicy?: 'timeline';\n /** Directly assigned AudioScript annotation times; annotation Markers only. */\n segmentRanges?: { segmentId: string; startMs: number; endMs: number }[];\n };\n viewport: JsonObject;\n 'audio-script': JsonObject & { segments: ScriptTextSegment[] };\n 'phonetic-script': JsonObject & { baseEntityIds: string[]; phonemeScript?: string; prosody?: JsonObject };\n caption: BoundedNativeSequencePayload & {\n baseEntityIds: string[];\n selections: CaptionTextSelection[];\n style?: JsonObject;\n };\n}\n\n/** Stored own fields; a variant may obtain required content fields from its declared bases. */\nexport type StoredEntityPayload<K extends KnownEntityKind> =\n | EntityPayloadByKind[K]\n | (JsonObject & Partial<EntityPayloadByKind[K]> & { baseEntityIds: string[] });\n\nexport interface SandboxEntity<K extends KnownEntityKind = KnownEntityKind> {\n entity_id: string;\n entity_kind: K;\n payload: StoredEntityPayload<K>;\n}\n\nexport interface SandboxRelation {\n relation_id: string;\n relation_kind: KnownRelationKind;\n endpoint_0_entity_id: string;\n endpoint_1_entity_id: string;\n metadata: JsonObject;\n trace: JsonObject;\n}\n\nexport interface EntityStoreSnapshot {\n /** Causal compiler baseline; required for publishing edits. */\n loroSnapshot?: string;\n revision: number;\n /** Current AudioScript version attached to the project; initialized projects always attach a script, possibly empty. */\n audioScriptEntityId: string | null;\n entities: SandboxEntity[];\n relations: SandboxRelation[];\n}\n\nexport type CreateEntityInput = {\n [K in KnownEntityKind]: {\n entity_id?: string;\n entity_kind: K;\n payload: StoredEntityPayload<K>;\n };\n}[KnownEntityKind];\n\n/** Patch supplied fields on the assembled entity; omitted fields remain unchanged. */\nexport interface UpdateEntityInput {\n entity_id: string;\n payload: JsonObject;\n}\n\nexport interface DeleteEntityInput {\n entity_id: string;\n}\n\nexport type EmptyRelationKind =\n | 'timeline-track'\n | 'track-clip'\n | 'clip-marker'\n | 'marker-content'\n | 'axvideo-marker'\n | 'marker-timeline'\n | 'audio-script-marker';\n\ninterface LinkRelationBase {\n relation_id?: string;\n endpoint_0_entity_id: string;\n endpoint_1_entity_id: string;\n trace?: JsonObject;\n}\n\nexport type LinkRelationInput =\n | (LinkRelationBase & {\n relation_kind: EmptyRelationKind;\n metadata?: { [key: string]: never };\n })\n | (LinkRelationBase & {\n relation_kind: 'physical-asset';\n metadata?: JsonObject;\n })\n | (LinkRelationBase & {\n relation_kind: 'caption-alignment';\n metadata: JsonObject & { alignment: JsonValue };\n });\n\nexport interface LinkGeneratedRelationInput {\n relation_id?: string;\n output_entity_id: string;\n input_entity_id: string;\n trace?: JsonObject;\n}\n\nexport interface LinkClipAnchorRelationInput {\n relation_id?: string;\n child_clip_entity_id: string;\n host_clip_entity_id: string;\n trace?: JsonObject;\n}\n\nexport interface LinkPhoneticScriptRenderRelationInput {\n relation_id?: string;\n output_entity_id: string;\n phonetic_script_entity_id: string;\n trace?: JsonObject;\n}\n\n/** `audio-script-source(script, source)`; the script was transcribed from the source media. */\nexport interface LinkAudioScriptSourceRelationInput {\n relation_id?: string;\n script_entity_id: string;\n source_entity_id: string;\n trace?: JsonObject;\n}\n\nexport interface UnlinkRelationInput {\n relation_id: string;\n}\n\nexport type EntityCommand =\n | { kind: 'create-entity'; entity: SandboxEntity }\n | { kind: 'update-entity'; entity_id: string; payload: JsonObject }\n | { kind: 'delete-entity'; entity_id: string }\n | { kind: 'link-relation'; relation: SandboxRelation }\n | { kind: 'unlink-relation'; relation_id: string };\n\nexport interface EntityPlanState {\n base_revision: number;\n commands: readonly EntityCommand[];\n rows: EntityStoreSnapshot;\n deleted_entity_ids: readonly string[];\n deleted_relation_ids: readonly string[];\n}\n\nexport interface EntityStateWireResponse {\n loro_snapshot: string;\n doc_id: string;\n audio_script_entity_id: string | null;\n revision: number;\n rows: {\n entities: SandboxEntity[];\n relations: SandboxRelation[];\n };\n}\n\nexport interface EntityFacade {\n /** Read complete assembled fields; returned objects are snapshots. Use update to persist edits. */\n list(): SandboxEntity[];\n get(entityId: string): SandboxEntity | null;\n /** Find document resources by external Memota asset id, including directly composed media variants. */\n findByAssetId(assetId: string): SandboxEntity<ResourceEntityKind>[];\n /** Assemble selected Caption text; missing composition is an error. */\n readCaptionContent(entityId: string): ComposedScriptContent;\n /** Assemble base text and pronunciation fields before generating Voice. */\n readPhoneticScriptContent(entityId: string): ComposedPhoneticContent;\n create(input: CreateEntityInput): string;\n /** Patch assembled fields, routing inherited fields to their declaring entity. */\n update(input: UpdateEntityInput): void;\n /** Explicitly declare own fields, overriding unambiguous bases without modifying them. Ordinary edits use update. */\n declareFields(input: UpdateEntityInput): void;\n /** Delete an Entity only after all of its incident Relations have been explicitly unlinked. */\n delete(input: DeleteEntityInput): void;\n /** Get or create one typed Asset by factual external id and return its single content identity. Never creates a Clip. */\n ensureMedia(fact: MediaAssetFact): { contentEntityId: string };\n}\n\nexport interface RelationFacade {\n list(): SandboxRelation[];\n /** Incident lookup is endpoint-agnostic; persisted endpoint positions stay unchanged. */\n of(entityId: string, relationKind?: KnownRelationKind): SandboxRelation[];\n /** Link existing entities through ordinary associations; variant bases are stored directly on the variant. */\n link(input: LinkRelationInput): string;\n /** Author ordered generated(output,input); generic link() deliberately rejects this kind. */\n linkGenerated(input: LinkGeneratedRelationInput): string;\n /** Author ordered clip-anchor(child,host) without positional endpoint ambiguity. */\n linkClipAnchor(input: LinkClipAnchorRelationInput): string;\n /** Author ordered phonetic-script-render(output,script) without positional endpoint ambiguity. */\n linkPhoneticScriptRender(input: LinkPhoneticScriptRenderRelationInput): string;\n /** Author ordered audio-script-source(script,source) without positional endpoint ambiguity. */\n linkAudioScriptSource(input: LinkAudioScriptSourceRelationInput): string;\n /** Remove a Relation by identity; endpoint replacement is an explicit unlink plus link. */\n unlink(input: UnlinkRelationInput): void;\n}\n\n/** Business editing surface. Infrastructure Assets are assembled by the host. */\nexport interface BusinessEntityFacade {\n list(): SandboxEntity[];\n get(entityId: string): SandboxEntity | null;\n readCaptionContent(entityId: string): ComposedScriptContent;\n readPhoneticScriptContent(entityId: string): ComposedPhoneticContent;\n create(input: Exclude<CreateEntityInput, { entity_kind: 'asset' }>): string;\n update(input: UpdateEntityInput): void;\n declareFields(input: UpdateEntityInput): void;\n delete(input: DeleteEntityInput): void;\n}\n\n/** Physical Asset bindings are maintained outside the sandbox. */\nexport interface BusinessRelationFacade {\n list(): SandboxRelation[];\n of(entityId: string, relationKind?: KnownRelationKind): SandboxRelation[];\n link(input: Exclude<LinkRelationInput, { relation_kind: 'physical-asset' }>): string;\n linkGenerated(input: LinkGeneratedRelationInput): string;\n linkClipAnchor(input: LinkClipAnchorRelationInput): string;\n linkPhoneticScriptRender(input: LinkPhoneticScriptRenderRelationInput): string;\n linkAudioScriptSource(input: LinkAudioScriptSourceRelationInput): string;\n unlink(input: UnlinkRelationInput): void;\n}\n","import { bytesToBase64, compileEntityRows, base64ToBytes } from '@mengine/medeo-client';\nimport { createEntityId, createRelationId } from '@mengine/medeo-dsl';\n\nimport {\n KNOWN_ENTITY_KINDS,\n KNOWN_RELATION_KINDS,\n type EntityStateWireResponse,\n type EntityStoreSnapshot,\n type JsonObject,\n type SandboxEntity,\n type SandboxRelation,\n} from './entity-contract.ts';\n\nconst API_PREFIX = '/api/mengine/v1';\nconst entityKinds = new Set<string>(KNOWN_ENTITY_KINDS);\nconst relationKinds = new Set<string>(KNOWN_RELATION_KINDS);\n\nexport interface EntityHttpClientOptions {\n docId: string;\n httpOrigin: string;\n authToken?: string | (() => string | undefined);\n userId?: string | (() => string | undefined);\n fetchImpl?: typeof fetch;\n}\n\nexport interface EntityCommitDeletions {\n deleted_entity_ids?: readonly string[];\n deleted_relation_ids?: readonly string[];\n}\n\nexport class MengineEntityHttpRequestError extends Error {\n constructor(\n readonly status: number,\n readonly payload: unknown,\n ) {\n super(`mengine entity-state request failed: ${status}`);\n this.name = 'MengineEntityHttpRequestError';\n }\n}\n\n/** Narrow authenticated client for the Loro entity endpoint. */\nexport class EntityHttpClient {\n private readonly fetchImpl: typeof fetch;\n\n constructor(private readonly options: EntityHttpClientOptions) {\n this.fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);\n }\n\n async fetchState(): Promise<EntityStoreSnapshot> {\n return toSnapshot(await this.requestJson({ method: 'GET' }), this.options.docId);\n }\n\n async commit(\n _transportSequence: number,\n state: EntityStoreSnapshot,\n _deletions: EntityCommitDeletions = {},\n ): Promise<EntityStoreSnapshot> {\n if (!state.loroSnapshot) throw new Error('Entity edit is missing its causal Loro baseline');\n // The baseline comes from this plan, never a freshly fetched replacement.\n const rows = {\n entities: state.entities.map((row) => ({\n entityId: createEntityId(row.entity_id),\n entityKind: row.entity_kind,\n payload: row.payload,\n })),\n relations: state.relations.map((row) => ({\n relationId: createRelationId(row.relation_id),\n relationKind: row.relation_kind,\n endpoint0EntityId: createEntityId(row.endpoint_0_entity_id),\n endpoint1EntityId: createEntityId(row.endpoint_1_entity_id),\n metadata: row.metadata,\n trace: row.trace,\n })),\n } as Parameters<typeof compileEntityRows>[1];\n const compiled = compileEntityRows(base64ToBytes(state.loroSnapshot), rows);\n return this.commitUpdate(bytesToBase64(compiled.update));\n }\n\n async commitUpdate(update: string): Promise<EntityStoreSnapshot> {\n return toSnapshot(await this.requestJson({ method: 'POST', body: JSON.stringify({ update }) }), this.options.docId);\n }\n\n private async requestJson(init: RequestInit): Promise<unknown> {\n const response = await this.fetchImpl(this.endpoint(), { ...init, headers: this.headers() });\n const payload = await safeReadJson(response);\n if (!response.ok) throw new MengineEntityHttpRequestError(response.status, payload);\n return payload;\n }\n\n private headers(): Headers {\n const headers = new Headers({ accept: 'application/json', 'content-type': 'application/json' });\n const authToken = typeof this.options.authToken === 'function' ? this.options.authToken() : this.options.authToken;\n if (authToken != null && authToken !== '') headers.set('authorization', `Bearer ${authToken}`);\n const userId = typeof this.options.userId === 'function' ? this.options.userId() : this.options.userId;\n if (userId != null && userId !== '') headers.set('medeo-user-id', userId);\n return headers;\n }\n\n private endpoint(): string {\n const origin = this.options.httpOrigin.replace(/\\/$/, '');\n return `${origin}${API_PREFIX}/docs/${encodeURIComponent(this.options.docId)}/entity-state`;\n }\n}\n\nfunction toSnapshot(value: unknown, expectedDocId: string): EntityStoreSnapshot {\n if (!isRecord(value) || typeof value.doc_id !== 'string' || !isNonNegativeInteger(value.revision)) {\n throw new Error('invalid entity-state response envelope');\n }\n if (value.doc_id !== expectedDocId) {\n throw new Error(`entity-state response doc_id mismatch: expected \"${expectedDocId}\"`);\n }\n if (!isRecord(value.rows) || !Array.isArray(value.rows.entities) || !Array.isArray(value.rows.relations)) {\n throw new Error('invalid entity-state response rows');\n }\n if (value.audio_script_entity_id === null) throw new Error('Document AudioScript is not initialized');\n if (!isTrimmed(value.audio_script_entity_id)) throw new Error('invalid document AudioScript identity');\n if (typeof value.loro_snapshot !== 'string') throw new Error('Missing causal Loro snapshot');\n const response = value as unknown as EntityStateWireResponse;\n if (\n response.audio_script_entity_id !== null &&\n !response.rows.entities.some(\n (entity) => entity.entity_id === response.audio_script_entity_id && entity.entity_kind === 'audio-script',\n )\n )\n throw new Error('Document AudioScript must name the project AudioScript');\n return {\n loroSnapshot: response.loro_snapshot,\n revision: response.revision,\n audioScriptEntityId: response.audio_script_entity_id,\n entities: response.rows.entities.map(parseEntity),\n relations: response.rows.relations.map(parseRelation),\n };\n}\n\nfunction parseEntity(value: unknown): SandboxEntity {\n if (\n !isRecord(value) ||\n !isTrimmed(value.entity_id) ||\n typeof value.entity_kind !== 'string' ||\n !entityKinds.has(value.entity_kind) ||\n !isJsonObject(value.payload)\n ) {\n throw new Error('invalid Entity row in entity-state response');\n }\n return structuredClone(value) as unknown as SandboxEntity;\n}\n\nfunction parseRelation(value: unknown): SandboxRelation {\n if (\n !isRecord(value) ||\n !isTrimmed(value.relation_id) ||\n typeof value.relation_kind !== 'string' ||\n !relationKinds.has(value.relation_kind) ||\n !isTrimmed(value.endpoint_0_entity_id) ||\n !isTrimmed(value.endpoint_1_entity_id) ||\n !isJsonObject(value.metadata) ||\n !isJsonObject(value.trace)\n ) {\n throw new Error('invalid Relation row in entity-state response');\n }\n return structuredClone(value) as unknown as SandboxRelation;\n}\n\nfunction isJsonObject(value: unknown): value is JsonObject {\n return isJsonValue(value, new Set()) && isRecord(value);\n}\n\nfunction isJsonValue(value: unknown, ancestors: Set<object>): boolean {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return true;\n if (typeof value === 'number') return Number.isFinite(value);\n if (typeof value !== 'object' || ancestors.has(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) return false;\n ancestors.add(value);\n const valid = Array.isArray(value)\n ? value.every((item) => isJsonValue(item, ancestors))\n : Object.values(value).every((item) => isJsonValue(item, ancestors));\n ancestors.delete(value);\n return valid;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isTrimmed(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0 && value.trim() === value;\n}\n\nfunction isNonNegativeInteger(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;\n}\n\nasync function safeReadJson(response: Response): Promise<unknown> {\n const text = await response.text();\n if (text.length === 0) return null;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n","import { randomUUID } from 'node:crypto';\n\nimport { isMediaAssetVariantKind } from '@mengine/medeo-dsl';\n\nimport type { EntityCommand, EntityStoreSnapshot, SandboxRelation } from './entity-contract.ts';\nimport type { EntityHttpClient } from './entity-http-client.ts';\n\n/**\n * External systems whose asset entities carry a factual Memota identity.\n * Voice results use the speech system; every other medium uses `memota`.\n */\nconst ASSET_SYSTEMS: ReadonlySet<string> = new Set(['memota', 'memota-speech']);\n\n/** Factual generation lineage for recalled Memota assets, supplied by the host. */\nexport interface AssetGenerationFact {\n /** External asset id of the generation output (memota asset or speech result id). */\n readonly outputAssetId: string;\n /** Factual input asset ids; empty for text-only generation. */\n readonly inputAssetIds: readonly string[];\n}\n\n/**\n * Host callback resolving lineage by external asset id. Implementations return\n * every known generation record involving the given ids in either role; an\n * empty array means no known lineage and a rejection means the lineage query\n * failed. Entity and Relation semantics stay inside this package.\n */\nexport type GenerationFactsLoader = (\n docId: string,\n assetIds: readonly string[],\n) => Promise<readonly AssetGenerationFact[]>;\n\n/**\n * Outcome of the post-commit lineage sync. `failed` is always also surfaced as\n * a `generation_sync_failed` warning so an unavailable lineage query is never\n * presented as synced state.\n */\nexport interface GenerationSyncOutcome {\n /**\n * applied: new generated Relations were committed.\n * current: the query succeeded and nothing was missing (no created asset,\n * single side absent, text-only generation, or pair already linked).\n * failed: the host query or the sync commit failed.\n */\n readonly status: 'applied' | 'current' | 'failed';\n readonly created_relation_ids?: readonly string[];\n readonly message?: string;\n}\n\nexport interface SyncGeneratedRelationsInput {\n readonly client: EntityHttpClient;\n readonly docId: string;\n /** Causal entity state the committed plan was based on. */\n readonly baseState: EntityStoreSnapshot;\n /** Entity commands of the committed plan; they scope which lineage is queried. */\n readonly entityCommands: readonly EntityCommand[];\n readonly loadFacts: GenerationFactsLoader;\n}\n\n/** Validate host-supplied facts; a malformed record fails the whole query. */\nexport function parseGenerationFacts(value: unknown): AssetGenerationFact[] {\n if (!Array.isArray(value)) throw new Error('generation facts must be an array');\n return value.map((item): AssetGenerationFact => {\n if (!isRecord(item)) throw new Error('each generation fact must be an object');\n const { outputAssetId, inputAssetIds } = item;\n if (typeof outputAssetId !== 'string' || outputAssetId.length === 0 || outputAssetId.trim() !== outputAssetId) {\n throw new Error('generation fact outputAssetId must be a non-empty trimmed string');\n }\n if (!Array.isArray(inputAssetIds)) {\n // A missing field is a malformed record, not text-only evidence: only an\n // explicit empty array states \"no factual inputs\" (pure text source).\n throw new Error('generation fact inputAssetIds must be an array (explicit [] means text-only)');\n }\n const inputs = inputAssetIds;\n for (const input of inputs) {\n if (typeof input !== 'string' || input.length === 0 || input.trim() !== input) {\n throw new Error('generation fact inputAssetIds entries must be non-empty trimmed strings');\n }\n }\n return { outputAssetId, inputAssetIds: [...inputs] };\n });\n}\n\n/**\n * Resource identities newly introduced by the edit. Asset identity is immutable;\n * Clip placement and display metadata updates are not new generation sources.\n * Untouched/deleted lineage is never resurrected.\n */\nexport interface GenerationSyncScope {\n readonly scopedMediaIds: ReadonlySet<string>;\n readonly queryAssetKeys: readonly string[];\n}\n\nexport function planGenerationScope(\n base: EntityStoreSnapshot,\n commands: readonly EntityCommand[],\n state: EntityStoreSnapshot,\n): GenerationSyncScope {\n const touchedIds = new Set<string>();\n for (const command of commands) {\n if (command.kind === 'create-entity' && isMediaAssetVariantKind(command.entity.entity_kind)) {\n touchedIds.add(command.entity.entity_id);\n }\n }\n const beforeByKey = resolveMediaByAssetKey(base);\n const scoped = new Set<string>();\n const queryKeys = new Set<string>();\n for (const [key, mediaIds] of resolveMediaByAssetKey(state)) {\n const previousIds = new Set(beforeByKey.get(key) ?? []);\n for (const id of mediaIds) {\n if (!touchedIds.has(id) || previousIds.has(id)) continue;\n scoped.add(id);\n queryKeys.add(key);\n }\n }\n return { scopedMediaIds: scoped, queryAssetKeys: [...queryKeys].sort() };\n}\n\n/**\n * Ordered generated(output,input) Relations missing from `state` for the given\n * factual records. Both endpoints must already exist and match their own Asset\n * identities, and the pair must involve a media Entity the plan\n * newly fact-exposed (`scopedMediaIds`): lineage scopes to the commit's diff,\n * so a pair the user deleted between untouched entities stays deleted. A pair\n * the facts already resolved against the plan's base state is likewise skipped.\n * One-sided facts, text-only records, self pairs, and already-linked pairs are\n * skipped. Duplicate records collapse to one Relation.\n */\nexport function planGeneratedRelations(input: {\n baseState: EntityStoreSnapshot;\n state: EntityStoreSnapshot;\n scopedMediaIds: ReadonlySet<string>;\n facts: readonly AssetGenerationFact[];\n newRelationId: () => string;\n}): SandboxRelation[] {\n const { state, facts } = input;\n const scoped = input.scopedMediaIds;\n const factKeys = new Set(facts.flatMap((fact) => [fact.outputAssetId, ...fact.inputAssetIds]));\n const mediaByAssetKey = resolveMediaByAssetKey(state, factKeys);\n const baseResolvable = new Set(resolvablePairs(resolveMediaByAssetKey(input.baseState, factKeys), facts));\n const linkedPairs = new Set(\n state.relations\n .filter((relation) => relation.relation_kind === 'generated')\n .map((relation) => pairKey(relation.endpoint_0_entity_id, relation.endpoint_1_entity_id)),\n );\n const relations: SandboxRelation[] = [];\n for (const fact of facts) {\n for (const outputId of mediaByAssetKey.get(fact.outputAssetId) ?? []) {\n for (const inputAssetId of fact.inputAssetIds) {\n for (const inputId of mediaByAssetKey.get(inputAssetId) ?? []) {\n if (outputId === inputId) continue;\n if (!scoped.has(outputId) && !scoped.has(inputId)) continue;\n const pair = pairKey(outputId, inputId);\n if (linkedPairs.has(pair) || baseResolvable.has(pair)) continue;\n linkedPairs.add(pair);\n relations.push({\n relation_id: input.newRelationId(),\n relation_kind: 'generated',\n endpoint_0_entity_id: outputId,\n endpoint_1_entity_id: inputId,\n metadata: {},\n trace: { synced_by: 'generation-sync' },\n });\n }\n }\n }\n }\n return relations;\n}\n\n/**\n * Sync generation lineage after a confirmed entity commit. Any failure is\n * returned as a `failed` outcome instead of thrown, so the already-durable\n * commit result is never masked; a successful query that finds nothing is\n * `current`. Asset identities are immutable, so facts are queried once. The native update retains its causal baseline and merges without whole-state retries; deleted endpoints are never recreated.\n */\nexport async function syncGeneratedRelations(input: SyncGeneratedRelationsInput): Promise<GenerationSyncOutcome> {\n const { client, docId, baseState, entityCommands, loadFacts } = input;\n try {\n const state = await client.fetchState();\n const scope = planGenerationScope(baseState, entityCommands, state);\n if (scope.queryAssetKeys.length === 0) return { status: 'current' };\n const facts = parseGenerationFacts(await loadFacts(docId, scope.queryAssetKeys));\n const relations = planGeneratedRelations({\n baseState,\n state,\n scopedMediaIds: scope.scopedMediaIds,\n facts,\n newRelationId: mintRelationId,\n });\n if (relations.length === 0) return { status: 'current' };\n const committed = await client.commit(state.revision, { ...state, relations: [...state.relations, ...relations] });\n const active = new Set(committed.relations.map((relation) => relation.relation_id));\n const created = relations.map((relation) => relation.relation_id).filter((id) => active.has(id));\n return created.length ? { status: 'applied', created_relation_ids: created } : { status: 'current' };\n } catch (error) {\n return { status: 'failed', message: `generation lineage query failed: ${errorMessage(error)}` };\n }\n}\n\ninterface AssetLike {\n entity_id: string;\n entity_kind: string;\n payload: unknown;\n}\n\nfunction assetKeyOf(entity: AssetLike): string | undefined {\n if (!isMediaAssetVariantKind(entity.entity_kind)) return undefined;\n const external = (entity.payload as Record<string, unknown> | undefined)?.external;\n if (external == null || typeof external !== 'object' || Array.isArray(external)) return undefined;\n const { system, key } = external as Record<string, unknown>;\n if (typeof system !== 'string' || !ASSET_SYSTEMS.has(system)) return undefined;\n if (typeof key !== 'string' || key.length === 0 || key.trim() !== key) return undefined;\n return key;\n}\n\n/** Media variants own their Asset locator; generation lookup never follows Relations. */\nfunction resolveMediaByAssetKey(state: EntityStoreSnapshot, factKeys?: ReadonlySet<string>): Map<string, string[]> {\n // The host history contract carries bare IDs, not namespaces. Never turn an\n // ambiguous ID into a Cartesian product of unrelated speech/media resources.\n const systemByKey = new Map<string, unknown>();\n for (const entity of state.entities) {\n const key = assetKeyOf(entity);\n if (key === undefined || !factKeys?.has(key)) continue;\n const system = (entity.payload.external as Record<string, unknown>).system;\n if (systemByKey.has(key) && systemByKey.get(key) !== system)\n throw new Error(`Ambiguous generation asset id ${key} across media and speech namespaces`);\n systemByKey.set(key, system);\n }\n const resolved = new Map<string, string[]>();\n for (const entity of state.entities) {\n if (!isMediaAssetVariantKind(entity.entity_kind)) continue;\n const key = assetKeyOf(entity);\n if (key === undefined) continue;\n const matches = resolved.get(key) ?? [];\n matches.push(entity.entity_id);\n resolved.set(key, matches);\n }\n return resolved;\n}\n\nfunction pairKey(endpoint0: string, endpoint1: string): string {\n return `${endpoint0}\\u0000${endpoint1}`;\n}\n\n/** Pair keys the facts already resolve to under the given base bindings. */\nfunction resolvablePairs(mediaByAssetKey: Map<string, string[]>, facts: readonly AssetGenerationFact[]): string[] {\n const pairs: string[] = [];\n for (const fact of facts) {\n for (const outputId of mediaByAssetKey.get(fact.outputAssetId) ?? []) {\n for (const inputAssetId of fact.inputAssetIds) {\n for (const inputId of mediaByAssetKey.get(inputAssetId) ?? []) {\n if (outputId !== inputId) pairs.push(pairKey(outputId, inputId));\n }\n }\n }\n }\n return pairs;\n}\n\nfunction mintRelationId(): string {\n return `relation_${randomUUID()}`;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n","/** @generated by gen:sandbox-dts. DO NOT EDIT. */\nexport const ENTITY_EDIT_SANDBOX_API_DTS = [\n '/** @generated by gen:sandbox-dts. Entity-native editor contract; DO NOT EDIT. */',\n 'export interface BoundedDerivedSequencePayload extends JsonObject {',\n ' extent: {',\n \" kind: 'bounded';\",\n ' start: number;',\n ' end: number;',\n ' };',\n \" sampling: 'derived';\",\n ' coordinateSpace: JsonValue;',\n '}',\n 'export interface BoundedNativeSequencePayload extends JsonObject {',\n ' /** Factual coordinates from recalled media metadata; never invent an end/duration. */',\n ' extent: {',\n \" kind: 'bounded';\",\n ' start: number;',\n ' end: number;',\n ' };',\n \" sampling: 'native';\",\n ' coordinateSpace: JsonValue;',\n '}',\n '/** Business editing surface. Infrastructure Assets are assembled by the host. */',\n 'export interface BusinessEntityFacade {',\n ' list(): SandboxEntity[];',\n ' get(entityId: string): SandboxEntity | null;',\n ' readCaptionContent(entityId: string): ComposedScriptContent;',\n ' readPhoneticScriptContent(entityId: string): ComposedPhoneticContent;',\n ' create(',\n ' input: Exclude<',\n ' CreateEntityInput,',\n ' {',\n \" entity_kind: 'asset';\",\n ' }',\n ' >,',\n ' ): string;',\n ' update(input: UpdateEntityInput): void;',\n ' declareFields(input: UpdateEntityInput): void;',\n ' delete(input: DeleteEntityInput): void;',\n '}',\n '/** Physical Asset bindings are maintained outside the sandbox. */',\n 'export interface BusinessRelationFacade {',\n ' list(): SandboxRelation[];',\n ' of(entityId: string, relationKind?: KnownRelationKind): SandboxRelation[];',\n ' link(',\n ' input: Exclude<',\n ' LinkRelationInput,',\n ' {',\n \" relation_kind: 'physical-asset';\",\n ' }',\n ' >,',\n ' ): string;',\n ' linkGenerated(input: LinkGeneratedRelationInput): string;',\n ' linkClipAnchor(input: LinkClipAnchorRelationInput): string;',\n ' linkPhoneticScriptRender(input: LinkPhoneticScriptRenderRelationInput): string;',\n ' linkAudioScriptSource(input: LinkAudioScriptSourceRelationInput): string;',\n ' unlink(input: UnlinkRelationInput): void;',\n '}',\n 'export interface CaptionFontDescriptor {',\n \" readonly system: 'font-library';\",\n ' readonly key: string;',\n '}',\n '/**',\n \" * One ordered entry of the Caption's segment selection. `segmentId` quotes the\",\n \" * composed AudioScript's own stable segment identity — a local id quoted by the\",\n ' * variant, never a peer Entity reference. Text itself is never copied here;',\n ' * complete Caption content is assembled through its direct baseEntityIds.',\n ' * The optional `textRange` narrows one Segment to an intra-Segment sub-span',\n ' * (intra-segment re-segmentation); without it the whole Segment text is selected.',\n ' */',\n 'export type CaptionSegmentSelection = JsonObject & {',\n ' readonly segmentId: string;',\n ' readonly textRange?: CaptionTextRange;',\n '};',\n 'export interface CaptionStyleFields {',\n ' readonly font?: CaptionFontDescriptor;',\n ' readonly fontSize?: number;',\n ' readonly fontColor?: string;',\n ' readonly fontWeight?: number;',\n ' readonly entranceAnimation?: string;',\n ' readonly entranceAnimationDurationMs?: number;',\n ' readonly strokeColor?: string;',\n ' readonly strokeWidth?: number;',\n ' readonly positionX?: number;',\n ' readonly positionY?: number;',\n '}',\n '/**',\n \" * Half-open `[start, end)` position window inside one Segment's text, counted\",\n ' * in Unicode code points (not UTF-16 code units), so a boundary never splits a',\n ' * surrogate pair. Positions are non-negative safe integers with `start < end`;',\n \" * `end` must not exceed the Segment's code-point length.\",\n ' */',\n 'export interface CaptionTextRange extends JsonObject {',\n ' readonly start: number;',\n ' readonly end: number;',\n '}',\n 'export type CaptionTextSelection = JsonObject & {',\n ' segmentId: string;',\n ' /** Half-open Unicode code-point range within the selected source segment. */',\n ' textRange?: {',\n ' start: number;',\n ' end: number;',\n ' };',\n '};',\n 'export type ClipEntityId = EntityId;',\n 'export type ClipPlacement =',\n ' | {',\n \" readonly kind: 'sequential';\",\n ' readonly order: number;',\n ' }',\n ' | {',\n \" readonly kind: 'absolute';\",\n ' readonly targetRange: SequenceRange<number>;',\n ' }',\n ' | {',\n \" readonly kind: 'anchored';\",\n ' readonly hostClipEntityId: string;',\n ' readonly anchorOffset: number;',\n ' };',\n 'export interface ComposedPhoneticContent extends ComposedScriptContent {',\n ' phonemeScript?: string;',\n ' prosody?: JsonObject;',\n '}',\n '/** Read result only: base text is assembled from the real AudioScript row. */',\n 'export interface ComposedScriptContent {',\n ' audio_script_entity_id: string;',\n ' text: string;',\n ' segments: ScriptTextSegment[];',\n '}',\n 'export type CreateEntityInput = {',\n ' [K in KnownEntityKind]: {',\n ' entity_id?: string;',\n ' entity_kind: K;',\n ' payload: StoredEntityPayload<K>;',\n ' };',\n '}[KnownEntityKind];',\n 'export interface DeleteBgmInput {',\n ' readonly timelineEntityId: string;',\n '}',\n 'export interface DeleteClipInput {',\n ' readonly clipEntityId: string;',\n '}',\n 'export interface DeleteClipTreeInput {',\n ' readonly clipEntityIds: readonly string[];',\n \" readonly onAnchored: 'cascade' | 'detach';\",\n '}',\n 'export interface DeleteEntityInput {',\n ' entity_id: string;',\n '}',\n 'export interface DeleteVoiceoverInput {',\n ' readonly voiceoverClipEntityIds: readonly string[];',\n '}',\n 'export type EmptyRelationKind =',\n \" | 'timeline-track'\",\n \" | 'track-clip'\",\n \" | 'clip-marker'\",\n \" | 'marker-content'\",\n \" | 'axvideo-marker'\",\n \" | 'marker-timeline'\",\n \" | 'audio-script-marker';\",\n 'export type EntityId = string;',\n 'export interface EntityPayloadByKind {',\n ' axvideo: BoundedDerivedSequencePayload;',\n ' timeline: JsonObject;',\n ' track: JsonObject & {',\n ' hidden?: boolean;',\n ' role?: string;',\n ' };',\n ' clip: JsonObject;',\n ' video: BoundedNativeSequencePayload;',\n ' audio: BoundedNativeSequencePayload;',\n ' voice: BoundedNativeSequencePayload;',\n ' image: UnboundedConstantSequencePayload;',\n \" 'sequence-marker': JsonObject & {\",\n ' sourceRange: {',\n ' start: number;',\n ' end: number;',\n ' };',\n ' targetRange?: {',\n ' start: number;',\n ' end: number;',\n ' };',\n ' duration:',\n ' | {',\n \" mode: 'from-source';\",\n ' }',\n ' | {',\n \" mode: 'fixed';\",\n ' value: number;',\n ' };',\n ' timeRemapping?: JsonValue;',\n ' anchorOffset?: number;',\n \" durationPolicy?: 'timeline';\",\n ' /** Directly assigned AudioScript annotation times; annotation Markers only. */',\n ' segmentRanges?: {',\n ' segmentId: string;',\n ' startMs: number;',\n ' endMs: number;',\n ' }[];',\n ' };',\n ' viewport: JsonObject;',\n \" 'audio-script': JsonObject & {\",\n ' segments: ScriptTextSegment[];',\n ' };',\n \" 'phonetic-script': JsonObject & {\",\n ' baseEntityIds: string[];',\n ' phonemeScript?: string;',\n ' prosody?: JsonObject;',\n ' };',\n ' caption: BoundedNativeSequencePayload & {',\n ' baseEntityIds: string[];',\n ' selections: CaptionTextSelection[];',\n ' style?: JsonObject;',\n ' };',\n '}',\n 'export interface EntityStoreSnapshot {',\n ' /** Causal compiler baseline; required for publishing edits. */',\n ' loroSnapshot?: string;',\n ' revision: number;',\n ' /** Current AudioScript version attached to the project; initialized projects always attach a script, possibly empty. */',\n ' audioScriptEntityId: string | null;',\n ' entities: SandboxEntity[];',\n ' relations: SandboxRelation[];',\n '}',\n 'export interface InsertCaptionClipInput {',\n ' readonly timelineEntityId: string;',\n ' /** Existing generation identity for newly materialized Caption content, distinct from its Clip. */',\n ' readonly captionEntityId?: string;',\n ' /** Stable placed caption identity, distinct from the Caption content identity. */',\n ' readonly captionClipEntityId?: string;',\n ' /** Existing bases composed by this variant; includes an AudioScript text owner. */',\n ' readonly baseEntityIds: readonly string[];',\n ' /** Ordered selection of the AudioScript segments this Caption displays. */',\n ' readonly selections: readonly CaptionSegmentSelection[];',\n ' /** Intrinsic cue length of the Caption entity itself; display comes from the placement. */',\n ' readonly durationMs: number;',\n ' readonly style?: CaptionStyleFields;',\n ' readonly placement: ClipPlacement;',\n '}',\n 'export interface InsertClipInput {',\n ' readonly trackEntityId: string;',\n ' /** Existing Sequence media Entity id. Asset ids and URLs are not content ids. */',\n ' readonly contentEntityId: string;',\n ' readonly sourceRange: SequenceRange<number>;',\n ' readonly duration: SequenceDuration<number>;',\n ' readonly targetRange?: SequenceRange<number>;',\n ' readonly clipPayload?: JsonObject;',\n '}',\n 'export interface InsertPlacedClipInput {',\n ' readonly trackEntityId: string;',\n ' readonly contentEntityId: string;',\n ' readonly sourceRange: SequenceRange<number>;',\n ' readonly duration: SequenceDuration<number>;',\n ' readonly placement: ClipPlacement;',\n ' readonly clipPayload?: JsonObject;',\n ' /** Stable caller-owned placement identity, when one already exists outside the graph. */',\n ' readonly clipEntityId?: string;',\n '}',\n 'export interface JsonObject {',\n ' [key: string]: JsonValue;',\n '}',\n 'export type JsonPrimitive = string | number | boolean | null;',\n 'export type JsonValue = JsonPrimitive | JsonObject | JsonValue[];',\n 'export type KnownEntityKind =',\n \" | 'axvideo'\",\n \" | 'timeline'\",\n \" | 'track'\",\n \" | 'clip'\",\n \" | 'video'\",\n \" | 'audio'\",\n \" | 'voice'\",\n \" | 'image'\",\n \" | 'sequence-marker'\",\n \" | 'viewport'\",\n \" | 'audio-script'\",\n \" | 'phonetic-script'\",\n \" | 'caption';\",\n 'export type KnownRelationKind =',\n \" | 'timeline-track'\",\n \" | 'track-clip'\",\n \" | 'clip-marker'\",\n \" | 'marker-content'\",\n \" | 'axvideo-marker'\",\n \" | 'marker-timeline'\",\n \" | 'generated'\",\n \" | 'caption-alignment'\",\n \" | 'clip-anchor'\",\n \" | 'phonetic-script-render'\",\n \" | 'audio-script-source'\",\n \" | 'audio-script-marker';\",\n 'export interface LinearClipSpeed {',\n \" readonly kind: 'linear';\",\n ' readonly rate: number;',\n ' readonly mode?: string;',\n '}',\n '/** `audio-script-source(script, source)`; the script was transcribed from the source media. */',\n 'export interface LinkAudioScriptSourceRelationInput {',\n ' relation_id?: string;',\n ' script_entity_id: string;',\n ' source_entity_id: string;',\n ' trace?: JsonObject;',\n '}',\n 'export interface LinkClipAnchorRelationInput {',\n ' relation_id?: string;',\n ' child_clip_entity_id: string;',\n ' host_clip_entity_id: string;',\n ' trace?: JsonObject;',\n '}',\n 'export interface LinkGeneratedRelationInput {',\n ' relation_id?: string;',\n ' output_entity_id: string;',\n ' input_entity_id: string;',\n ' trace?: JsonObject;',\n '}',\n 'export interface LinkPhoneticScriptRenderRelationInput {',\n ' relation_id?: string;',\n ' output_entity_id: string;',\n ' phonetic_script_entity_id: string;',\n ' trace?: JsonObject;',\n '}',\n 'interface LinkRelationBase {',\n ' relation_id?: string;',\n ' endpoint_0_entity_id: string;',\n ' endpoint_1_entity_id: string;',\n ' trace?: JsonObject;',\n '}',\n 'export type LinkRelationInput =',\n ' | (LinkRelationBase & {',\n ' relation_kind: EmptyRelationKind;',\n ' metadata?: {',\n ' [key: string]: never;',\n ' };',\n ' })',\n ' | (LinkRelationBase & {',\n \" relation_kind: 'physical-asset';\",\n ' metadata?: JsonObject;',\n ' })',\n ' | (LinkRelationBase & {',\n \" relation_kind: 'caption-alignment';\",\n ' metadata: JsonObject & {',\n ' alignment: JsonValue;',\n ' };',\n ' });',\n 'export interface MoveClipInput {',\n ' readonly clipEntityId: string;',\n ' readonly trackEntityId: string;',\n '}',\n 'export interface MoveClipsToStartsInput {',\n ' readonly moves: readonly {',\n ' readonly clipEntityId: string;',\n ' readonly newStartMs: number;',\n ' }[];',\n \" /** Absolute-time drags preserve every voiceover's current visible landing. */\",\n \" readonly onAnchored: 'keepAbsolute';\",\n '}',\n 'export interface MoveSequentialClipsInput {',\n ' readonly clipEntityIds: readonly string[];',\n ' readonly anchor: SequentialClipAnchor;',\n \" readonly onAnchored: 'follow' | 'keepAbsolute';\",\n '}',\n 'export interface MoveVoiceoverInput {',\n ' readonly voiceoverClipEntityId: string;',\n ' /** Absolute requested timeline start; MEngine resolves and persists the host relation. */',\n ' readonly newStartMs: number;',\n '}',\n 'export interface PatchCaptionStyleInput {',\n ' readonly timelineEntityId: string;',\n ' readonly style: CaptionStyleFields;',\n '}',\n 'export interface ReplaceClipContentInput {',\n ' readonly clipEntityId: string;',\n ' /** Existing Sequence media Entity id. Asset ids and URLs are not content ids. */',\n ' readonly contentEntityId: string;',\n ' readonly sourceRange: SequenceRange<number>;',\n ' readonly duration: SequenceDuration<number>;',\n ' readonly targetRange?: SequenceRange<number>;',\n ' readonly timeRemapping?: JsonValue;',\n '}',\n 'export interface SandboxEntity<K extends KnownEntityKind = KnownEntityKind> {',\n ' entity_id: string;',\n ' entity_kind: K;',\n ' payload: StoredEntityPayload<K>;',\n '}',\n 'export interface SandboxRelation {',\n ' relation_id: string;',\n ' relation_kind: KnownRelationKind;',\n ' endpoint_0_entity_id: string;',\n ' endpoint_1_entity_id: string;',\n ' metadata: JsonObject;',\n ' trace: JsonObject;',\n '}',\n 'export type ScriptTextSegment = JsonObject & {',\n ' segmentId: string;',\n ' text: string;',\n ' language?: string;',\n '};',\n 'export type SequenceDuration<Span = unknown> =',\n ' | {',\n \" readonly mode: 'from-source';\",\n ' }',\n ' | {',\n \" readonly mode: 'fixed';\",\n ' readonly value: Span;',\n ' };',\n 'export interface SequenceRange<Point = unknown> {',\n ' readonly start: Point;',\n ' readonly end: Point;',\n '}',\n 'export type SequentialClipAnchor =',\n ' | {',\n \" readonly position: 'before' | 'after';\",\n ' readonly clipEntityId: string;',\n ' }',\n ' | {',\n \" readonly position: 'trackStart';\",\n ' };',\n 'export interface SetCaptionVisibilityInput {',\n ' readonly timelineEntityId: string;',\n ' readonly hidden: boolean;',\n '}',\n 'export interface SetClipPlacementInput {',\n ' readonly clipEntityId: string;',\n ' readonly placement: ClipPlacement;',\n '}',\n 'export interface SetClipSpeedInput {',\n ' readonly clipEntityId: string;',\n ' readonly timeRemapping: LinearClipSpeed | null;',\n '}',\n 'export interface SetClipVolumeInput {',\n ' readonly clipEntityId: string;',\n ' /** Playback gain in decibels. */',\n ' readonly volume: number;',\n '}',\n '/** Stored own fields; a variant may obtain required content fields from its declared bases. */',\n 'export type StoredEntityPayload<K extends KnownEntityKind> =',\n ' | EntityPayloadByKind[K]',\n ' | (JsonObject &',\n ' Partial<EntityPayloadByKind[K]> & {',\n ' baseEntityIds: string[];',\n ' });',\n 'export interface TrimClipInput {',\n ' readonly clipEntityId: string;',\n ' readonly sourceRange: SequenceRange<number>;',\n '}',\n 'export interface UnboundedConstantSequencePayload extends JsonObject {',\n ' extent: {',\n \" kind: 'unbounded';\",\n ' start: number;',\n ' };',\n \" sampling: 'constant';\",\n ' coordinateSpace: JsonValue;',\n '}',\n 'export interface UnlinkRelationInput {',\n ' relation_id: string;',\n '}',\n 'export interface UpdateClipInput {',\n ' readonly clipEntityId: string;',\n ' /** Complete replacement for the Clip-owned payload. */',\n ' readonly payload: JsonObject;',\n '}',\n 'export interface UpdateClipMarkerInput {',\n ' readonly clipEntityId: string;',\n ' readonly sourceRange?: SequenceRange<number>;',\n ' /** Passing `undefined` explicitly removes the optional target range. */',\n ' readonly targetRange?: SequenceRange<number> | undefined;',\n ' readonly duration?: SequenceDuration<number>;',\n ' /** Passing `undefined` explicitly removes the optional remapping value. */',\n ' readonly timeRemapping?: JsonValue | undefined;',\n '}',\n '/** Patch supplied fields on the assembled entity; omitted fields remain unchanged. */',\n 'export interface UpdateEntityInput {',\n ' entity_id: string;',\n ' payload: JsonObject;',\n '}',\n '/** Timeline writes accept existing media Entity ids, never Memota asset ids or URLs. */',\n 'export interface EditApi {',\n ' insertClip(input: InsertClipInput): ClipEntityId;',\n ' insertPlacedClip(input: InsertPlacedClipInput): ClipEntityId;',\n ' updateClipMarker(input: UpdateClipMarkerInput): void;',\n ' setClipPlacement(input: SetClipPlacementInput): void;',\n ' moveSequentialClips(input: MoveSequentialClipsInput): void;',\n ' moveClip(input: MoveClipInput): void;',\n ' replaceClipContent(input: ReplaceClipContentInput): void;',\n ' setClipVolume(input: SetClipVolumeInput): void;',\n ' setClipSpeed(input: SetClipSpeedInput): void;',\n ' trimClip(input: TrimClipInput): void;',\n ' deleteClip(input: DeleteClipInput): void;',\n ' deleteClipTree(input: DeleteClipTreeInput): void;',\n ' updateClip(input: UpdateClipInput): void;',\n ' moveVoiceover(input: MoveVoiceoverInput): void;',\n ' moveClipsToStarts(input: MoveClipsToStartsInput): void;',\n ' deleteVoiceover(input: DeleteVoiceoverInput): void;',\n ' deleteBgm(input: DeleteBgmInput): void;',\n ' setCaptionVisibility(input: SetCaptionVisibilityInput): void;',\n ' patchCaptionStyle(input: PatchCaptionStyleInput): void;',\n ' insertCaptionClip(input: InsertCaptionClipInput): ClipEntityId;',\n '}',\n 'export interface TimelineApi {',\n ' snapshot(): EntityStoreSnapshot & {',\n ' audioScriptEntityId: string;',\n ' };',\n '}',\n 'export interface SandboxCheckpoint {',\n ' readonly index: number;',\n '}',\n 'export declare const edit: EditApi;',\n 'export declare const timeline: TimelineApi;',\n 'export declare const entities: BusinessEntityFacade;',\n 'export declare const relations: BusinessRelationFacade;',\n 'export declare function checkpoint(): SandboxCheckpoint;',\n 'export declare function rollbackTo(cp: SandboxCheckpoint): void;',\n 'export declare const inputs: Readonly<Record<string, unknown>>;',\n '',\n].join('\\n');\n","import { ENTITY_EDIT_SANDBOX_API_DTS } from './sandbox/generated/entity-edit-sandbox-model-context.ts';\n\nexport const MEDEO_TOOL_DESCRIPTION = `\nEdit the authoritative Medeo Entity/Relation graph through a deterministic, side-effect-free JavaScript sandbox. Timeline objects and edit targets are Entities, not Memota assets or legacy parts.\n\nOperations:\n- snapshot: read the current Entity/Relation view, project attachments and causal Loro baseline. Reading does not initialize or mutate domain data.\n- run-edit-script: inspect timeline.snapshot(), entities.*, and relations.*; edit.* operates existing Entity ids and creates the required Clip/SequenceMarker structural graph. The sandbox has no network, storage or generation access. Use assembled entity fields; the host manages resource storage and generation provenance. A successful run returns preview, logs, base revision and plan_id.\n- commit-plan: publish the native Loro update compiled against the plan’s causal baseline. Concurrent independent edits merge through Loro. The timeline and AudioScript panel read the merged entity state. A failed transport is unconfirmed; retry the same plan_id so operation identities are preserved.\n\nDefault flow: snapshot → run-edit-script with auto_commit=false → inspect preview → commit-plan. Use auto_commit=true only for low-risk edits when the host does not need user confirmation. Concurrent edits do not require replaying the script against a newer snapshot. If a domain conflict is reported, inspect the merged state and resolve it explicitly; never replace the complete document to force the edit through.\n\nGenerated resources are materialized into domain Entities by the host. Use the returned Entity ids and assembled fields to edit or place content with edit.insertClip. Asset creation, lookup, reading, binding, resource locators and storage are host infrastructure, unavailable to the model through any tool or sandbox API. Each placement has its own Clip and SequenceMarker. Generation lineage is host-synced; relations.of(entityId) is endpoint-agnostic.\n`.trim();\n\nconst MEDEO_TOOL_EXECUTION_RULES = `\nThe host supplies the current document. Do not ask for, invent, or pass a document id.\ntimeline.snapshot() returns the Entity/Relation graph with its revision, not a legacy VideoDraft. Inspect Timeline, Track, Clip, SequenceMarker and their relations to plan edits.\nInspect existing Image/Video/Audio/Voice Entities and their factual extents before placing them. The host materializes generated content and resolves its physical resource. Replace a Clip's content using another content Entity id. Never fabricate a duration.\nCaption composes AudioScript text. Its optional physical resource binding is host-owned. A Caption created from AudioScript may have no physical resource. Read and edit assembled fields through entities; do not author infrastructure bindings or generated Relations.\nThe editor projection supports the existing four Track roles: video_clip (Image/Video), speech (Voice), caption (Caption), and bgm (Audio), one of each. Clip.volume is decibels (-60 to 20, 0 = original). Marker.sourceRange is the selected source interval; Marker.duration is effective display/playback duration. Coordinates and duration are whole milliseconds for this reader, not a global DSL restriction. Placement is exactly one of Clip.order, Marker.targetRange, or clip-anchor(child,host) plus Marker.anchorOffset. Use the native move/delete/voiceover helpers so placement and cascade decisions are in the same entity plan. Reading the graph never rebinds anchors or invents empty clips. Linear timeRemapping is {kind:'linear',rate:2,mode:'constant'} and agrees with rounded source span divided by rate. Image remains unbounded/constant; an explicit linear rate scales its display window, not an invented media extent. Nonlinear speed and multiple visual overlay tracks are unsupported.\nEntities own fields; ordinary Relations express associations; variants directly hold baseEntityIds and assemble the referenced entities. These foundations are fixed: implementation must follow them, never redefine them. Any entity may compose multiple bases. Equal field names from multiple bases (even equal values) are errors, even when the variant declares that field itself. After validating all base fields are unambiguous, explicitly declared own fields may override base fields without mutating the bases. Base ordering never resolves conflicts. AudioScript owns segmented text. Caption and PhoneticScript persist baseEntityIds including their AudioScript, plus their own fields; no composition Relation exists. Create the real bases before reading or committing a variant. Inside the DSL sandbox, entities.get/list expose complete assembled fields. Consumers read fields without inspecting base IDs or merging bases. entities.update patches supplied fields and routes inherited fields to their declaring entity; omitted fields remain unchanged. entities.declareFields explicitly declares own overrides and is distinct from an ordinary field edit. Persistence keeps owned fields only. entities.readCaptionContent(id) and entities.readPhoneticScriptContent(id) return assembled text. Missing/cyclic bases and field conflicts fail before persistence.\nUse edit.insertCaptionClip with baseEntityIds and selections, plus captionEntityId when generation returned a Caption identity; each voiceover caption also supplies baseEntityIds. A selection names segmentId and may use a half-open Unicode code-point textRange to split a segment for the screen without rewriting AudioScript. Generate Voice from an existing PhoneticScript, then use phoneticScriptEntityId in the voiceover helper or relations.linkPhoneticScriptRender({output_entity_id,phonetic_script_entity_id}) for its render relation. Caption and Voice have their own Clips; display anchoring is explicit and independent of composition/alignment.\nMove or stretch only the Clip's display Marker; preserve Caption intrinsic Sequence, AudioScript text and its annotation Markers. AudioScript cannot enter a Clip and has no intrinsic time. audio-script-source links its ASR source Audio/Video/Voice; audio-script-marker attaches annotation Markers with directly assigned segmentRanges:{segmentId,startMs,endMs} in whole milliseconds. Annotation Markers have no Clip/AXVideo/content/Timeline relations and never refer to other Markers for time. BGM keeps factual source duration with durationPolicy:'timeline'. Never introduce a speech entity kind.\nCreate only the known entity kinds. Project creation initializes one current Timeline, four Tracks and an attached AudioScript with segments:[]. Read the current AudioScript ID from timeline.snapshot(); the panel displays this attachment and preserves its segments. Normal edits operate this script, not an unrelated newly created script.\nImmutable updates apply to every entity: editing an owned field creates a new content version ID; changing only a variant's base ID preserves the variant ID. Editing a base through a variant updates the owner, and the compiler advances the affected base links and project attachment. A variant-owned edit creates a new variant version and retains its unchanged bases. Do not manually clone entities or duplicate inherited fields to implement versioning. Versions preserve native text and list editing identities so independent concurrent edits survive. Missing facts, unsupported layouts and composition conflicts are explicit errors; there is no legacy migration or whole-state overwrite path.\nUse only the globals and methods declared by the following TypeScript interface. Values not declared here are unavailable.\n`.trim();\n\nexport interface RenderMedeoModelContextInput {\n documentVersion: string;\n updatedSincePreviousModelCall: boolean | null;\n}\n\n/** Render the complete MEngine-owned context injected before one model call. */\nexport function renderMedeoModelContext(input: RenderMedeoModelContextInput): string {\n const updated =\n input.updatedSincePreviousModelCall == null\n ? 'unknown (first model call)'\n : String(input.updatedSincePreviousModelCall);\n return `\n${MEDEO_TOOL_DESCRIPTION}\n\n${MEDEO_TOOL_EXECUTION_RULES}\n\nCurrent MEngine document state (sampled dynamically immediately before this model call):\n- document_version: ${JSON.stringify(input.documentVersion)}\n- updated_since_previous_model_call: ${updated}\n\nWhen updated_since_previous_model_call is true, the document changed after the previous model call. The change may have come from this tool or another editor, so take a fresh snapshot before planning further edits.\n\nSandbox TypeScript interface:\n\\`\\`\\`ts\n${ENTITY_EDIT_SANDBOX_API_DTS}\n\\`\\`\\`\n`.trim();\n}\n","export const MEDEO_TOOL_NAME = 'medeo';\n\nexport type MedeoToolOp = 'snapshot' | 'run-edit-script' | 'commit-plan';\n\n/**\n * JSON Schema for the host-facing `medeo` tool surface.\n *\n * The schema intentionally does not return or accept the full op journal:\n * journals stay in the tool process and are referenced by `plan_id`. This keeps\n * large intermediate products out of model context while preserving the exact\n * journal used for commit.\n */\nexport const MEDEO_TOOL_PARAMETERS = {\n type: 'object',\n required: ['op', 'doc_id'],\n additionalProperties: false,\n properties: {\n op: {\n type: 'string',\n enum: ['snapshot', 'run-edit-script', 'commit-plan'],\n description: 'Which Medeo document operation to run.',\n },\n doc_id: {\n type: 'string',\n minLength: 1,\n description: 'Medeo document id. Copy it from the host context; never invent it.',\n },\n script: {\n type: 'string',\n minLength: 1,\n description:\n 'JavaScript body for run-edit-script. Use edit, timeline, entities, relations, checkpoint, rollbackTo, inputs, and console. Asset import, media relations, and timeline entity edits share one entity plan.',\n },\n inputs: {\n type: 'object',\n description:\n 'Pre-materialized, side-effect-free values passed into the script, including recalled asset facts. Generation history is never an input: the host queries lineage itself and syncs generated Relations after each commit. Generation and network IO must happen in the host before this call.',\n },\n timeout_ms: {\n type: 'integer',\n minimum: 1,\n description: 'Maximum script wall-clock time after worker startup (default 2000).',\n },\n memory_limit_mb: {\n type: 'integer',\n minimum: 16,\n description: 'Worker old-generation memory ceiling in MB (default 256).',\n },\n auto_commit: {\n type: 'boolean',\n description:\n 'Commit the returned plan immediately after the sandbox succeeds. Default false: return preview plus plan_id for explicit commit.',\n },\n plan_id: {\n type: 'string',\n minLength: 1,\n description: 'Plan id returned by run-edit-script; required by commit-plan.',\n },\n validation: {\n type: 'string',\n enum: ['preflight'],\n description: 'Publish the native update already validated on its causal Loro fork.',\n },\n },\n oneOf: [\n {\n required: ['op', 'doc_id'],\n properties: {\n op: { const: 'snapshot' },\n doc_id: { $ref: '#/properties/doc_id' },\n },\n additionalProperties: false,\n },\n {\n required: ['op', 'doc_id', 'script'],\n properties: {\n op: { const: 'run-edit-script' },\n doc_id: { $ref: '#/properties/doc_id' },\n script: { $ref: '#/properties/script' },\n inputs: { $ref: '#/properties/inputs' },\n timeout_ms: { $ref: '#/properties/timeout_ms' },\n memory_limit_mb: { $ref: '#/properties/memory_limit_mb' },\n auto_commit: { $ref: '#/properties/auto_commit' },\n },\n additionalProperties: false,\n },\n {\n required: ['op', 'doc_id', 'plan_id'],\n properties: {\n op: { const: 'commit-plan' },\n doc_id: { $ref: '#/properties/doc_id' },\n plan_id: { $ref: '#/properties/plan_id' },\n validation: { $ref: '#/properties/validation' },\n },\n additionalProperties: false,\n },\n ],\n} as const;\n","import {\n createPlainMemoryAdapter,\n decodeDocVersionMark,\n encodeDocVersionMark,\n replayJournal,\n ValidationError,\n type JournalEntry,\n type ManualSyncDoc,\n type SemanticOpName,\n} from '@mengine/medeo-client';\n\n/**\n * A sandbox journal plus the opaque version token taken at fork time.\n * `commitPlan` rejects the whole plan when the live document has moved on\n * (phase-1 version gate), or localizes a business conflict to a journal\n * entry under `{ validation: 'preflight' }`.\n */\nexport interface CommitPlan {\n /** Encoded `ManualSyncDoc.versionMark()` from when the sandbox was forked. */\n base_version: string;\n ops: readonly JournalEntry[];\n}\n\nexport interface CommitPlanWarning {\n kind: 'pull_failed';\n message: string;\n}\n\nexport type CommitPlanResult =\n | {\n kind: 'committed';\n ops_applied: number;\n collaborated: boolean;\n warnings?: CommitPlanWarning[];\n }\n | { kind: 'unconfirmed'; reason: 'push_failed'; ops_applied: number; message: string }\n | { kind: 'rejected'; reason: 'version_mismatch'; expected: string; actual: string }\n | { kind: 'rejected'; reason: 'push_rejected'; code?: string; message: string }\n | {\n kind: 'rejected';\n reason: 'op_conflict';\n /** Failing entry index in the journal — agent rerun anchor. */\n index: number;\n op_kind: SemanticOpName;\n /** Validator message, passed through verbatim (never a raw Error). */\n message: string;\n };\n\nexport interface CommitPlanOptions {\n /** `'version'` (default, phase-1 hard gate) | `'preflight'` (phase-2 per-op revalidation). */\n validation?: 'version' | 'preflight';\n}\n\n/**\n * Replay a sandbox journal into a manually-synchronized document and push the\n * whole plan as one causally complete update.\n *\n * - Default / `{ validation: 'version' }`: if the current document mark differs\n * from `plan.base_version`, reject with zero writes.\n * - `{ validation: 'preflight' }`: skip the version gate; revalidate each op\n * against a PlainMemoryAdapter seeded from the current live snapshot, then\n * replay for real. A SchemaValidator failure becomes `op_conflict` with the\n * failing entry's index. Journal integrity errors (unrecorded/unconsumed\n * ids) still propagate as throws in both modes.\n */\nexport async function commitPlan(\n doc: ManualSyncDoc,\n plan: CommitPlan,\n options?: CommitPlanOptions,\n): Promise<CommitPlanResult> {\n if (options?.validation === 'preflight') {\n return commitPlanPreflight(doc, plan);\n }\n\n const actual = encodeDocVersionMark(doc.versionMark());\n const expected = decodeDocVersionMark(plan.base_version);\n if (expected == null || doc.hasChangedSince(expected)) {\n return {\n kind: 'rejected',\n reason: 'version_mismatch',\n expected: plan.base_version,\n actual,\n };\n }\n\n await doc.replayJournal(plan.ops);\n return retryPlanPush(doc, plan.ops.length);\n}\n\n/**\n * Phase-2 path: scratch revalidation then real replay. Each entry is driven\n * through `replayJournal` alone so a ValidationError maps to a stable index;\n * integrity throws are not wrapped.\n */\nasync function commitPlanPreflight(doc: ManualSyncDoc, plan: CommitPlan): Promise<CommitPlanResult> {\n const scratch = createPlainMemoryAdapter(doc.snapshot());\n\n for (let index = 0; index < plan.ops.length; index++) {\n const entry = plan.ops[index];\n if (entry == null) continue;\n try {\n await replayJournal(scratch, [entry]);\n } catch (error) {\n if (error instanceof ValidationError) {\n return opConflict(index, entry.kind, error.message);\n }\n throw error;\n }\n }\n\n // Real replay: optimistic window may still collide; wrap ValidationError the\n // same way. Prior entries in this loop have already been written.\n for (let index = 0; index < plan.ops.length; index++) {\n const entry = plan.ops[index];\n if (entry == null) continue;\n try {\n await doc.replayJournal([entry]);\n } catch (error) {\n if (error instanceof ValidationError) {\n return opConflict(index, entry.kind, `real replay: ${error.message}`);\n }\n throw error;\n }\n }\n\n return retryPlanPush(doc, plan.ops.length);\n}\n\n/** Push an already-replayed plan again without replaying or re-running its version gate. */\nexport async function retryPlanPush(doc: ManualSyncDoc, opsApplied: number): Promise<CommitPlanResult> {\n const result = await doc.push();\n if (result.kind === 'ack' || result.kind === 'duplicate' || result.kind === 'nothing_to_push') {\n // A push can reveal that another peer wrote concurrently. Pull after the\n // durable verdict so the cached document does not serve a stale snapshot on\n // the next tool call; a pull failure cannot undo the acknowledged write.\n const reconciled = result.collaborated ? await doc.pull() : undefined;\n const warnings =\n reconciled != null && !reconciled.ok\n ? [{ kind: 'pull_failed' as const, message: reconciled.error.message }]\n : undefined;\n return {\n kind: 'committed',\n ops_applied: opsApplied,\n collaborated: result.collaborated,\n ...(warnings !== undefined ? { warnings } : {}),\n };\n }\n if (result.kind === 'rejected') {\n return {\n kind: 'rejected',\n reason: 'push_rejected',\n ...(result.code !== undefined ? { code: result.code } : {}),\n message: result.error?.message ?? 'mengine rejected the sandbox plan',\n };\n }\n return {\n kind: 'unconfirmed',\n reason: 'push_failed',\n ops_applied: opsApplied,\n message: result.error?.message ?? 'mengine push failed',\n };\n}\n\nfunction opConflict(index: number, op_kind: SemanticOpName, message: string): CommitPlanResult {\n return { kind: 'rejected', reason: 'op_conflict', index, op_kind, message };\n}\n","import { randomUUID } from 'node:crypto';\n\nimport {\n createMirrorVideoDocument,\n encodeDocVersionMark,\n ManualSyncDoc,\n MengineHttpClient,\n MengineHttpRequestError,\n ensureEditorFoundation,\n LoroEntityDocument,\n toVideoDocument,\n type ManualSyncDocOptions,\n type VideoDocument,\n type VideoDraft,\n} from '@mengine/medeo-client';\n\nimport {\n assembleCaptionAssets,\n type CaptionAssetsLoader,\n type CaptionAssetAssemblyOutcome,\n} from './entity/caption-asset-assembly.ts';\nimport type { EntityStoreSnapshot } from './entity/entity-contract.ts';\nimport { EntityHttpClient, MengineEntityHttpRequestError } from './entity/entity-http-client.ts';\nimport {\n syncGeneratedRelations,\n type GenerationFactsLoader,\n type GenerationSyncOutcome,\n} from './entity/generation-sync.ts';\nimport { MEDEO_TOOL_DESCRIPTION, renderMedeoModelContext } from './prompt.ts';\nimport { businessState } from './sandbox/business-facades.ts';\nimport { runEditScript } from './sandbox/node-host.ts';\nimport type { ChangePlan } from './sandbox/script-session.ts';\nimport { MEDEO_TOOL_NAME, MEDEO_TOOL_PARAMETERS, type MedeoToolOp } from './schema.ts';\nimport { retryPlanPush, type CommitPlanResult } from './session/commit-plan.ts';\n\ntype ContextualValue<T> = T | ((docId: string) => T | undefined);\n\nexport interface CreateMedeoToolOptions {\n /**\n * Mengine HTTP origin for a document. The host owns environment routing\n * (local/stg/prd/lane) and may return a different origin per document.\n * Documents cache by doc id, so the origin must remain stable for that doc.\n */\n httpOrigin: ContextualValue<string>;\n /** Optional bearer token, evaluated for each HTTP request. */\n authToken?: ContextualValue<string>;\n /** Optional end-user id header, evaluated for each HTTP request. */\n userId?: ContextualValue<string>;\n /** Stable agent peer id. Supply a host-scoped value so audit provenance is durable. */\n peerId?: ContextualValue<string>;\n /**\n * Load the authoritative legacy draft used to create a missing Mengine\n * document. The tool owns the get-or-create flow: it first probes Mengine,\n * converts this draft into a VideoDocument only on a 404, bootstraps the\n * snapshot, and tolerates a concurrent creator winning the race.\n */\n loadInitialDraft?: (docId: string) => Promise<VideoDraft>;\n /**\n * Resolve factual generation lineage by external asset id after a confirmed\n * entity commit. Return every known generation record involving the given\n * ids in either role; an empty array means no known lineage and a rejection\n * means the lineage query failed (surfaced as a warning, never as synced\n * state). The package owns all Entity/Relation semantics: the host never\n * names entities, relations, or endpoints.\n */\n loadGenerationFacts?: GenerationFactsLoader;\n /** Assemble optional Caption artifacts by immutable entity ID; never exposed to scripts. */\n loadCaptionAssets?: CaptionAssetsLoader;\n fetchImpl?: typeof fetch;\n /** @deprecated ManualSyncDoc has no SSE or reconnect loop. */\n sseReconnectDelayMs?: number;\n /** Defaults passed to runEditScript; each call may override them. */\n sandbox?: { timeoutMs?: number; memoryLimitMb?: number };\n /** Maximum cached plans; oldest plans are evicted (default 16). */\n maxPlans?: number;\n /** Maximum model-call version baselines retained across host contexts (default 128). */\n maxModelContexts?: number;\n}\n\nexport interface MedeoModelContextInput {\n /** Internal MEngine document id. This is host-supplied and never model-facing. */\n doc_id: string;\n /** Stable host conversation/session key used to compare consecutive model calls. */\n context_id: string;\n}\n\nexport interface MedeoModelContext {\n /** Complete MEngine-owned prompt: workflow, runtime state, and sandbox TypeScript interface. */\n prompt: string;\n document_version: string;\n updated_since_previous_model_call: boolean | null;\n}\n\nexport type MedeoToolInput =\n | { op: 'snapshot'; doc_id: string }\n | {\n op: 'run-edit-script';\n doc_id: string;\n script: string;\n inputs?: Record<string, unknown>;\n timeout_ms?: number;\n memory_limit_mb?: number;\n auto_commit?: boolean;\n }\n | {\n op: 'commit-plan';\n doc_id: string;\n plan_id: string;\n validation?: 'preflight';\n };\n\nexport type MedeoToolWarning =\n | { kind: 'asset_assembly_failed'; message: string }\n | { kind: 'pull_failed'; message: string }\n | { kind: 'generation_sync_failed'; message: string };\n\nexport type EntityCommitResult =\n | { kind: 'conflicted'; accepted: true; entity_revision: number; message: string }\n | {\n kind: 'committed';\n ops_applied: number;\n collaborated: boolean;\n entity_revision: number;\n /** Present only when the host supplies loadGenerationFacts. */\n generation_sync?: GenerationSyncOutcome;\n asset_assembly?: CaptionAssetAssemblyOutcome;\n warnings?: MedeoToolWarning[];\n }\n | { kind: 'unconfirmed'; reason: 'push_failed'; ops_applied: number; message: string }\n | {\n kind: 'rejected';\n reason: 'entity_state_rejected';\n status: number;\n message: string;\n };\n\nexport type MedeoCommitResult = CommitPlanResult | EntityCommitResult;\n\nexport type MedeoToolResult =\n | {\n ok: true;\n op: 'snapshot';\n doc_id: string;\n version: string;\n preview: string;\n collaborated?: boolean;\n warnings?: MedeoToolWarning[];\n }\n | {\n ok: true;\n op: 'run-edit-script';\n doc_id: string;\n plan_id: string;\n plan_kind: 'timeline' | 'entities';\n base_version: string;\n entity_base_revision: number;\n ops_count: number;\n preview: string;\n logs: string[];\n duration_ms: number;\n committed?: boolean;\n commit_result?: MedeoCommitResult;\n collaborated?: boolean;\n warnings?: MedeoToolWarning[];\n }\n | {\n ok: false;\n op: 'run-edit-script';\n doc_id: string;\n phase: 'parse' | 'runtime' | 'timeout' | 'memory';\n error: { message: string; line?: number; column?: number; stack?: string };\n partial: { ops_count: number; logs: string[] };\n }\n | {\n ok: true;\n op: 'commit-plan';\n doc_id: string;\n plan_id: string;\n plan_kind: 'timeline' | 'entities';\n committed: boolean;\n result: MedeoCommitResult;\n collaborated?: boolean;\n warnings?: MedeoToolWarning[];\n }\n | { ok: false; op: MedeoToolOp; error: string };\n\nexport interface MedeoTool {\n name: typeof MEDEO_TOOL_NAME;\n description: typeof MEDEO_TOOL_DESCRIPTION;\n parameters: typeof MEDEO_TOOL_PARAMETERS;\n getModelContext(input: MedeoModelContextInput): Promise<MedeoModelContext>;\n handle(input: unknown): Promise<MedeoToolResult>;\n close(): Promise<void>;\n}\n\nexport type MedeoInitialDraft = VideoDraft;\n\ninterface CachedPlan {\n docId: string;\n plan: ChangePlan;\n /** Entity-store state the plan was built from; the generation sync's diff base. */\n baseState?: EntityStoreSnapshot;\n}\n\ninterface TimelinePendingPush {\n kind: 'timeline';\n planId: string;\n plan: ChangePlan;\n opsApplied: number;\n}\n\ninterface EntityPendingPush {\n kind: 'entities';\n planId: string;\n plan: ChangePlan;\n /** Diff base for the generation sync after recovery; see CachedPlan. */\n baseState?: EntityStoreSnapshot;\n}\n\ntype PendingPush = TimelinePendingPush | EntityPendingPush;\n\ninterface PullObservation {\n collaborated: boolean;\n warnings?: MedeoToolWarning[];\n}\n\nconst DEFAULT_MAX_PLANS = 16;\nconst DEFAULT_MAX_MODEL_CONTEXTS = 128;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction optionalContext<T>(value: ContextualValue<T> | undefined, docId: string): T | undefined {\n if (value === undefined) return undefined;\n return typeof value === 'function' ? (value as (id: string) => T | undefined)(docId) : value;\n}\n\nfunction requiredContext(value: ContextualValue<string>, docId: string, field: string): string {\n const resolved = optionalContext(value, docId)?.trim();\n if (resolved == null || resolved.length === 0) {\n throw new Error(`${field} must resolve to a non-empty string for doc ${docId}`);\n }\n return resolved;\n}\n\nfunction renderEntitySnapshot(raw: EntityStoreSnapshot): string {\n const state = businessState(raw);\n const rows = [\n ...state.entities.map((entity) => JSON.stringify(entity)),\n ...state.relations.map((relation) => JSON.stringify(relation)),\n ];\n const shown = rows.slice(0, 200);\n return [\n `Entity revision=${state.revision} audioScriptEntityId=${JSON.stringify(state.audioScriptEntityId)} entities=${state.entities.length} relations=${state.relations.length}`,\n ...shown,\n ...(shown.length < rows.length ? ['[truncated; inspect entities/relations in the sandbox]'] : []),\n ].join('\\n');\n}\n\nasync function commitEntityPlan(client: EntityHttpClient, plan: ChangePlan): Promise<EntityCommitResult> {\n const rows = plan.entity_rows;\n if (rows === undefined) throw new Error('entity plan is missing its authoritative rows');\n try {\n if (!plan.loro_update) throw new Error('Entity plan has no compiled Loro update');\n const committed = await client.commitUpdate(plan.loro_update);\n return {\n kind: 'committed',\n ops_applied: plan.entity_commands.length,\n collaborated: committed.revision > plan.entity_base_revision + 1,\n entity_revision: committed.revision,\n };\n } catch (error) {\n if (error instanceof MengineEntityHttpRequestError) {\n if (isRecord(error.payload) && error.payload.accepted === true && typeof error.payload.revision === 'number')\n return {\n kind: 'conflicted',\n accepted: true,\n entity_revision: error.payload.revision,\n message: entityHttpErrorMessage(error.payload),\n };\n return {\n kind: 'rejected',\n reason: 'entity_state_rejected',\n status: error.status,\n message: entityHttpErrorMessage(error.payload),\n };\n }\n return {\n kind: 'unconfirmed',\n reason: 'push_failed',\n ops_applied: plan.entity_commands.length,\n message: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\nfunction entityHttpErrorMessage(payload: unknown): string {\n if (isRecord(payload) && isRecord(payload.error) && typeof payload.error.message === 'string')\n return payload.error.message;\n if (isRecord(payload) && typeof payload.message === 'string' && payload.message.length > 0) return payload.message;\n return typeof payload === 'string' && payload.length > 0 ? payload : 'mengine rejected the entity-state plan';\n}\n\nfunction commitWarnings(result: MedeoCommitResult): MedeoToolWarning[] | undefined {\n return result.kind === 'committed' && 'warnings' in result && result.warnings !== undefined\n ? [...result.warnings]\n : undefined;\n}\n\nfunction parseInput(value: unknown): MedeoToolInput {\n if (!isRecord(value)) throw new Error('input must be an object');\n const op = value.op;\n const docId = value.doc_id;\n if (typeof op !== 'string') throw new Error('op must be a string');\n if (typeof docId !== 'string' || docId.trim().length === 0) throw new Error('doc_id must be a non-empty string');\n\n if (op === 'snapshot') return { op, doc_id: docId };\n\n if (op === 'run-edit-script') {\n if (typeof value.script !== 'string' || value.script.length === 0) {\n throw new Error('script must be a non-empty string');\n }\n if (value.inputs !== undefined && !isRecord(value.inputs)) {\n throw new Error('inputs must be an object');\n }\n const timeoutMs = value.timeout_ms;\n if (timeoutMs !== undefined && (typeof timeoutMs !== 'number' || !Number.isInteger(timeoutMs) || timeoutMs <= 0)) {\n throw new Error('timeout_ms must be a positive integer');\n }\n const memoryLimitMb = value.memory_limit_mb;\n if (\n memoryLimitMb !== undefined &&\n (typeof memoryLimitMb !== 'number' || !Number.isInteger(memoryLimitMb) || memoryLimitMb < 16)\n ) {\n throw new Error('memory_limit_mb must be an integer >= 16');\n }\n if (value.auto_commit !== undefined && typeof value.auto_commit !== 'boolean') {\n throw new Error('auto_commit must be a boolean');\n }\n return {\n op,\n doc_id: docId,\n script: value.script,\n ...(value.inputs !== undefined ? { inputs: value.inputs } : {}),\n ...(timeoutMs !== undefined ? { timeout_ms: timeoutMs } : {}),\n ...(memoryLimitMb !== undefined ? { memory_limit_mb: memoryLimitMb } : {}),\n ...(value.auto_commit !== undefined ? { auto_commit: value.auto_commit } : {}),\n };\n }\n\n if (op === 'commit-plan') {\n if (typeof value.plan_id !== 'string' || value.plan_id.length === 0) {\n throw new Error('plan_id must be a non-empty string');\n }\n if (value.validation !== undefined && value.validation !== 'preflight') {\n throw new Error('validation must be \"preflight\"');\n }\n return {\n op,\n doc_id: docId,\n plan_id: value.plan_id,\n ...(value.validation !== undefined ? { validation: value.validation } : {}),\n };\n }\n\n throw new Error(`unknown op: ${op}`);\n}\n\n/**\n * Create the self-contained Medeo LLM tool.\n *\n * The package owns document construction, compact projection, sandbox execution,\n * plan caching, commit, document get-or-create, and shutdown. The host supplies\n * environment facts plus the authoritative legacy draft loader used only when\n * Mengine has no document yet.\n */\nexport function createMedeoTool(options: CreateMedeoToolOptions): MedeoTool {\n const documents = new Map<string, Promise<ManualSyncDoc>>();\n const entityClients = new Map<string, EntityHttpClient>();\n const documentTails = new Map<string, Promise<void>>();\n const pendingPushes = new Map<string, PendingPush>();\n const plans = new Map<string, CachedPlan>();\n const modelContextVersions = new Map<string, string>();\n const maxPlans = options.maxPlans ?? DEFAULT_MAX_PLANS;\n const maxModelContexts = options.maxModelContexts ?? DEFAULT_MAX_MODEL_CONTEXTS;\n let closed = false;\n\n async function getDocument(docId: string): Promise<ManualSyncDoc> {\n if (closed) throw new Error('medeo tool is closed');\n const existing = documents.get(docId);\n if (existing != null) return await existing;\n\n const created = (async () => {\n const client = new MengineHttpClient({\n docId,\n httpOrigin: requiredContext(options.httpOrigin, docId, 'httpOrigin'),\n ...(options.authToken !== undefined ? { authToken: () => optionalContext(options.authToken, docId) } : {}),\n ...(options.userId !== undefined ? { userId: () => optionalContext(options.userId, docId) } : {}),\n ...(options.fetchImpl !== undefined ? { fetchImpl: options.fetchImpl } : {}),\n });\n const peerId = optionalContext(options.peerId, docId) as ManualSyncDocOptions['peerId'] | undefined;\n return await getOrCreateDocument(client, docId, peerId);\n })();\n\n documents.set(docId, created);\n try {\n return await created;\n } catch (error) {\n if (documents.get(docId) === created) documents.delete(docId);\n throw error;\n }\n }\n\n function getEntityClient(docId: string): EntityHttpClient {\n if (closed) throw new Error('medeo tool is closed');\n const existing = entityClients.get(docId);\n if (existing != null) return existing;\n const client = new EntityHttpClient({\n docId,\n httpOrigin: requiredContext(options.httpOrigin, docId, 'httpOrigin'),\n ...(options.authToken !== undefined ? { authToken: () => optionalContext(options.authToken, docId) } : {}),\n ...(options.userId !== undefined ? { userId: () => optionalContext(options.userId, docId) } : {}),\n ...(options.fetchImpl !== undefined ? { fetchImpl: options.fetchImpl } : {}),\n });\n entityClients.set(docId, client);\n return client;\n }\n\n async function runExclusive<T>(docId: string, use: (doc: ManualSyncDoc) => Promise<T>): Promise<T> {\n const previous = documentTails.get(docId) ?? Promise.resolve();\n let release!: () => void;\n const gate = new Promise<void>((resolve) => {\n release = resolve;\n });\n const tail = previous.catch(() => {}).then(() => gate);\n documentTails.set(docId, tail);\n\n await previous.catch(() => {});\n try {\n return await use(await getDocument(docId));\n } finally {\n release();\n if (documentTails.get(docId) === tail) documentTails.delete(docId);\n }\n }\n\n async function getOrCreateDocument(\n client: MengineHttpClient,\n docId: string,\n peerId: ManualSyncDocOptions['peerId'] | undefined,\n ): Promise<ManualSyncDoc> {\n try {\n return await ManualSyncDoc.open({ client, ...(peerId !== undefined ? { peerId } : {}) });\n } catch (error) {\n if (!(error instanceof MengineHttpRequestError) || error.status !== 404) throw error;\n if (options.loadInitialDraft === undefined) throw error;\n }\n\n const draft = await options.loadInitialDraft(docId);\n const document = toVideoDocument(draft);\n if (Object.keys(document.part_library ?? {}).length > 0) {\n throw new Error('Legacy content cannot bootstrap a Loro entity project');\n }\n const seed = createMirrorVideoDocument(document, {\n ...(peerId !== undefined ? { peerId } : {}),\n origin: 'mengine.medeo_tool.bootstrap',\n });\n const foundation = ensureEditorFoundation({ entities: [], relations: [] });\n const entities = LoroEntityDocument.create(foundation.rows, {\n timelineEntityId: foundation.timelineEntityId,\n audioScriptEntityId: foundation.audioScriptEntityId,\n });\n seed.import(entities.doc.export({ mode: 'snapshot' }));\n\n try {\n await client.bootstrapSnapshot(seed.export({ mode: 'snapshot' }));\n } catch (error) {\n // Bootstrap is create-only. If another worker created the same document\n // after our 404 probe, accept that winner only after an authenticated\n // snapshot read proves the document now exists and is accessible.\n if (!(error instanceof MengineHttpRequestError) || error.status !== 400) throw error;\n // The open below is the authenticated proof that the winner exists.\n }\n return await ManualSyncDoc.open({ client, ...(peerId !== undefined ? { peerId } : {}) });\n }\n\n function rememberPlan(docId: string, plan: ChangePlan, baseState: EntityStoreSnapshot | undefined): string {\n const planId = randomUUID();\n plans.set(planId, {\n docId,\n plan,\n ...(plan.plan_kind === 'entities' ? { baseState: baseState && structuredClone(baseState) } : {}),\n });\n while (plans.size > maxPlans) {\n const protectedPlanIds = new Set([...pendingPushes.values()].map((pending) => pending.planId));\n protectedPlanIds.add(planId);\n const oldestEvictable = [...plans.keys()].find((candidate) => !protectedPlanIds.has(candidate));\n // Pending plans are recovery state, and the plan just returned by this\n // call must remain usable. Let the cache exceed its nominal bound until a\n // later insertion can evict an older, non-pending plan.\n if (oldestEvictable === undefined) break;\n plans.delete(oldestEvictable);\n }\n return planId;\n }\n\n function assertNoPendingPush(docId: string): void {\n const pending = pendingPushes.get(docId);\n if (pending != null) {\n throw new Error(`doc ${docId} has an unconfirmed push; retry plan_id ${pending.planId} before continuing`);\n }\n }\n\n function recordPushResult(\n docId: string,\n planId: string,\n plan: ChangePlan,\n result: MedeoCommitResult,\n baseState: EntityStoreSnapshot | undefined,\n ): void {\n if (result.kind === 'unconfirmed') {\n pendingPushes.set(\n docId,\n plan.plan_kind === 'timeline'\n ? { kind: 'timeline', planId, plan, opsApplied: result.ops_applied }\n : { kind: 'entities', planId, plan, ...(baseState !== undefined ? { baseState } : {}) },\n );\n return;\n }\n pendingPushes.delete(docId);\n if (plan.plan_kind === 'timeline' && result.kind === 'rejected' && result.reason === 'push_rejected') {\n documents.delete(docId);\n }\n }\n\n async function fetchEntityStateForSandbox(\n docId: string,\n _doc: ManualSyncDoc,\n _pull: PullObservation,\n ): Promise<EntityStoreSnapshot> {\n const state = await getEntityClient(docId).fetchState();\n if (!state.loroSnapshot) throw new Error('Project requires the Loro entity contract');\n return state;\n }\n\n async function commitCachedPlan(\n docId: string,\n _doc: ManualSyncDoc,\n plan: ChangePlan,\n validation?: 'preflight',\n baseState?: EntityStoreSnapshot,\n ) {\n if (plan.plan_kind === 'timeline') {\n throw new Error('Legacy timeline plans are not editable; use an Entity/Relation plan');\n }\n // Every plan was preflighted on its causal Loro fork before publication.\n void validation;\n if (plan.entity_rows === undefined) throw new Error('entity plan is missing its authoritative rows');\n const client = getEntityClient(docId);\n // The generation diff must use the same causal baseline as the compiled update.\n if (options.loadGenerationFacts !== undefined && baseState === undefined)\n throw new Error('Generation synchronization is missing the cached causal plan baseline');\n const result = await commitEntityPlan(client, plan);\n const synced = await attachGenerationSync(docId, plan, result, baseState);\n if (synced.kind !== 'committed' || options.loadCaptionAssets === undefined) return synced;\n const assembly = await assembleCaptionAssets({ client, docId, loadAssets: options.loadCaptionAssets });\n return {\n ...synced,\n asset_assembly: assembly,\n ...(assembly.status === 'failed'\n ? {\n warnings: [\n ...(synced.warnings ?? []),\n {\n kind: 'asset_assembly_failed' as const,\n message: assembly.message ?? 'Caption Asset assembly failed',\n },\n ],\n }\n : {}),\n };\n }\n\n /**\n * After a confirmed entity commit, connect fact-matched generated Relations\n * from host-recalled lineage. The commit is already durable, so a sync\n * failure never fails the op; it is attached to the result and surfaced as a\n * warning instead. The plan's diff against `baseState` scopes the sync:\n * newly created media Asset identities — not untouched pairs or placement-only edits.\n * One-sided facts are skipped silently inside the sync.\n */\n async function attachGenerationSync(\n docId: string,\n plan: ChangePlan,\n result: EntityCommitResult,\n baseState: EntityStoreSnapshot | undefined,\n ): Promise<EntityCommitResult> {\n if (result.kind !== 'committed' || options.loadGenerationFacts === undefined || baseState === undefined) {\n return result;\n }\n let outcome: GenerationSyncOutcome;\n try {\n outcome = await syncGeneratedRelations({\n client: getEntityClient(docId),\n docId,\n baseState,\n entityCommands: plan.entity_commands,\n loadFacts: options.loadGenerationFacts,\n });\n } catch (error) {\n outcome = { status: 'failed', message: error instanceof Error ? error.message : String(error) };\n }\n const warnings: MedeoToolWarning[] | undefined =\n outcome.status === 'failed'\n ? [{ kind: 'generation_sync_failed', message: outcome.message ?? 'generation lineage sync failed' }]\n : undefined;\n return {\n ...result,\n generation_sync: outcome,\n ...(warnings !== undefined ? { warnings } : {}),\n };\n }\n\n async function observePull(doc: ManualSyncDoc): Promise<PullObservation> {\n const result = await doc.pull();\n if (result.ok) return { collaborated: result.changed };\n return {\n collaborated: false,\n warnings: [{ kind: 'pull_failed', message: result.error.message }],\n };\n }\n\n function mergeWarnings(\n ...groups: readonly (readonly MedeoToolWarning[] | undefined)[]\n ): MedeoToolWarning[] | undefined {\n const warnings = groups.flatMap((group) => group ?? []);\n return warnings.length > 0 ? warnings : undefined;\n }\n\n async function getModelContext(input: MedeoModelContextInput): Promise<MedeoModelContext> {\n const docId = input.doc_id.trim();\n const contextId = input.context_id.trim();\n if (docId.length === 0) throw new Error('doc_id must be a non-empty string');\n if (contextId.length === 0) throw new Error('context_id must be a non-empty string');\n\n return await runExclusive(docId, async (doc) => {\n // ManualSyncDoc has no background stream. Pull before sampling so remote\n // edits made between model calls participate in the version comparison.\n const pull = await observePull(doc);\n const entityState = await fetchEntityStateForSandbox(docId, doc, pull);\n const documentVersion = `${encodeDocVersionMark(doc.versionMark())}:entities:${entityState.revision}`;\n const baselineKey = `${contextId}\\u0000${docId}`;\n const previousVersion = modelContextVersions.get(baselineKey);\n const updatedSincePreviousModelCall = previousVersion == null ? null : previousVersion !== documentVersion;\n\n // Refresh insertion order so the bounded map behaves as an LRU.\n modelContextVersions.delete(baselineKey);\n modelContextVersions.set(baselineKey, documentVersion);\n while (modelContextVersions.size > maxModelContexts) {\n const oldest = modelContextVersions.keys().next().value;\n if (oldest === undefined) break;\n modelContextVersions.delete(oldest);\n }\n\n return {\n prompt: renderMedeoModelContext({ documentVersion, updatedSincePreviousModelCall }),\n document_version: documentVersion,\n updated_since_previous_model_call: updatedSincePreviousModelCall,\n };\n });\n }\n\n async function snapshot(input: Extract<MedeoToolInput, { op: 'snapshot' }>): Promise<MedeoToolResult> {\n return runExclusive(input.doc_id, async (doc) => {\n assertNoPendingPush(input.doc_id);\n const pull = await observePull(doc);\n const entityState = await fetchEntityStateForSandbox(input.doc_id, doc, pull);\n return {\n ok: true,\n op: 'snapshot',\n doc_id: input.doc_id,\n version: `${encodeDocVersionMark(doc.versionMark())}:entities:${entityState.revision}`,\n preview: renderEntitySnapshot(entityState),\n collaborated: pull.collaborated,\n ...(pull.warnings !== undefined ? { warnings: pull.warnings } : {}),\n };\n });\n }\n\n async function run(input: Extract<MedeoToolInput, { op: 'run-edit-script' }>): Promise<MedeoToolResult> {\n return runExclusive(input.doc_id, async (doc) => {\n assertNoPendingPush(input.doc_id);\n const pull = await observePull(doc);\n const entityState = await fetchEntityStateForSandbox(input.doc_id, doc, pull);\n const document: VideoDocument = doc.snapshot();\n const baseVersion = encodeDocVersionMark(doc.versionMark());\n const result = await runEditScript({\n document,\n baseVersion,\n entityState,\n entityOnly: true,\n script: input.script,\n ...(input.inputs !== undefined ? { inputs: input.inputs } : {}),\n timeoutMs: input.timeout_ms ?? options.sandbox?.timeoutMs,\n memoryLimitMb: input.memory_limit_mb ?? options.sandbox?.memoryLimitMb,\n });\n\n if (!result.ok) {\n return {\n ok: false,\n op: 'run-edit-script',\n doc_id: input.doc_id,\n phase: result.phase,\n error: result.error,\n partial: {\n ops_count: result.partial.ops.length + result.partial.entityCommands.length,\n logs: result.partial.logs,\n },\n };\n }\n\n // The host-selected mapping is authoritative. A legacy document snapshot\n // may omit meta.draft_id, so never derive an entity route from it.\n const plan = { ...result.plan, doc_id: input.doc_id };\n const planId = rememberPlan(input.doc_id, plan, entityState);\n const base = {\n ok: true as const,\n op: 'run-edit-script' as const,\n doc_id: input.doc_id,\n plan_id: planId,\n plan_kind: plan.plan_kind,\n base_version: baseVersion,\n entity_base_revision: plan.entity_base_revision,\n ops_count: plan.ops.length + plan.entity_commands.length,\n preview: plan.preview,\n logs: plan.logs,\n duration_ms: result.durationMs,\n collaborated: pull.collaborated,\n ...(pull.warnings !== undefined ? { warnings: pull.warnings } : {}),\n };\n if (input.auto_commit !== true) return base;\n\n const commit = await commitCachedPlan(input.doc_id, doc, plan, undefined, entityState);\n recordPushResult(input.doc_id, planId, plan, commit, entityState);\n const warnings = mergeWarnings(pull.warnings, commitWarnings(commit));\n return {\n ...base,\n committed: commit.kind === 'committed',\n commit_result: commit,\n collaborated: pull.collaborated || (commit.kind === 'committed' && commit.collaborated),\n ...(warnings !== undefined ? { warnings } : {}),\n };\n });\n }\n\n async function commit(input: Extract<MedeoToolInput, { op: 'commit-plan' }>): Promise<MedeoToolResult> {\n return runExclusive(input.doc_id, async (doc) => {\n const pending = pendingPushes.get(input.doc_id);\n if (pending != null) {\n if (pending.planId !== input.plan_id) {\n throw new Error(\n `doc ${input.doc_id} has an unconfirmed push for plan_id ${pending.planId}; retry it before ${input.plan_id}`,\n );\n }\n const result =\n pending.kind === 'timeline'\n ? await retryPlanPush(doc, pending.opsApplied)\n : await commitCachedPlan(input.doc_id, doc, pending.plan, input.validation, pending.baseState);\n recordPushResult(\n input.doc_id,\n input.plan_id,\n pending.plan,\n result,\n pending.kind === 'entities' ? pending.baseState : undefined,\n );\n const warnings = commitWarnings(result);\n return {\n ok: true,\n op: 'commit-plan',\n doc_id: input.doc_id,\n plan_id: input.plan_id,\n plan_kind: pending.plan.plan_kind,\n committed: result.kind === 'committed',\n result,\n collaborated: result.kind === 'committed' && result.collaborated,\n ...(warnings !== undefined ? { warnings } : {}),\n };\n }\n\n const cached = plans.get(input.plan_id);\n if (cached == null || cached.docId !== input.doc_id) {\n throw new Error(`plan_id ${input.plan_id} is not available for doc ${input.doc_id}`);\n }\n const pull = cached.plan.plan_kind === 'timeline' ? await observePull(doc) : { collaborated: false };\n const result = await commitCachedPlan(input.doc_id, doc, cached.plan, input.validation, cached.baseState);\n recordPushResult(input.doc_id, input.plan_id, cached.plan, result, cached.baseState);\n const warnings = mergeWarnings(pull.warnings, commitWarnings(result));\n return {\n ok: true,\n op: 'commit-plan',\n doc_id: input.doc_id,\n plan_id: input.plan_id,\n plan_kind: cached.plan.plan_kind,\n committed: result.kind === 'committed',\n result,\n collaborated: pull.collaborated || (result.kind === 'committed' && result.collaborated),\n ...(warnings !== undefined ? { warnings } : {}),\n };\n });\n }\n\n return {\n name: MEDEO_TOOL_NAME,\n description: MEDEO_TOOL_DESCRIPTION,\n parameters: MEDEO_TOOL_PARAMETERS,\n getModelContext,\n async handle(input: unknown): Promise<MedeoToolResult> {\n try {\n const parsed = parseInput(input);\n if (parsed.op === 'snapshot') return await snapshot(parsed);\n if (parsed.op === 'run-edit-script') return await run(parsed);\n return await commit(parsed);\n } catch (error) {\n const op = isRecord(input) && typeof input.op === 'string' ? (input.op as MedeoToolOp) : 'snapshot';\n return {\n ok: false,\n op,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n },\n async close(): Promise<void> {\n closed = true;\n await Promise.allSettled(documentTails.values());\n const opening = [...documents.values()];\n documents.clear();\n entityClients.clear();\n documentTails.clear();\n pendingPushes.clear();\n plans.clear();\n modelContextVersions.clear();\n const errors: unknown[] = [];\n for (const documentPromise of opening) {\n try {\n await documentPromise;\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length === 1) throw errors[0];\n if (errors.length > 1) throw new AggregateError(errors, 'failed to close medeo tool documents');\n },\n };\n}\n","import { createHash } from 'node:crypto';\n\nimport type { MediaAssetFact } from '@mengine/medeo-client';\n\nimport type { JsonObject, SandboxEntity } from './entity-contract.ts';\nimport { EntityHttpClient, type EntityHttpClientOptions } from './entity-http-client.ts';\nimport { EntitySandbox } from './entity-sandbox.ts';\nimport { planGeneratedRelations, parseGenerationFacts, type GenerationFactsLoader } from './generation-sync.ts';\n\n/** Host facts only. This contract is never included in the model's sandbox API. */\nexport type GeneratedResource =\n | MediaAssetFact\n | {\n kind: 'caption';\n assetId: string;\n storageKey: string;\n segments: readonly {\n text: string;\n startMs: number;\n endMs: number;\n /** ASR word timing is available as an annotation for model segmentation. */\n words?: readonly { text: string; startMs: number; endMs: number }[];\n }[];\n };\n\n/** Persist resources before model consumption. The host serializes repeated imports of the same generation task. */\nexport async function materializeResources(\n options: EntityHttpClientOptions & { loadGenerationFacts?: GenerationFactsLoader },\n resources: readonly GeneratedResource[],\n): Promise<readonly string[]> {\n const client = new EntityHttpClient(options);\n const state = await client.fetchState();\n let resourceKey = '';\n const sandbox = new EntitySandbox({ state, idFactory: (prefix) => stableId(prefix, options.docId, resourceKey) });\n const ids: string[] = [];\n for (const resource of resources) {\n resourceKey = `${resource.kind}:${resource.assetId}`;\n if (resource.kind !== 'caption') {\n ids.push(sandbox.entities.ensureMedia(resource).contentEntityId);\n continue;\n }\n const assetId = stableId('asset', resource.assetId);\n const asset = sandbox.entities.get(assetId);\n if (asset) {\n if (asset.entity_kind !== 'asset' || asset.payload.storageKey !== resource.storageKey)\n throw new Error('Conflicting Caption resource identity');\n const bindings = sandbox.relations.of(assetId, 'physical-asset');\n const captions = bindings\n .map((edge) => sandbox.entities.get(edge.endpoint_0_entity_id))\n .filter((entity): entity is SandboxEntity => entity?.entity_kind === 'caption');\n if (captions.length !== 1) throw new Error('Caption resource must resolve to one materialized Caption');\n ids.push(captions[0]!.entity_id);\n continue;\n }\n if (!resource.assetId.trim() || !resource.storageKey.trim() || !resource.segments.length)\n throw new Error('Caption resource requires a physical locator and timed segments');\n for (const segment of resource.segments) {\n if (\n typeof segment.text !== 'string' ||\n !Number.isFinite(segment.startMs) ||\n !Number.isFinite(segment.endMs) ||\n segment.startMs < 0 ||\n segment.endMs <= segment.startMs\n )\n throw new Error('Caption resource has invalid ASR text or timing');\n for (const word of segment.words ?? []) {\n if (\n typeof word.text !== 'string' ||\n !Number.isFinite(word.startMs) ||\n !Number.isFinite(word.endMs) ||\n word.startMs < segment.startMs ||\n word.endMs > segment.endMs ||\n word.endMs < word.startMs\n )\n throw new Error('Caption resource has invalid ASR word timing');\n }\n }\n const scriptId = sandbox.audioScriptEntityId;\n if (!scriptId) throw new Error('Document AudioScript is not initialized');\n const script = sandbox.entities.get(scriptId)!;\n const segments = resource.segments.map((segment, index) => ({\n segmentId: stableId('segment', resource.assetId, String(index)),\n text: segment.text,\n }));\n const start = Math.min(...resource.segments.map((segment) => segment.startMs));\n const end = Math.max(...resource.segments.map((segment) => segment.endMs));\n // Patch the current text owner. The Loro compiler versions it and rewires\n // variant bases and the project attachment, preserving unrelated segments.\n sandbox.entities.update({\n entity_id: scriptId,\n payload: { segments: [...(script.payload.segments as JsonObject[]), ...segments] },\n });\n const captionId = stableId('entity', 'caption', resource.assetId);\n sandbox.entities.create({\n entity_id: captionId,\n entity_kind: 'caption',\n payload: {\n baseEntityIds: [scriptId],\n selections: segments.map(({ segmentId }) => ({ segmentId })),\n extent: { kind: 'bounded', start, end },\n sampling: 'native',\n coordinateSpace: 'milliseconds',\n },\n });\n const markerId = sandbox.entities.create({\n entity_id: stableId('entity', 'asr-marker', resource.assetId),\n entity_kind: 'sequence-marker',\n payload: {\n sourceRange: { start, end },\n duration: { mode: 'from-source' },\n segmentRanges: resource.segments.map((segment, index) => ({\n segmentId: segments[index]!.segmentId,\n startMs: segment.startMs,\n endMs: segment.endMs,\n })),\n wordRanges: resource.segments.flatMap((segment, index) =>\n (segment.words ?? []).map((word) => ({ ...word, segmentIndex: index })),\n ),\n },\n });\n sandbox.relations.link({\n relation_id: stableId('relation', 'asr-marker', resource.assetId),\n relation_kind: 'audio-script-marker',\n endpoint_0_entity_id: scriptId,\n endpoint_1_entity_id: markerId,\n });\n sandbox.entities.create({\n entity_id: assetId,\n entity_kind: 'asset',\n payload: {\n external: { system: 'memota', key: resource.assetId },\n storageKey: resource.storageKey,\n },\n });\n sandbox.relations.link({\n relation_id: stableId('relation', captionId, assetId),\n relation_kind: 'physical-asset',\n endpoint_0_entity_id: captionId,\n endpoint_1_entity_id: assetId,\n });\n ids.push(captionId);\n }\n const candidate = sandbox.buildPlan();\n if (candidate.commands.length && options.loadGenerationFacts) {\n const newIds = new Set(ids.filter((id) => !state.entities.some((row) => row.entity_id === id)));\n const facts = parseGenerationFacts(\n await options.loadGenerationFacts(\n options.docId,\n resources.map((item) => item.assetId),\n ),\n );\n const relations = planGeneratedRelations({\n baseState: state,\n state: candidate.rows,\n scopedMediaIds: newIds,\n facts,\n newRelationId: () => `relation_${globalThis.crypto.randomUUID()}`,\n });\n for (const relation of relations)\n sandbox.relations.linkGenerated({\n relation_id: relation.relation_id,\n output_entity_id: relation.endpoint_0_entity_id,\n input_entity_id: relation.endpoint_1_entity_id,\n trace: relation.trace,\n });\n }\n const plan = sandbox.buildPlan();\n if (!plan.commands.length) return ids;\n const committed = await client.commit(state.revision, plan.rows);\n for (const id of ids) {\n if (!committed.entities.some((entity) => entity.entity_id === id))\n throw new Error(`Resource entity ${id} was not confirmed by the merged document`);\n }\n return ids;\n}\n\nfunction stableId(prefix: string, ...parts: string[]): string {\n return `${prefix}_${createHash('sha256').update(JSON.stringify(parts)).digest('hex')}`;\n}\n"],"mappings":";;;;;AA+EA,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;;;;;;AAO1B,SAAS,cAAc,UAAuB;CAC5C,MAAM,UAAU,IAAI,IAAI,OAAO,KAAK,GAAG;CACvC,MAAM,YAAY,QAAQ,SAAS,SAAS,KAAK,IAAI,OAAO;CAC5D,OAAO,IAAI,IAAI,KAAK,SAA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A;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,EAAE,KAAK,IAAI;;;AC/fX,MAAa,yBAAyB;;;;;;;;;;;EAWpC,KAAK;AAEP,MAAM,6BAA6B;;;;;;;;;;;;EAYjC,KAAK;;AAQP,SAAgB,wBAAwB,OAA6C;CACnF,MAAM,UACJ,MAAM,iCAAiC,OACnC,+BACA,OAAO,MAAM,6BAA6B;CAChD,OAAO;EACP,uBAAuB;;EAEvB,2BAA2B;;;sBAGP,KAAK,UAAU,MAAM,eAAe,EAAE;uCACrB,QAAQ;;;;;;EAM7C,4BAA4B;;EAE5B,KAA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,GAAG,OAAyB;CAC5D,OAAO,GAAG,OAAO,GAAG,WAAW,QAAQ,EAAE,OAAO,KAAK,UAAU,KAAK,CAAC,EAAE,OAAO,KAAK;AACrF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["stableId","isRecord","isRecord"],"sources":["../src/sandbox/node-host.ts","../src/entity/caption-asset-assembly.ts","../src/entity/entity-contract.ts","../src/entity/entity-http-client.ts","../src/entity/generation-sync.ts","../src/sandbox/generated/entity-edit-sandbox-model-context.ts","../src/prompt.ts","../src/schema.ts","../src/session/commit-plan.ts","../src/host-tool.ts","../src/entity/materialize-resources.ts"],"sourcesContent":["/// <reference types=\"node\" />\nimport { Worker } from 'node:worker_threads';\n\nimport type { JournalEntry, VideoDocument } from '@mengine/medeo-client';\n\nimport type { EntityAssetContent } from '../entity/entity-asset.ts';\nimport type { SandboxEntity } from '../entity/entity-contract.ts';\nimport type { EntityCommand, EntityStoreSnapshot } from '../entity/entity-contract.ts';\nimport type { ChangePlan } from './script-session.ts';\n\n/**\n * Host API for running an agent edit script in an isolated Node worker.\n *\n * Requires Node.js >= 24.15 (engines) so the worker can load TypeScript via\n * `--experimental-transform-types`. Do not inherit `process.execArgv` — vitest\n * injects loaders that break worker boot.\n */\n\nexport interface RunEditScriptOptions {\n loadEntityAsset?: (entity: SandboxEntity) => Promise<EntityAssetContent>;\n document: VideoDocument;\n baseVersion: string;\n script: string;\n inputs?: Record<string, unknown>;\n /** Authoritative entity/relation rows and revision fetched for this document. */\n entityState?: EntityStoreSnapshot;\n /** Deterministic id mint label for tests; omit to use the default ULID factory. */\n idLabel?: string;\n /** @internal Select the graph-native Entity session used by the production host. */\n entityOnly?: boolean;\n /** Hard wall-clock timeout; default 2000 ms. */\n timeoutMs?: number;\n /** V8 old-generation ceiling for the worker; default 256 MB. */\n memoryLimitMb?: number;\n /** Override worker module URL (defaults to sibling `worker-entry.ts`). */\n workerEntryUrl?: URL;\n}\n\nexport type EditScriptResult =\n | {\n ok: true;\n plan: ChangePlan;\n /** Script execution time after worker readiness; excludes cold start. */\n durationMs: number;\n }\n | {\n ok: false;\n phase: 'parse' | 'runtime' | 'timeout' | 'memory';\n error: { message: string; line?: number; column?: number; stack?: string };\n partial: {\n ops: readonly JournalEntry[];\n entityCommands: readonly EntityCommand[];\n logs: string[];\n };\n };\n\ntype WorkerMessage =\n | { t: 'entity-asset'; requestId: number; entity: SandboxEntity }\n | { t: 'ready' }\n | { t: 'entry'; entry: JournalEntry }\n | { t: 'entity-entry'; command: EntityCommand }\n | { t: 'log'; line: string }\n | { t: 'truncate'; index: number }\n | { t: 'entity-truncate'; index: number }\n | {\n t: 'done';\n preview: string;\n opsCount: number;\n entityCommandsCount: number;\n loroUpdate?: string;\n entityBaseRevision: number;\n entityRows?: EntityStoreSnapshot;\n deletedEntityIds: readonly string[];\n deletedRelationIds: readonly string[];\n planKind: 'timeline' | 'entities';\n }\n | {\n t: 'fail';\n phase: 'parse' | 'runtime';\n error: { message: string; line?: number; column?: number; stack?: string };\n };\n\nconst DEFAULT_TIMEOUT_MS = 2000;\nconst DEFAULT_MEMORY_MB = 256;\n\n/**\n * Source runs load the checked-in TypeScript worker; packed runs load the\n * sibling JavaScript chunk emitted as a second package entry. Keeping this\n * branch explicit avoids shipping a `dist/*.ts` URL in the npm artifact.\n */\nfunction sourceSibling(fileName: string): URL {\n const selfUrl = new URL(import.meta.url);\n const extension = selfUrl.pathname.endsWith('.ts') ? 'ts' : 'mjs';\n return new URL(`./${fileName}.${extension}`, selfUrl);\n}\n\n/** Run `script` against a forked document snapshot; always resolves (never rejects). */\nexport function runEditScript(options: RunEditScriptOptions): Promise<EditScriptResult> {\n // Set when the worker has loaded its bundle and is about to invoke the script.\n // Keep this clock separate from worker boot so success timing matches the\n // timeout boundary and excludes cold-start/module-loading cost.\n let scriptStartedAt = performance.now();\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const memoryLimitMb = options.memoryLimitMb ?? DEFAULT_MEMORY_MB;\n const workerEntryUrl = options.workerEntryUrl ?? sourceSibling('worker-entry');\n const resolveRegisterUrl = sourceSibling('node-esm-resolve-register');\n\n const ops: JournalEntry[] = [];\n const entityCommands: EntityCommand[] = [];\n const logs: string[] = [];\n\n return new Promise<EditScriptResult>((resolve) => {\n let settled = false;\n let timedOut = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const worker = new Worker(workerEntryUrl, {\n workerData: {\n document: options.document,\n script: options.script,\n inputs: options.inputs,\n entityState: options.entityState,\n idLabel: options.idLabel,\n entityOnly: options.entityOnly,\n },\n // Explicit argv only — never inherit process.execArgv (vitest loaders).\n // Source workers need TypeScript transform plus the resolver hook for\n // workspace packages that still use extensionless directory imports.\n // Packed JavaScript workers already contain those dependencies.\n execArgv: resolveRegisterUrl.pathname.endsWith('.ts')\n ? [\n '--experimental-transform-types',\n '--disable-warning=ExperimentalWarning',\n `--import=${resolveRegisterUrl.href}`,\n ]\n : [],\n resourceLimits: { maxOldGenerationSizeMb: memoryLimitMb },\n });\n\n /** Start wall-clock timeout only after worker signals script is about to run. */\n const armTimeout = (): void => {\n if (settled || timer != null) return;\n timer = setTimeout(() => {\n timedOut = true;\n void worker.terminate();\n finish({\n ok: false,\n phase: 'timeout',\n error: { message: `edit script exceeded timeout of ${timeoutMs}ms` },\n partial: {\n ops: ops.slice(),\n entityCommands: entityCommands.slice(),\n logs: logs.slice(),\n },\n });\n }, timeoutMs);\n };\n\n const finish = (result: EditScriptResult): void => {\n if (settled) return;\n settled = true;\n if (timer != null) clearTimeout(timer);\n void worker.terminate();\n if (result.ok) {\n resolve({ ...result, durationMs: performance.now() - scriptStartedAt });\n } else {\n resolve(result);\n }\n };\n\n worker.on('message', (message: WorkerMessage) => {\n if (settled) return;\n if (message.t === 'ready') {\n scriptStartedAt = performance.now();\n armTimeout();\n return;\n }\n if (message.t === 'entity-asset') {\n void (async () => {\n try {\n if (!options.loadEntityAsset) throw new Error('Entity Asset loader is unavailable');\n const result = await options.loadEntityAsset(message.entity);\n if (!settled) worker.postMessage({ t: 'entity-asset-result', requestId: message.requestId, result });\n } catch (error) {\n if (!settled)\n worker.postMessage({\n t: 'entity-asset-result',\n requestId: message.requestId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n })();\n return;\n }\n if (message.t === 'entry') {\n ops.push(message.entry);\n return;\n }\n if (message.t === 'entity-entry') {\n entityCommands.push(message.command);\n return;\n }\n if (message.t === 'log') {\n logs.push(message.line);\n return;\n }\n if (message.t === 'truncate') {\n ops.length = Math.max(0, Math.min(message.index, ops.length));\n return;\n }\n if (message.t === 'entity-truncate') {\n entityCommands.length = Math.max(0, Math.min(message.index, entityCommands.length));\n return;\n }\n if (message.t === 'done') {\n if (message.opsCount !== ops.length || message.entityCommandsCount !== entityCommands.length) {\n finish({\n ok: false,\n phase: 'runtime',\n error: {\n message:\n `journal count mismatch: worker reported timeline=${message.opsCount}, entities=${message.entityCommandsCount}; ` +\n `host collected timeline=${ops.length}, entities=${entityCommands.length}`,\n },\n partial: {\n ops: ops.slice(),\n entityCommands: entityCommands.slice(),\n logs: logs.slice(),\n },\n });\n return;\n }\n finish({\n ok: true,\n plan: {\n plan_kind: message.planKind,\n doc_id: options.document.meta.draft_id ?? '',\n base_version: options.baseVersion,\n ops: ops.slice(),\n ...(message.loroUpdate ? { loro_update: message.loroUpdate } : {}),\n entity_base_revision: message.entityBaseRevision,\n entity_commands: entityCommands.slice(),\n ...(message.entityRows !== undefined ? { entity_rows: message.entityRows } : {}),\n deleted_entity_ids: message.deletedEntityIds,\n deleted_relation_ids: message.deletedRelationIds,\n preview: message.preview,\n logs: logs.slice(),\n },\n durationMs: 0,\n });\n return;\n }\n if (message.t === 'fail') {\n finish({\n ok: false,\n phase: message.phase,\n error: message.error,\n partial: {\n ops: ops.slice(),\n entityCommands: entityCommands.slice(),\n logs: logs.slice(),\n },\n });\n }\n });\n\n worker.on('error', (error: Error) => {\n if (settled) return;\n const text = error.message ?? String(error);\n const phase = /memory limit/i.test(text) ? 'memory' : 'runtime';\n finish({\n ok: false,\n phase,\n error: { message: text, stack: error.stack },\n partial: {\n ops: ops.slice(),\n entityCommands: entityCommands.slice(),\n logs: logs.slice(),\n },\n });\n });\n\n worker.on('exit', (code: number) => {\n if (settled) return;\n if (timedOut) return;\n finish({\n ok: false,\n phase: 'runtime',\n error: { message: `worker exited with code ${code ?? 'null'} before completion` },\n partial: {\n ops: ops.slice(),\n entityCommands: entityCommands.slice(),\n logs: logs.slice(),\n },\n });\n });\n });\n}\n","import { createHash } from 'node:crypto';\n\nimport type { SandboxEntity, SandboxRelation } from './entity-contract.ts';\nimport type { EntityHttpClient } from './entity-http-client.ts';\n\n/** Optional physical artifact registered for one immutable Caption identity. */\nexport interface CaptionAssetFact {\n readonly captionEntityId: string;\n readonly assetId: string;\n readonly storageKey: string;\n}\n\n/** Host-only lookup. Missing facts mean the Caption has no physical artifact. */\nexport type CaptionAssetsLoader = (\n docId: string,\n captionEntityIds: readonly string[],\n) => Promise<readonly CaptionAssetFact[]>;\n\nexport interface CaptionAssetAssemblyOutcome {\n readonly status: 'applied' | 'current' | 'failed';\n readonly message?: string;\n}\n\n/** Assemble optional infrastructure after business execution, using exact entity identity. */\nexport async function assembleCaptionAssets(input: {\n client: EntityHttpClient;\n docId: string;\n loadAssets: CaptionAssetsLoader;\n}): Promise<CaptionAssetAssemblyOutcome> {\n try {\n const state = await input.client.fetchState();\n const candidates = state.entities.filter(\n (entity) =>\n entity.entity_kind === 'caption' &&\n !state.relations.some(\n (relation) =>\n relation.relation_kind === 'physical-asset' &&\n (relation.endpoint_0_entity_id === entity.entity_id || relation.endpoint_1_entity_id === entity.entity_id),\n ),\n );\n if (!candidates.length) return { status: 'current' };\n const ids = new Set(candidates.map((entity) => entity.entity_id));\n const facts = await input.loadAssets(input.docId, [...ids]);\n const entities: SandboxEntity[] = [...state.entities];\n const relations: SandboxRelation[] = [...state.relations];\n const bound = new Map<string, string>();\n for (const fact of facts) {\n if (!ids.has(fact.captionEntityId) || !trimmed(fact.assetId) || !trimmed(fact.storageKey))\n throw new Error('Caption Asset fact must identify a requested Caption and a real Asset locator');\n const previous = bound.get(fact.captionEntityId);\n if (previous !== undefined) {\n if (previous !== fact.assetId) throw new Error(`Conflicting Assets for Caption ${fact.captionEntityId}`);\n continue;\n }\n bound.set(fact.captionEntityId, fact.assetId);\n const matches = entities.filter((entity) => {\n const external = entity.payload.external;\n return (\n external !== null &&\n typeof external === 'object' &&\n !Array.isArray(external) &&\n external.system === 'memota' &&\n external.key === fact.assetId\n );\n });\n if (matches.length > 1 || (matches[0] && matches[0].entity_kind !== 'asset'))\n throw new Error(`Conflicting resource identity for Caption Asset ${fact.assetId}`);\n let asset = matches[0];\n if (asset && asset.payload.storageKey !== fact.storageKey)\n throw new Error(`Conflicting storage key for Caption Asset ${fact.assetId}`);\n if (!asset) {\n asset = {\n entity_id: stableId('asset', fact.assetId),\n entity_kind: 'asset',\n payload: { external: { system: 'memota', key: fact.assetId }, storageKey: fact.storageKey },\n };\n if (entities.some((entity) => entity.entity_id === asset!.entity_id))\n throw new Error('Caption Asset identity collision');\n entities.push(asset);\n }\n relations.push({\n relation_id: stableId('relation', fact.captionEntityId, asset.entity_id),\n relation_kind: 'physical-asset',\n endpoint_0_entity_id: fact.captionEntityId,\n endpoint_1_entity_id: asset.entity_id,\n metadata: {},\n trace: {},\n });\n }\n if (!bound.size) return { status: 'current' };\n await input.client.commit(state.revision, { ...state, entities, relations });\n return { status: 'applied' };\n } catch (error) {\n return { status: 'failed', message: error instanceof Error ? error.message : String(error) };\n }\n}\n\nfunction stableId(prefix: string, ...parts: string[]): string {\n return `${prefix}_${createHash('sha256').update(JSON.stringify(parts)).digest('hex')}`;\n}\nfunction trimmed(value: string): boolean {\n return typeof value === 'string' && value.length > 0 && value.trim() === value;\n}\n","import type { MediaAssetFact } from '@mengine/medeo-client';\n\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue = JsonPrimitive | JsonObject | JsonValue[];\nexport interface JsonObject {\n [key: string]: JsonValue;\n}\n\nexport type KnownEntityKind =\n | 'axvideo'\n | 'timeline'\n | 'track'\n | 'clip'\n | 'asset'\n | 'video'\n | 'audio'\n | 'voice'\n | 'image'\n | 'sequence-marker'\n | 'viewport'\n | 'audio-script'\n | 'phonetic-script'\n | 'caption';\n\n/** Asset identity, either an old physical-only row or a directly composed media variant. */\nexport type ResourceEntityKind = 'image' | 'video' | 'audio' | 'voice';\n\nexport const KNOWN_ENTITY_KINDS: readonly KnownEntityKind[] = [\n 'axvideo',\n 'timeline',\n 'track',\n 'clip',\n 'asset',\n 'video',\n 'audio',\n 'voice',\n 'image',\n 'sequence-marker',\n 'viewport',\n 'audio-script',\n 'phonetic-script',\n 'caption',\n];\n\nexport type KnownRelationKind =\n | 'timeline-track'\n | 'track-clip'\n | 'clip-marker'\n | 'marker-content'\n | 'axvideo-marker'\n | 'marker-timeline'\n | 'physical-asset'\n | 'generated'\n | 'caption-alignment'\n | 'clip-anchor'\n | 'phonetic-script-render'\n | 'audio-script-source'\n | 'audio-script-marker';\n\nexport const KNOWN_RELATION_KINDS: readonly KnownRelationKind[] = [\n 'timeline-track',\n 'track-clip',\n 'clip-marker',\n 'marker-content',\n 'axvideo-marker',\n 'marker-timeline',\n 'physical-asset',\n 'generated',\n 'caption-alignment',\n 'clip-anchor',\n 'phonetic-script-render',\n 'audio-script-source',\n 'audio-script-marker',\n];\n\nexport type AuthorableRelationKind = Exclude<KnownRelationKind, 'generated'>;\n\nexport interface BoundedNativeSequencePayload extends JsonObject {\n /** Factual coordinates from recalled media metadata; never invent an end/duration. */\n extent: { kind: 'bounded'; start: number; end: number };\n sampling: 'native';\n coordinateSpace: JsonValue;\n}\n\nexport interface UnboundedConstantSequencePayload extends JsonObject {\n extent: { kind: 'unbounded'; start: number };\n sampling: 'constant';\n coordinateSpace: JsonValue;\n}\n\nexport interface BoundedDerivedSequencePayload extends JsonObject {\n extent: { kind: 'bounded'; start: number; end: number };\n sampling: 'derived';\n coordinateSpace: JsonValue;\n}\n\nexport type ScriptTextSegment = JsonObject & {\n segmentId: string;\n text: string;\n language?: string;\n};\n\nexport type MediaAssetPayload = JsonObject & {\n external: { system: 'memota' | 'memota-speech'; key: string };\n storageKey?: string;\n};\n\nexport type CaptionTextSelection = JsonObject & {\n segmentId: string;\n /** Half-open Unicode code-point range within the selected source segment. */\n textRange?: { start: number; end: number };\n};\n\n/** Read result only: base text is assembled from the real AudioScript row. */\nexport interface ComposedScriptContent {\n audio_script_entity_id: string;\n text: string;\n segments: ScriptTextSegment[];\n}\n\nexport interface ComposedPhoneticContent extends ComposedScriptContent {\n phonemeScript?: string;\n prosody?: JsonObject;\n}\n\nexport interface EntityPayloadByKind {\n axvideo: BoundedDerivedSequencePayload;\n timeline: JsonObject;\n track: JsonObject & { hidden?: boolean; role?: string };\n clip: JsonObject;\n /** Physical resource fields; never a copy of Caption content. */\n asset: JsonObject;\n video: BoundedNativeSequencePayload & MediaAssetPayload;\n audio: BoundedNativeSequencePayload & MediaAssetPayload;\n voice: BoundedNativeSequencePayload & MediaAssetPayload;\n image: UnboundedConstantSequencePayload & MediaAssetPayload;\n 'sequence-marker': JsonObject & {\n sourceRange: { start: number; end: number };\n targetRange?: { start: number; end: number };\n duration: { mode: 'from-source' } | { mode: 'fixed'; value: number };\n timeRemapping?: JsonValue;\n anchorOffset?: number;\n durationPolicy?: 'timeline';\n /** Directly assigned AudioScript annotation times; annotation Markers only. */\n segmentRanges?: { segmentId: string; startMs: number; endMs: number }[];\n };\n viewport: JsonObject;\n 'audio-script': JsonObject & { segments: ScriptTextSegment[] };\n 'phonetic-script': JsonObject & { baseEntityIds: string[]; phonemeScript?: string; prosody?: JsonObject };\n caption: BoundedNativeSequencePayload & {\n baseEntityIds: string[];\n selections: CaptionTextSelection[];\n style?: JsonObject;\n segmentRanges?: { segmentId: string; startMs: number; endMs: number }[];\n };\n}\n\n/** Stored own fields; a variant may obtain required content fields from its declared bases. */\nexport type StoredEntityPayload<K extends KnownEntityKind> =\n | EntityPayloadByKind[K]\n | (K extends 'caption' ? JsonObject & Pick<MediaAssetPayload, 'external'> : never)\n | (JsonObject & Partial<EntityPayloadByKind[K]> & { baseEntityIds: string[] });\n\nexport interface SandboxEntity<K extends KnownEntityKind = KnownEntityKind> {\n entity_id: string;\n entity_kind: K;\n payload: StoredEntityPayload<K>;\n}\n\nexport interface SandboxRelation {\n relation_id: string;\n relation_kind: KnownRelationKind;\n endpoint_0_entity_id: string;\n endpoint_1_entity_id: string;\n metadata: JsonObject;\n trace: JsonObject;\n}\n\nexport interface EntityStoreSnapshot {\n /** Causal compiler baseline; required for publishing edits. */\n loroSnapshot?: string;\n revision: number;\n /** Current AudioScript version attached to the project; initialized projects always attach a script, possibly empty. */\n audioScriptEntityId: string | null;\n entities: SandboxEntity[];\n relations: SandboxRelation[];\n}\n\nexport type CreateEntityInput = {\n [K in KnownEntityKind]: {\n entity_id?: string;\n entity_kind: K;\n payload: StoredEntityPayload<K>;\n };\n}[KnownEntityKind];\n\n/** Patch supplied fields on the assembled entity; omitted fields remain unchanged. */\nexport interface UpdateEntityInput {\n entity_id: string;\n payload: JsonObject;\n}\n\nexport interface DeleteEntityInput {\n entity_id: string;\n}\n\nexport type EmptyRelationKind =\n | 'timeline-track'\n | 'track-clip'\n | 'clip-marker'\n | 'marker-content'\n | 'axvideo-marker'\n | 'marker-timeline'\n | 'audio-script-marker';\n\ninterface LinkRelationBase {\n relation_id?: string;\n endpoint_0_entity_id: string;\n endpoint_1_entity_id: string;\n trace?: JsonObject;\n}\n\nexport type LinkRelationInput =\n | (LinkRelationBase & {\n relation_kind: EmptyRelationKind;\n metadata?: { [key: string]: never };\n })\n | (LinkRelationBase & {\n relation_kind: 'physical-asset';\n metadata?: JsonObject;\n })\n | (LinkRelationBase & {\n relation_kind: 'caption-alignment';\n metadata: JsonObject & { alignment: JsonValue };\n });\n\nexport interface LinkGeneratedRelationInput {\n relation_id?: string;\n output_entity_id: string;\n input_entity_id: string;\n trace?: JsonObject;\n}\n\nexport interface LinkClipAnchorRelationInput {\n relation_id?: string;\n child_clip_entity_id: string;\n host_clip_entity_id: string;\n trace?: JsonObject;\n}\n\nexport interface LinkPhoneticScriptRenderRelationInput {\n relation_id?: string;\n output_entity_id: string;\n phonetic_script_entity_id: string;\n trace?: JsonObject;\n}\n\n/** `audio-script-source(script, source)`; the script was transcribed from the source media. */\nexport interface LinkAudioScriptSourceRelationInput {\n relation_id?: string;\n script_entity_id: string;\n source_entity_id: string;\n trace?: JsonObject;\n}\n\nexport interface UnlinkRelationInput {\n relation_id: string;\n}\n\nexport type EntityCommand =\n | { kind: 'create-entity'; entity: SandboxEntity }\n | { kind: 'update-entity'; entity_id: string; payload: JsonObject }\n | { kind: 'delete-entity'; entity_id: string }\n | { kind: 'link-relation'; relation: SandboxRelation }\n | { kind: 'unlink-relation'; relation_id: string };\n\nexport interface EntityPlanState {\n base_revision: number;\n commands: readonly EntityCommand[];\n rows: EntityStoreSnapshot;\n deleted_entity_ids: readonly string[];\n deleted_relation_ids: readonly string[];\n}\n\nexport interface EntityStateWireResponse {\n loro_snapshot: string;\n doc_id: string;\n audio_script_entity_id: string | null;\n revision: number;\n rows: {\n entities: SandboxEntity[];\n relations: SandboxRelation[];\n };\n}\n\nexport interface EntityFacade {\n /** Read complete assembled fields; returned objects are snapshots. Use update to persist edits. */\n list(): SandboxEntity[];\n get(entityId: string): SandboxEntity | null;\n /** Find document resources by external Memota asset id, including directly composed media variants. */\n findByAssetId(assetId: string): SandboxEntity<ResourceEntityKind>[];\n /** Assemble selected Caption text; missing composition is an error. */\n readCaptionContent(entityId: string): ComposedScriptContent;\n /** Assemble base text and pronunciation fields before generating Voice. */\n readPhoneticScriptContent(entityId: string): ComposedPhoneticContent;\n create(input: CreateEntityInput): string;\n /** Patch assembled fields, routing inherited fields to their declaring entity. */\n update(input: UpdateEntityInput): void;\n /** Explicitly declare own fields, overriding unambiguous bases without modifying them. Ordinary edits use update. */\n declareFields(input: UpdateEntityInput): void;\n /** Delete an Entity only after all of its incident Relations have been explicitly unlinked. */\n delete(input: DeleteEntityInput): void;\n /** Get or create one typed Asset by factual external id and return its single content identity. Never creates a Clip. */\n ensureMedia(fact: MediaAssetFact): { contentEntityId: string };\n}\n\nexport interface RelationFacade {\n list(): SandboxRelation[];\n /** Incident lookup is endpoint-agnostic; persisted endpoint positions stay unchanged. */\n of(entityId: string, relationKind?: KnownRelationKind): SandboxRelation[];\n /** Link existing entities through ordinary associations; variant bases are stored directly on the variant. */\n link(input: LinkRelationInput): string;\n /** Author ordered generated(output,input); generic link() deliberately rejects this kind. */\n linkGenerated(input: LinkGeneratedRelationInput): string;\n /** Author ordered clip-anchor(child,host) without positional endpoint ambiguity. */\n linkClipAnchor(input: LinkClipAnchorRelationInput): string;\n /** Author ordered phonetic-script-render(output,script) without positional endpoint ambiguity. */\n linkPhoneticScriptRender(input: LinkPhoneticScriptRenderRelationInput): string;\n /** Author ordered audio-script-source(script,source) without positional endpoint ambiguity. */\n linkAudioScriptSource(input: LinkAudioScriptSourceRelationInput): string;\n /** Remove a Relation by identity; endpoint replacement is an explicit unlink plus link. */\n unlink(input: UnlinkRelationInput): void;\n}\n\n/** Business editing surface. Infrastructure Assets are assembled by the host. */\nexport interface BusinessEntityFacade {\n list(): SandboxEntity[];\n get(entityId: string): SandboxEntity | null;\n readCaptionContent(entityId: string): ComposedScriptContent;\n readPhoneticScriptContent(entityId: string): ComposedPhoneticContent;\n create(input: Exclude<CreateEntityInput, { entity_kind: 'asset' }>): string;\n update(input: UpdateEntityInput): void;\n declareFields(input: UpdateEntityInput): void;\n delete(input: DeleteEntityInput): void;\n}\n\n/** Physical Asset bindings are maintained outside the sandbox. */\nexport interface BusinessRelationFacade {\n list(): SandboxRelation[];\n of(entityId: string, relationKind?: KnownRelationKind): SandboxRelation[];\n link(input: Exclude<LinkRelationInput, { relation_kind: 'physical-asset' }>): string;\n linkGenerated(input: LinkGeneratedRelationInput): string;\n linkClipAnchor(input: LinkClipAnchorRelationInput): string;\n linkPhoneticScriptRender(input: LinkPhoneticScriptRenderRelationInput): string;\n linkAudioScriptSource(input: LinkAudioScriptSourceRelationInput): string;\n unlink(input: UnlinkRelationInput): void;\n}\n","import { bytesToBase64, compileEntityRows, base64ToBytes } from '@mengine/medeo-client';\nimport { createEntityId, createRelationId } from '@mengine/medeo-dsl';\n\nimport {\n KNOWN_ENTITY_KINDS,\n KNOWN_RELATION_KINDS,\n type EntityStateWireResponse,\n type EntityStoreSnapshot,\n type JsonObject,\n type SandboxEntity,\n type SandboxRelation,\n} from './entity-contract.ts';\n\nconst API_PREFIX = '/api/mengine/v1';\nconst entityKinds = new Set<string>(KNOWN_ENTITY_KINDS);\nconst relationKinds = new Set<string>(KNOWN_RELATION_KINDS);\n\nexport interface EntityHttpClientOptions {\n docId: string;\n httpOrigin: string;\n authToken?: string | (() => string | undefined);\n userId?: string | (() => string | undefined);\n fetchImpl?: typeof fetch;\n}\n\nexport interface EntityCommitDeletions {\n deleted_entity_ids?: readonly string[];\n deleted_relation_ids?: readonly string[];\n}\n\nexport class MengineEntityHttpRequestError extends Error {\n constructor(\n readonly status: number,\n readonly payload: unknown,\n ) {\n super(`mengine entity-state request failed: ${status}`);\n this.name = 'MengineEntityHttpRequestError';\n }\n}\n\n/** Narrow authenticated client for the Loro entity endpoint. */\nexport class EntityHttpClient {\n private readonly fetchImpl: typeof fetch;\n\n constructor(private readonly options: EntityHttpClientOptions) {\n this.fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);\n }\n\n async fetchState(): Promise<EntityStoreSnapshot> {\n return toSnapshot(await this.requestJson({ method: 'GET' }), this.options.docId);\n }\n\n async commit(\n _transportSequence: number,\n state: EntityStoreSnapshot,\n _deletions: EntityCommitDeletions = {},\n ): Promise<EntityStoreSnapshot> {\n if (!state.loroSnapshot) throw new Error('Entity edit is missing its causal Loro baseline');\n // The baseline comes from this plan, never a freshly fetched replacement.\n const rows = {\n entities: state.entities.map((row) => ({\n entityId: createEntityId(row.entity_id),\n entityKind: row.entity_kind,\n payload: row.payload,\n })),\n relations: state.relations.map((row) => ({\n relationId: createRelationId(row.relation_id),\n relationKind: row.relation_kind,\n endpoint0EntityId: createEntityId(row.endpoint_0_entity_id),\n endpoint1EntityId: createEntityId(row.endpoint_1_entity_id),\n metadata: row.metadata,\n trace: row.trace,\n })),\n } as Parameters<typeof compileEntityRows>[1];\n const compiled = compileEntityRows(base64ToBytes(state.loroSnapshot), rows);\n return this.commitUpdate(bytesToBase64(compiled.update));\n }\n\n async commitUpdate(update: string): Promise<EntityStoreSnapshot> {\n return toSnapshot(await this.requestJson({ method: 'POST', body: JSON.stringify({ update }) }), this.options.docId);\n }\n\n private async requestJson(init: RequestInit): Promise<unknown> {\n const response = await this.fetchImpl(this.endpoint(), { ...init, headers: this.headers() });\n const payload = await safeReadJson(response);\n if (!response.ok) throw new MengineEntityHttpRequestError(response.status, payload);\n return payload;\n }\n\n private headers(): Headers {\n const headers = new Headers({ accept: 'application/json', 'content-type': 'application/json' });\n const authToken = typeof this.options.authToken === 'function' ? this.options.authToken() : this.options.authToken;\n if (authToken != null && authToken !== '') headers.set('authorization', `Bearer ${authToken}`);\n const userId = typeof this.options.userId === 'function' ? this.options.userId() : this.options.userId;\n if (userId != null && userId !== '') headers.set('medeo-user-id', userId);\n return headers;\n }\n\n private endpoint(): string {\n const origin = this.options.httpOrigin.replace(/\\/$/, '');\n return `${origin}${API_PREFIX}/docs/${encodeURIComponent(this.options.docId)}/entity-state`;\n }\n}\n\nfunction toSnapshot(value: unknown, expectedDocId: string): EntityStoreSnapshot {\n if (!isRecord(value) || typeof value.doc_id !== 'string' || !isNonNegativeInteger(value.revision)) {\n throw new Error('invalid entity-state response envelope');\n }\n if (value.doc_id !== expectedDocId) {\n throw new Error(`entity-state response doc_id mismatch: expected \"${expectedDocId}\"`);\n }\n if (!isRecord(value.rows) || !Array.isArray(value.rows.entities) || !Array.isArray(value.rows.relations)) {\n throw new Error('invalid entity-state response rows');\n }\n if (value.audio_script_entity_id === null) throw new Error('Document AudioScript is not initialized');\n if (!isTrimmed(value.audio_script_entity_id)) throw new Error('invalid document AudioScript identity');\n if (typeof value.loro_snapshot !== 'string') throw new Error('Missing causal Loro snapshot');\n const response = value as unknown as EntityStateWireResponse;\n if (\n response.audio_script_entity_id !== null &&\n !response.rows.entities.some(\n (entity) => entity.entity_id === response.audio_script_entity_id && entity.entity_kind === 'audio-script',\n )\n )\n throw new Error('Document AudioScript must name the project AudioScript');\n return {\n loroSnapshot: response.loro_snapshot,\n revision: response.revision,\n audioScriptEntityId: response.audio_script_entity_id,\n entities: response.rows.entities.map(parseEntity),\n relations: response.rows.relations.map(parseRelation),\n };\n}\n\nfunction parseEntity(value: unknown): SandboxEntity {\n if (\n !isRecord(value) ||\n !isTrimmed(value.entity_id) ||\n typeof value.entity_kind !== 'string' ||\n !entityKinds.has(value.entity_kind) ||\n !isJsonObject(value.payload)\n ) {\n throw new Error('invalid Entity row in entity-state response');\n }\n return structuredClone(value) as unknown as SandboxEntity;\n}\n\nfunction parseRelation(value: unknown): SandboxRelation {\n if (\n !isRecord(value) ||\n !isTrimmed(value.relation_id) ||\n typeof value.relation_kind !== 'string' ||\n !relationKinds.has(value.relation_kind) ||\n !isTrimmed(value.endpoint_0_entity_id) ||\n !isTrimmed(value.endpoint_1_entity_id) ||\n !isJsonObject(value.metadata) ||\n !isJsonObject(value.trace)\n ) {\n throw new Error('invalid Relation row in entity-state response');\n }\n return structuredClone(value) as unknown as SandboxRelation;\n}\n\nfunction isJsonObject(value: unknown): value is JsonObject {\n return isJsonValue(value, new Set()) && isRecord(value);\n}\n\nfunction isJsonValue(value: unknown, ancestors: Set<object>): boolean {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return true;\n if (typeof value === 'number') return Number.isFinite(value);\n if (typeof value !== 'object' || ancestors.has(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) return false;\n ancestors.add(value);\n const valid = Array.isArray(value)\n ? value.every((item) => isJsonValue(item, ancestors))\n : Object.values(value).every((item) => isJsonValue(item, ancestors));\n ancestors.delete(value);\n return valid;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isTrimmed(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0 && value.trim() === value;\n}\n\nfunction isNonNegativeInteger(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;\n}\n\nasync function safeReadJson(response: Response): Promise<unknown> {\n const text = await response.text();\n if (text.length === 0) return null;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n","import { randomUUID } from 'node:crypto';\n\nimport { isMediaAssetVariantKind } from '@mengine/medeo-dsl';\n\nimport type { EntityCommand, EntityStoreSnapshot, SandboxRelation } from './entity-contract.ts';\nimport type { EntityHttpClient } from './entity-http-client.ts';\n\n/**\n * External systems whose asset entities carry a factual Memota identity.\n * Voice results use the speech system; every other medium uses `memota`.\n */\nconst ASSET_SYSTEMS: ReadonlySet<string> = new Set(['memota', 'memota-speech']);\n\n/** Factual generation lineage for recalled Memota assets, supplied by the host. */\nexport interface AssetGenerationFact {\n /** External asset id of the generation output (memota asset or speech result id). */\n readonly outputAssetId: string;\n /** Factual input asset ids; empty for text-only generation. */\n readonly inputAssetIds: readonly string[];\n}\n\n/**\n * Host callback resolving lineage by external asset id. Implementations return\n * every known generation record involving the given ids in either role; an\n * empty array means no known lineage and a rejection means the lineage query\n * failed. Entity and Relation semantics stay inside this package.\n */\nexport type GenerationFactsLoader = (\n docId: string,\n assetIds: readonly string[],\n) => Promise<readonly AssetGenerationFact[]>;\n\n/**\n * Outcome of the post-commit lineage sync. `failed` is always also surfaced as\n * a `generation_sync_failed` warning so an unavailable lineage query is never\n * presented as synced state.\n */\nexport interface GenerationSyncOutcome {\n /**\n * applied: new generated Relations were committed.\n * current: the query succeeded and nothing was missing (no created asset,\n * single side absent, text-only generation, or pair already linked).\n * failed: the host query or the sync commit failed.\n */\n readonly status: 'applied' | 'current' | 'failed';\n readonly created_relation_ids?: readonly string[];\n readonly message?: string;\n}\n\nexport interface SyncGeneratedRelationsInput {\n readonly client: EntityHttpClient;\n readonly docId: string;\n /** Causal entity state the committed plan was based on. */\n readonly baseState: EntityStoreSnapshot;\n /** Entity commands of the committed plan; they scope which lineage is queried. */\n readonly entityCommands: readonly EntityCommand[];\n readonly loadFacts: GenerationFactsLoader;\n}\n\n/** Validate host-supplied facts; a malformed record fails the whole query. */\nexport function parseGenerationFacts(value: unknown): AssetGenerationFact[] {\n if (!Array.isArray(value)) throw new Error('generation facts must be an array');\n return value.map((item): AssetGenerationFact => {\n if (!isRecord(item)) throw new Error('each generation fact must be an object');\n const { outputAssetId, inputAssetIds } = item;\n if (typeof outputAssetId !== 'string' || outputAssetId.length === 0 || outputAssetId.trim() !== outputAssetId) {\n throw new Error('generation fact outputAssetId must be a non-empty trimmed string');\n }\n if (!Array.isArray(inputAssetIds)) {\n // A missing field is a malformed record, not text-only evidence: only an\n // explicit empty array states \"no factual inputs\" (pure text source).\n throw new Error('generation fact inputAssetIds must be an array (explicit [] means text-only)');\n }\n const inputs = inputAssetIds;\n for (const input of inputs) {\n if (typeof input !== 'string' || input.length === 0 || input.trim() !== input) {\n throw new Error('generation fact inputAssetIds entries must be non-empty trimmed strings');\n }\n }\n return { outputAssetId, inputAssetIds: [...inputs] };\n });\n}\n\n/**\n * Resource identities newly introduced by the edit. Asset identity is immutable;\n * Clip placement and display metadata updates are not new generation sources.\n * Untouched/deleted lineage is never resurrected.\n */\nexport interface GenerationSyncScope {\n readonly scopedMediaIds: ReadonlySet<string>;\n readonly queryAssetKeys: readonly string[];\n}\n\nexport function planGenerationScope(\n base: EntityStoreSnapshot,\n commands: readonly EntityCommand[],\n state: EntityStoreSnapshot,\n): GenerationSyncScope {\n const touchedIds = new Set<string>();\n for (const command of commands) {\n if (command.kind === 'create-entity' && isMediaAssetVariantKind(command.entity.entity_kind)) {\n touchedIds.add(command.entity.entity_id);\n }\n }\n const beforeByKey = resolveMediaByAssetKey(base);\n const scoped = new Set<string>();\n const queryKeys = new Set<string>();\n for (const [key, mediaIds] of resolveMediaByAssetKey(state)) {\n const previousIds = new Set(beforeByKey.get(key) ?? []);\n for (const id of mediaIds) {\n if (!touchedIds.has(id) || previousIds.has(id)) continue;\n scoped.add(id);\n queryKeys.add(key);\n }\n }\n return { scopedMediaIds: scoped, queryAssetKeys: [...queryKeys].sort() };\n}\n\n/**\n * Ordered generated(output,input) Relations missing from `state` for the given\n * factual records. Both endpoints must already exist and match their own Asset\n * identities, and the pair must involve a media Entity the plan\n * newly fact-exposed (`scopedMediaIds`): lineage scopes to the commit's diff,\n * so a pair the user deleted between untouched entities stays deleted. A pair\n * the facts already resolved against the plan's base state is likewise skipped.\n * One-sided facts, text-only records, self pairs, and already-linked pairs are\n * skipped. Duplicate records collapse to one Relation.\n */\nexport function planGeneratedRelations(input: {\n baseState: EntityStoreSnapshot;\n state: EntityStoreSnapshot;\n scopedMediaIds: ReadonlySet<string>;\n facts: readonly AssetGenerationFact[];\n newRelationId: () => string;\n}): SandboxRelation[] {\n const { state, facts } = input;\n const scoped = input.scopedMediaIds;\n const factKeys = new Set(facts.flatMap((fact) => [fact.outputAssetId, ...fact.inputAssetIds]));\n const mediaByAssetKey = resolveMediaByAssetKey(state, factKeys);\n const baseResolvable = new Set(resolvablePairs(resolveMediaByAssetKey(input.baseState, factKeys), facts));\n const linkedPairs = new Set(\n state.relations\n .filter((relation) => relation.relation_kind === 'generated')\n .map((relation) => pairKey(relation.endpoint_0_entity_id, relation.endpoint_1_entity_id)),\n );\n const relations: SandboxRelation[] = [];\n for (const fact of facts) {\n for (const outputId of mediaByAssetKey.get(fact.outputAssetId) ?? []) {\n for (const inputAssetId of fact.inputAssetIds) {\n for (const inputId of mediaByAssetKey.get(inputAssetId) ?? []) {\n if (outputId === inputId) continue;\n if (!scoped.has(outputId) && !scoped.has(inputId)) continue;\n const pair = pairKey(outputId, inputId);\n if (linkedPairs.has(pair) || baseResolvable.has(pair)) continue;\n linkedPairs.add(pair);\n relations.push({\n relation_id: input.newRelationId(),\n relation_kind: 'generated',\n endpoint_0_entity_id: outputId,\n endpoint_1_entity_id: inputId,\n metadata: {},\n trace: { synced_by: 'generation-sync' },\n });\n }\n }\n }\n }\n return relations;\n}\n\n/**\n * Sync generation lineage after a confirmed entity commit. Any failure is\n * returned as a `failed` outcome instead of thrown, so the already-durable\n * commit result is never masked; a successful query that finds nothing is\n * `current`. Asset identities are immutable, so facts are queried once. The native update retains its causal baseline and merges without whole-state retries; deleted endpoints are never recreated.\n */\nexport async function syncGeneratedRelations(input: SyncGeneratedRelationsInput): Promise<GenerationSyncOutcome> {\n const { client, docId, baseState, entityCommands, loadFacts } = input;\n try {\n const state = await client.fetchState();\n const scope = planGenerationScope(baseState, entityCommands, state);\n if (scope.queryAssetKeys.length === 0) return { status: 'current' };\n const facts = parseGenerationFacts(await loadFacts(docId, scope.queryAssetKeys));\n const relations = planGeneratedRelations({\n baseState,\n state,\n scopedMediaIds: scope.scopedMediaIds,\n facts,\n newRelationId: mintRelationId,\n });\n if (relations.length === 0) return { status: 'current' };\n const committed = await client.commit(state.revision, { ...state, relations: [...state.relations, ...relations] });\n const active = new Set(committed.relations.map((relation) => relation.relation_id));\n const created = relations.map((relation) => relation.relation_id).filter((id) => active.has(id));\n return created.length ? { status: 'applied', created_relation_ids: created } : { status: 'current' };\n } catch (error) {\n return { status: 'failed', message: `generation lineage query failed: ${errorMessage(error)}` };\n }\n}\n\ninterface AssetLike {\n entity_id: string;\n entity_kind: string;\n payload: unknown;\n}\n\nfunction assetKeyOf(entity: AssetLike): string | undefined {\n if (!isMediaAssetVariantKind(entity.entity_kind)) return undefined;\n const external = (entity.payload as Record<string, unknown> | undefined)?.external;\n if (external == null || typeof external !== 'object' || Array.isArray(external)) return undefined;\n const { system, key } = external as Record<string, unknown>;\n if (typeof system !== 'string' || !ASSET_SYSTEMS.has(system)) return undefined;\n if (typeof key !== 'string' || key.length === 0 || key.trim() !== key) return undefined;\n return key;\n}\n\n/** Media variants own their Asset locator; generation lookup never follows Relations. */\nfunction resolveMediaByAssetKey(state: EntityStoreSnapshot, factKeys?: ReadonlySet<string>): Map<string, string[]> {\n // The host history contract carries bare IDs, not namespaces. Never turn an\n // ambiguous ID into a Cartesian product of unrelated speech/media resources.\n const systemByKey = new Map<string, unknown>();\n for (const entity of state.entities) {\n const key = assetKeyOf(entity);\n if (key === undefined || !factKeys?.has(key)) continue;\n const system = (entity.payload.external as Record<string, unknown>).system;\n if (systemByKey.has(key) && systemByKey.get(key) !== system)\n throw new Error(`Ambiguous generation asset id ${key} across media and speech namespaces`);\n systemByKey.set(key, system);\n }\n const resolved = new Map<string, string[]>();\n for (const entity of state.entities) {\n if (!isMediaAssetVariantKind(entity.entity_kind)) continue;\n const key = assetKeyOf(entity);\n if (key === undefined) continue;\n const matches = resolved.get(key) ?? [];\n matches.push(entity.entity_id);\n resolved.set(key, matches);\n }\n return resolved;\n}\n\nfunction pairKey(endpoint0: string, endpoint1: string): string {\n return `${endpoint0}\\u0000${endpoint1}`;\n}\n\n/** Pair keys the facts already resolve to under the given base bindings. */\nfunction resolvablePairs(mediaByAssetKey: Map<string, string[]>, facts: readonly AssetGenerationFact[]): string[] {\n const pairs: string[] = [];\n for (const fact of facts) {\n for (const outputId of mediaByAssetKey.get(fact.outputAssetId) ?? []) {\n for (const inputAssetId of fact.inputAssetIds) {\n for (const inputId of mediaByAssetKey.get(inputAssetId) ?? []) {\n if (outputId !== inputId) pairs.push(pairKey(outputId, inputId));\n }\n }\n }\n }\n return pairs;\n}\n\nfunction mintRelationId(): string {\n return `relation_${randomUUID()}`;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n","/** @generated by gen:sandbox-dts. DO NOT EDIT. */\nexport const ENTITY_EDIT_SANDBOX_API_DTS = [\n '/** @generated by gen:sandbox-dts. Entity-native editor contract; DO NOT EDIT. */',\n 'export interface BoundedDerivedSequencePayload extends JsonObject {',\n ' extent: {',\n \" kind: 'bounded';\",\n ' start: number;',\n ' end: number;',\n ' };',\n \" sampling: 'derived';\",\n ' coordinateSpace: JsonValue;',\n '}',\n 'export interface BoundedNativeSequencePayload extends JsonObject {',\n ' /** Factual coordinates from recalled media metadata; never invent an end/duration. */',\n ' extent: {',\n \" kind: 'bounded';\",\n ' start: number;',\n ' end: number;',\n ' };',\n \" sampling: 'native';\",\n ' coordinateSpace: JsonValue;',\n '}',\n '/** Business editing surface. Infrastructure Assets are assembled by the host. */',\n 'export interface BusinessEntityFacade {',\n ' list(): SandboxEntity[];',\n ' get(entityId: string): SandboxEntity | null;',\n ' readCaptionContent(entityId: string): ComposedScriptContent;',\n ' readPhoneticScriptContent(entityId: string): ComposedPhoneticContent;',\n ' create(',\n ' input: Exclude<',\n ' CreateEntityInput,',\n ' {',\n \" entity_kind: 'asset';\",\n ' }',\n ' >,',\n ' ): string;',\n ' update(input: UpdateEntityInput): void;',\n ' declareFields(input: UpdateEntityInput): void;',\n ' delete(input: DeleteEntityInput): void;',\n '}',\n '/** Physical Asset bindings are maintained outside the sandbox. */',\n 'export interface BusinessRelationFacade {',\n ' list(): SandboxRelation[];',\n ' of(entityId: string, relationKind?: KnownRelationKind): SandboxRelation[];',\n ' link(',\n ' input: Exclude<',\n ' LinkRelationInput,',\n ' {',\n \" relation_kind: 'physical-asset';\",\n ' }',\n ' >,',\n ' ): string;',\n ' linkGenerated(input: LinkGeneratedRelationInput): string;',\n ' linkClipAnchor(input: LinkClipAnchorRelationInput): string;',\n ' linkPhoneticScriptRender(input: LinkPhoneticScriptRenderRelationInput): string;',\n ' linkAudioScriptSource(input: LinkAudioScriptSourceRelationInput): string;',\n ' unlink(input: UnlinkRelationInput): void;',\n '}',\n 'export interface CaptionFontDescriptor {',\n \" readonly system: 'font-library';\",\n ' readonly key: string;',\n '}',\n '/**',\n \" * One ordered entry of the Caption's segment selection. `segmentId` quotes the\",\n \" * composed AudioScript's own stable segment identity — a local id quoted by the\",\n ' * variant, never a peer Entity reference. Text itself is never copied here;',\n ' * complete Caption content is assembled through its direct baseEntityIds.',\n ' * The optional `textRange` narrows one Segment to an intra-Segment sub-span',\n ' * (intra-segment re-segmentation); without it the whole Segment text is selected.',\n ' */',\n 'export type CaptionSegmentSelection = JsonObject & {',\n ' readonly segmentId: string;',\n ' readonly textRange?: CaptionTextRange;',\n '};',\n 'export interface CaptionStyleFields {',\n ' readonly font?: CaptionFontDescriptor;',\n ' readonly fontSize?: number;',\n ' readonly fontColor?: string;',\n ' readonly fontWeight?: number;',\n ' readonly entranceAnimation?: string;',\n ' readonly entranceAnimationDurationMs?: number;',\n ' readonly strokeColor?: string;',\n ' readonly strokeWidth?: number;',\n ' readonly positionX?: number;',\n ' readonly positionY?: number;',\n '}',\n '/**',\n \" * Half-open `[start, end)` position window inside one Segment's text, counted\",\n ' * in Unicode code points (not UTF-16 code units), so a boundary never splits a',\n ' * surrogate pair. Positions are non-negative safe integers with `start < end`;',\n \" * `end` must not exceed the Segment's code-point length.\",\n ' */',\n 'export interface CaptionTextRange extends JsonObject {',\n ' readonly start: number;',\n ' readonly end: number;',\n '}',\n 'export type CaptionTextSelection = JsonObject & {',\n ' segmentId: string;',\n ' /** Half-open Unicode code-point range within the selected source segment. */',\n ' textRange?: {',\n ' start: number;',\n ' end: number;',\n ' };',\n '};',\n 'export type ClipEntityId = EntityId;',\n 'export type ClipPlacement =',\n ' | {',\n \" readonly kind: 'sequential';\",\n ' readonly order: number;',\n ' }',\n ' | {',\n \" readonly kind: 'absolute';\",\n ' readonly targetRange: SequenceRange<number>;',\n ' }',\n ' | {',\n \" readonly kind: 'anchored';\",\n ' readonly hostClipEntityId: string;',\n ' readonly anchorOffset: number;',\n ' };',\n 'export interface ComposedPhoneticContent extends ComposedScriptContent {',\n ' phonemeScript?: string;',\n ' prosody?: JsonObject;',\n '}',\n '/** Read result only: base text is assembled from the real AudioScript row. */',\n 'export interface ComposedScriptContent {',\n ' audio_script_entity_id: string;',\n ' text: string;',\n ' segments: ScriptTextSegment[];',\n '}',\n 'export type CreateEntityInput = {',\n ' [K in KnownEntityKind]: {',\n ' entity_id?: string;',\n ' entity_kind: K;',\n ' payload: StoredEntityPayload<K>;',\n ' };',\n '}[KnownEntityKind];',\n 'export interface DeleteBgmInput {',\n ' readonly timelineEntityId: string;',\n '}',\n 'export interface DeleteClipInput {',\n ' readonly clipEntityId: string;',\n '}',\n 'export interface DeleteClipTreeInput {',\n ' readonly clipEntityIds: readonly string[];',\n \" readonly onAnchored: 'cascade' | 'detach';\",\n '}',\n 'export interface DeleteEntityInput {',\n ' entity_id: string;',\n '}',\n 'export interface DeleteVoiceoverInput {',\n ' readonly voiceoverClipEntityIds: readonly string[];',\n '}',\n 'export type EmptyRelationKind =',\n \" | 'timeline-track'\",\n \" | 'track-clip'\",\n \" | 'clip-marker'\",\n \" | 'marker-content'\",\n \" | 'axvideo-marker'\",\n \" | 'marker-timeline'\",\n \" | 'audio-script-marker';\",\n '/** Immutable resource content resolved by the host for a document Entity. */',\n 'export interface EntityAssetContent {',\n ' assetId: string;',\n ' content: JsonValue;',\n '}',\n 'export type EntityId = string;',\n 'export interface EntityPayloadByKind {',\n ' axvideo: BoundedDerivedSequencePayload;',\n ' timeline: JsonObject;',\n ' track: JsonObject & {',\n ' hidden?: boolean;',\n ' role?: string;',\n ' };',\n ' clip: JsonObject;',\n ' video: BoundedNativeSequencePayload & MediaAssetPayload;',\n ' audio: BoundedNativeSequencePayload & MediaAssetPayload;',\n ' voice: BoundedNativeSequencePayload & MediaAssetPayload;',\n ' image: UnboundedConstantSequencePayload & MediaAssetPayload;',\n \" 'sequence-marker': JsonObject & {\",\n ' sourceRange: {',\n ' start: number;',\n ' end: number;',\n ' };',\n ' targetRange?: {',\n ' start: number;',\n ' end: number;',\n ' };',\n ' duration:',\n ' | {',\n \" mode: 'from-source';\",\n ' }',\n ' | {',\n \" mode: 'fixed';\",\n ' value: number;',\n ' };',\n ' timeRemapping?: JsonValue;',\n ' anchorOffset?: number;',\n \" durationPolicy?: 'timeline';\",\n ' /** Directly assigned AudioScript annotation times; annotation Markers only. */',\n ' segmentRanges?: {',\n ' segmentId: string;',\n ' startMs: number;',\n ' endMs: number;',\n ' }[];',\n ' };',\n ' viewport: JsonObject;',\n \" 'audio-script': JsonObject & {\",\n ' segments: ScriptTextSegment[];',\n ' };',\n \" 'phonetic-script': JsonObject & {\",\n ' baseEntityIds: string[];',\n ' phonemeScript?: string;',\n ' prosody?: JsonObject;',\n ' };',\n ' caption: BoundedNativeSequencePayload & {',\n ' baseEntityIds: string[];',\n ' selections: CaptionTextSelection[];',\n ' style?: JsonObject;',\n ' segmentRanges?: {',\n ' segmentId: string;',\n ' startMs: number;',\n ' endMs: number;',\n ' }[];',\n ' };',\n '}',\n 'export interface EntityStoreSnapshot {',\n ' /** Causal compiler baseline; required for publishing edits. */',\n ' loroSnapshot?: string;',\n ' revision: number;',\n ' /** Current AudioScript version attached to the project; initialized projects always attach a script, possibly empty. */',\n ' audioScriptEntityId: string | null;',\n ' entities: SandboxEntity[];',\n ' relations: SandboxRelation[];',\n '}',\n 'export interface InsertCaptionClipInput {',\n ' readonly timelineEntityId: string;',\n ' /** Existing generation identity for newly materialized Caption content, distinct from its Clip. */',\n ' readonly captionEntityId?: string;',\n ' /** Stable placed caption identity, distinct from the Caption content identity. */',\n ' readonly captionClipEntityId?: string;',\n ' /** Existing bases composed by this variant; includes an AudioScript text owner. */',\n ' readonly baseEntityIds: readonly string[];',\n ' /** Ordered selection of the AudioScript segments this Caption displays. */',\n ' readonly selections: readonly CaptionSegmentSelection[];',\n ' /** Intrinsic cue length of the Caption entity itself; display comes from the placement. */',\n ' readonly durationMs: number;',\n ' readonly style?: CaptionStyleFields;',\n ' readonly placement: ClipPlacement;',\n '}',\n 'export interface InsertClipInput {',\n ' readonly trackEntityId: string;',\n ' /** Existing Sequence media Entity id. Asset ids and URLs are not content ids. */',\n ' readonly contentEntityId: string;',\n ' readonly sourceRange: SequenceRange<number>;',\n ' readonly duration: SequenceDuration<number>;',\n ' readonly targetRange?: SequenceRange<number>;',\n ' readonly clipPayload?: JsonObject;',\n '}',\n 'export interface InsertPlacedClipInput {',\n ' readonly trackEntityId: string;',\n ' readonly contentEntityId: string;',\n ' readonly sourceRange: SequenceRange<number>;',\n ' readonly duration: SequenceDuration<number>;',\n ' readonly placement: ClipPlacement;',\n ' readonly clipPayload?: JsonObject;',\n ' /** Stable caller-owned placement identity, when one already exists outside the graph. */',\n ' readonly clipEntityId?: string;',\n '}',\n 'export interface JsonObject {',\n ' [key: string]: JsonValue;',\n '}',\n 'export type JsonPrimitive = string | number | boolean | null;',\n 'export type JsonValue = JsonPrimitive | JsonObject | JsonValue[];',\n 'export type KnownEntityKind =',\n \" | 'axvideo'\",\n \" | 'timeline'\",\n \" | 'track'\",\n \" | 'clip'\",\n \" | 'video'\",\n \" | 'audio'\",\n \" | 'voice'\",\n \" | 'image'\",\n \" | 'sequence-marker'\",\n \" | 'viewport'\",\n \" | 'audio-script'\",\n \" | 'phonetic-script'\",\n \" | 'caption';\",\n 'export type KnownRelationKind =',\n \" | 'timeline-track'\",\n \" | 'track-clip'\",\n \" | 'clip-marker'\",\n \" | 'marker-content'\",\n \" | 'axvideo-marker'\",\n \" | 'marker-timeline'\",\n \" | 'generated'\",\n \" | 'caption-alignment'\",\n \" | 'clip-anchor'\",\n \" | 'phonetic-script-render'\",\n \" | 'audio-script-source'\",\n \" | 'audio-script-marker';\",\n 'export interface LinearClipSpeed {',\n \" readonly kind: 'linear';\",\n ' readonly rate: number;',\n ' readonly mode?: string;',\n '}',\n '/** `audio-script-source(script, source)`; the script was transcribed from the source media. */',\n 'export interface LinkAudioScriptSourceRelationInput {',\n ' relation_id?: string;',\n ' script_entity_id: string;',\n ' source_entity_id: string;',\n ' trace?: JsonObject;',\n '}',\n 'export interface LinkClipAnchorRelationInput {',\n ' relation_id?: string;',\n ' child_clip_entity_id: string;',\n ' host_clip_entity_id: string;',\n ' trace?: JsonObject;',\n '}',\n 'export interface LinkGeneratedRelationInput {',\n ' relation_id?: string;',\n ' output_entity_id: string;',\n ' input_entity_id: string;',\n ' trace?: JsonObject;',\n '}',\n 'export interface LinkPhoneticScriptRenderRelationInput {',\n ' relation_id?: string;',\n ' output_entity_id: string;',\n ' phonetic_script_entity_id: string;',\n ' trace?: JsonObject;',\n '}',\n 'interface LinkRelationBase {',\n ' relation_id?: string;',\n ' endpoint_0_entity_id: string;',\n ' endpoint_1_entity_id: string;',\n ' trace?: JsonObject;',\n '}',\n 'export type LinkRelationInput =',\n ' | (LinkRelationBase & {',\n ' relation_kind: EmptyRelationKind;',\n ' metadata?: {',\n ' [key: string]: never;',\n ' };',\n ' })',\n ' | (LinkRelationBase & {',\n \" relation_kind: 'physical-asset';\",\n ' metadata?: JsonObject;',\n ' })',\n ' | (LinkRelationBase & {',\n \" relation_kind: 'caption-alignment';\",\n ' metadata: JsonObject & {',\n ' alignment: JsonValue;',\n ' };',\n ' });',\n 'export type MediaAssetPayload = JsonObject & {',\n ' external: {',\n \" system: 'memota' | 'memota-speech';\",\n ' key: string;',\n ' };',\n '};',\n 'export interface MoveClipInput {',\n ' readonly clipEntityId: string;',\n ' readonly trackEntityId: string;',\n '}',\n 'export interface MoveClipsToStartsInput {',\n ' readonly moves: readonly {',\n ' readonly clipEntityId: string;',\n ' readonly newStartMs: number;',\n ' }[];',\n \" /** Absolute-time drags preserve every voiceover's current visible landing. */\",\n \" readonly onAnchored: 'keepAbsolute';\",\n '}',\n 'export interface MoveSequentialClipsInput {',\n ' readonly clipEntityIds: readonly string[];',\n ' readonly anchor: SequentialClipAnchor;',\n \" readonly onAnchored: 'follow' | 'keepAbsolute';\",\n '}',\n 'export interface MoveVoiceoverInput {',\n ' readonly voiceoverClipEntityId: string;',\n ' /** Absolute requested timeline start; MEngine resolves and persists the host relation. */',\n ' readonly newStartMs: number;',\n '}',\n 'export interface PatchCaptionStyleInput {',\n ' readonly timelineEntityId: string;',\n ' readonly style: CaptionStyleFields;',\n '}',\n 'export interface ReplaceClipContentInput {',\n ' readonly clipEntityId: string;',\n ' /** Existing Sequence media Entity id. Asset ids and URLs are not content ids. */',\n ' readonly contentEntityId: string;',\n ' readonly sourceRange: SequenceRange<number>;',\n ' readonly duration: SequenceDuration<number>;',\n ' readonly targetRange?: SequenceRange<number>;',\n ' readonly timeRemapping?: JsonValue;',\n '}',\n 'export interface SandboxEntity<K extends KnownEntityKind = KnownEntityKind> {',\n ' entity_id: string;',\n ' entity_kind: K;',\n ' payload: StoredEntityPayload<K>;',\n '}',\n 'export interface SandboxRelation {',\n ' relation_id: string;',\n ' relation_kind: KnownRelationKind;',\n ' endpoint_0_entity_id: string;',\n ' endpoint_1_entity_id: string;',\n ' metadata: JsonObject;',\n ' trace: JsonObject;',\n '}',\n 'export type ScriptTextSegment = JsonObject & {',\n ' segmentId: string;',\n ' text: string;',\n ' language?: string;',\n '};',\n 'export type SequenceDuration<Span = unknown> =',\n ' | {',\n \" readonly mode: 'from-source';\",\n ' }',\n ' | {',\n \" readonly mode: 'fixed';\",\n ' readonly value: Span;',\n ' };',\n 'export interface SequenceRange<Point = unknown> {',\n ' readonly start: Point;',\n ' readonly end: Point;',\n '}',\n 'export type SequentialClipAnchor =',\n ' | {',\n \" readonly position: 'before' | 'after';\",\n ' readonly clipEntityId: string;',\n ' }',\n ' | {',\n \" readonly position: 'trackStart';\",\n ' };',\n 'export interface SetCaptionVisibilityInput {',\n ' readonly timelineEntityId: string;',\n ' readonly hidden: boolean;',\n '}',\n 'export interface SetClipPlacementInput {',\n ' readonly clipEntityId: string;',\n ' readonly placement: ClipPlacement;',\n '}',\n 'export interface SetClipSpeedInput {',\n ' readonly clipEntityId: string;',\n ' readonly timeRemapping: LinearClipSpeed | null;',\n '}',\n 'export interface SetClipVolumeInput {',\n ' readonly clipEntityId: string;',\n ' /** Playback gain in decibels. */',\n ' readonly volume: number;',\n '}',\n '/** Stored own fields; a variant may obtain required content fields from its declared bases. */',\n 'export type StoredEntityPayload<K extends KnownEntityKind> =',\n ' | EntityPayloadByKind[K]',\n \" | (K extends 'caption' ? JsonObject & Pick<MediaAssetPayload, 'external'> : never)\",\n ' | (JsonObject &',\n ' Partial<EntityPayloadByKind[K]> & {',\n ' baseEntityIds: string[];',\n ' });',\n 'export interface TrimClipInput {',\n ' readonly clipEntityId: string;',\n ' readonly sourceRange: SequenceRange<number>;',\n '}',\n 'export interface UnboundedConstantSequencePayload extends JsonObject {',\n ' extent: {',\n \" kind: 'unbounded';\",\n ' start: number;',\n ' };',\n \" sampling: 'constant';\",\n ' coordinateSpace: JsonValue;',\n '}',\n 'export interface UnlinkRelationInput {',\n ' relation_id: string;',\n '}',\n 'export interface UpdateClipInput {',\n ' readonly clipEntityId: string;',\n ' /** Complete replacement for the Clip-owned payload. */',\n ' readonly payload: JsonObject;',\n '}',\n 'export interface UpdateClipMarkerInput {',\n ' readonly clipEntityId: string;',\n ' readonly sourceRange?: SequenceRange<number>;',\n ' /** Passing `undefined` explicitly removes the optional target range. */',\n ' readonly targetRange?: SequenceRange<number> | undefined;',\n ' readonly duration?: SequenceDuration<number>;',\n ' /** Passing `undefined` explicitly removes the optional remapping value. */',\n ' readonly timeRemapping?: JsonValue | undefined;',\n '}',\n '/** Patch supplied fields on the assembled entity; omitted fields remain unchanged. */',\n 'export interface UpdateEntityInput {',\n ' entity_id: string;',\n ' payload: JsonObject;',\n '}',\n '/** Timeline writes accept existing media Entity ids, never Memota asset ids or URLs. */',\n 'export interface EditApi {',\n ' insertClip(input: InsertClipInput): ClipEntityId;',\n ' insertPlacedClip(input: InsertPlacedClipInput): ClipEntityId;',\n ' updateClipMarker(input: UpdateClipMarkerInput): void;',\n ' setClipPlacement(input: SetClipPlacementInput): void;',\n ' moveSequentialClips(input: MoveSequentialClipsInput): void;',\n ' moveClip(input: MoveClipInput): void;',\n ' replaceClipContent(input: ReplaceClipContentInput): void;',\n ' setClipVolume(input: SetClipVolumeInput): void;',\n ' setClipSpeed(input: SetClipSpeedInput): void;',\n ' trimClip(input: TrimClipInput): void;',\n ' deleteClip(input: DeleteClipInput): void;',\n ' deleteClipTree(input: DeleteClipTreeInput): void;',\n ' updateClip(input: UpdateClipInput): void;',\n ' moveVoiceover(input: MoveVoiceoverInput): void;',\n ' moveClipsToStarts(input: MoveClipsToStartsInput): void;',\n ' deleteVoiceover(input: DeleteVoiceoverInput): void;',\n ' deleteBgm(input: DeleteBgmInput): void;',\n ' setCaptionVisibility(input: SetCaptionVisibilityInput): void;',\n ' patchCaptionStyle(input: PatchCaptionStyleInput): void;',\n ' insertCaptionClip(input: InsertCaptionClipInput): ClipEntityId;',\n '}',\n 'export interface TimelineApi {',\n ' snapshot(): EntityStoreSnapshot & {',\n ' audioScriptEntityId: string;',\n ' };',\n '}',\n 'export interface SandboxCheckpoint {',\n ' readonly index: number;',\n '}',\n 'export declare const edit: EditApi;',\n 'export declare const timeline: TimelineApi;',\n 'export declare const entities: BusinessEntityFacade;',\n 'export declare const relations: BusinessRelationFacade;',\n '/** Resolve the resource attached to an Entity through the host; await before using a new Caption. */',\n 'export declare function rgetAssetFromEntity(entityId: string): Promise<EntityAssetContent>;',\n 'export declare function checkpoint(): SandboxCheckpoint;',\n 'export declare function rollbackTo(cp: SandboxCheckpoint): void;',\n 'export declare const inputs: Readonly<Record<string, unknown>>;',\n '',\n].join('\\n');\n","import { ENTITY_EDIT_SANDBOX_API_DTS } from './sandbox/generated/entity-edit-sandbox-model-context.ts';\n\nexport const MEDEO_TOOL_DESCRIPTION = `\nEdit the authoritative Medeo Entity/Relation graph through a deterministic, side-effect-free JavaScript sandbox. Timeline objects and edit targets are Entities, not Memota assets or legacy parts.\n\nOperations:\n- snapshot: read the current Entity/Relation view, project attachments and causal Loro baseline. Reading does not initialize or mutate domain data.\n- run-edit-script: inspect timeline.snapshot(), entities.*, and relations.*; edit.* operates existing Entity ids and creates the required Clip/SequenceMarker structural graph. The sandbox has no direct network, storage or generation access. rgetAssetFromEntity(entityId) delegates an attached-resource read to the host. Use assembled entity fields; the host manages resource storage and generation provenance. A successful run returns preview, logs, base revision and plan_id.\n- commit-plan: publish the native Loro update compiled against the plan’s causal baseline. Concurrent independent edits merge through Loro. The timeline and AudioScript panel read the merged entity state. A failed transport is unconfirmed; retry the same plan_id so operation identities are preserved.\n\nDefault flow: snapshot → run-edit-script with auto_commit=false → inspect preview → commit-plan. Use auto_commit=true only for low-risk edits when the host does not need user confirmation. Concurrent edits do not require replaying the script against a newer snapshot. If a domain conflict is reported, inspect the merged state and resolve it explicitly; never replace the complete document to force the edit through.\n\nGeneration tools return Asset references, not domain Entity ids. An Asset id may be passed as an entity resource field: external: { system: \"memota\", key: assetId }. Create or update the domain Entity using entities.*, then place its Entity id with edit.insertClip. Asset ids are not Entity ids, baseEntityIds or Relation endpoints. The sandbox exposes no Asset creation, lookup, reading or storage API; the host resolves resource references. Each placement has its own Clip and SequenceMarker. Generation lineage is host-synced; relations.of(entityId) is endpoint-agnostic.\n`.trim();\n\nconst MEDEO_TOOL_EXECUTION_RULES = `\nThe host supplies the current document. Do not ask for, invent, or pass a document id.\ntimeline.snapshot() returns the Entity/Relation graph with its revision, not a legacy VideoDraft. Inspect Timeline, Track, Clip, SequenceMarker and their relations to plan edits.\nInspect existing Image/Video/Audio/Voice Entities and their factual extents before placing them. For an uploaded or generated resource, create its media Entity with the returned Asset id in external.key and the factual media extent. The host resolves its physical resource. Replace a Clip's content using another content Entity id. Never fabricate a duration.\nFor a Caption Asset, create a Caption with payload:{external:{system:'memota',key:assetId}}, then await rgetAssetFromEntity(captionEntityId). This initializes its intrinsic segmentRanges/extent and the project AudioScript text in the same plan. The result {assetId,content} is the original resource content. entities.get/readCaptionContent then expose editable assembled text. Call the getter before placing a newly resource-backed Caption. Caption resource initialization also runs before final plan validation; failure aborts the plan. Do not transcribe repeatedly or infer speech absence from visual descriptions when an output_caption Asset already exists. Existing text edits are preserved on repeated reads. No Asset ID can be used as the getter argument.\nCaption composes AudioScript text. Its optional external field may carry the Caption Asset id; the host resolves that resource. A Caption created from AudioScript may have no physical resource. Read and edit assembled fields through entities; do not create Asset entities or physical-asset Relations.\nThe editor projection supports the existing four Track roles: video_clip (Image/Video), speech (Voice), caption (Caption), and bgm (Audio), one of each. Clip.volume is decibels (-60 to 20, 0 = original). Marker.sourceRange is the selected source interval; Marker.duration is effective display/playback duration. Coordinates and duration are whole milliseconds for this reader, not a global DSL restriction. Placement is exactly one of Clip.order, Marker.targetRange, or clip-anchor(child,host) plus Marker.anchorOffset. Use the native move/delete/voiceover helpers so placement and cascade decisions are in the same entity plan. Reading the graph never rebinds anchors or invents empty clips. Linear timeRemapping is {kind:'linear',rate:2,mode:'constant'} and agrees with rounded source span divided by rate. Image remains unbounded/constant; an explicit linear rate scales its display window, not an invented media extent. Nonlinear speed and multiple visual overlay tracks are unsupported.\nEntities own fields; ordinary Relations express associations; variants directly hold baseEntityIds and assemble the referenced entities. These foundations are fixed: implementation must follow them, never redefine them. Any entity may compose multiple bases. Equal field names from multiple bases (even equal values) are errors, even when the variant declares that field itself. After validating all base fields are unambiguous, explicitly declared own fields may override base fields without mutating the bases. Base ordering never resolves conflicts. AudioScript owns segmented text. Caption and PhoneticScript persist baseEntityIds including their AudioScript, plus their own fields; no composition Relation exists. Create the real bases before reading or committing a variant. Inside the DSL sandbox, entities.get/list expose complete assembled fields. Consumers read fields without inspecting base IDs or merging bases. entities.update patches supplied fields and routes inherited fields to their declaring entity; omitted fields remain unchanged. entities.declareFields explicitly declares own overrides and is distinct from an ordinary field edit. Persistence keeps owned fields only. entities.readCaptionContent(id) and entities.readPhoneticScriptContent(id) return assembled text. Missing/cyclic bases and field conflicts fail before persistence.\nUse edit.insertCaptionClip with baseEntityIds and selections, plus captionEntityId when generation returned a Caption identity; each voiceover caption also supplies baseEntityIds. A selection names segmentId and may use a half-open Unicode code-point textRange to split a segment for the screen without rewriting AudioScript. Generate Voice from an existing PhoneticScript, then use phoneticScriptEntityId in the voiceover helper or relations.linkPhoneticScriptRender({output_entity_id,phonetic_script_entity_id}) for its render relation. Caption and Voice have their own Clips; display anchoring is explicit and independent of composition/alignment.\nMove or stretch only the Clip's display Marker; preserve Caption intrinsic Sequence, AudioScript text and its annotation Markers. AudioScript cannot enter a Clip and has no intrinsic time. audio-script-source links its ASR source Audio/Video/Voice; audio-script-marker attaches annotation Markers with directly assigned segmentRanges:{segmentId,startMs,endMs} in whole milliseconds. Annotation Markers have no Clip/AXVideo/content/Timeline relations and never refer to other Markers for time. BGM keeps factual source duration with durationPolicy:'timeline'. Never introduce a speech entity kind.\nCreate only the known entity kinds. Project creation initializes one current Timeline, four Tracks and an attached AudioScript with segments:[]. Read the current AudioScript ID from timeline.snapshot(); the panel displays this attachment and preserves its segments. Normal edits operate this script, not an unrelated newly created script.\nImmutable updates apply to every entity: editing an owned field creates a new content version ID; changing only a variant's base ID preserves the variant ID. Editing a base through a variant updates the owner, and the compiler advances the affected base links and project attachment. A variant-owned edit creates a new variant version and retains its unchanged bases. Do not manually clone entities or duplicate inherited fields to implement versioning. Versions preserve native text and list editing identities so independent concurrent edits survive. Missing facts, unsupported layouts and composition conflicts are explicit errors; there is no legacy migration or whole-state overwrite path.\nUse only the globals and methods declared by the following TypeScript interface. Values not declared here are unavailable.\n`.trim();\n\nexport interface RenderMedeoModelContextInput {\n documentVersion: string;\n updatedSincePreviousModelCall: boolean | null;\n}\n\n/** Render the complete MEngine-owned context injected before one model call. */\nexport function renderMedeoModelContext(input: RenderMedeoModelContextInput): string {\n const updated =\n input.updatedSincePreviousModelCall == null\n ? 'unknown (first model call)'\n : String(input.updatedSincePreviousModelCall);\n return `\n${MEDEO_TOOL_DESCRIPTION}\n\n${MEDEO_TOOL_EXECUTION_RULES}\n\nCurrent MEngine document state (sampled dynamically immediately before this model call):\n- document_version: ${JSON.stringify(input.documentVersion)}\n- updated_since_previous_model_call: ${updated}\n\nWhen updated_since_previous_model_call is true, the document changed after the previous model call. The change may have come from this tool or another editor, so take a fresh snapshot before planning further edits.\n\nSandbox TypeScript interface:\n\\`\\`\\`ts\n${ENTITY_EDIT_SANDBOX_API_DTS}\n\\`\\`\\`\n`.trim();\n}\n","export const MEDEO_TOOL_NAME = 'medeo';\n\nexport type MedeoToolOp = 'snapshot' | 'run-edit-script' | 'commit-plan';\n\n/**\n * JSON Schema for the host-facing `medeo` tool surface.\n *\n * The schema intentionally does not return or accept the full op journal:\n * journals stay in the tool process and are referenced by `plan_id`. This keeps\n * large intermediate products out of model context while preserving the exact\n * journal used for commit.\n */\nexport const MEDEO_TOOL_PARAMETERS = {\n type: 'object',\n required: ['op', 'doc_id'],\n additionalProperties: false,\n properties: {\n op: {\n type: 'string',\n enum: ['snapshot', 'run-edit-script', 'commit-plan'],\n description: 'Which Medeo document operation to run.',\n },\n doc_id: {\n type: 'string',\n minLength: 1,\n description: 'Medeo document id. Copy it from the host context; never invent it.',\n },\n script: {\n type: 'string',\n minLength: 1,\n description:\n 'JavaScript body for run-edit-script. Use edit, timeline, entities, relations, checkpoint, rollbackTo, inputs, and console. Asset import, media relations, and timeline entity edits share one entity plan.',\n },\n inputs: {\n type: 'object',\n description:\n 'Pre-materialized, side-effect-free values passed into the script, including recalled asset facts. Generation history is never an input: the host queries lineage itself and syncs generated Relations after each commit. Generation and network IO must happen in the host before this call.',\n },\n timeout_ms: {\n type: 'integer',\n minimum: 1,\n description: 'Maximum script wall-clock time after worker startup (default 2000).',\n },\n memory_limit_mb: {\n type: 'integer',\n minimum: 16,\n description: 'Worker old-generation memory ceiling in MB (default 256).',\n },\n auto_commit: {\n type: 'boolean',\n description:\n 'Commit the returned plan immediately after the sandbox succeeds. Default false: return preview plus plan_id for explicit commit.',\n },\n plan_id: {\n type: 'string',\n minLength: 1,\n description: 'Plan id returned by run-edit-script; required by commit-plan.',\n },\n validation: {\n type: 'string',\n enum: ['preflight'],\n description: 'Publish the native update already validated on its causal Loro fork.',\n },\n },\n oneOf: [\n {\n required: ['op', 'doc_id'],\n properties: {\n op: { const: 'snapshot' },\n doc_id: { $ref: '#/properties/doc_id' },\n },\n additionalProperties: false,\n },\n {\n required: ['op', 'doc_id', 'script'],\n properties: {\n op: { const: 'run-edit-script' },\n doc_id: { $ref: '#/properties/doc_id' },\n script: { $ref: '#/properties/script' },\n inputs: { $ref: '#/properties/inputs' },\n timeout_ms: { $ref: '#/properties/timeout_ms' },\n memory_limit_mb: { $ref: '#/properties/memory_limit_mb' },\n auto_commit: { $ref: '#/properties/auto_commit' },\n },\n additionalProperties: false,\n },\n {\n required: ['op', 'doc_id', 'plan_id'],\n properties: {\n op: { const: 'commit-plan' },\n doc_id: { $ref: '#/properties/doc_id' },\n plan_id: { $ref: '#/properties/plan_id' },\n validation: { $ref: '#/properties/validation' },\n },\n additionalProperties: false,\n },\n ],\n} as const;\n","import {\n createPlainMemoryAdapter,\n decodeDocVersionMark,\n encodeDocVersionMark,\n replayJournal,\n ValidationError,\n type JournalEntry,\n type ManualSyncDoc,\n type SemanticOpName,\n} from '@mengine/medeo-client';\n\n/**\n * A sandbox journal plus the opaque version token taken at fork time.\n * `commitPlan` rejects the whole plan when the live document has moved on\n * (phase-1 version gate), or localizes a business conflict to a journal\n * entry under `{ validation: 'preflight' }`.\n */\nexport interface CommitPlan {\n /** Encoded `ManualSyncDoc.versionMark()` from when the sandbox was forked. */\n base_version: string;\n ops: readonly JournalEntry[];\n}\n\nexport interface CommitPlanWarning {\n kind: 'pull_failed';\n message: string;\n}\n\nexport type CommitPlanResult =\n | {\n kind: 'committed';\n ops_applied: number;\n collaborated: boolean;\n warnings?: CommitPlanWarning[];\n }\n | { kind: 'unconfirmed'; reason: 'push_failed'; ops_applied: number; message: string }\n | { kind: 'rejected'; reason: 'version_mismatch'; expected: string; actual: string }\n | { kind: 'rejected'; reason: 'push_rejected'; code?: string; message: string }\n | {\n kind: 'rejected';\n reason: 'op_conflict';\n /** Failing entry index in the journal — agent rerun anchor. */\n index: number;\n op_kind: SemanticOpName;\n /** Validator message, passed through verbatim (never a raw Error). */\n message: string;\n };\n\nexport interface CommitPlanOptions {\n /** `'version'` (default, phase-1 hard gate) | `'preflight'` (phase-2 per-op revalidation). */\n validation?: 'version' | 'preflight';\n}\n\n/**\n * Replay a sandbox journal into a manually-synchronized document and push the\n * whole plan as one causally complete update.\n *\n * - Default / `{ validation: 'version' }`: if the current document mark differs\n * from `plan.base_version`, reject with zero writes.\n * - `{ validation: 'preflight' }`: skip the version gate; revalidate each op\n * against a PlainMemoryAdapter seeded from the current live snapshot, then\n * replay for real. A SchemaValidator failure becomes `op_conflict` with the\n * failing entry's index. Journal integrity errors (unrecorded/unconsumed\n * ids) still propagate as throws in both modes.\n */\nexport async function commitPlan(\n doc: ManualSyncDoc,\n plan: CommitPlan,\n options?: CommitPlanOptions,\n): Promise<CommitPlanResult> {\n if (options?.validation === 'preflight') {\n return commitPlanPreflight(doc, plan);\n }\n\n const actual = encodeDocVersionMark(doc.versionMark());\n const expected = decodeDocVersionMark(plan.base_version);\n if (expected == null || doc.hasChangedSince(expected)) {\n return {\n kind: 'rejected',\n reason: 'version_mismatch',\n expected: plan.base_version,\n actual,\n };\n }\n\n await doc.replayJournal(plan.ops);\n return retryPlanPush(doc, plan.ops.length);\n}\n\n/**\n * Phase-2 path: scratch revalidation then real replay. Each entry is driven\n * through `replayJournal` alone so a ValidationError maps to a stable index;\n * integrity throws are not wrapped.\n */\nasync function commitPlanPreflight(doc: ManualSyncDoc, plan: CommitPlan): Promise<CommitPlanResult> {\n const scratch = createPlainMemoryAdapter(doc.snapshot());\n\n for (let index = 0; index < plan.ops.length; index++) {\n const entry = plan.ops[index];\n if (entry == null) continue;\n try {\n await replayJournal(scratch, [entry]);\n } catch (error) {\n if (error instanceof ValidationError) {\n return opConflict(index, entry.kind, error.message);\n }\n throw error;\n }\n }\n\n // Real replay: optimistic window may still collide; wrap ValidationError the\n // same way. Prior entries in this loop have already been written.\n for (let index = 0; index < plan.ops.length; index++) {\n const entry = plan.ops[index];\n if (entry == null) continue;\n try {\n await doc.replayJournal([entry]);\n } catch (error) {\n if (error instanceof ValidationError) {\n return opConflict(index, entry.kind, `real replay: ${error.message}`);\n }\n throw error;\n }\n }\n\n return retryPlanPush(doc, plan.ops.length);\n}\n\n/** Push an already-replayed plan again without replaying or re-running its version gate. */\nexport async function retryPlanPush(doc: ManualSyncDoc, opsApplied: number): Promise<CommitPlanResult> {\n const result = await doc.push();\n if (result.kind === 'ack' || result.kind === 'duplicate' || result.kind === 'nothing_to_push') {\n // A push can reveal that another peer wrote concurrently. Pull after the\n // durable verdict so the cached document does not serve a stale snapshot on\n // the next tool call; a pull failure cannot undo the acknowledged write.\n const reconciled = result.collaborated ? await doc.pull() : undefined;\n const warnings =\n reconciled != null && !reconciled.ok\n ? [{ kind: 'pull_failed' as const, message: reconciled.error.message }]\n : undefined;\n return {\n kind: 'committed',\n ops_applied: opsApplied,\n collaborated: result.collaborated,\n ...(warnings !== undefined ? { warnings } : {}),\n };\n }\n if (result.kind === 'rejected') {\n return {\n kind: 'rejected',\n reason: 'push_rejected',\n ...(result.code !== undefined ? { code: result.code } : {}),\n message: result.error?.message ?? 'mengine rejected the sandbox plan',\n };\n }\n return {\n kind: 'unconfirmed',\n reason: 'push_failed',\n ops_applied: opsApplied,\n message: result.error?.message ?? 'mengine push failed',\n };\n}\n\nfunction opConflict(index: number, op_kind: SemanticOpName, message: string): CommitPlanResult {\n return { kind: 'rejected', reason: 'op_conflict', index, op_kind, message };\n}\n","/// <reference types=\"node\" />\nimport { randomUUID } from 'node:crypto';\n\nimport {\n createMirrorVideoDocument,\n encodeDocVersionMark,\n ManualSyncDoc,\n MengineHttpClient,\n MengineHttpRequestError,\n ensureEditorFoundation,\n LoroEntityDocument,\n toVideoDocument,\n type ManualSyncDocOptions,\n type VideoDocument,\n type VideoDraft,\n} from '@mengine/medeo-client';\n\nimport {\n assembleCaptionAssets,\n type CaptionAssetsLoader,\n type CaptionAssetAssemblyOutcome,\n} from './entity/caption-asset-assembly.ts';\nimport type { EntityAssetLoader } from './entity/entity-asset.ts';\nimport type { EntityStoreSnapshot } from './entity/entity-contract.ts';\nimport { EntityHttpClient, MengineEntityHttpRequestError } from './entity/entity-http-client.ts';\nimport {\n syncGeneratedRelations,\n type GenerationFactsLoader,\n type GenerationSyncOutcome,\n} from './entity/generation-sync.ts';\nimport { MEDEO_TOOL_DESCRIPTION, renderMedeoModelContext } from './prompt.ts';\nimport { businessState } from './sandbox/business-facades.ts';\nimport { runEditScript } from './sandbox/node-host.ts';\nimport type { ChangePlan } from './sandbox/script-session.ts';\nimport { MEDEO_TOOL_NAME, MEDEO_TOOL_PARAMETERS, type MedeoToolOp } from './schema.ts';\nimport { retryPlanPush, type CommitPlanResult } from './session/commit-plan.ts';\n\ntype ContextualValue<T> = T | ((docId: string) => T | undefined);\n\nexport interface CreateMedeoToolOptions {\n /**\n * Mengine HTTP origin for a document. The host owns environment routing\n * (local/stg/prd/lane) and may return a different origin per document.\n * Documents cache by doc id, so the origin must remain stable for that doc.\n */\n httpOrigin: ContextualValue<string>;\n /** Optional bearer token, evaluated for each HTTP request. */\n authToken?: ContextualValue<string>;\n /** Optional end-user id header, evaluated for each HTTP request. */\n userId?: ContextualValue<string>;\n /** Stable agent peer id. Supply a host-scoped value so audit provenance is durable. */\n peerId?: ContextualValue<string>;\n /**\n * Load the authoritative legacy draft used to create a missing Mengine\n * document. The tool owns the get-or-create flow: it first probes Mengine,\n * converts this draft into a VideoDocument only on a 404, bootstraps the\n * snapshot, and tolerates a concurrent creator winning the race.\n */\n loadInitialDraft?: (docId: string) => Promise<VideoDraft>;\n /**\n * Resolve factual generation lineage by external asset id after a confirmed\n * entity commit. Return every known generation record involving the given\n * ids in either role; an empty array means no known lineage and a rejection\n * means the lineage query failed (surfaced as a warning, never as synced\n * state). The package owns all Entity/Relation semantics: the host never\n * names entities, relations, or endpoints.\n */\n loadGenerationFacts?: GenerationFactsLoader;\n /** Assemble optional Caption artifacts by immutable entity ID; never exposed to scripts. */\n loadCaptionAssets?: CaptionAssetsLoader;\n loadEntityAsset?: EntityAssetLoader;\n fetchImpl?: typeof fetch;\n /** @deprecated ManualSyncDoc has no SSE or reconnect loop. */\n sseReconnectDelayMs?: number;\n /** Defaults passed to runEditScript; each call may override them. */\n sandbox?: { timeoutMs?: number; memoryLimitMb?: number };\n /** Maximum cached plans; oldest plans are evicted (default 16). */\n maxPlans?: number;\n /** Maximum model-call version baselines retained across host contexts (default 128). */\n maxModelContexts?: number;\n}\n\nexport interface MedeoModelContextInput {\n /** Internal MEngine document id. This is host-supplied and never model-facing. */\n doc_id: string;\n /** Stable host conversation/session key used to compare consecutive model calls. */\n context_id: string;\n}\n\nexport interface MedeoModelContext {\n /** Complete MEngine-owned prompt: workflow, runtime state, and sandbox TypeScript interface. */\n prompt: string;\n document_version: string;\n updated_since_previous_model_call: boolean | null;\n}\n\nexport type MedeoToolInput =\n | { op: 'snapshot'; doc_id: string }\n | {\n op: 'run-edit-script';\n doc_id: string;\n script: string;\n inputs?: Record<string, unknown>;\n timeout_ms?: number;\n memory_limit_mb?: number;\n auto_commit?: boolean;\n }\n | {\n op: 'commit-plan';\n doc_id: string;\n plan_id: string;\n validation?: 'preflight';\n };\n\nexport type MedeoToolWarning =\n | { kind: 'asset_assembly_failed'; message: string }\n | { kind: 'pull_failed'; message: string }\n | { kind: 'generation_sync_failed'; message: string };\n\nexport type EntityCommitResult =\n | { kind: 'conflicted'; accepted: true; entity_revision: number; message: string }\n | {\n kind: 'committed';\n ops_applied: number;\n collaborated: boolean;\n entity_revision: number;\n /** Present only when the host supplies loadGenerationFacts. */\n generation_sync?: GenerationSyncOutcome;\n asset_assembly?: CaptionAssetAssemblyOutcome;\n warnings?: MedeoToolWarning[];\n }\n | { kind: 'unconfirmed'; reason: 'push_failed'; ops_applied: number; message: string }\n | {\n kind: 'rejected';\n reason: 'entity_state_rejected';\n status: number;\n message: string;\n };\n\nexport type MedeoCommitResult = CommitPlanResult | EntityCommitResult;\n\nexport type MedeoToolResult =\n | {\n ok: true;\n op: 'snapshot';\n doc_id: string;\n version: string;\n preview: string;\n collaborated?: boolean;\n warnings?: MedeoToolWarning[];\n }\n | {\n ok: true;\n op: 'run-edit-script';\n doc_id: string;\n plan_id: string;\n plan_kind: 'timeline' | 'entities';\n base_version: string;\n entity_base_revision: number;\n ops_count: number;\n preview: string;\n logs: string[];\n duration_ms: number;\n committed?: boolean;\n commit_result?: MedeoCommitResult;\n collaborated?: boolean;\n warnings?: MedeoToolWarning[];\n }\n | {\n ok: false;\n op: 'run-edit-script';\n doc_id: string;\n phase: 'parse' | 'runtime' | 'timeout' | 'memory';\n error: { message: string; line?: number; column?: number; stack?: string };\n partial: { ops_count: number; logs: string[] };\n }\n | {\n ok: true;\n op: 'commit-plan';\n doc_id: string;\n plan_id: string;\n plan_kind: 'timeline' | 'entities';\n committed: boolean;\n result: MedeoCommitResult;\n collaborated?: boolean;\n warnings?: MedeoToolWarning[];\n }\n | { ok: false; op: MedeoToolOp; error: string };\n\nexport interface MedeoTool {\n name: typeof MEDEO_TOOL_NAME;\n description: typeof MEDEO_TOOL_DESCRIPTION;\n parameters: typeof MEDEO_TOOL_PARAMETERS;\n getModelContext(input: MedeoModelContextInput): Promise<MedeoModelContext>;\n handle(input: unknown): Promise<MedeoToolResult>;\n close(): Promise<void>;\n}\n\nexport type MedeoInitialDraft = VideoDraft;\n\ninterface CachedPlan {\n docId: string;\n plan: ChangePlan;\n /** Entity-store state the plan was built from; the generation sync's diff base. */\n baseState?: EntityStoreSnapshot;\n}\n\ninterface TimelinePendingPush {\n kind: 'timeline';\n planId: string;\n plan: ChangePlan;\n opsApplied: number;\n}\n\ninterface EntityPendingPush {\n kind: 'entities';\n planId: string;\n plan: ChangePlan;\n /** Diff base for the generation sync after recovery; see CachedPlan. */\n baseState?: EntityStoreSnapshot;\n}\n\ntype PendingPush = TimelinePendingPush | EntityPendingPush;\n\ninterface PullObservation {\n collaborated: boolean;\n warnings?: MedeoToolWarning[];\n}\n\nconst DEFAULT_MAX_PLANS = 16;\nconst DEFAULT_MAX_MODEL_CONTEXTS = 128;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction optionalContext<T>(value: ContextualValue<T> | undefined, docId: string): T | undefined {\n if (value === undefined) return undefined;\n return typeof value === 'function' ? (value as (id: string) => T | undefined)(docId) : value;\n}\n\nfunction requiredContext(value: ContextualValue<string>, docId: string, field: string): string {\n const resolved = optionalContext(value, docId)?.trim();\n if (resolved == null || resolved.length === 0) {\n throw new Error(`${field} must resolve to a non-empty string for doc ${docId}`);\n }\n return resolved;\n}\n\nfunction renderEntitySnapshot(raw: EntityStoreSnapshot): string {\n const state = businessState(raw);\n const rows = [\n ...state.entities.map((entity) => JSON.stringify(entity)),\n ...state.relations.map((relation) => JSON.stringify(relation)),\n ];\n const shown = rows.slice(0, 200);\n return [\n `Entity revision=${state.revision} audioScriptEntityId=${JSON.stringify(state.audioScriptEntityId)} entities=${state.entities.length} relations=${state.relations.length}`,\n ...shown,\n ...(shown.length < rows.length ? ['[truncated; inspect entities/relations in the sandbox]'] : []),\n ].join('\\n');\n}\n\nasync function commitEntityPlan(client: EntityHttpClient, plan: ChangePlan): Promise<EntityCommitResult> {\n const rows = plan.entity_rows;\n if (rows === undefined) throw new Error('entity plan is missing its authoritative rows');\n try {\n if (!plan.loro_update) throw new Error('Entity plan has no compiled Loro update');\n const committed = await client.commitUpdate(plan.loro_update);\n return {\n kind: 'committed',\n ops_applied: plan.entity_commands.length,\n collaborated: committed.revision > plan.entity_base_revision + 1,\n entity_revision: committed.revision,\n };\n } catch (error) {\n if (error instanceof MengineEntityHttpRequestError) {\n if (isRecord(error.payload) && error.payload.accepted === true && typeof error.payload.revision === 'number')\n return {\n kind: 'conflicted',\n accepted: true,\n entity_revision: error.payload.revision,\n message: entityHttpErrorMessage(error.payload),\n };\n return {\n kind: 'rejected',\n reason: 'entity_state_rejected',\n status: error.status,\n message: entityHttpErrorMessage(error.payload),\n };\n }\n return {\n kind: 'unconfirmed',\n reason: 'push_failed',\n ops_applied: plan.entity_commands.length,\n message: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\nfunction entityHttpErrorMessage(payload: unknown): string {\n if (isRecord(payload) && isRecord(payload.error) && typeof payload.error.message === 'string')\n return payload.error.message;\n if (isRecord(payload) && typeof payload.message === 'string' && payload.message.length > 0) return payload.message;\n return typeof payload === 'string' && payload.length > 0 ? payload : 'mengine rejected the entity-state plan';\n}\n\nfunction commitWarnings(result: MedeoCommitResult): MedeoToolWarning[] | undefined {\n return result.kind === 'committed' && 'warnings' in result && result.warnings !== undefined\n ? [...result.warnings]\n : undefined;\n}\n\nfunction parseInput(value: unknown): MedeoToolInput {\n if (!isRecord(value)) throw new Error('input must be an object');\n const op = value.op;\n const docId = value.doc_id;\n if (typeof op !== 'string') throw new Error('op must be a string');\n if (typeof docId !== 'string' || docId.trim().length === 0) throw new Error('doc_id must be a non-empty string');\n\n if (op === 'snapshot') return { op, doc_id: docId };\n\n if (op === 'run-edit-script') {\n if (typeof value.script !== 'string' || value.script.length === 0) {\n throw new Error('script must be a non-empty string');\n }\n if (value.inputs !== undefined && !isRecord(value.inputs)) {\n throw new Error('inputs must be an object');\n }\n const timeoutMs = value.timeout_ms;\n if (timeoutMs !== undefined && (typeof timeoutMs !== 'number' || !Number.isInteger(timeoutMs) || timeoutMs <= 0)) {\n throw new Error('timeout_ms must be a positive integer');\n }\n const memoryLimitMb = value.memory_limit_mb;\n if (\n memoryLimitMb !== undefined &&\n (typeof memoryLimitMb !== 'number' || !Number.isInteger(memoryLimitMb) || memoryLimitMb < 16)\n ) {\n throw new Error('memory_limit_mb must be an integer >= 16');\n }\n if (value.auto_commit !== undefined && typeof value.auto_commit !== 'boolean') {\n throw new Error('auto_commit must be a boolean');\n }\n return {\n op,\n doc_id: docId,\n script: value.script,\n ...(value.inputs !== undefined ? { inputs: value.inputs } : {}),\n ...(timeoutMs !== undefined ? { timeout_ms: timeoutMs } : {}),\n ...(memoryLimitMb !== undefined ? { memory_limit_mb: memoryLimitMb } : {}),\n ...(value.auto_commit !== undefined ? { auto_commit: value.auto_commit } : {}),\n };\n }\n\n if (op === 'commit-plan') {\n if (typeof value.plan_id !== 'string' || value.plan_id.length === 0) {\n throw new Error('plan_id must be a non-empty string');\n }\n if (value.validation !== undefined && value.validation !== 'preflight') {\n throw new Error('validation must be \"preflight\"');\n }\n return {\n op,\n doc_id: docId,\n plan_id: value.plan_id,\n ...(value.validation !== undefined ? { validation: value.validation } : {}),\n };\n }\n\n throw new Error(`unknown op: ${op}`);\n}\n\n/**\n * Create the self-contained Medeo LLM tool.\n *\n * The package owns document construction, compact projection, sandbox execution,\n * plan caching, commit, document get-or-create, and shutdown. The host supplies\n * environment facts plus the authoritative legacy draft loader used only when\n * Mengine has no document yet.\n */\nexport function createMedeoTool(options: CreateMedeoToolOptions): MedeoTool {\n const documents = new Map<string, Promise<ManualSyncDoc>>();\n const entityClients = new Map<string, EntityHttpClient>();\n const documentTails = new Map<string, Promise<void>>();\n const pendingPushes = new Map<string, PendingPush>();\n const plans = new Map<string, CachedPlan>();\n const modelContextVersions = new Map<string, string>();\n const maxPlans = options.maxPlans ?? DEFAULT_MAX_PLANS;\n const maxModelContexts = options.maxModelContexts ?? DEFAULT_MAX_MODEL_CONTEXTS;\n let closed = false;\n\n async function getDocument(docId: string): Promise<ManualSyncDoc> {\n if (closed) throw new Error('medeo tool is closed');\n const existing = documents.get(docId);\n if (existing != null) return await existing;\n\n const created = (async () => {\n const client = new MengineHttpClient({\n docId,\n httpOrigin: requiredContext(options.httpOrigin, docId, 'httpOrigin'),\n ...(options.authToken !== undefined ? { authToken: () => optionalContext(options.authToken, docId) } : {}),\n ...(options.userId !== undefined ? { userId: () => optionalContext(options.userId, docId) } : {}),\n ...(options.fetchImpl !== undefined ? { fetchImpl: options.fetchImpl } : {}),\n });\n const peerId = optionalContext(options.peerId, docId) as ManualSyncDocOptions['peerId'] | undefined;\n return await getOrCreateDocument(client, docId, peerId);\n })();\n\n documents.set(docId, created);\n try {\n return await created;\n } catch (error) {\n if (documents.get(docId) === created) documents.delete(docId);\n throw error;\n }\n }\n\n function getEntityClient(docId: string): EntityHttpClient {\n if (closed) throw new Error('medeo tool is closed');\n const existing = entityClients.get(docId);\n if (existing != null) return existing;\n const client = new EntityHttpClient({\n docId,\n httpOrigin: requiredContext(options.httpOrigin, docId, 'httpOrigin'),\n ...(options.authToken !== undefined ? { authToken: () => optionalContext(options.authToken, docId) } : {}),\n ...(options.userId !== undefined ? { userId: () => optionalContext(options.userId, docId) } : {}),\n ...(options.fetchImpl !== undefined ? { fetchImpl: options.fetchImpl } : {}),\n });\n entityClients.set(docId, client);\n return client;\n }\n\n async function runExclusive<T>(docId: string, use: (doc: ManualSyncDoc) => Promise<T>): Promise<T> {\n const previous = documentTails.get(docId) ?? Promise.resolve();\n let release!: () => void;\n const gate = new Promise<void>((resolve) => {\n release = resolve;\n });\n const tail = previous.catch(() => {}).then(() => gate);\n documentTails.set(docId, tail);\n\n await previous.catch(() => {});\n try {\n return await use(await getDocument(docId));\n } finally {\n release();\n if (documentTails.get(docId) === tail) documentTails.delete(docId);\n }\n }\n\n async function getOrCreateDocument(\n client: MengineHttpClient,\n docId: string,\n peerId: ManualSyncDocOptions['peerId'] | undefined,\n ): Promise<ManualSyncDoc> {\n try {\n return await ManualSyncDoc.open({ client, ...(peerId !== undefined ? { peerId } : {}) });\n } catch (error) {\n if (!(error instanceof MengineHttpRequestError) || error.status !== 404) throw error;\n if (options.loadInitialDraft === undefined) throw error;\n }\n\n const draft = await options.loadInitialDraft(docId);\n const document = toVideoDocument(draft);\n if (Object.keys(document.part_library ?? {}).length > 0) {\n throw new Error('Legacy content cannot bootstrap a Loro entity project');\n }\n const seed = createMirrorVideoDocument(document, {\n ...(peerId !== undefined ? { peerId } : {}),\n origin: 'mengine.medeo_tool.bootstrap',\n });\n const foundation = ensureEditorFoundation({ entities: [], relations: [] });\n const entities = LoroEntityDocument.create(foundation.rows, {\n timelineEntityId: foundation.timelineEntityId,\n audioScriptEntityId: foundation.audioScriptEntityId,\n });\n seed.import(entities.doc.export({ mode: 'snapshot' }));\n\n try {\n await client.bootstrapSnapshot(seed.export({ mode: 'snapshot' }));\n } catch (error) {\n // Bootstrap is create-only. If another worker created the same document\n // after our 404 probe, accept that winner only after an authenticated\n // snapshot read proves the document now exists and is accessible.\n if (!(error instanceof MengineHttpRequestError) || error.status !== 400) throw error;\n // The open below is the authenticated proof that the winner exists.\n }\n return await ManualSyncDoc.open({ client, ...(peerId !== undefined ? { peerId } : {}) });\n }\n\n function rememberPlan(docId: string, plan: ChangePlan, baseState: EntityStoreSnapshot | undefined): string {\n const planId = randomUUID();\n plans.set(planId, {\n docId,\n plan,\n ...(plan.plan_kind === 'entities' ? { baseState: baseState && structuredClone(baseState) } : {}),\n });\n while (plans.size > maxPlans) {\n const protectedPlanIds = new Set([...pendingPushes.values()].map((pending) => pending.planId));\n protectedPlanIds.add(planId);\n const oldestEvictable = [...plans.keys()].find((candidate) => !protectedPlanIds.has(candidate));\n // Pending plans are recovery state, and the plan just returned by this\n // call must remain usable. Let the cache exceed its nominal bound until a\n // later insertion can evict an older, non-pending plan.\n if (oldestEvictable === undefined) break;\n plans.delete(oldestEvictable);\n }\n return planId;\n }\n\n function assertNoPendingPush(docId: string): void {\n const pending = pendingPushes.get(docId);\n if (pending != null) {\n throw new Error(`doc ${docId} has an unconfirmed push; retry plan_id ${pending.planId} before continuing`);\n }\n }\n\n function recordPushResult(\n docId: string,\n planId: string,\n plan: ChangePlan,\n result: MedeoCommitResult,\n baseState: EntityStoreSnapshot | undefined,\n ): void {\n if (result.kind === 'unconfirmed') {\n pendingPushes.set(\n docId,\n plan.plan_kind === 'timeline'\n ? { kind: 'timeline', planId, plan, opsApplied: result.ops_applied }\n : { kind: 'entities', planId, plan, ...(baseState !== undefined ? { baseState } : {}) },\n );\n return;\n }\n pendingPushes.delete(docId);\n if (plan.plan_kind === 'timeline' && result.kind === 'rejected' && result.reason === 'push_rejected') {\n documents.delete(docId);\n }\n }\n\n async function fetchEntityStateForSandbox(\n docId: string,\n _doc: ManualSyncDoc,\n _pull: PullObservation,\n ): Promise<EntityStoreSnapshot> {\n const state = await getEntityClient(docId).fetchState();\n if (!state.loroSnapshot) throw new Error('Project requires the Loro entity contract');\n return state;\n }\n\n async function commitCachedPlan(\n docId: string,\n _doc: ManualSyncDoc,\n plan: ChangePlan,\n validation?: 'preflight',\n baseState?: EntityStoreSnapshot,\n ) {\n if (plan.plan_kind === 'timeline') {\n throw new Error('Legacy timeline plans are not editable; use an Entity/Relation plan');\n }\n // Every plan was preflighted on its causal Loro fork before publication.\n void validation;\n if (plan.entity_rows === undefined) throw new Error('entity plan is missing its authoritative rows');\n const client = getEntityClient(docId);\n // The generation diff must use the same causal baseline as the compiled update.\n if (options.loadGenerationFacts !== undefined && baseState === undefined)\n throw new Error('Generation synchronization is missing the cached causal plan baseline');\n const result = await commitEntityPlan(client, plan);\n const synced = await attachGenerationSync(docId, plan, result, baseState);\n if (synced.kind !== 'committed' || options.loadCaptionAssets === undefined) return synced;\n const assembly = await assembleCaptionAssets({ client, docId, loadAssets: options.loadCaptionAssets });\n return {\n ...synced,\n asset_assembly: assembly,\n ...(assembly.status === 'failed'\n ? {\n warnings: [\n ...(synced.warnings ?? []),\n {\n kind: 'asset_assembly_failed' as const,\n message: assembly.message ?? 'Caption Asset assembly failed',\n },\n ],\n }\n : {}),\n };\n }\n\n /**\n * After a confirmed entity commit, connect fact-matched generated Relations\n * from host-recalled lineage. The commit is already durable, so a sync\n * failure never fails the op; it is attached to the result and surfaced as a\n * warning instead. The plan's diff against `baseState` scopes the sync:\n * newly created media Asset identities — not untouched pairs or placement-only edits.\n * One-sided facts are skipped silently inside the sync.\n */\n async function attachGenerationSync(\n docId: string,\n plan: ChangePlan,\n result: EntityCommitResult,\n baseState: EntityStoreSnapshot | undefined,\n ): Promise<EntityCommitResult> {\n if (result.kind !== 'committed' || options.loadGenerationFacts === undefined || baseState === undefined) {\n return result;\n }\n let outcome: GenerationSyncOutcome;\n try {\n outcome = await syncGeneratedRelations({\n client: getEntityClient(docId),\n docId,\n baseState,\n entityCommands: plan.entity_commands,\n loadFacts: options.loadGenerationFacts,\n });\n } catch (error) {\n outcome = { status: 'failed', message: error instanceof Error ? error.message : String(error) };\n }\n const warnings: MedeoToolWarning[] | undefined =\n outcome.status === 'failed'\n ? [{ kind: 'generation_sync_failed', message: outcome.message ?? 'generation lineage sync failed' }]\n : undefined;\n return {\n ...result,\n generation_sync: outcome,\n ...(warnings !== undefined ? { warnings } : {}),\n };\n }\n\n async function observePull(doc: ManualSyncDoc): Promise<PullObservation> {\n const result = await doc.pull();\n if (result.ok) return { collaborated: result.changed };\n return {\n collaborated: false,\n warnings: [{ kind: 'pull_failed', message: result.error.message }],\n };\n }\n\n function mergeWarnings(\n ...groups: readonly (readonly MedeoToolWarning[] | undefined)[]\n ): MedeoToolWarning[] | undefined {\n const warnings = groups.flatMap((group) => group ?? []);\n return warnings.length > 0 ? warnings : undefined;\n }\n\n async function getModelContext(input: MedeoModelContextInput): Promise<MedeoModelContext> {\n const docId = input.doc_id.trim();\n const contextId = input.context_id.trim();\n if (docId.length === 0) throw new Error('doc_id must be a non-empty string');\n if (contextId.length === 0) throw new Error('context_id must be a non-empty string');\n\n return await runExclusive(docId, async (doc) => {\n // ManualSyncDoc has no background stream. Pull before sampling so remote\n // edits made between model calls participate in the version comparison.\n const pull = await observePull(doc);\n const entityState = await fetchEntityStateForSandbox(docId, doc, pull);\n const documentVersion = `${encodeDocVersionMark(doc.versionMark())}:entities:${entityState.revision}`;\n const baselineKey = `${contextId}\\u0000${docId}`;\n const previousVersion = modelContextVersions.get(baselineKey);\n const updatedSincePreviousModelCall = previousVersion == null ? null : previousVersion !== documentVersion;\n\n // Refresh insertion order so the bounded map behaves as an LRU.\n modelContextVersions.delete(baselineKey);\n modelContextVersions.set(baselineKey, documentVersion);\n while (modelContextVersions.size > maxModelContexts) {\n const oldest = modelContextVersions.keys().next().value;\n if (oldest === undefined) break;\n modelContextVersions.delete(oldest);\n }\n\n return {\n prompt: renderMedeoModelContext({ documentVersion, updatedSincePreviousModelCall }),\n document_version: documentVersion,\n updated_since_previous_model_call: updatedSincePreviousModelCall,\n };\n });\n }\n\n async function snapshot(input: Extract<MedeoToolInput, { op: 'snapshot' }>): Promise<MedeoToolResult> {\n return runExclusive(input.doc_id, async (doc) => {\n assertNoPendingPush(input.doc_id);\n const pull = await observePull(doc);\n const entityState = await fetchEntityStateForSandbox(input.doc_id, doc, pull);\n return {\n ok: true,\n op: 'snapshot',\n doc_id: input.doc_id,\n version: `${encodeDocVersionMark(doc.versionMark())}:entities:${entityState.revision}`,\n preview: renderEntitySnapshot(entityState),\n collaborated: pull.collaborated,\n ...(pull.warnings !== undefined ? { warnings: pull.warnings } : {}),\n };\n });\n }\n\n async function run(input: Extract<MedeoToolInput, { op: 'run-edit-script' }>): Promise<MedeoToolResult> {\n return runExclusive(input.doc_id, async (doc) => {\n assertNoPendingPush(input.doc_id);\n const pull = await observePull(doc);\n const entityState = await fetchEntityStateForSandbox(input.doc_id, doc, pull);\n const document: VideoDocument = doc.snapshot();\n const baseVersion = encodeDocVersionMark(doc.versionMark());\n const result = await runEditScript({\n document,\n baseVersion,\n entityState,\n entityOnly: true,\n loadEntityAsset: options.loadEntityAsset\n ? (entity) => options.loadEntityAsset!(input.doc_id, entity)\n : undefined,\n script: input.script,\n ...(input.inputs !== undefined ? { inputs: input.inputs } : {}),\n timeoutMs: input.timeout_ms ?? options.sandbox?.timeoutMs ?? 30_000,\n memoryLimitMb: input.memory_limit_mb ?? options.sandbox?.memoryLimitMb,\n });\n\n if (!result.ok) {\n return {\n ok: false,\n op: 'run-edit-script',\n doc_id: input.doc_id,\n phase: result.phase,\n error: result.error,\n partial: {\n ops_count: result.partial.ops.length + result.partial.entityCommands.length,\n logs: result.partial.logs,\n },\n };\n }\n\n // The host-selected mapping is authoritative. A legacy document snapshot\n // may omit meta.draft_id, so never derive an entity route from it.\n const plan = { ...result.plan, doc_id: input.doc_id };\n const planId = rememberPlan(input.doc_id, plan, entityState);\n const base = {\n ok: true as const,\n op: 'run-edit-script' as const,\n doc_id: input.doc_id,\n plan_id: planId,\n plan_kind: plan.plan_kind,\n base_version: baseVersion,\n entity_base_revision: plan.entity_base_revision,\n ops_count: plan.ops.length + plan.entity_commands.length,\n preview: plan.preview,\n logs: plan.logs,\n duration_ms: result.durationMs,\n collaborated: pull.collaborated,\n ...(pull.warnings !== undefined ? { warnings: pull.warnings } : {}),\n };\n if (input.auto_commit !== true) return base;\n\n const commit = await commitCachedPlan(input.doc_id, doc, plan, undefined, entityState);\n recordPushResult(input.doc_id, planId, plan, commit, entityState);\n const warnings = mergeWarnings(pull.warnings, commitWarnings(commit));\n return {\n ...base,\n committed: commit.kind === 'committed',\n commit_result: commit,\n collaborated: pull.collaborated || (commit.kind === 'committed' && commit.collaborated),\n ...(warnings !== undefined ? { warnings } : {}),\n };\n });\n }\n\n async function commit(input: Extract<MedeoToolInput, { op: 'commit-plan' }>): Promise<MedeoToolResult> {\n return runExclusive(input.doc_id, async (doc) => {\n const pending = pendingPushes.get(input.doc_id);\n if (pending != null) {\n if (pending.planId !== input.plan_id) {\n throw new Error(\n `doc ${input.doc_id} has an unconfirmed push for plan_id ${pending.planId}; retry it before ${input.plan_id}`,\n );\n }\n const result =\n pending.kind === 'timeline'\n ? await retryPlanPush(doc, pending.opsApplied)\n : await commitCachedPlan(input.doc_id, doc, pending.plan, input.validation, pending.baseState);\n recordPushResult(\n input.doc_id,\n input.plan_id,\n pending.plan,\n result,\n pending.kind === 'entities' ? pending.baseState : undefined,\n );\n const warnings = commitWarnings(result);\n return {\n ok: true,\n op: 'commit-plan',\n doc_id: input.doc_id,\n plan_id: input.plan_id,\n plan_kind: pending.plan.plan_kind,\n committed: result.kind === 'committed',\n result,\n collaborated: result.kind === 'committed' && result.collaborated,\n ...(warnings !== undefined ? { warnings } : {}),\n };\n }\n\n const cached = plans.get(input.plan_id);\n if (cached == null || cached.docId !== input.doc_id) {\n throw new Error(`plan_id ${input.plan_id} is not available for doc ${input.doc_id}`);\n }\n const pull = cached.plan.plan_kind === 'timeline' ? await observePull(doc) : { collaborated: false };\n const result = await commitCachedPlan(input.doc_id, doc, cached.plan, input.validation, cached.baseState);\n recordPushResult(input.doc_id, input.plan_id, cached.plan, result, cached.baseState);\n const warnings = mergeWarnings(pull.warnings, commitWarnings(result));\n return {\n ok: true,\n op: 'commit-plan',\n doc_id: input.doc_id,\n plan_id: input.plan_id,\n plan_kind: cached.plan.plan_kind,\n committed: result.kind === 'committed',\n result,\n collaborated: pull.collaborated || (result.kind === 'committed' && result.collaborated),\n ...(warnings !== undefined ? { warnings } : {}),\n };\n });\n }\n\n return {\n name: MEDEO_TOOL_NAME,\n description: MEDEO_TOOL_DESCRIPTION,\n parameters: MEDEO_TOOL_PARAMETERS,\n getModelContext,\n async handle(input: unknown): Promise<MedeoToolResult> {\n try {\n const parsed = parseInput(input);\n if (parsed.op === 'snapshot') return await snapshot(parsed);\n if (parsed.op === 'run-edit-script') return await run(parsed);\n return await commit(parsed);\n } catch (error) {\n const op = isRecord(input) && typeof input.op === 'string' ? (input.op as MedeoToolOp) : 'snapshot';\n return {\n ok: false,\n op,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n },\n async close(): Promise<void> {\n closed = true;\n await Promise.allSettled(documentTails.values());\n const opening = [...documents.values()];\n documents.clear();\n entityClients.clear();\n documentTails.clear();\n pendingPushes.clear();\n plans.clear();\n modelContextVersions.clear();\n const errors: unknown[] = [];\n for (const documentPromise of opening) {\n try {\n await documentPromise;\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length === 1) throw errors[0];\n if (errors.length > 1) throw new AggregateError(errors, 'failed to close medeo tool documents');\n },\n };\n}\n","import { createHash } from 'node:crypto';\n\nimport type { MediaAssetFact } from '@mengine/medeo-client';\n\nimport type { JsonObject, SandboxEntity } from './entity-contract.ts';\nimport { EntityHttpClient, type EntityHttpClientOptions } from './entity-http-client.ts';\nimport { EntitySandbox } from './entity-sandbox.ts';\nimport { planGeneratedRelations, parseGenerationFacts, type GenerationFactsLoader } from './generation-sync.ts';\n\n/** Host facts only. This contract is never included in the model's sandbox API. */\nexport type GeneratedResource =\n | MediaAssetFact\n | {\n kind: 'caption';\n assetId: string;\n storageKey: string;\n segments: readonly {\n text: string;\n startMs: number;\n endMs: number;\n /** ASR word timing is available as an annotation for model segmentation. */\n words?: readonly { text: string; startMs: number; endMs: number }[];\n }[];\n };\n\n/** Persist resources before model consumption. The host serializes repeated imports of the same generation task. */\nexport async function materializeResources(\n options: EntityHttpClientOptions & { loadGenerationFacts?: GenerationFactsLoader },\n resources: readonly GeneratedResource[],\n): Promise<readonly string[]> {\n const client = new EntityHttpClient(options);\n const state = await client.fetchState();\n let resourceKey = '';\n const sandbox = new EntitySandbox({ state, idFactory: (prefix) => stableId(prefix, options.docId, resourceKey) });\n const ids: string[] = [];\n for (const resource of resources) {\n resourceKey = `${resource.kind}:${resource.assetId}`;\n if (resource.kind !== 'caption') {\n ids.push(sandbox.entities.ensureMedia(resource).contentEntityId);\n continue;\n }\n const assetId = stableId('asset', resource.assetId);\n const asset = sandbox.entities.get(assetId);\n if (asset) {\n if (asset.entity_kind !== 'asset' || asset.payload.storageKey !== resource.storageKey)\n throw new Error('Conflicting Caption resource identity');\n const bindings = sandbox.relations.of(assetId, 'physical-asset');\n const captions = bindings\n .map((edge) => sandbox.entities.get(edge.endpoint_0_entity_id))\n .filter((entity): entity is SandboxEntity => entity?.entity_kind === 'caption');\n if (captions.length !== 1) throw new Error('Caption resource must resolve to one materialized Caption');\n ids.push(captions[0]!.entity_id);\n continue;\n }\n if (!resource.assetId.trim() || !resource.storageKey.trim() || !resource.segments.length)\n throw new Error('Caption resource requires a physical locator and timed segments');\n for (const segment of resource.segments) {\n if (\n typeof segment.text !== 'string' ||\n !Number.isFinite(segment.startMs) ||\n !Number.isFinite(segment.endMs) ||\n segment.startMs < 0 ||\n segment.endMs <= segment.startMs\n )\n throw new Error('Caption resource has invalid ASR text or timing');\n for (const word of segment.words ?? []) {\n if (\n typeof word.text !== 'string' ||\n !Number.isFinite(word.startMs) ||\n !Number.isFinite(word.endMs) ||\n word.startMs < segment.startMs ||\n word.endMs > segment.endMs ||\n word.endMs < word.startMs\n )\n throw new Error('Caption resource has invalid ASR word timing');\n }\n }\n const scriptId = sandbox.audioScriptEntityId;\n if (!scriptId) throw new Error('Document AudioScript is not initialized');\n const script = sandbox.entities.get(scriptId)!;\n const segments = resource.segments.map((segment, index) => ({\n segmentId: stableId('segment', resource.assetId, String(index)),\n text: segment.text,\n }));\n const start = Math.min(...resource.segments.map((segment) => segment.startMs));\n const end = Math.max(...resource.segments.map((segment) => segment.endMs));\n // Patch the current text owner. The Loro compiler versions it and rewires\n // variant bases and the project attachment, preserving unrelated segments.\n sandbox.entities.update({\n entity_id: scriptId,\n payload: { segments: [...(script.payload.segments as JsonObject[]), ...segments] },\n });\n const captionId = stableId('entity', 'caption', resource.assetId);\n sandbox.entities.create({\n entity_id: captionId,\n entity_kind: 'caption',\n payload: {\n baseEntityIds: [scriptId],\n selections: segments.map(({ segmentId }) => ({ segmentId })),\n extent: { kind: 'bounded', start, end },\n sampling: 'native',\n coordinateSpace: 'milliseconds',\n },\n });\n const markerId = sandbox.entities.create({\n entity_id: stableId('entity', 'asr-marker', resource.assetId),\n entity_kind: 'sequence-marker',\n payload: {\n sourceRange: { start, end },\n duration: { mode: 'from-source' },\n segmentRanges: resource.segments.map((segment, index) => ({\n segmentId: segments[index]!.segmentId,\n startMs: segment.startMs,\n endMs: segment.endMs,\n })),\n wordRanges: resource.segments.flatMap((segment, index) =>\n (segment.words ?? []).map((word) => ({ ...word, segmentIndex: index })),\n ),\n },\n });\n sandbox.relations.link({\n relation_id: stableId('relation', 'asr-marker', resource.assetId),\n relation_kind: 'audio-script-marker',\n endpoint_0_entity_id: scriptId,\n endpoint_1_entity_id: markerId,\n });\n sandbox.entities.create({\n entity_id: assetId,\n entity_kind: 'asset',\n payload: {\n external: { system: 'memota', key: resource.assetId },\n storageKey: resource.storageKey,\n },\n });\n sandbox.relations.link({\n relation_id: stableId('relation', captionId, assetId),\n relation_kind: 'physical-asset',\n endpoint_0_entity_id: captionId,\n endpoint_1_entity_id: assetId,\n });\n ids.push(captionId);\n }\n const candidate = sandbox.buildPlan();\n if (candidate.commands.length && options.loadGenerationFacts) {\n const newIds = new Set(ids.filter((id) => !state.entities.some((row) => row.entity_id === id)));\n const facts = parseGenerationFacts(\n await options.loadGenerationFacts(\n options.docId,\n resources.map((item) => item.assetId),\n ),\n );\n const relations = planGeneratedRelations({\n baseState: state,\n state: candidate.rows,\n scopedMediaIds: newIds,\n facts,\n newRelationId: () => `relation_${globalThis.crypto.randomUUID()}`,\n });\n for (const relation of relations)\n sandbox.relations.linkGenerated({\n relation_id: relation.relation_id,\n output_entity_id: relation.endpoint_0_entity_id,\n input_entity_id: relation.endpoint_1_entity_id,\n trace: relation.trace,\n });\n }\n const plan = sandbox.buildPlan();\n if (!plan.commands.length) return ids;\n const committed = await client.commit(state.revision, plan.rows);\n for (const id of ids) {\n if (!committed.entities.some((entity) => entity.entity_id === id))\n throw new Error(`Resource entity ${id} was not confirmed by the merged document`);\n }\n return ids;\n}\n\nfunction stableId(prefix: string, ...parts: string[]): string {\n return `${prefix}_${createHash('sha256').update(JSON.stringify(parts)).digest('hex')}`;\n}\n"],"mappings":";;;;;AAkFA,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;;;;;;AAO1B,SAAS,cAAc,UAAuB;CAC5C,MAAM,UAAU,IAAI,IAAI,OAAO,KAAK,GAAG;CACvC,MAAM,YAAY,QAAQ,SAAS,SAAS,KAAK,IAAI,OAAO;CAC5D,OAAO,IAAI,IAAI,KAAK,SAAS,GAAG,aAAa,OAAO;AACtD;;AAGA,SAAgB,cAAc,SAA0D;CAItF,IAAI,kBAAkB,YAAY,IAAI;CACtC,MAAM,YAAY,QAAQ,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A;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAC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