@mengine/medeo-tool 1.3.1-alpha.6 → 1.3.1-alpha.8

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["isRecord","isRecord"],"sources":["../src/sandbox/node-host.ts","../src/entity/entity-contract.ts","../src/entity/entity-http-client.ts","../src/entity/generation-sync.ts","../src/migration-input.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"],"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 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 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 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 revision: number;\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 doc_id: string;\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","import {\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 entity-store CAS 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 expectedRevision: number,\n state: EntityStoreSnapshot,\n deletions: EntityCommitDeletions = {},\n ): Promise<EntityStoreSnapshot> {\n const response = await this.requestJson({\n method: 'POST',\n body: JSON.stringify({\n expected_revision: expectedRevision,\n rows: { entities: state.entities, relations: state.relations },\n deleted_entity_ids: [...(deletions.deleted_entity_ids ?? [])],\n deleted_relation_ids: [...(deletions.deleted_relation_ids ?? [])],\n }),\n });\n return toSnapshot(response, 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 const response = value as unknown as EntityStateWireResponse;\n return {\n revision: response.revision,\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 { MengineEntityHttpRequestError, 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/** Bounded CAS retry budget for the sync commit after a concurrent winner. */\nconst MAX_COMMIT_ATTEMPTS = 3;\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 /** Entity-store state the committed plan was based on (its CAS base). */\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. A\n * revision conflict re-reads current entities and relations, re-plans, and\n * retries within `MAX_COMMIT_ATTEMPTS`; 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 let state = await client.fetchState();\n let scope = planGenerationScope(baseState, entityCommands, state);\n if (scope.queryAssetKeys.length === 0) return { status: 'current' };\n const facts = parseGenerationFacts(await loadFacts(docId, scope.queryAssetKeys));\n for (let attempt = 1; attempt <= MAX_COMMIT_ATTEMPTS; attempt++) {\n if (scope.queryAssetKeys.length === 0) return { status: 'current' };\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 try {\n await client.commit(state.revision, { ...state, relations: [...state.relations, ...relations] });\n return { status: 'applied', created_relation_ids: relations.map((relation) => relation.relation_id) };\n } catch (error) {\n const conflict = error instanceof MengineEntityHttpRequestError && error.status === 409;\n if (!conflict || attempt === MAX_COMMIT_ATTEMPTS) {\n return { status: 'failed', message: `generation lineage sync commit failed: ${errorMessage(error)}` };\n }\n state = await client.fetchState();\n scope = planGenerationScope(baseState, entityCommands, state);\n }\n }\n return { status: 'failed', message: 'generation lineage sync exhausted its retry budget' };\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","import type { MediaAssetFact } from '@mengine/medeo-client';\n\n/** Validate host-recalled facts without accepting a caller-controlled snapshot or VV. */\nexport function parseMigrationAssetFacts(value: unknown): MediaAssetFact[] {\n if (!Array.isArray(value)) throw new Error('asset_facts is required for migrate-legacy and must be an array');\n return value.map((item): MediaAssetFact => {\n if (!record(item)) throw new Error('Each asset_facts entry must be an object');\n const { assetId, kind, durationMs, storageKey, voice } = item;\n if (!nonempty(assetId)) throw new Error('asset_facts.assetId must be a non-empty trimmed string');\n if (kind !== 'image' && kind !== 'video' && kind !== 'audio' && kind !== 'voice')\n throw new Error('asset_facts.kind must be image, video, audio, or voice');\n if (Object.keys(item).some((key) => !['assetId', 'kind', 'durationMs', 'storageKey', 'voice'].includes(key)))\n throw new Error('Unknown asset_facts field');\n if (storageKey !== undefined && !nonempty(storageKey)) throw new Error('asset_facts.storageKey must be non-empty');\n if (kind === 'image') {\n if (durationMs !== undefined || voice !== undefined)\n throw new Error('Image facts cannot declare duration or voice');\n return { assetId, kind, ...(storageKey === undefined ? {} : { storageKey: storageKey as string }) };\n }\n if (typeof durationMs !== 'number' || !Number.isSafeInteger(durationMs) || durationMs <= 0)\n throw new Error('asset_facts.durationMs must be factual positive whole milliseconds');\n if (kind === 'video') {\n if (voice !== undefined) throw new Error('Video facts cannot declare voice');\n return { assetId, kind, durationMs, ...(storageKey === undefined ? {} : { storageKey: storageKey as string }) };\n }\n if (!nonempty(storageKey)) throw new Error('Audio and Voice facts require their physical storageKey');\n if (kind === 'audio') {\n if (voice !== undefined) throw new Error('Audio facts cannot declare a Voice descriptor');\n return { assetId, kind, durationMs, storageKey };\n }\n if (\n !record(voice) ||\n voice.system !== 'voice-library' ||\n !nonempty(voice.key) ||\n (voice.name !== undefined && typeof voice.name !== 'string') ||\n Object.keys(voice).some((key) => !['system', 'key', 'name'].includes(key))\n )\n throw new Error('Voice facts require an explicit voice-library descriptor');\n return {\n assetId,\n kind,\n durationMs,\n storageKey,\n voice: { system: 'voice-library', key: voice.key, ...(voice.name === undefined ? {} : { name: voice.name }) },\n };\n });\n}\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction nonempty(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0 && value.trim() === 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 AudioMediaAssetFact {',\n ' readonly assetId: string;',\n \" readonly kind: 'audio';\",\n ' readonly durationMs: number;',\n ' readonly storageKey: string;',\n '}',\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 '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 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): {',\n ' contentEntityId: string;',\n ' };',\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 ' /** 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: {',\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 ' revision: number;',\n ' entities: SandboxEntity[];',\n ' relations: SandboxRelation[];',\n '}',\n 'export interface ImageMediaAssetFact {',\n ' readonly assetId: string;',\n \" readonly kind: 'image';\",\n ' readonly storageKey?: string;',\n '}',\n 'export interface InsertCaptionClipInput {',\n ' readonly timelineEntityId: 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 InsertMediaClipInput {',\n ' readonly timelineEntityId: string;',\n ' readonly clipEntityId?: string;',\n ' readonly media: VisualMediaAssetFact;',\n ' /** Source/display window in whole milliseconds. Images use this as their finite display span. */',\n ' readonly sourceRange: SequenceRange<number>;',\n ' readonly placement: ClipPlacement;',\n ' readonly volume?: number;',\n '}',\n 'export interface InsertMediaClipsInput {',\n ' readonly timelineEntityId: string;',\n ' readonly clips: readonly ReplacementMediaClipInput[];',\n ' /** One placement decision for the whole input-ordered block. */',\n ' readonly insertion: MediaClipInsertion;',\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 \" | 'asset'\",\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 \" | 'physical-asset'\",\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 '/** Facts resolved from media storage. A trim window never substitutes for intrinsic duration. */',\n 'export type MediaAssetFact = ImageMediaAssetFact | VideoMediaAssetFact | AudioMediaAssetFact | VoiceMediaAssetFact;',\n 'export type MediaAssetPayload = JsonObject & {',\n ' external: {',\n \" system: 'memota' | 'memota-speech';\",\n ' key: string;',\n ' };',\n ' storageKey?: string;',\n '};',\n 'export type MediaClipInsertion =',\n ' | {',\n \" readonly kind: 'before';\",\n ' readonly clipEntityId: string;',\n ' }',\n ' | {',\n \" readonly kind: 'after';\",\n ' readonly clipEntityId: string;',\n ' }',\n ' | {',\n \" readonly kind: 'firstStart';\",\n ' readonly startMs: number;',\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 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 '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 ReplaceMediaClipInput {',\n ' readonly clipEntityId: string;',\n ' readonly media: VisualMediaAssetFact;',\n ' readonly sourceRange: SequenceRange<number>;',\n '}',\n 'export interface ReplaceSequentialClipsInput {',\n ' readonly timelineEntityId: string;',\n ' readonly oldClipEntityIds: readonly string[];',\n ' readonly newClips: readonly ReplacementMediaClipInput[];',\n \" readonly onAnchored: 'remap' | 'cascade';\",\n '}',\n 'export interface ReplacementMediaClipInput {',\n ' readonly clipEntityId?: string;',\n ' readonly media: VisualMediaAssetFact;',\n ' readonly sourceRange: SequenceRange<number>;',\n ' readonly volume?: number;',\n '}',\n '/** Asset identity, either an old physical-only row or a directly composed media variant. */',\n \"export type ResourceEntityKind = 'image' | 'video' | 'audio' | 'voice';\",\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 SetBgmInput {',\n ' readonly timelineEntityId: string;',\n ' readonly bgmClipEntityId: string;',\n ' readonly media: AudioMediaAssetFact;',\n ' readonly volume: number;',\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 'export interface VideoMediaAssetFact {',\n ' readonly assetId: string;',\n \" readonly kind: 'video';\",\n ' readonly durationMs: number;',\n ' readonly storageKey?: string;',\n '}',\n 'export type VisualMediaAssetFact = ImageMediaAssetFact | VideoMediaAssetFact;',\n 'export interface VoiceDescriptor {',\n \" readonly system: 'voice-library';\",\n ' readonly key: string;',\n ' readonly name?: string;',\n '}',\n 'export interface VoiceMediaAssetFact {',\n ' /** Stable external speech result id, independent of the placed Clip id. */',\n ' readonly assetId: string;',\n \" readonly kind: 'voice';\",\n ' readonly durationMs: number;',\n ' readonly storageKey: string;',\n ' /** Present for synthesized voice, absent for original recorded audio. */',\n ' readonly voice?: VoiceDescriptor;',\n '}',\n 'export interface VoiceoverCaptionFact {',\n ' /** Stable placed caption identity supplied by the materialized side effect. */',\n ' readonly captionClipEntityId: string;',\n ' /** Directly held bases; includes the AudioScript used by the Voice. */',\n ' readonly baseEntityIds: readonly string[];',\n ' /** Ordered selection of AudioScript segments; caption text is never passed inline. */',\n ' readonly selections: readonly CaptionSegmentSelection[];',\n ' readonly startMs: number;',\n ' readonly durationMs: number;',\n ' readonly style?: CaptionStyleFields;',\n '}',\n 'export type VoiceoverTakeInput = {',\n ' readonly timelineEntityId: string;',\n ' /** Stable placed speech identity, distinct from media.assetId. */',\n ' readonly voiceoverClipEntityId: string;',\n ' readonly media: VoiceMediaAssetFact;',\n ' /** Existing pronunciation variant; its composed AudioScript stays the text owner. */',\n ' readonly phoneticScriptEntityId: string;',\n ' readonly volume: number;',\n ' readonly captions: readonly VoiceoverCaptionFact[];',\n '} & (',\n ' | {',\n ' readonly placement: ClipPlacement;',\n ' readonly hostClipEntityId?: never;',\n ' readonly anchorOffset?: never;',\n ' }',\n ' | {',\n ' readonly placement?: never;',\n ' readonly hostClipEntityId: string;',\n ' readonly anchorOffset: number;',\n ' }',\n ');',\n 'export interface VoiceoverTakeResult {',\n ' readonly voiceoverClipEntityId: string;',\n ' readonly voiceEntityId: string;',\n ' /** The pronunciation variant the Voice was rendered from. */',\n ' readonly phoneticScriptEntityId: string;',\n ' /** The base-text owner resolved from the PhoneticScript baseEntityIds. */',\n ' readonly audioScriptEntityId: string;',\n ' readonly captionClipEntityIds: readonly string[];',\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 ' insertMediaClip(input: InsertMediaClipInput): ClipEntityId;',\n ' insertMediaClips(input: InsertMediaClipsInput): readonly ClipEntityId[];',\n ' replaceMediaClip(input: ReplaceMediaClipInput): void;',\n ' setClipVolume(input: SetClipVolumeInput): void;',\n ' setClipSpeed(input: SetClipSpeedInput): void;',\n ' trimClip(input: TrimClipInput): void;',\n ' replaceSequentialClips(input: ReplaceSequentialClipsInput): readonly ClipEntityId[];',\n ' deleteClip(input: DeleteClipInput): void;',\n ' deleteClipTree(input: DeleteClipTreeInput): void;',\n ' updateClip(input: UpdateClipInput): void;',\n ' upsertVoiceoverTake(input: VoiceoverTakeInput): VoiceoverTakeResult;',\n ' moveVoiceover(input: MoveVoiceoverInput): void;',\n ' moveClipsToStarts(input: MoveClipsToStartsInput): void;',\n ' deleteVoiceover(input: DeleteVoiceoverInput): void;',\n ' setBgm(input: SetBgmInput): ClipEntityId;',\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 '}',\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: EntityFacade;',\n 'export declare const relations: RelationFacade;',\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: initialize missing fixed editor structure, then return the Entity/Relation state summary and opaque base version. Initialization is idempotent and may advance the entity revision once; unchanged snapshots do not write.\n- migrate-legacy: explicitly migrate an existing legacy timeline using recalled asset_facts. MEngine reads the canonical document and version, verifies that editing facts are preserved, and commits migration alone. Then take a fresh snapshot before any edit; never pass a caller-created legacy snapshot or version.\n- run-edit-script: inspect timeline.snapshot(), entities.*, and relations.*; edit.* operates existing Entity ids and creates the required Clip/SequenceMarker structural graph. Asset import, media Entity creation and timeline edits belong in ONE plan. The sandbox has no network, storage or generation access. Pass recalled asset facts through inputs; generation history is not a script input — the host program queries it itself after each commit. A successful run returns preview, logs, base revision and plan_id.\n- commit-plan: commit the complete Entity/Relation plan through revision CAS. The server derives the read-only timeline projection in the same transaction. There is no separate writable timeline plan and no preflight replay into a legacy editor. A failed transport is unconfirmed, never committed; retry the same plan_id.\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. On version mismatch, rerun snapshot and the script; never try to patch a rejected journal by hand.\n\nGenerating an Asset alone does not require an Entity. Using that resource in the editor DOES: recall the Asset facts, call entities.ensureMedia(fact), then pass its contentEntityId to edit.insertClip. A raw external asset id or URL is not valid contentEntityId. Image/Video/Audio/Voice are logical variants of Asset: a resource has ONE identity and ONE typed row owning both media fields and external {system,key}/storageKey, with no separate Asset row or physical-asset relation. ensureMedia returns contentEntityId and reuses that single identity by external asset id. Each placement still gets its own Clip and SequenceMarker. Generation lineage is program-synced: after each successful commit the tool connects existing typed Assets from host-recalled generation facts (endpoint 0 output, endpoint 1 input) that the host queries itself — do not pass generation history through inputs. Do not author generated Relations yourself, and never create an Entity merely to backfill or represent lineage; media variants the edit itself legitimately needs are still created normally. Text-only generation has no input and no lineage edge. 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.\nGeneration lineage is not a model input: the host program queries it via loadGenerationFacts and syncs generated Relations after each successful commit. Memota asset facts are host-provided through inputs. Never invent an asset id, Entity kind, or peer Entity id.\nUse entities.ensureMedia(fact) to get or create the canonical typed Asset. Native media placement helpers use the same resolver. findByAssetId includes directly composed media variants, including Voice. Every Image/Video/Audio/Voice must own its external identity; separate Asset+media graphs are invalid. A typed Asset's external identity cannot be removed or rewritten: to replace its source, ensureMedia for the new Asset and replace the Clip's content. Conflicting facts fail closed. Asset generation itself still creates no editor Entities.\nFor recalled video/audio/voice, create a bounded/native payload whose extent end comes from factual media duration/coordinates in inputs; never fabricate a duration. Image uses unbounded/constant semantics and has no invented end. If required facts are absent, do not create the media Entity yet.\nCaption content is assembled from AudioScript; never create an inline text Asset for it. Generated media lineage is host-owned; do not author generated Relations yourself. relations.of remains endpoint-agnostic for lookup.\nThe compatibility reader 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; 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. The host initializes one Timeline and four fixed Tracks before editing; inspect and reuse their IDs from timeline.snapshot(), never create another Timeline or Track for each operation. If snapshot reports legacy migration is required, recall the listed asset facts and call migrate-legacy first. Missing facts, unsupported layouts, and version conflicts fail closed; never fall back to an old timeline method or raw update endpoint.\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' | 'migrate-legacy' | 'run-edit-script' | 'commit-plan';\n\nconst assetFactProperties = {\n assetId: { type: 'string', minLength: 1 },\n kind: { type: 'string', enum: ['image', 'video', 'audio', 'voice'] },\n durationMs: { type: 'integer', minimum: 1 },\n storageKey: { type: 'string', minLength: 1 },\n voice: {\n type: 'object',\n additionalProperties: false,\n required: ['system', 'key'],\n properties: { system: { const: 'voice-library' }, key: { type: 'string', minLength: 1 }, name: { type: 'string' } },\n },\n} as const;\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', 'migrate-legacy', '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 asset_facts: {\n type: 'array',\n description:\n 'Factual asset metadata recalled by the host for migrate-legacy only. The package reads the canonical legacy snapshot and version itself; never supply a clip trim window as media duration.',\n items: {\n oneOf: [\n {\n type: 'object',\n additionalProperties: false,\n required: ['assetId', 'kind'],\n properties: {\n assetId: assetFactProperties.assetId,\n kind: { const: 'image' },\n storageKey: assetFactProperties.storageKey,\n },\n },\n {\n type: 'object',\n additionalProperties: false,\n required: ['assetId', 'kind', 'durationMs'],\n properties: {\n assetId: assetFactProperties.assetId,\n kind: { const: 'video' },\n durationMs: assetFactProperties.durationMs,\n storageKey: assetFactProperties.storageKey,\n },\n },\n {\n type: 'object',\n additionalProperties: false,\n required: ['assetId', 'kind', 'durationMs', 'storageKey'],\n properties: {\n assetId: assetFactProperties.assetId,\n kind: { const: 'audio' },\n durationMs: assetFactProperties.durationMs,\n storageKey: assetFactProperties.storageKey,\n },\n },\n {\n type: 'object',\n additionalProperties: false,\n required: ['assetId', 'kind', 'durationMs', 'storageKey', 'voice'],\n properties: { ...assetFactProperties, kind: { const: 'voice' } },\n },\n ],\n },\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: ['version'],\n description: 'Commit with Entity revision CAS; reject concurrent changes.',\n },\n },\n oneOf: [\n {\n required: ['op', 'doc_id', 'asset_facts'],\n properties: {\n op: { const: 'migrate-legacy' },\n doc_id: { $ref: '#/properties/doc_id' },\n asset_facts: { $ref: '#/properties/asset_facts' },\n },\n additionalProperties: false,\n },\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 EntityGraphHttpClient,\n ManualSyncDoc,\n migrateLegacyTimelineToEntities,\n MengineHttpClient,\n MengineHttpRequestError,\n toVideoDocument,\n type ManualSyncDocOptions,\n type MediaAssetFact,\n type VideoDocument,\n type VideoDraft,\n} from '@mengine/medeo-client';\n\nimport type { EntityStoreSnapshot } from './entity/entity-contract.ts';\nimport { EntityHttpClient, MengineEntityHttpRequestError } from './entity/entity-http-client.ts';\nimport { EntitySandbox, toDslRows } from './entity/entity-sandbox.ts';\nimport {\n syncGeneratedRelations,\n type GenerationFactsLoader,\n type GenerationSyncOutcome,\n} from './entity/generation-sync.ts';\nimport { parseMigrationAssetFacts } from './migration-input.ts';\nimport { MEDEO_TOOL_DESCRIPTION, renderMedeoModelContext } from './prompt.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 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 | { op: 'migrate-legacy'; doc_id: string; asset_facts: readonly MediaAssetFact[] }\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?: 'version' | 'preflight';\n };\n\nexport type MedeoToolWarning =\n | { kind: 'pull_failed'; message: string }\n | { kind: 'generation_sync_failed'; message: string };\n\nexport type EntityCommitResult =\n | {\n kind: 'committed';\n ops_applied: number;\n collaborated: false;\n entity_revision: number;\n /** Present only when the host supplies loadGenerationFacts. */\n generation_sync?: GenerationSyncOutcome;\n warnings?: MedeoToolWarning[];\n }\n | { kind: 'unconfirmed'; reason: 'push_failed'; ops_applied: number; message: string }\n | {\n kind: 'rejected';\n reason: 'entity_revision_mismatch';\n expected: number;\n actual: number;\n }\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: 'migrate-legacy';\n doc_id: string;\n migration_status: 'committed' | 'already_entity';\n entity_revision: number;\n next_action: 'snapshot';\n }\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(state: EntityStoreSnapshot): string {\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} 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\nfunction migrationNotice(document: VideoDocument, state: EntityStoreSnapshot): string {\n if (\n state.entities.some((row) => row.entity_kind === 'timeline') ||\n Object.keys(document.part_library ?? {}).length === 0\n )\n return '';\n const assetIds = new Set(\n Object.values(document.part_library ?? {}).flatMap((part) => {\n const id = part.video_clip?.origin_media_id ?? part.bgm?.origin_media_id;\n return typeof id === 'string' && id !== '' ? [id] : [];\n }),\n );\n return `\\nLegacy timeline migration required. Recall factual media metadata for ${JSON.stringify([...assetIds])}, then call migrate-legacy with asset_facts. Speech facts are read from the canonical legacy document. Take a fresh snapshot after migration before editing.`;\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 const committed = await client.commit(plan.entity_base_revision, rows, {\n deleted_entity_ids: plan.deleted_entity_ids ?? [],\n deleted_relation_ids: plan.deleted_relation_ids ?? [],\n });\n return {\n kind: 'committed',\n ops_applied: plan.entity_commands.length,\n collaborated: false,\n entity_revision: committed.revision,\n };\n } catch (error) {\n if (error instanceof MengineEntityHttpRequestError) {\n if (error.status === 409 && isRevisionConflictPayload(error.payload)) {\n const actualFromPayload = revisionConflictActual(error.payload);\n try {\n const current = await client.fetchState();\n // A lost POST response is indistinguishable from a retry conflict.\n // Recover only when the one expected revision landed with exactly the\n // authoritative rows this plan submitted.\n if (current.revision === plan.entity_base_revision + 1 && entityRowsEquivalent(current, rows)) {\n return {\n kind: 'committed',\n ops_applied: plan.entity_commands.length,\n collaborated: false,\n entity_revision: current.revision,\n };\n }\n return {\n kind: 'rejected',\n reason: 'entity_revision_mismatch',\n expected: plan.entity_base_revision,\n actual: current.revision,\n };\n } catch {\n if (actualFromPayload !== undefined) {\n return {\n kind: 'rejected',\n reason: 'entity_revision_mismatch',\n expected: plan.entity_base_revision,\n actual: actualFromPayload,\n };\n }\n return {\n kind: 'unconfirmed',\n reason: 'push_failed',\n ops_applied: plan.entity_commands.length,\n message: 'entity-state conflict could not be reconciled',\n };\n }\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 revisionConflictActual(payload: unknown): number | undefined {\n if (!isRecord(payload)) return undefined;\n const actual = payload.actual_revision;\n return typeof actual === 'number' && Number.isSafeInteger(actual) && actual >= 0 ? actual : undefined;\n}\n\nfunction isRevisionConflictPayload(payload: unknown): boolean {\n return isRecord(payload) && payload.code === 'revision_conflict';\n}\n\nfunction entityHttpErrorMessage(payload: unknown): string {\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 entityRowsEquivalent(left: EntityStoreSnapshot, right: EntityStoreSnapshot): boolean {\n const normalize = (state: EntityStoreSnapshot) => ({\n entities: [...state.entities]\n .sort((a, b) => a.entity_id.localeCompare(b.entity_id))\n .map((entity) => canonicalJson(entity)),\n relations: [...state.relations]\n .sort((a, b) => a.relation_id.localeCompare(b.relation_id))\n .map((relation) => canonicalJson(relation)),\n });\n return JSON.stringify(normalize(left)) === JSON.stringify(normalize(right));\n}\n\nfunction canonicalJson(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(canonicalJson);\n if (!isRecord(value)) return value;\n return Object.fromEntries(\n Object.keys(value)\n .sort()\n .map((key) => [key, canonicalJson(value[key])]),\n );\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 === 'migrate-legacy') {\n if (Object.keys(value).some((key) => !['op', 'doc_id', 'asset_facts'].includes(key)))\n throw new Error('migrate-legacy accepts asset_facts only; the package reads the canonical document and version');\n return { op, doc_id: docId, asset_facts: parseMigrationAssetFacts(value.asset_facts) };\n }\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 !== 'version' && value.validation !== 'preflight') {\n throw new Error('validation must be \"version\" or \"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 const seed = createMirrorVideoDocument(document, {\n ...(peerId !== undefined ? { peerId } : {}),\n origin: 'mengine.medeo_tool.bootstrap',\n });\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 client = getEntityClient(docId);\n for (let attempt = 0; attempt < 4; attempt += 1) {\n const state = await client.fetchState();\n // Context reads during an unconfirmed edit must never insert an unrelated CAS revision.\n if (pendingPushes.has(docId)) return state;\n const document = doc.snapshot();\n const hasTimeline = state.entities.some((row) => row.entity_kind === 'timeline');\n const hasLegacyContent =\n Object.keys(document.part_library ?? {}).length > 0 ||\n (document.tracks ?? []).some((track) => (track.items ?? []).length > 0);\n if (!hasTimeline && hasLegacyContent) return state;\n if (!hasTimeline) {\n if (pull.warnings !== undefined)\n throw new Error('Editor initialization requires a fresh canonical snapshot; retry snapshot');\n // Even an empty draft can own configured Track visibility, identities,\n // order and timing. Preserve them through the existing version-guarded\n // migration gate instead of silently cutting over to a blank graph.\n const baseRows = toDslRows(state);\n const migrated = migrateLegacyTimelineToEntities(document, [], baseRows);\n try {\n await getGraphClient(docId).commit({ revision: state.revision, rows: baseRows }, migrated, {\n migrationBaseVv: encodeDocVersionMark(doc.versionMark()),\n });\n } catch (error) {\n if (!(error instanceof MengineHttpRequestError) || error.status !== 409)\n throw new Error(\n `Editor initialization was not confirmed; retry snapshot to reconcile state: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n pull = await observePull(doc);\n continue;\n }\n const sandbox = new EntitySandbox({ state, idFactory: (prefix) => `${prefix}_${randomUUID()}` });\n sandbox.ensureFoundation();\n if (sandbox.commandCount === 0) return state;\n if (pull.warnings !== undefined)\n throw new Error('Editor initialization requires a fresh canonical snapshot; retry snapshot');\n try {\n const committed = await client.commit(state.revision, sandbox.buildPlan().rows);\n // Server projects the new foundation into Loro in the same transaction.\n await doc.pull();\n return committed;\n } catch (error) {\n if (!(error instanceof MengineEntityHttpRequestError) || error.status !== 409) {\n throw new Error(\n `Editor initialization was not confirmed; retry snapshot to reconcile state: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n pull = await observePull(doc);\n }\n }\n throw new Error('Editor initialization conflicted repeatedly; take a fresh snapshot');\n }\n\n function getGraphClient(docId: string): EntityGraphHttpClient {\n return new EntityGraphHttpClient({\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 }\n\n async function commitCachedPlan(\n docId: string,\n _doc: ManualSyncDoc,\n plan: ChangePlan,\n validation?: 'version' | '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 if (validation === 'preflight') {\n throw new Error('Entity plans use revision CAS; validation=preflight is not supported');\n }\n if (plan.entity_rows === undefined) throw new Error('entity plan is missing its authoritative rows');\n const client = getEntityClient(docId);\n // Generation sync scopes the plan's diff against its CAS base. The base is\n // captured when the plan is built and cached with it; the defensive fetch\n // below only covers a caller that lost the cached base, and the commit's\n // revision CAS makes that read the plan base whenever the commit lands.\n const preCommitState =\n baseState ?? (options.loadGenerationFacts !== undefined ? await client.fetchState() : undefined);\n const result = await commitEntityPlan(client, plan);\n return await attachGenerationSync(docId, plan, result, preCommitState);\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) + migrationNotice(doc.snapshot(), entityState),\n collaborated: pull.collaborated,\n ...(pull.warnings !== undefined ? { warnings: pull.warnings } : {}),\n };\n });\n }\n\n async function migrate(input: Extract<MedeoToolInput, { op: 'migrate-legacy' }>): Promise<MedeoToolResult> {\n return runExclusive(input.doc_id, async (doc) => {\n assertNoPendingPush(input.doc_id);\n const client = getGraphClient(input.doc_id);\n const base = await client.fetchState();\n if (base.rows.entities.some((row) => row.entityKind === 'timeline')) {\n return {\n ok: true,\n op: 'migrate-legacy',\n doc_id: input.doc_id,\n migration_status: 'already_entity',\n entity_revision: base.revision,\n next_action: 'snapshot',\n };\n }\n // Migration must not use observePull's deliberately tolerant stale-read mode.\n const pull = await doc.pull();\n if (!pull.ok) throw new Error(`Migration requires a fresh canonical snapshot: ${pull.error.message}`);\n const migrationBaseVv = encodeDocVersionMark(doc.versionMark());\n const nextRows = migrateLegacyTimelineToEntities(doc.snapshot(), input.asset_facts, base.rows);\n let revision: number;\n try {\n revision = (await client.commit(base, nextRows, { migrationBaseVv })).revision;\n } catch (error) {\n if (error instanceof MengineHttpRequestError) {\n throw new Error(\n `Migration rejected (HTTP ${error.status}): ${entityHttpErrorMessage(error.payload)}; take a fresh snapshot before retrying`,\n );\n }\n throw new Error(\n 'Migration submission is unconfirmed; take a fresh snapshot and retry migrate-legacy to inspect whether the Entity timeline already exists',\n );\n }\n // An old plan cannot span the authority cutover. The next call opens the\n // committed canonical projection and reads a new graph revision.\n documents.delete(input.doc_id);\n for (const [id, cached] of plans) if (cached.docId === input.doc_id) plans.delete(id);\n return {\n ok: true,\n op: 'migrate-legacy',\n doc_id: input.doc_id,\n migration_status: 'committed',\n entity_revision: revision,\n next_action: 'snapshot',\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 === 'migrate-legacy') return await migrate(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"],"mappings":";;;;;AA8EA,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,aAAa;CACvC,MAAM,gBAAgB,QAAQ,iBAAiB;CAC/C,MAAM,iBAAiB,QAAQ,kBAAkB,cAAc,cAAc;CAC7E,MAAM,qBAAqB,cAAc,2BAA2B;CAEpE,MAAM,MAAsB,CAAC;CAC7B,MAAM,iBAAkC,CAAC;CACzC,MAAM,OAAiB,CAAC;CAExB,OAAO,IAAI,SAA2B,YAAY;EAChD,IAAI,UAAU;EACd,IAAI,WAAW;EACf,IAAI;EAEJ,MAAM,SAAS,IAAI,OAAO,gBAAgB;GACxC,YAAY;IACV,UAAU,QAAQ;IAClB,QAAQ,QAAQ;IAChB,QAAQ,QAAQ;IAChB,aAAa,QAAQ;IACrB,SAAS,QAAQ;IACjB,YAAY,QAAQ;GACtB;GAKA,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,YACnD,OAAO,KAAK,KAAK,EAAE,MAAM,QAAQ,CAAC;GAAC;GAAU;GAAO;EAAM,EAAE,SAAS,GAAG,CAAC,GAEzE,MAAM,IAAI,MAAM,0DAA0D;EAC5E,OAAO;GACL;GACA;GACA;GACA;GACA,OAAO;IAAE,QAAQ;IAAiB,KAAK,MAAM;IAAK,GAAI,MAAM,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,MAAM,KAAK;GAAG;EAC9G;CACF,CAAC;AACH;AAEA,SAAS,OAAO,OAAkD;CAChE,OAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,SAAS,OAAiC;CACjD,OAAO,OAAO,UAAU,YAAY,MAAM,SAAS,KAAK,MAAM,KAAK,MAAM;AAC3E;;;;ACrDA,MAAa,8BAA8B;CACzC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;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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KACJ,IAHS,SAAS,KAAK,KAAK,OAAO,MAAM,OAAO,WAAY,MAAM,KAAqB;KAIvF,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;IAC9D;GACF;EACF;EACA,MAAM,QAAuB;GAC3B,SAAS;GACT,MAAM,QAAQ,WAAW,cAAc,OAAO,CAAC;GAC/C,MAAM,UAAU,CAAC,GAAG,UAAU,OAAO,CAAC;GACtC,UAAU,MAAM;GAChB,cAAc,MAAM;GACpB,cAAc,MAAM;GACpB,cAAc,MAAM;GACpB,MAAM,MAAM;GACZ,qBAAqB,MAAM;GAC3B,MAAM,SAAoB,CAAC;GAC3B,KAAK,MAAM,mBAAmB,SAC5B,IAAI;IACF,MAAM;GACR,SAAS,OAAO;IACd,OAAO,KAAK,KAAK;GACnB;GAEF,IAAI,OAAO,WAAW,GAAG,MAAM,OAAO;GACtC,IAAI,OAAO,SAAS,GAAG,MAAM,IAAI,eAAe,QAAQ,sCAAsC;EAChG;CACF;AACF"}
1
+ {"version":3,"file":"index.mjs","names":["isRecord","isRecord"],"sources":["../src/sandbox/node-host.ts","../src/entity/entity-contract.ts","../src/entity/entity-http-client.ts","../src/entity/generation-sync.ts","../src/migration-input.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"],"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 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 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 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 revision: number;\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: 'set-document-audio-script'; audioScriptEntityId: string | null }\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 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","import {\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 entity-store CAS 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 expectedRevision: number,\n state: EntityStoreSnapshot,\n deletions: EntityCommitDeletions = {},\n ): Promise<EntityStoreSnapshot> {\n const response = await this.requestJson({\n method: 'POST',\n body: JSON.stringify({\n expected_revision: expectedRevision,\n audio_script_entity_id: state.audioScriptEntityId,\n rows: { entities: state.entities, relations: state.relations },\n deleted_entity_ids: [...(deletions.deleted_entity_ids ?? [])],\n deleted_relation_ids: [...(deletions.deleted_relation_ids ?? [])],\n }),\n });\n return toSnapshot(response, 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 && !isTrimmed(value.audio_script_entity_id)) {\n throw new Error('invalid document AudioScript association');\n }\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 an AudioScript in this document');\n return {\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 { MengineEntityHttpRequestError, 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/** Bounded CAS retry budget for the sync commit after a concurrent winner. */\nconst MAX_COMMIT_ATTEMPTS = 3;\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 /** Entity-store state the committed plan was based on (its CAS base). */\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. A\n * revision conflict re-reads current entities and relations, re-plans, and\n * retries within `MAX_COMMIT_ATTEMPTS`; 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 let state = await client.fetchState();\n let scope = planGenerationScope(baseState, entityCommands, state);\n if (scope.queryAssetKeys.length === 0) return { status: 'current' };\n const facts = parseGenerationFacts(await loadFacts(docId, scope.queryAssetKeys));\n for (let attempt = 1; attempt <= MAX_COMMIT_ATTEMPTS; attempt++) {\n if (scope.queryAssetKeys.length === 0) return { status: 'current' };\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 try {\n await client.commit(state.revision, { ...state, relations: [...state.relations, ...relations] });\n return { status: 'applied', created_relation_ids: relations.map((relation) => relation.relation_id) };\n } catch (error) {\n const conflict = error instanceof MengineEntityHttpRequestError && error.status === 409;\n if (!conflict || attempt === MAX_COMMIT_ATTEMPTS) {\n return { status: 'failed', message: `generation lineage sync commit failed: ${errorMessage(error)}` };\n }\n state = await client.fetchState();\n scope = planGenerationScope(baseState, entityCommands, state);\n }\n }\n return { status: 'failed', message: 'generation lineage sync exhausted its retry budget' };\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","import type { MediaAssetFact } from '@mengine/medeo-client';\n\n/** Validate host-recalled facts without accepting a caller-controlled snapshot or VV. */\nexport function parseMigrationAssetFacts(value: unknown): MediaAssetFact[] {\n if (!Array.isArray(value)) throw new Error('asset_facts is required for migrate-legacy and must be an array');\n return value.map((item): MediaAssetFact => {\n if (!record(item)) throw new Error('Each asset_facts entry must be an object');\n const { assetId, kind, durationMs, storageKey, voice } = item;\n if (!nonempty(assetId)) throw new Error('asset_facts.assetId must be a non-empty trimmed string');\n if (kind !== 'image' && kind !== 'video' && kind !== 'audio' && kind !== 'voice')\n throw new Error('asset_facts.kind must be image, video, audio, or voice');\n if (Object.keys(item).some((key) => !['assetId', 'kind', 'durationMs', 'storageKey', 'voice'].includes(key)))\n throw new Error('Unknown asset_facts field');\n if (storageKey !== undefined && !nonempty(storageKey)) throw new Error('asset_facts.storageKey must be non-empty');\n if (kind === 'image') {\n if (durationMs !== undefined || voice !== undefined)\n throw new Error('Image facts cannot declare duration or voice');\n return { assetId, kind, ...(storageKey === undefined ? {} : { storageKey: storageKey as string }) };\n }\n if (typeof durationMs !== 'number' || !Number.isSafeInteger(durationMs) || durationMs <= 0)\n throw new Error('asset_facts.durationMs must be factual positive whole milliseconds');\n if (kind === 'video') {\n if (voice !== undefined) throw new Error('Video facts cannot declare voice');\n return { assetId, kind, durationMs, ...(storageKey === undefined ? {} : { storageKey: storageKey as string }) };\n }\n if (!nonempty(storageKey)) throw new Error('Audio and Voice facts require their physical storageKey');\n if (kind === 'audio') {\n if (voice !== undefined) throw new Error('Audio facts cannot declare a Voice descriptor');\n return { assetId, kind, durationMs, storageKey };\n }\n if (\n !record(voice) ||\n voice.system !== 'voice-library' ||\n !nonempty(voice.key) ||\n (voice.name !== undefined && typeof voice.name !== 'string') ||\n Object.keys(voice).some((key) => !['system', 'key', 'name'].includes(key))\n )\n throw new Error('Voice facts require an explicit voice-library descriptor');\n return {\n assetId,\n kind,\n durationMs,\n storageKey,\n voice: { system: 'voice-library', key: voice.key, ...(voice.name === undefined ? {} : { name: voice.name }) },\n };\n });\n}\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction nonempty(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0 && value.trim() === 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 AudioMediaAssetFact {',\n ' readonly assetId: string;',\n \" readonly kind: 'audio';\",\n ' readonly durationMs: number;',\n ' readonly storageKey: string;',\n '}',\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 '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 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): {',\n ' contentEntityId: string;',\n ' };',\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 ' /** 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: {',\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 ' revision: number;',\n ' audioScriptEntityId: string | null;',\n ' entities: SandboxEntity[];',\n ' relations: SandboxRelation[];',\n '}',\n 'export interface ImageMediaAssetFact {',\n ' readonly assetId: string;',\n \" readonly kind: 'image';\",\n ' readonly storageKey?: string;',\n '}',\n 'export interface InsertCaptionClipInput {',\n ' readonly timelineEntityId: 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 InsertMediaClipInput {',\n ' readonly timelineEntityId: string;',\n ' readonly clipEntityId?: string;',\n ' readonly media: VisualMediaAssetFact;',\n ' /** Source/display window in whole milliseconds. Images use this as their finite display span. */',\n ' readonly sourceRange: SequenceRange<number>;',\n ' readonly placement: ClipPlacement;',\n ' readonly volume?: number;',\n '}',\n 'export interface InsertMediaClipsInput {',\n ' readonly timelineEntityId: string;',\n ' readonly clips: readonly ReplacementMediaClipInput[];',\n ' /** One placement decision for the whole input-ordered block. */',\n ' readonly insertion: MediaClipInsertion;',\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 \" | 'asset'\",\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 \" | 'physical-asset'\",\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 '/** Facts resolved from media storage. A trim window never substitutes for intrinsic duration. */',\n 'export type MediaAssetFact = ImageMediaAssetFact | VideoMediaAssetFact | AudioMediaAssetFact | VoiceMediaAssetFact;',\n 'export type MediaAssetPayload = JsonObject & {',\n ' external: {',\n \" system: 'memota' | 'memota-speech';\",\n ' key: string;',\n ' };',\n ' storageKey?: string;',\n '};',\n 'export type MediaClipInsertion =',\n ' | {',\n \" readonly kind: 'before';\",\n ' readonly clipEntityId: string;',\n ' }',\n ' | {',\n \" readonly kind: 'after';\",\n ' readonly clipEntityId: string;',\n ' }',\n ' | {',\n \" readonly kind: 'firstStart';\",\n ' readonly startMs: number;',\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 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 '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 ReplaceMediaClipInput {',\n ' readonly clipEntityId: string;',\n ' readonly media: VisualMediaAssetFact;',\n ' readonly sourceRange: SequenceRange<number>;',\n '}',\n 'export interface ReplaceSequentialClipsInput {',\n ' readonly timelineEntityId: string;',\n ' readonly oldClipEntityIds: readonly string[];',\n ' readonly newClips: readonly ReplacementMediaClipInput[];',\n \" readonly onAnchored: 'remap' | 'cascade';\",\n '}',\n 'export interface ReplacementMediaClipInput {',\n ' readonly clipEntityId?: string;',\n ' readonly media: VisualMediaAssetFact;',\n ' readonly sourceRange: SequenceRange<number>;',\n ' readonly volume?: number;',\n '}',\n '/** Asset identity, either an old physical-only row or a directly composed media variant. */',\n \"export type ResourceEntityKind = 'image' | 'video' | 'audio' | 'voice';\",\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 SetBgmInput {',\n ' readonly timelineEntityId: string;',\n ' readonly bgmClipEntityId: string;',\n ' readonly media: AudioMediaAssetFact;',\n ' readonly volume: number;',\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 'export interface VideoMediaAssetFact {',\n ' readonly assetId: string;',\n \" readonly kind: 'video';\",\n ' readonly durationMs: number;',\n ' readonly storageKey?: string;',\n '}',\n 'export type VisualMediaAssetFact = ImageMediaAssetFact | VideoMediaAssetFact;',\n 'export interface VoiceDescriptor {',\n \" readonly system: 'voice-library';\",\n ' readonly key: string;',\n ' readonly name?: string;',\n '}',\n 'export interface VoiceMediaAssetFact {',\n ' /** Stable external speech result id, independent of the placed Clip id. */',\n ' readonly assetId: string;',\n \" readonly kind: 'voice';\",\n ' readonly durationMs: number;',\n ' readonly storageKey: string;',\n ' /** Present for synthesized voice, absent for original recorded audio. */',\n ' readonly voice?: VoiceDescriptor;',\n '}',\n 'export interface VoiceoverCaptionFact {',\n ' /** Stable placed caption identity supplied by the materialized side effect. */',\n ' readonly captionClipEntityId: string;',\n ' /** Directly held bases; includes the AudioScript used by the Voice. */',\n ' readonly baseEntityIds: readonly string[];',\n ' /** Ordered selection of AudioScript segments; caption text is never passed inline. */',\n ' readonly selections: readonly CaptionSegmentSelection[];',\n ' readonly startMs: number;',\n ' readonly durationMs: number;',\n ' readonly style?: CaptionStyleFields;',\n '}',\n 'export type VoiceoverTakeInput = {',\n ' readonly timelineEntityId: string;',\n ' /** Stable placed speech identity, distinct from media.assetId. */',\n ' readonly voiceoverClipEntityId: string;',\n ' readonly media: VoiceMediaAssetFact;',\n ' /** Existing pronunciation variant; its composed AudioScript stays the text owner. */',\n ' readonly phoneticScriptEntityId: string;',\n ' readonly volume: number;',\n ' readonly captions: readonly VoiceoverCaptionFact[];',\n '} & (',\n ' | {',\n ' readonly placement: ClipPlacement;',\n ' readonly hostClipEntityId?: never;',\n ' readonly anchorOffset?: never;',\n ' }',\n ' | {',\n ' readonly placement?: never;',\n ' readonly hostClipEntityId: string;',\n ' readonly anchorOffset: number;',\n ' }',\n ');',\n 'export interface VoiceoverTakeResult {',\n ' readonly voiceoverClipEntityId: string;',\n ' readonly voiceEntityId: string;',\n ' /** The pronunciation variant the Voice was rendered from. */',\n ' readonly phoneticScriptEntityId: string;',\n ' /** The base-text owner resolved from the PhoneticScript baseEntityIds. */',\n ' readonly audioScriptEntityId: string;',\n ' readonly captionClipEntityIds: readonly string[];',\n '}',\n '/** Timeline writes accept existing media Entity ids, never Memota asset ids or URLs. */',\n 'export interface EditApi {',\n ' /** Select the document AudioScript, or clear the optional association with null. */',\n ' setDocumentAudioScript(entityId: string | null): void;',\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 ' insertMediaClip(input: InsertMediaClipInput): ClipEntityId;',\n ' insertMediaClips(input: InsertMediaClipsInput): readonly ClipEntityId[];',\n ' replaceMediaClip(input: ReplaceMediaClipInput): void;',\n ' setClipVolume(input: SetClipVolumeInput): void;',\n ' setClipSpeed(input: SetClipSpeedInput): void;',\n ' trimClip(input: TrimClipInput): void;',\n ' replaceSequentialClips(input: ReplaceSequentialClipsInput): readonly ClipEntityId[];',\n ' deleteClip(input: DeleteClipInput): void;',\n ' deleteClipTree(input: DeleteClipTreeInput): void;',\n ' updateClip(input: UpdateClipInput): void;',\n ' upsertVoiceoverTake(input: VoiceoverTakeInput): VoiceoverTakeResult;',\n ' moveVoiceover(input: MoveVoiceoverInput): void;',\n ' moveClipsToStarts(input: MoveClipsToStartsInput): void;',\n ' deleteVoiceover(input: DeleteVoiceoverInput): void;',\n ' setBgm(input: SetBgmInput): ClipEntityId;',\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 '}',\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: EntityFacade;',\n 'export declare const relations: RelationFacade;',\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: initialize missing fixed editor structure, then return the Entity/Relation state summary and opaque base version. Initialization is idempotent and may advance the entity revision once; unchanged snapshots do not write.\n- migrate-legacy: explicitly migrate an existing legacy timeline using recalled asset_facts. MEngine reads the canonical document and version, verifies that editing facts are preserved, and commits migration alone. Then take a fresh snapshot before any edit; never pass a caller-created legacy snapshot or version.\n- run-edit-script: inspect timeline.snapshot(), entities.*, and relations.*; edit.* operates existing Entity ids and creates the required Clip/SequenceMarker structural graph. Asset import, media Entity creation and timeline edits belong in ONE plan. The sandbox has no network, storage or generation access. Pass recalled asset facts through inputs; generation history is not a script input — the host program queries it itself after each commit. A successful run returns preview, logs, base revision and plan_id.\n- commit-plan: commit the complete Entity/Relation plan through revision CAS. The server derives the read-only timeline projection in the same transaction. There is no separate writable timeline plan and no preflight replay into a legacy editor. A failed transport is unconfirmed, never committed; retry the same plan_id.\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. On version mismatch, rerun snapshot and the script; never try to patch a rejected journal by hand.\n\nGenerating an Asset alone does not require an Entity. Using that resource in the editor DOES: recall the Asset facts, call entities.ensureMedia(fact), then pass its contentEntityId to edit.insertClip. A raw external asset id or URL is not valid contentEntityId. Image/Video/Audio/Voice are logical variants of Asset: a resource has ONE identity and ONE typed row owning both media fields and external {system,key}/storageKey, with no separate Asset row or physical-asset relation. ensureMedia returns contentEntityId and reuses that single identity by external asset id. Each placement still gets its own Clip and SequenceMarker. Generation lineage is program-synced: after each successful commit the tool connects existing typed Assets from host-recalled generation facts (endpoint 0 output, endpoint 1 input) that the host queries itself — do not pass generation history through inputs. Do not author generated Relations yourself, and never create an Entity merely to backfill or represent lineage; media variants the edit itself legitimately needs are still created normally. Text-only generation has no input and no lineage edge. 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.\nGeneration lineage is not a model input: the host program queries it via loadGenerationFacts and syncs generated Relations after each successful commit. Memota asset facts are host-provided through inputs. Never invent an asset id, Entity kind, or peer Entity id.\nUse entities.ensureMedia(fact) to get or create the canonical typed Asset. Native media placement helpers use the same resolver. findByAssetId includes directly composed media variants, including Voice. Every Image/Video/Audio/Voice must own its external identity; separate Asset+media graphs are invalid. A typed Asset's external identity cannot be removed or rewritten: to replace its source, ensureMedia for the new Asset and replace the Clip's content. Conflicting facts fail closed. Asset generation itself still creates no editor Entities.\nFor recalled video/audio/voice, create a bounded/native payload whose extent end comes from factual media duration/coordinates in inputs; never fabricate a duration. Image uses unbounded/constant semantics and has no invented end. If required facts are absent, do not create the media Entity yet.\nCaption content is assembled from AudioScript; never create an inline text Asset for it. Generated media lineage is host-owned; do not author generated Relations yourself. relations.of remains endpoint-agnostic for lookup.\nThe compatibility reader 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; 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. The host initializes one Timeline and four fixed Tracks before editing; inspect and reuse their IDs from timeline.snapshot(), never create another Timeline or Track for each operation. If snapshot reports legacy migration is required, recall the listed asset facts and call migrate-legacy first. Missing facts, unsupported layouts, and version conflicts fail closed; never fall back to an old timeline method or raw update endpoint.\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' | 'migrate-legacy' | 'run-edit-script' | 'commit-plan';\n\nconst assetFactProperties = {\n assetId: { type: 'string', minLength: 1 },\n kind: { type: 'string', enum: ['image', 'video', 'audio', 'voice'] },\n durationMs: { type: 'integer', minimum: 1 },\n storageKey: { type: 'string', minLength: 1 },\n voice: {\n type: 'object',\n additionalProperties: false,\n required: ['system', 'key'],\n properties: { system: { const: 'voice-library' }, key: { type: 'string', minLength: 1 }, name: { type: 'string' } },\n },\n} as const;\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', 'migrate-legacy', '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 asset_facts: {\n type: 'array',\n description:\n 'Factual asset metadata recalled by the host for migrate-legacy only. The package reads the canonical legacy snapshot and version itself; never supply a clip trim window as media duration.',\n items: {\n oneOf: [\n {\n type: 'object',\n additionalProperties: false,\n required: ['assetId', 'kind'],\n properties: {\n assetId: assetFactProperties.assetId,\n kind: { const: 'image' },\n storageKey: assetFactProperties.storageKey,\n },\n },\n {\n type: 'object',\n additionalProperties: false,\n required: ['assetId', 'kind', 'durationMs'],\n properties: {\n assetId: assetFactProperties.assetId,\n kind: { const: 'video' },\n durationMs: assetFactProperties.durationMs,\n storageKey: assetFactProperties.storageKey,\n },\n },\n {\n type: 'object',\n additionalProperties: false,\n required: ['assetId', 'kind', 'durationMs', 'storageKey'],\n properties: {\n assetId: assetFactProperties.assetId,\n kind: { const: 'audio' },\n durationMs: assetFactProperties.durationMs,\n storageKey: assetFactProperties.storageKey,\n },\n },\n {\n type: 'object',\n additionalProperties: false,\n required: ['assetId', 'kind', 'durationMs', 'storageKey', 'voice'],\n properties: { ...assetFactProperties, kind: { const: 'voice' } },\n },\n ],\n },\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: ['version'],\n description: 'Commit with Entity revision CAS; reject concurrent changes.',\n },\n },\n oneOf: [\n {\n required: ['op', 'doc_id', 'asset_facts'],\n properties: {\n op: { const: 'migrate-legacy' },\n doc_id: { $ref: '#/properties/doc_id' },\n asset_facts: { $ref: '#/properties/asset_facts' },\n },\n additionalProperties: false,\n },\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 EntityGraphHttpClient,\n ManualSyncDoc,\n migrateLegacyTimelineToEntities,\n MengineHttpClient,\n MengineHttpRequestError,\n toVideoDocument,\n type ManualSyncDocOptions,\n type MediaAssetFact,\n type VideoDocument,\n type VideoDraft,\n} from '@mengine/medeo-client';\n\nimport type { EntityStoreSnapshot } from './entity/entity-contract.ts';\nimport { EntityHttpClient, MengineEntityHttpRequestError } from './entity/entity-http-client.ts';\nimport { EntitySandbox, toDslRows } from './entity/entity-sandbox.ts';\nimport {\n syncGeneratedRelations,\n type GenerationFactsLoader,\n type GenerationSyncOutcome,\n} from './entity/generation-sync.ts';\nimport { parseMigrationAssetFacts } from './migration-input.ts';\nimport { MEDEO_TOOL_DESCRIPTION, renderMedeoModelContext } from './prompt.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 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 | { op: 'migrate-legacy'; doc_id: string; asset_facts: readonly MediaAssetFact[] }\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?: 'version' | 'preflight';\n };\n\nexport type MedeoToolWarning =\n | { kind: 'pull_failed'; message: string }\n | { kind: 'generation_sync_failed'; message: string };\n\nexport type EntityCommitResult =\n | {\n kind: 'committed';\n ops_applied: number;\n collaborated: false;\n entity_revision: number;\n /** Present only when the host supplies loadGenerationFacts. */\n generation_sync?: GenerationSyncOutcome;\n warnings?: MedeoToolWarning[];\n }\n | { kind: 'unconfirmed'; reason: 'push_failed'; ops_applied: number; message: string }\n | {\n kind: 'rejected';\n reason: 'entity_revision_mismatch';\n expected: number;\n actual: number;\n }\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: 'migrate-legacy';\n doc_id: string;\n migration_status: 'committed' | 'already_entity';\n entity_revision: number;\n next_action: 'snapshot';\n }\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(state: EntityStoreSnapshot): string {\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\nfunction migrationNotice(document: VideoDocument, state: EntityStoreSnapshot): string {\n if (\n state.entities.some((row) => row.entity_kind === 'timeline') ||\n Object.keys(document.part_library ?? {}).length === 0\n )\n return '';\n const assetIds = new Set(\n Object.values(document.part_library ?? {}).flatMap((part) => {\n const id = part.video_clip?.origin_media_id ?? part.bgm?.origin_media_id;\n return typeof id === 'string' && id !== '' ? [id] : [];\n }),\n );\n return `\\nLegacy timeline migration required. Recall factual media metadata for ${JSON.stringify([...assetIds])}, then call migrate-legacy with asset_facts. Speech facts are read from the canonical legacy document. Take a fresh snapshot after migration before editing.`;\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 const committed = await client.commit(plan.entity_base_revision, rows, {\n deleted_entity_ids: plan.deleted_entity_ids ?? [],\n deleted_relation_ids: plan.deleted_relation_ids ?? [],\n });\n return {\n kind: 'committed',\n ops_applied: plan.entity_commands.length,\n collaborated: false,\n entity_revision: committed.revision,\n };\n } catch (error) {\n if (error instanceof MengineEntityHttpRequestError) {\n if (error.status === 409 && isRevisionConflictPayload(error.payload)) {\n const actualFromPayload = revisionConflictActual(error.payload);\n try {\n const current = await client.fetchState();\n // A lost POST response is indistinguishable from a retry conflict.\n // Recover only when the one expected revision landed with exactly the\n // authoritative rows this plan submitted.\n if (current.revision === plan.entity_base_revision + 1 && entityRowsEquivalent(current, rows)) {\n return {\n kind: 'committed',\n ops_applied: plan.entity_commands.length,\n collaborated: false,\n entity_revision: current.revision,\n };\n }\n return {\n kind: 'rejected',\n reason: 'entity_revision_mismatch',\n expected: plan.entity_base_revision,\n actual: current.revision,\n };\n } catch {\n if (actualFromPayload !== undefined) {\n return {\n kind: 'rejected',\n reason: 'entity_revision_mismatch',\n expected: plan.entity_base_revision,\n actual: actualFromPayload,\n };\n }\n return {\n kind: 'unconfirmed',\n reason: 'push_failed',\n ops_applied: plan.entity_commands.length,\n message: 'entity-state conflict could not be reconciled',\n };\n }\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 revisionConflictActual(payload: unknown): number | undefined {\n if (!isRecord(payload)) return undefined;\n const actual = payload.actual_revision;\n return typeof actual === 'number' && Number.isSafeInteger(actual) && actual >= 0 ? actual : undefined;\n}\n\nfunction isRevisionConflictPayload(payload: unknown): boolean {\n return isRecord(payload) && payload.code === 'revision_conflict';\n}\n\nfunction entityHttpErrorMessage(payload: unknown): string {\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 entityRowsEquivalent(left: EntityStoreSnapshot, right: EntityStoreSnapshot): boolean {\n const normalize = (state: EntityStoreSnapshot) => ({\n audioScriptEntityId: state.audioScriptEntityId,\n entities: [...state.entities]\n .sort((a, b) => a.entity_id.localeCompare(b.entity_id))\n .map((entity) => canonicalJson(entity)),\n relations: [...state.relations]\n .sort((a, b) => a.relation_id.localeCompare(b.relation_id))\n .map((relation) => canonicalJson(relation)),\n });\n return JSON.stringify(normalize(left)) === JSON.stringify(normalize(right));\n}\n\nfunction canonicalJson(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(canonicalJson);\n if (!isRecord(value)) return value;\n return Object.fromEntries(\n Object.keys(value)\n .sort()\n .map((key) => [key, canonicalJson(value[key])]),\n );\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 === 'migrate-legacy') {\n if (Object.keys(value).some((key) => !['op', 'doc_id', 'asset_facts'].includes(key)))\n throw new Error('migrate-legacy accepts asset_facts only; the package reads the canonical document and version');\n return { op, doc_id: docId, asset_facts: parseMigrationAssetFacts(value.asset_facts) };\n }\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 !== 'version' && value.validation !== 'preflight') {\n throw new Error('validation must be \"version\" or \"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 const seed = createMirrorVideoDocument(document, {\n ...(peerId !== undefined ? { peerId } : {}),\n origin: 'mengine.medeo_tool.bootstrap',\n });\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 client = getEntityClient(docId);\n for (let attempt = 0; attempt < 4; attempt += 1) {\n const state = await client.fetchState();\n // Context reads during an unconfirmed edit must never insert an unrelated CAS revision.\n if (pendingPushes.has(docId)) return state;\n const document = doc.snapshot();\n const hasTimeline = state.entities.some((row) => row.entity_kind === 'timeline');\n const hasLegacyContent =\n Object.keys(document.part_library ?? {}).length > 0 ||\n (document.tracks ?? []).some((track) => (track.items ?? []).length > 0);\n if (!hasTimeline && hasLegacyContent) return state;\n if (!hasTimeline) {\n if (pull.warnings !== undefined)\n throw new Error('Editor initialization requires a fresh canonical snapshot; retry snapshot');\n // Even an empty draft can own configured Track visibility, identities,\n // order and timing. Preserve them through the existing version-guarded\n // migration gate instead of silently cutting over to a blank graph.\n const baseRows = toDslRows(state);\n const migrated = migrateLegacyTimelineToEntities(document, [], baseRows);\n try {\n await getGraphClient(docId).commit(\n { revision: state.revision, audioScriptEntityId: state.audioScriptEntityId, rows: baseRows },\n migrated,\n {\n migrationBaseVv: encodeDocVersionMark(doc.versionMark()),\n },\n );\n } catch (error) {\n if (!(error instanceof MengineHttpRequestError) || error.status !== 409)\n throw new Error(\n `Editor initialization was not confirmed; retry snapshot to reconcile state: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n pull = await observePull(doc);\n continue;\n }\n const sandbox = new EntitySandbox({ state, idFactory: (prefix) => `${prefix}_${randomUUID()}` });\n sandbox.ensureFoundation();\n if (sandbox.commandCount === 0) return state;\n if (pull.warnings !== undefined)\n throw new Error('Editor initialization requires a fresh canonical snapshot; retry snapshot');\n try {\n const committed = await client.commit(state.revision, sandbox.buildPlan().rows);\n // Server projects the new foundation into Loro in the same transaction.\n await doc.pull();\n return committed;\n } catch (error) {\n if (!(error instanceof MengineEntityHttpRequestError) || error.status !== 409) {\n throw new Error(\n `Editor initialization was not confirmed; retry snapshot to reconcile state: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n pull = await observePull(doc);\n }\n }\n throw new Error('Editor initialization conflicted repeatedly; take a fresh snapshot');\n }\n\n function getGraphClient(docId: string): EntityGraphHttpClient {\n return new EntityGraphHttpClient({\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 }\n\n async function commitCachedPlan(\n docId: string,\n _doc: ManualSyncDoc,\n plan: ChangePlan,\n validation?: 'version' | '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 if (validation === 'preflight') {\n throw new Error('Entity plans use revision CAS; validation=preflight is not supported');\n }\n if (plan.entity_rows === undefined) throw new Error('entity plan is missing its authoritative rows');\n const client = getEntityClient(docId);\n // Generation sync scopes the plan's diff against its CAS base. The base is\n // captured when the plan is built and cached with it; the defensive fetch\n // below only covers a caller that lost the cached base, and the commit's\n // revision CAS makes that read the plan base whenever the commit lands.\n const preCommitState =\n baseState ?? (options.loadGenerationFacts !== undefined ? await client.fetchState() : undefined);\n const result = await commitEntityPlan(client, plan);\n return await attachGenerationSync(docId, plan, result, preCommitState);\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) + migrationNotice(doc.snapshot(), entityState),\n collaborated: pull.collaborated,\n ...(pull.warnings !== undefined ? { warnings: pull.warnings } : {}),\n };\n });\n }\n\n async function migrate(input: Extract<MedeoToolInput, { op: 'migrate-legacy' }>): Promise<MedeoToolResult> {\n return runExclusive(input.doc_id, async (doc) => {\n assertNoPendingPush(input.doc_id);\n const client = getGraphClient(input.doc_id);\n const base = await client.fetchState();\n if (base.rows.entities.some((row) => row.entityKind === 'timeline')) {\n return {\n ok: true,\n op: 'migrate-legacy',\n doc_id: input.doc_id,\n migration_status: 'already_entity',\n entity_revision: base.revision,\n next_action: 'snapshot',\n };\n }\n // Migration must not use observePull's deliberately tolerant stale-read mode.\n const pull = await doc.pull();\n if (!pull.ok) throw new Error(`Migration requires a fresh canonical snapshot: ${pull.error.message}`);\n const migrationBaseVv = encodeDocVersionMark(doc.versionMark());\n const nextRows = migrateLegacyTimelineToEntities(doc.snapshot(), input.asset_facts, base.rows);\n let revision: number;\n try {\n revision = (await client.commit(base, nextRows, { migrationBaseVv })).revision;\n } catch (error) {\n if (error instanceof MengineHttpRequestError) {\n throw new Error(\n `Migration rejected (HTTP ${error.status}): ${entityHttpErrorMessage(error.payload)}; take a fresh snapshot before retrying`,\n );\n }\n throw new Error(\n 'Migration submission is unconfirmed; take a fresh snapshot and retry migrate-legacy to inspect whether the Entity timeline already exists',\n );\n }\n // An old plan cannot span the authority cutover. The next call opens the\n // committed canonical projection and reads a new graph revision.\n documents.delete(input.doc_id);\n for (const [id, cached] of plans) if (cached.docId === input.doc_id) plans.delete(id);\n return {\n ok: true,\n op: 'migrate-legacy',\n doc_id: input.doc_id,\n migration_status: 'committed',\n entity_revision: revision,\n next_action: 'snapshot',\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 === 'migrate-legacy') return await migrate(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"],"mappings":";;;;;AA8EA,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,aAAa;CACvC,MAAM,gBAAgB,QAAQ,iBAAiB;CAC/C,MAAM,iBAAiB,QAAQ,kBAAkB,cAAc,cAAc;CAC7E,MAAM,qBAAqB,cAAc,2BAA2B;CAEpE,MAAM,MAAsB,CAAC;CAC7B,MAAM,iBAAkC,CAAC;CACzC,MAAM,OAAiB,CAAC;CAExB,OAAO,IAAI,SAA2B,YAAY;EAChD,IAAI,UAAU;EACd,IAAI,WAAW;EACf,IAAI;EAEJ,MAAM,SAAS,IAAI,OAAO,gBAAgB;GACxC,YAAY;IACV,UAAU,QAAQ;IAClB,QAAQ,QAAQ;IAChB,QAAQ,QAAQ;IAChB,aAAa,QAAQ;IACrB,SAAS,QAAQ;IACjB,YAAY,QAAQ;GACtB;GAKA,UAAU,mBAAmB,SAAS,SAAS,KAAK,IAChD;IACE;IACA;IACA,YAAY,mBAAmB;GACjC,IACA,CAAC;GACL,gBAAgB,EAAE,wBAAwB,cAAc;EAC1D,CAAC;;EAGD,MAAM,mBAAyB;GAC7B,IAAI,WAAW,SAAS,MAAM;GAC9B,QAAQ,iBAAiB;IACvB,WAAW;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AC,SAAS,MAAM,GAAG,KAClB,MAAM,SAAS,KAAA,KAAa,OAAO,MAAM,SAAS,YACnD,OAAO,KAAK,KAAK,EAAE,MAAM,QAAQ,CAAC;GAAC;GAAU;GAAO;EAAM,EAAE,SAAS,GAAG,CAAC,GAEzE,MAAM,IAAI,MAAM,0DAA0D;EAC5E,OAAO;GACL;GACA;GACA;GACA;GACA,OAAO;IAAE,QAAQ;IAAiB,KAAK,MAAM;IAAK,GAAI,MAAM,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,MAAM,KAAK;GAAG;EAC9G;CACF,CAAC;AACH;AAEA,SAAS,OAAO,OAAkD;CAChE,OAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,SAAS,OAAiC;CACjD,OAAO,OAAO,UAAU,YAAY,MAAM,SAAS,KAAK,MAAM,KAAK,MAAM;AAC3E;;;;ACrDA,MAAa,8BAA8B;CACzC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;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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