@mengine/medeo-tool 1.2.1-alpha.7 → 1.2.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.
- package/README.md +49 -16
- package/dist/{entity-contract-B3txrzTt.d.mts → entity-contract-DycLxdQ5.d.mts} +49 -3
- package/dist/index.d.mts +142 -9
- package/dist/index.mjs +756 -906
- package/dist/index.mjs.map +1 -1
- package/dist/sandbox-api.d.mts +397 -818
- package/dist/{script-session-BF44uKv_.mjs → script-session-CHyIUBkO.mjs} +366 -26
- package/dist/script-session-CHyIUBkO.mjs.map +1 -0
- package/dist/worker-entry.d.mts +5 -4
- package/dist/worker-entry.mjs +286 -5
- package/dist/worker-entry.mjs.map +1 -1
- package/package.json +2 -2
- package/dist/script-session-BF44uKv_.mjs.map +0 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["isRecord"],"sources":["../src/sandbox/node-host.ts","../src/entity/entity-contract.ts","../src/entity/entity-http-client.ts","../src/sandbox/generated/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 /** 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 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 },\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 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","export 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\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 | 'phonetic-script-provenance'\n | 'caption-provenance'\n | 'caption-alignment';\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 'phonetic-script-provenance',\n 'caption-provenance',\n 'caption-alignment',\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 interface EntityPayloadByKind {\n axvideo: BoundedDerivedSequencePayload;\n timeline: JsonObject;\n track: JsonObject & { hidden?: boolean; role?: string };\n clip: JsonObject;\n /** Asset-owned metadata. Peer media associations belong in physical-asset Relations. */\n asset: JsonObject;\n video: BoundedNativeSequencePayload;\n audio: BoundedNativeSequencePayload;\n voice: BoundedNativeSequencePayload;\n image: UnboundedConstantSequencePayload;\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 };\n viewport: JsonObject;\n 'audio-script': JsonObject & { segments: ScriptTextSegment[] };\n 'phonetic-script': JsonObject & { segments: ScriptTextSegment[] };\n caption: BoundedNativeSequencePayload;\n}\n\nexport interface SandboxEntity<K extends KnownEntityKind = KnownEntityKind> {\n entity_id: string;\n entity_kind: K;\n payload: EntityPayloadByKind[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: EntityPayloadByKind[K];\n };\n}[KnownEntityKind];\n\nexport interface ImportAssetInput {\n asset_id: string;\n entity_id?: string;\n payload?: JsonObject;\n}\n\nexport type EmptyRelationKind =\n | 'timeline-track'\n | 'track-clip'\n | 'clip-marker'\n | 'marker-content'\n | 'axvideo-marker'\n | 'marker-timeline';\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: 'phonetic-script-provenance' | 'caption-provenance';\n metadata: JsonObject & { segmentAlignment: JsonValue };\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 type EntityCommand =\n | { kind: 'create-entity'; entity: SandboxEntity }\n | { kind: 'link-relation'; relation: SandboxRelation };\n\nexport interface EntityPlanState {\n base_revision: number;\n commands: readonly EntityCommand[];\n rows: EntityStoreSnapshot;\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 list(): SandboxEntity[];\n get(entityId: string): SandboxEntity | null;\n /** Return every explicitly imported Asset entity for a Memota asset id. */\n findByAssetId(assetId: string): SandboxEntity<'asset'>[];\n create(input: CreateEntityInput): string;\n /** Import one physical asset without implying a one-to-one media Entity mapping. */\n importAsset(input: ImportAssetInput): 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 /** For physical-asset use sequence media as endpoint 0 and Asset as endpoint 1. */\n link(input: LinkRelationInput): string;\n /** Author ordered generated(output,input); generic link() deliberately rejects this kind. */\n linkGenerated(input: LinkGeneratedRelationInput): string;\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 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(expectedRevision: number, state: EntityStoreSnapshot): 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 }),\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","/**\n * @generated by gen:sandbox-dts — DO NOT EDIT MANUALLY\n *\n * Runtime copy of the sandbox TypeScript disclosure. The model prompt imports\n * this value so its interface and the checked-in declaration cannot drift.\n */\nexport const EDIT_SANDBOX_API_DTS = [\n '/**',\n ' * @generated by gen:sandbox-dts — DO NOT EDIT MANUALLY',\n ' *',\n ' * Schema version: video-document/v0',\n ' * Semantic ops: 20',\n ' *',\n ' * Boundary: zod `superRefine` / custom refine rules are NOT introspectable and',\n ' * do not appear here. Business mutual-exclusion rules surface via runtime',\n ' * validation errors (L3 feedback channel).',\n ' *',\n ' * @example 读取→计算→批量写',\n ' * ```ts',\n ' * const clips = timeline.clipsInRange(0, 10_000);',\n ' * await edit.setVideoClipSpeedShift({',\n \" * clips: clips.map((c) => ({ clip_id: c.id, speed_shift: { category: 'linear', mode: 'constant', config: { linear: { speed: 1.5 } } } })),\",\n ' * });',\n ' * ```',\n ' *',\n ' * @example anchored 删除',\n ' * ```ts',\n \" * await edit.deleteVideoClips({ clip_ids: ['clip_a'], on_anchored: 'detach' });\",\n ' * ```',\n ' */',\n '',\n '/**',\n \" * A clip's playback-speed fact, the only thing `SetVideoClipSpeedShift` writes.\",\n ' */',\n 'export interface SpeedShift {',\n \" category: 'linear' | 'curve';\",\n ' mode: string;',\n ' config:',\n ' | {',\n ' linear: {',\n ' /**',\n ' * @constraint positive',\n ' */',\n ' speed: number;',\n ' };',\n ' }',\n ' | {',\n ' curve: {',\n ' /**',\n ' * @constraint minLength(2)',\n ' */',\n ' keyframes: {',\n ' /**',\n ' * @constraint min(0)',\n ' * @constraint max(1)',\n ' */',\n ' position: number;',\n ' /**',\n ' * @constraint min(0)',\n ' */',\n ' rate: number;',\n ' /**',\n ' * Bezier tangent handle (x, y)',\n ' */',\n ' in_tangent?: { x: number; y: number };',\n ' /**',\n ' * Bezier tangent handle (x, y)',\n ' */',\n ' out_tangent?: { x: number; y: number };',\n ' }[];',\n ' };',\n ' };',\n '}',\n '',\n '/**',\n ' * TTS voice summary attached to a speech',\n ' */',\n 'export interface Voice {',\n ' /**',\n ' * @constraint minLength(1)',\n ' */',\n ' id: string;',\n ' name: string;',\n '}',\n '',\n '/**',\n ' * A materialized speech-subtree write (speeches + their captions).',\n ' */',\n 'export interface SpeechAssets {',\n ' /**',\n ' * Materialized speech parts to write',\n ' * @constraint minLength(1)',\n ' */',\n ' speeches: {',\n ' /**',\n ' * The speech part ID (= side-effect speech_parts[].id)',\n ' * @constraint minLength(1)',\n ' */',\n ' speech_id: string;',\n ' /**',\n ' * Host video clip part ID the speech anchors to (RFC 02 §4)',\n ' * @constraint minLength(1)',\n ' */',\n ' anchor_part_id: string;',\n ' /**',\n ' * Offset within the host clip (speech.abs = host.abs + offset_ms)',\n ' * @constraint int',\n ' * @constraint min(0)',\n ' */',\n ' offset_ms: number;',\n ' /**',\n ' * @constraint minLength(1)',\n ' */',\n ' audio_storage_key: string;',\n ' /**',\n ' * Duration in milliseconds (> 0)',\n ' * @constraint int',\n ' * @constraint positive',\n ' */',\n ' duration_ms: number;',\n ' audio_script: string;',\n ' /**',\n ' * Volume in decibels (-60.0 to 20.0; 0.0 = original, -60 = mute, +20 = max)',\n ' * @constraint min(-60)',\n ' * @constraint max(20)',\n ' */',\n ' volume: number;',\n ' /**',\n ' * TTS voice summary attached to a speech',\n ' */',\n ' voice: {',\n ' /**',\n ' * @constraint minLength(1)',\n ' */',\n ' id: string;',\n ' name: string;',\n ' };',\n ' /**',\n ' * @constraint minLength(1)',\n ' */',\n ' origin_speech_id: string;',\n ' /**',\n ' * Caption part IDs owned by this speech',\n ' */',\n ' caption_ids: string[];',\n ' }[];',\n ' /**',\n ' * Materialized caption parts owned by the speeches',\n ' */',\n ' captions: {',\n ' /**',\n ' * The caption part ID (= side-effect created_caption_parts[].id)',\n ' * @constraint minLength(1)',\n ' */',\n ' caption_id: string;',\n ' /**',\n ' * The owning speech part ID',\n ' * @constraint minLength(1)',\n ' */',\n ' speech_part_id: string;',\n ' text: string;',\n ' /**',\n ' * Offset within the host speech (caption.abs = speech.abs + start_ms)',\n ' * @constraint int',\n ' * @constraint min(0)',\n ' */',\n ' start_ms: number;',\n ' /**',\n ' * Duration in milliseconds (> 0)',\n ' * @constraint int',\n ' * @constraint positive',\n ' */',\n ' duration_ms: number;',\n ' }[];',\n '}',\n '',\n 'export interface MoveVideoClipsInput {',\n ' /**',\n ' * List of video clips to move to new positions',\n ' * @constraint minLength(1)',\n ' */',\n ' clips: {',\n ' /**',\n ' * The video clip part ID to move',\n ' * @constraint minLength(1)',\n ' */',\n ' clip_id: string;',\n ' /**',\n ' * New absolute start time in milliseconds on the timeline',\n ' * @constraint int',\n ' * @constraint min(0)',\n ' */',\n ' new_start_ms: number;',\n ' /**',\n ' * Target track ID to move the clip to (optional)',\n ' * @constraint minLength(1)',\n ' */',\n ' new_track_id?: string;',\n ' }[];',\n '}',\n '',\n '/**',\n ' * Reorder a set of main-track clips relative to a reference clip.',\n ' */',\n 'export interface MoveVideoClipsByAnchorInput {',\n ' /**',\n ' * Clips to move as one block, keeping their relative order. Need not be contiguous on the track.',\n ' * @constraint minLength(1)',\n ' */',\n ' clip_ids: string[];',\n ' /**',\n ' * Where the moved block lands: before/after a reference clip, or at the head of the track',\n ' */',\n ' anchor:',\n ' | {',\n \" position: 'before';\",\n ' /**',\n ' * The moved block lands immediately before this clip',\n ' * @constraint minLength(1)',\n ' */',\n ' clip_id: string;',\n ' }',\n ' | {',\n \" position: 'after';\",\n ' /**',\n ' * The moved block lands immediately after this clip',\n ' * @constraint minLength(1)',\n ' */',\n ' clip_id: string;',\n ' }',\n \" | { position: 'track_start' };\",\n ' /**',\n ' * What happens to speeches anchored to the moved clips (required — see the policy doc)',\n ' */',\n \" on_anchored: 'follow' | 'keep_absolute';\",\n '}',\n '',\n 'export interface DeleteVideoClipsInput {',\n ' /**',\n ' * List of video clip part IDs to delete from the main track',\n ' * @constraint minLength(1)',\n ' */',\n ' clip_ids: string[];',\n ' /**',\n ' * How to treat anchored children (default cascade)',\n ' */',\n \" on_anchored?: 'cascade' | 'detach';\",\n '}',\n '',\n '/**',\n ' * Add video clips to a track.',\n ' */',\n 'export interface AddVideoClipsInput {',\n ' /**',\n ' * List of video clips to create',\n ' * @constraint minLength(1)',\n ' */',\n ' clips: {',\n ' /**',\n ' * The media asset ID for the video clip',\n ' * @constraint minLength(1)',\n ' */',\n ' media_id: string;',\n ' /**',\n ' * Absolute start time in milliseconds on the timeline',\n ' * @constraint int',\n ' * @constraint min(0)',\n ' */',\n ' start_ms?: number;',\n ' /**',\n \" * The source media's intrinsic full length in ms\",\n ' * @constraint int',\n ' * @constraint positive',\n ' */',\n ' media_duration_ms: number;',\n ' /**',\n ' * Trim window start in the media (default 0)',\n ' * @constraint int',\n ' * @constraint min(0)',\n ' */',\n ' play_in?: number;',\n ' /**',\n ' * Trim window end in the media (default media_duration_ms)',\n ' * @constraint int',\n ' * @constraint positive',\n ' */',\n ' play_out?: number;',\n ' /**',\n ' * Target track ID (optional, defaults to main track)',\n ' * @constraint minLength(1)',\n ' */',\n ' track_id?: string;',\n ' }[];',\n ' /**',\n ' * Insert new clips before this clip ID',\n ' * @constraint minLength(1)',\n ' */',\n ' before_clip_id?: string;',\n ' /**',\n ' * Insert new clips after this clip ID',\n ' * @constraint minLength(1)',\n ' */',\n ' after_clip_id?: string;',\n '}',\n '',\n 'export interface AdjustVideoClipVolumeInput {',\n ' /**',\n ' * List of video clips with their new volume settings',\n ' * @constraint minLength(1)',\n ' */',\n ' clips: {',\n ' /**',\n ' * The video clip part ID to adjust volume for',\n ' * @constraint minLength(1)',\n ' */',\n ' clip_id: string;',\n ' /**',\n ' * Volume in decibels (-60.0 to 20.0; 0.0 = original)',\n ' * @constraint min(-60)',\n ' * @constraint max(20)',\n ' */',\n ' volume: number;',\n ' }[];',\n '}',\n '',\n '/**',\n ' * Set the playback speed of existing video clips.',\n ' */',\n 'export interface SetVideoClipSpeedShiftInput {',\n ' /**',\n ' * Video clips with their new speed settings',\n ' * @constraint minLength(1)',\n ' */',\n ' clips: {',\n ' /**',\n ' * The video clip part ID to set speed for',\n ' * @constraint minLength(1)',\n ' */',\n ' clip_id: string;',\n ' /**',\n ' * The new speed setting, or null to reset to 1×',\n ' */',\n ' speed_shift: {',\n \" category: 'linear' | 'curve';\",\n ' mode: string;',\n ' config:',\n ' | {',\n ' linear: {',\n ' /**',\n ' * @constraint positive',\n ' */',\n ' speed: number;',\n ' };',\n ' }',\n ' | {',\n ' curve: {',\n ' /**',\n ' * @constraint minLength(2)',\n ' */',\n ' keyframes: {',\n ' /**',\n ' * @constraint min(0)',\n ' * @constraint max(1)',\n ' */',\n ' position: number;',\n ' /**',\n ' * @constraint min(0)',\n ' */',\n ' rate: number;',\n ' /**',\n ' * Bezier tangent handle (x, y)',\n ' */',\n ' in_tangent?: { x: number; y: number };',\n ' /**',\n ' * Bezier tangent handle (x, y)',\n ' */',\n ' out_tangent?: { x: number; y: number };',\n ' }[];',\n ' };',\n ' };',\n ' } | null;',\n ' }[];',\n '}',\n '',\n '/**',\n ' * Replace the media backing existing video clips.',\n ' */',\n 'export interface ReplaceVideoClipContentInput {',\n ' /**',\n ' * Video clips whose media is being replaced',\n ' * @constraint minLength(1)',\n ' */',\n ' clips: {',\n ' /**',\n ' * Existing video clip part ID to re-point',\n ' * @constraint minLength(1)',\n ' */',\n ' clip_id: string;',\n ' /**',\n ' * The new media asset ID',\n ' * @constraint minLength(1)',\n ' */',\n ' origin_media_id: string;',\n ' /**',\n \" * The new media's intrinsic full length\",\n ' * @constraint int',\n ' * @constraint positive',\n ' */',\n ' media_duration_ms: number;',\n ' /**',\n ' * Trim window start in the new media (usually 0)',\n ' * @constraint int',\n ' * @constraint min(0)',\n ' */',\n ' play_in: number;',\n ' /**',\n ' * Trim window end in the new media (usually = media_duration_ms)',\n ' * @constraint int',\n ' * @constraint positive',\n ' */',\n ' play_out: number;',\n ' /**',\n ' * Volume in decibels (-60.0 to 20.0; 0.0 = original, -60 = mute, +20 = max)',\n ' * @constraint min(-60)',\n ' * @constraint max(20)',\n ' */',\n ' volume: number;',\n ' }[];',\n '}',\n '',\n '/**',\n ' * Replace a contiguous run of main-track clips with a new run.',\n ' */',\n 'export interface ReplaceVideoClipSequenceInput {',\n ' /**',\n ' * The clips being replaced: a contiguous main-track run, listed in timeline order',\n ' * @constraint minLength(1)',\n ' */',\n ' old_clip_ids: string[];',\n ' /**',\n ' * The replacement clips, in the order they take on the track',\n ' * @constraint minLength(1)',\n ' */',\n ' new_clips: {',\n ' /**',\n ' * The replacement media asset ID. Omit to create an empty placeholder clip.',\n ' * @constraint minLength(1)',\n ' */',\n ' media_id?: string;',\n ' /**',\n \" * The source media's intrinsic full length in ms\",\n ' * @constraint int',\n ' * @constraint positive',\n ' */',\n ' media_duration_ms: number;',\n ' /**',\n ' * Trim window start in the media (default 0)',\n ' * @constraint int',\n ' * @constraint min(0)',\n ' */',\n ' play_in?: number;',\n ' /**',\n ' * Trim window end in the media (default media_duration_ms)',\n ' * @constraint int',\n ' * @constraint positive',\n ' */',\n ' play_out?: number;',\n ' }[];',\n ' /**',\n ' * What happens to speeches anchored to the replaced clips (required — see the policy doc)',\n ' */',\n \" on_anchored: 'remap' | 'cascade';\",\n '}',\n '',\n '/**',\n ' * Re-trim existing video clips (the user-facing \"adjust duration\" gesture is a trim of the source window).',\n ' */',\n 'export interface AdjustVideoClipDurationInput {',\n ' /**',\n ' * Video clips with their new trim windows',\n ' * @constraint minLength(1)',\n ' */',\n ' clips: {',\n ' /**',\n ' * The video clip part ID to re-trim',\n ' * @constraint minLength(1)',\n ' */',\n ' clip_id: string;',\n ' /**',\n ' * New trim window start in the source media',\n ' * @constraint int',\n ' * @constraint min(0)',\n ' */',\n ' play_in: number;',\n ' /**',\n ' * New trim window end in the source media',\n ' * @constraint int',\n ' * @constraint positive',\n ' */',\n ' play_out: number;',\n ' }[];',\n '}',\n '',\n '/**',\n ' * Add speeches (and their captions).',\n ' */',\n 'export interface AddSpeechesInput extends SpeechAssets {}',\n '',\n '/**',\n ' * Delete speeches with their captions.',\n ' */',\n 'export interface DeleteSpeechesInput {',\n ' /**',\n ' * Speech part IDs to delete (their captions cascade-delete)',\n ' * @constraint minLength(1)',\n ' */',\n ' speech_ids: string[];',\n '}',\n '',\n '/**',\n ' * Move speeches in time.',\n ' */',\n 'export interface MoveSpeechesInput {',\n ' /**',\n ' * Speeches to move to new positions',\n ' * @constraint minLength(1)',\n ' */',\n ' speeches: {',\n ' /**',\n ' * The speech part ID to move',\n ' * @constraint minLength(1)',\n ' */',\n ' speech_id: string;',\n ' /**',\n ' * New absolute start time on the timeline',\n ' * @constraint int',\n ' * @constraint min(0)',\n ' */',\n ' new_start_ms: number;',\n ' }[];',\n '}',\n '',\n '/**',\n \" * Change a speech's script or voice.\",\n ' */',\n 'export interface ChangeSpeechScriptInput extends SpeechAssets {}',\n '',\n 'export interface ChangeSpeechVoiceInput extends SpeechAssets {}',\n '',\n 'export interface AdjustSpeechVolumeInput {',\n ' /**',\n ' * List of speeches with their new volume settings',\n ' * @constraint minLength(1)',\n ' */',\n ' speeches: {',\n ' /**',\n ' * The speech part ID to adjust volume for',\n ' * @constraint minLength(1)',\n ' */',\n ' speech_id: string;',\n ' /**',\n ' * Volume in decibels (-60.0 to 20.0; 0.0 = original)',\n ' * @constraint min(-60)',\n ' * @constraint max(20)',\n ' */',\n ' volume: number;',\n ' }[];',\n '}',\n '',\n '/**',\n \" * Toggle caption visibility (the caption track's `is_hidden` flag).\",\n ' */',\n 'export interface SetCaptionVisibilityInput {',\n ' /**',\n ' * Whether the caption track is hidden',\n ' */',\n ' is_hidden: boolean;',\n '}',\n '',\n '/**',\n ' * Set the caption visual style.',\n ' */',\n 'export interface SetCaptionStyleInput {',\n ' /**',\n ' * Font ID referencing a font from the font library',\n ' * @constraint minLength(1)',\n ' */',\n ' font_id?: string;',\n ' /**',\n ' * Font size in points',\n ' * @constraint positive',\n ' */',\n ' font_size?: number;',\n ' /**',\n ' * Font color as hex string, e.g. \"#FFFFFF\"',\n ' * @constraint minLength(1)',\n ' */',\n ' font_color?: string;',\n ' /**',\n ' * Numeric font weight, e.g. 400 or 700',\n ' * @constraint int',\n ' */',\n ' font_weight?: number;',\n ' /**',\n ' * Entrance animation preset ID, e.g. \"fade\" or \"none\"',\n ' */',\n ' entrance_animation?: string;',\n ' /**',\n ' * Entrance animation duration in ms',\n ' * @constraint min(0)',\n ' */',\n ' entrance_animation_duration_ms?: number;',\n ' /**',\n ' * Outline/stroke color as hex string, e.g. \"#000000\"',\n ' * @constraint minLength(1)',\n ' */',\n ' stroke_color?: string;',\n ' /**',\n ' * Outline/stroke width in pixels',\n ' * @constraint min(0)',\n ' */',\n ' stroke_width?: number;',\n ' /**',\n ' * Caption center X as a fraction (0.0 to 1.0)',\n ' */',\n ' position_x?: number;',\n ' /**',\n ' * Caption center Y as a fraction (0.0 to 1.0)',\n ' */',\n ' position_y?: number;',\n '}',\n '',\n '/**',\n ' * Set the document BGM.',\n ' */',\n 'export interface SetBgmInput {',\n ' /**',\n ' * The bgm part ID to write',\n ' * @constraint minLength(1)',\n ' */',\n ' bgm_id: string;',\n ' /**',\n ' * @constraint minLength(1)',\n ' */',\n ' audio_storage_key: string;',\n ' /**',\n ' * The media asset ID',\n ' * @constraint minLength(1)',\n ' */',\n ' origin_media_id: string;',\n ' /**',\n ' * Volume in decibels (-60.0 to 20.0; 0.0 = original, -60 = mute, +20 = max)',\n ' * @constraint min(-60)',\n ' * @constraint max(20)',\n ' */',\n ' volume: number;',\n '}',\n '',\n '/**',\n ' * Remove the document BGM.',\n ' */',\n 'export interface DeleteBgmInput {',\n ' [key: string]: never;',\n '}',\n '',\n 'export interface AdjustBgmVolumeInput {',\n ' /**',\n ' * List of bgm parts with their new volume settings',\n ' * @constraint minLength(1)',\n ' */',\n ' bgm: {',\n ' /**',\n ' * The bgm part ID to adjust volume for',\n ' * @constraint minLength(1)',\n ' */',\n ' bgm_id: string;',\n ' /**',\n ' * Volume in decibels (-60.0 to 20.0; 0.0 = original)',\n ' * @constraint min(-60)',\n ' * @constraint max(20)',\n ' */',\n ' volume: number;',\n ' }[];',\n '}',\n '',\n '/** Agent write surface — one method per SemanticOp kind. */',\n 'export interface EditApi {',\n ' moveVideoClips(input: MoveVideoClipsInput): Promise<void>;',\n ' /** Reorder a set of main-track clips relative to a reference clip. */',\n ' moveVideoClipsByAnchor(input: MoveVideoClipsByAnchorInput): Promise<void>;',\n ' deleteVideoClips(input: DeleteVideoClipsInput): Promise<void>;',\n ' /** Add video clips to a track. */',\n ' addVideoClips(input: AddVideoClipsInput): Promise<void>;',\n ' adjustVideoClipVolume(input: AdjustVideoClipVolumeInput): Promise<void>;',\n ' /** Set the playback speed of existing video clips. */',\n ' setVideoClipSpeedShift(input: SetVideoClipSpeedShiftInput): Promise<void>;',\n ' /** Replace the media backing existing video clips. */',\n ' replaceVideoClipContent(input: ReplaceVideoClipContentInput): Promise<void>;',\n ' /** Replace a contiguous run of main-track clips with a new run. */',\n ' replaceVideoClipSequence(input: ReplaceVideoClipSequenceInput): Promise<void>;',\n ' /** Re-trim existing video clips (the user-facing \"adjust duration\" gesture is a trim of the source window). */',\n ' adjustVideoClipDuration(input: AdjustVideoClipDurationInput): Promise<void>;',\n ' /** Add speeches (and their captions). */',\n ' addSpeeches(input: AddSpeechesInput): Promise<void>;',\n ' /** Delete speeches with their captions. */',\n ' deleteSpeeches(input: DeleteSpeechesInput): Promise<void>;',\n ' /** Move speeches in time. */',\n ' moveSpeeches(input: MoveSpeechesInput): Promise<void>;',\n \" /** Change a speech's script or voice. */\",\n ' changeSpeechScript(input: ChangeSpeechScriptInput): Promise<void>;',\n ' changeSpeechVoice(input: ChangeSpeechVoiceInput): Promise<void>;',\n ' adjustSpeechVolume(input: AdjustSpeechVolumeInput): Promise<void>;',\n \" /** Toggle caption visibility (the caption track's `is_hidden` flag). */\",\n ' setCaptionVisibility(input: SetCaptionVisibilityInput): Promise<void>;',\n ' /** Set the caption visual style. */',\n ' setCaptionStyle(input: SetCaptionStyleInput): Promise<void>;',\n ' /** Set the document BGM. */',\n ' setBgm(input: SetBgmInput): Promise<void>;',\n ' /** Remove the document BGM. */',\n ' deleteBgm(input: DeleteBgmInput): Promise<void>;',\n ' adjustBgmVolume(input: AdjustBgmVolumeInput): Promise<void>;',\n '}',\n '',\n 'export type JsonPrimitive = string | number | boolean | null;',\n 'export type JsonValue = JsonPrimitive | JsonObject | JsonValue[];',\n 'export interface JsonObject {',\n ' [key: string]: JsonValue;',\n '}',\n '',\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 '',\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 \" | 'phonetic-script-provenance'\",\n \" | 'caption-provenance'\",\n \" | 'caption-alignment';\",\n '',\n 'export interface BoundedNativeSequencePayload extends JsonObject {',\n ' /** Use factual recalled coordinates; never invent an end or duration. */',\n \" extent: { kind: 'bounded'; start: number; end: number };\",\n \" sampling: 'native';\",\n ' coordinateSpace: JsonValue;',\n '}',\n 'export interface UnboundedConstantSequencePayload extends JsonObject {',\n \" extent: { kind: 'unbounded'; start: number };\",\n \" sampling: 'constant';\",\n ' coordinateSpace: JsonValue;',\n '}',\n 'export interface BoundedDerivedSequencePayload extends JsonObject {',\n \" extent: { kind: 'bounded'; start: number; end: number };\",\n \" sampling: 'derived';\",\n ' coordinateSpace: JsonValue;',\n '}',\n 'export type ScriptTextSegment = JsonObject & {',\n ' segmentId: string;',\n ' text: string;',\n ' language?: string;',\n '};',\n '',\n 'export interface EntityPayloadByKind {',\n ' axvideo: BoundedDerivedSequencePayload;',\n ' timeline: JsonObject;',\n ' track: JsonObject & { hidden?: boolean; role?: string };',\n ' clip: JsonObject;',\n ' asset: JsonObject;',\n ' video: BoundedNativeSequencePayload;',\n ' audio: BoundedNativeSequencePayload;',\n ' voice: BoundedNativeSequencePayload;',\n ' image: UnboundedConstantSequencePayload;',\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 ' };',\n ' viewport: JsonObject;',\n \" 'audio-script': JsonObject & { segments: ScriptTextSegment[] };\",\n \" 'phonetic-script': JsonObject & { segments: ScriptTextSegment[] };\",\n ' caption: BoundedNativeSequencePayload;',\n '}',\n '',\n 'export type CreateEntityInput = {',\n ' [K in KnownEntityKind]: {',\n ' entity_id?: string;',\n ' entity_kind: K;',\n ' payload: EntityPayloadByKind[K];',\n ' };',\n '}[KnownEntityKind];',\n '',\n 'export interface ImportAssetInput {',\n ' asset_id: string;',\n ' entity_id?: string;',\n ' payload?: JsonObject;',\n '}',\n '',\n 'export interface SandboxEntity<K extends KnownEntityKind = KnownEntityKind> {',\n ' entity_id: string;',\n ' entity_kind: K;',\n ' payload: EntityPayloadByKind[K];',\n '}',\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 '',\n 'export type EmptyRelationKind =',\n \" | 'timeline-track'\",\n \" | 'track-clip'\",\n \" | 'clip-marker'\",\n \" | 'marker-content'\",\n \" | 'axvideo-marker'\",\n \" | 'marker-timeline';\",\n 'export type LinkRelationInput =',\n ' | {',\n ' relation_id?: string;',\n ' relation_kind: EmptyRelationKind;',\n ' endpoint_0_entity_id: string;',\n ' endpoint_1_entity_id: string;',\n ' metadata?: { [key: string]: never };',\n ' trace?: JsonObject;',\n ' }',\n ' | {',\n ' relation_id?: string;',\n \" relation_kind: 'physical-asset';\",\n ' /** Canonical endpoint 0 is sequence media; endpoint 1 is Asset. */',\n ' endpoint_0_entity_id: string;',\n ' endpoint_1_entity_id: string;',\n ' metadata?: JsonObject;',\n ' trace?: JsonObject;',\n ' }',\n ' | {',\n ' relation_id?: string;',\n \" relation_kind: 'phonetic-script-provenance' | 'caption-provenance';\",\n ' endpoint_0_entity_id: string;',\n ' endpoint_1_entity_id: string;',\n ' metadata: JsonObject & { segmentAlignment: JsonValue };',\n ' trace?: JsonObject;',\n ' }',\n ' | {',\n ' relation_id?: string;',\n \" relation_kind: 'caption-alignment';\",\n ' endpoint_0_entity_id: string;',\n ' endpoint_1_entity_id: string;',\n ' metadata: JsonObject & { alignment: JsonValue };',\n ' trace?: JsonObject;',\n ' };',\n '',\n 'export interface LinkGeneratedRelationInput {',\n ' relation_id?: string;',\n ' /** Generated output media Entity; persisted as endpoint 0. */',\n ' output_entity_id: string;',\n ' /** Input media Entity used to generate the output; persisted as endpoint 1. */',\n ' input_entity_id: string;',\n ' trace?: JsonObject;',\n '}',\n '',\n '/** Explicit Entity authoring. Assets and media Entities are not one-to-one. */',\n 'export interface EntityApi {',\n ' list(): SandboxEntity[];',\n ' get(entityId: string): SandboxEntity | null;',\n ' /** Call before importAsset; inspect every match and decide whether to reuse one. */',\n \" findByAssetId(assetId: string): SandboxEntity<'asset'>[];\",\n ' create(input: CreateEntityInput): string;',\n ' /** Create only an Asset Entity when no existing match should be reused; this does not infer media. */',\n ' importAsset(input: ImportAssetInput): string;',\n '}',\n '',\n '/** Incident reads ignore endpoint position; relation semantics preserve it. */',\n 'export interface RelationApi {',\n ' list(): SandboxRelation[];',\n ' of(entityId: string, relationKind?: KnownRelationKind): SandboxRelation[];',\n ' link(input: LinkRelationInput): string;',\n ' /** Author ordered generated(output,input). */',\n ' linkGenerated(input: LinkGeneratedRelationInput): string;',\n '}',\n '',\n '/** Clip hit from `clipsInRange`. */',\n 'export interface TimelineClipDescriptor {',\n ' id: string;',\n ' start_ms: number;',\n ' end_ms: number;',\n ' duration_ms: number;',\n ' speed_shift: unknown;',\n ' volume: number | undefined;',\n ' media_id: string | undefined;',\n '}',\n '',\n '/** Part descriptor from `part(id)`. */',\n 'export interface TimelinePartDescriptor {',\n ' id: string;',\n ' kind: string;',\n ' lane: string;',\n ' start_ms: number;',\n ' end_ms: number;',\n ' duration_ms: number;',\n ' part: unknown;',\n '}',\n '',\n '/** Opaque VideoDraft projection (full IDL lives in host document types). */',\n 'export type VideoDraftProjection = {',\n ' readonly timeline?: { readonly duration_ms?: number };',\n ' readonly [key: string]: unknown;',\n '};',\n '',\n '/** Agent read surface over the forked document. */',\n 'export interface TimelineApi {',\n ' /** Snapshot the current VideoDraft projection. */',\n ' snapshot(): VideoDraftProjection;',\n ' /** Clips whose midpoint falls in `[startMs, endMs)`. */',\n ' clipsInRange(startMs: number, endMs: number): TimelineClipDescriptor[];',\n ' /** Look up a part by id, or null if missing. */',\n ' part(id: string): TimelinePartDescriptor | null;',\n '}',\n '',\n '/** Opaque checkpoint handle for rollback. */',\n 'export interface SandboxCheckpoint {',\n ' readonly index: number;',\n '}',\n '',\n 'export declare const edit: EditApi;',\n 'export declare const timeline: TimelineApi;',\n 'export declare const entities: EntityApi;',\n 'export declare const relations: RelationApi;',\n '',\n '/** Capture a rollback point. */',\n 'export declare function checkpoint(): SandboxCheckpoint;',\n '/** Roll the sandbox document back to a prior checkpoint. */',\n 'export declare function rollbackTo(cp: SandboxCheckpoint): void;',\n '/** Host-injected, pre-materialized facts. Validate each field before use. */',\n 'export declare const inputs: Readonly<Record<string, unknown>>;',\n '',\n].join('\\n');\n","import { EDIT_SANDBOX_API_DTS } from './sandbox/generated/edit-sandbox-model-context.ts';\n\nexport const MEDEO_TOOL_DESCRIPTION = `\nEdit a Medeo video document and its explicit Entity/Relation state through a deterministic, side-effect-free JavaScript sandbox.\n\nOperations:\n- snapshot: return the compact timeline projection and opaque base version.\n- run-edit-script: execute JavaScript against forked timeline and Entity/Relation snapshots. Inspect timeline.*, entities.*, and relations.*; call edit.* for timeline mutations or the explicit entity APIs for domain mutations. The sandbox has no network, storage, clock, or generation access. Pass recalled generation/asset facts through inputs. A successful run returns preview, logs, plan_kind, base versions, and plan_id — not the full journals.\n- commit-plan: commit a cached plan_id. Timeline plans replay into ManualSyncDoc and push one causally complete update; Entity plans replace the authoritative row set through revision CAS. validation=preflight is timeline-only. 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\nOne plan must mutate exactly one store: timeline or Entity/Relation state. If both are needed, author and commit two separate plans. There is no automatic Asset→Entity projection: select the relevant recalled fact, explicitly import an Asset if useful, explicitly create only known typed Entities, and author relations. Asset and media Entity identity are not one-to-one. relations.linkGenerated({ output_entity_id, input_entity_id }) means generated(output,input); incident lookup with 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.\nUse timeline.snapshot() for the whole draft projection. Its duration is timeline.snapshot().timeline?.duration_ms; there is no top-level duration_ms.\nGeneration lineage and Memota asset facts are host-provided through inputs. Never invent an asset id, Entity kind, or peer Entity id.\nBefore importing an Asset, call entities.findByAssetId(assetId), inspect every match, and decide whether an existing Entity represents the intended logical asset. Multiple matches are valid; do not assume Asset↔media is one-to-one.\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.\nFor physical-asset authoring, use sequence media as endpoint_0_entity_id and Asset as endpoint_1_entity_id. For generated lineage, use linkGenerated so endpoint 0 is output and endpoint 1 is input. relations.of remains endpoint-agnostic for lookup.\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${EDIT_SANDBOX_API_DTS}\n\\`\\`\\`\n`.trim();\n}\n","export const MEDEO_TOOL_NAME = 'medeo';\n\nexport type MedeoToolOp = 'snapshot' | 'run-edit-script' | 'commit-plan';\n\n/**\n * JSON Schema for the host-facing three-op `medeo` tool surface.\n *\n * The schema intentionally does not return or accept the full op journal:\n * journals stay in the tool process and are referenced by `plan_id`. This keeps\n * large intermediate products out of model context while preserving the exact\n * journal used for commit.\n */\nexport const MEDEO_TOOL_PARAMETERS = {\n type: 'object',\n required: ['op', 'doc_id'],\n additionalProperties: false,\n properties: {\n op: {\n type: 'string',\n enum: ['snapshot', 'run-edit-script', 'commit-plan'],\n description: 'Which Medeo document operation to run.',\n },\n doc_id: {\n type: 'string',\n minLength: 1,\n description: 'Medeo document id. Copy it from the host context; never invent it.',\n },\n script: {\n type: 'string',\n minLength: 1,\n description:\n 'JavaScript body for run-edit-script. It receives edit, timeline, entities, relations, checkpoint, rollbackTo, inputs, and console. A plan may mutate the timeline or Entity/Relation state, never both.',\n },\n inputs: {\n type: 'object',\n description:\n 'Pre-materialized, side-effect-free values passed into the script, including recalled generation lineage and asset facts. Generation and network IO must happen in the host before this call.',\n },\n timeout_ms: {\n type: 'integer',\n minimum: 1,\n description: 'Maximum script wall-clock time after worker startup (default 2000).',\n },\n memory_limit_mb: {\n type: 'integer',\n minimum: 16,\n description: 'Worker old-generation memory ceiling in MB (default 256).',\n },\n auto_commit: {\n type: 'boolean',\n description:\n 'Commit the returned plan immediately after the sandbox succeeds. Default false: return preview plus plan_id for explicit commit.',\n },\n plan_id: {\n type: 'string',\n minLength: 1,\n description: 'Plan id returned by run-edit-script; required by commit-plan.',\n },\n validation: {\n type: 'string',\n enum: ['version', 'preflight'],\n description:\n 'Timeline commit mode: version rejects any concurrent change; preflight revalidates each op. Entity plans always use revision CAS and reject preflight.',\n },\n },\n oneOf: [\n {\n required: ['op', 'doc_id'],\n properties: {\n op: { const: 'snapshot' },\n doc_id: { $ref: '#/properties/doc_id' },\n },\n additionalProperties: false,\n },\n {\n required: ['op', 'doc_id', 'script'],\n properties: {\n op: { const: 'run-edit-script' },\n doc_id: { $ref: '#/properties/doc_id' },\n script: { $ref: '#/properties/script' },\n inputs: { $ref: '#/properties/inputs' },\n timeout_ms: { $ref: '#/properties/timeout_ms' },\n memory_limit_mb: { $ref: '#/properties/memory_limit_mb' },\n auto_commit: { $ref: '#/properties/auto_commit' },\n },\n additionalProperties: false,\n },\n {\n required: ['op', 'doc_id', 'plan_id'],\n properties: {\n op: { const: 'commit-plan' },\n doc_id: { $ref: '#/properties/doc_id' },\n plan_id: { $ref: '#/properties/plan_id' },\n validation: { $ref: '#/properties/validation' },\n },\n additionalProperties: false,\n },\n ],\n} as const;\n","import {\n createPlainMemoryAdapter,\n decodeDocVersionMark,\n encodeDocVersionMark,\n replayJournal,\n ValidationError,\n type JournalEntry,\n type ManualSyncDoc,\n type SemanticOpName,\n} from '@mengine/medeo-client';\n\n/**\n * A sandbox journal plus the opaque version token taken at fork time.\n * `commitPlan` rejects the whole plan when the live document has moved on\n * (phase-1 version gate), or localizes a business conflict to a journal\n * entry under `{ validation: 'preflight' }`.\n */\nexport interface CommitPlan {\n /** Encoded `ManualSyncDoc.versionMark()` from when the sandbox was forked. */\n base_version: string;\n ops: readonly JournalEntry[];\n}\n\nexport interface CommitPlanWarning {\n kind: 'pull_failed';\n message: string;\n}\n\nexport type CommitPlanResult =\n | {\n kind: 'committed';\n ops_applied: number;\n collaborated: boolean;\n warnings?: CommitPlanWarning[];\n }\n | { kind: 'unconfirmed'; reason: 'push_failed'; ops_applied: number; message: string }\n | { kind: 'rejected'; reason: 'version_mismatch'; expected: string; actual: string }\n | { kind: 'rejected'; reason: 'push_rejected'; code?: string; message: string }\n | {\n kind: 'rejected';\n reason: 'op_conflict';\n /** Failing entry index in the journal — agent rerun anchor. */\n index: number;\n op_kind: SemanticOpName;\n /** Validator message, passed through verbatim (never a raw Error). */\n message: string;\n };\n\nexport interface CommitPlanOptions {\n /** `'version'` (default, phase-1 hard gate) | `'preflight'` (phase-2 per-op revalidation). */\n validation?: 'version' | 'preflight';\n}\n\n/**\n * Replay a sandbox journal into a manually-synchronized document and push the\n * whole plan as one causally complete update.\n *\n * - Default / `{ validation: 'version' }`: if the current document mark differs\n * from `plan.base_version`, reject with zero writes.\n * - `{ validation: 'preflight' }`: skip the version gate; revalidate each op\n * against a PlainMemoryAdapter seeded from the current live snapshot, then\n * replay for real. A SchemaValidator failure becomes `op_conflict` with the\n * failing entry's index. Journal integrity errors (unrecorded/unconsumed\n * ids) still propagate as throws in both modes.\n */\nexport async function commitPlan(\n doc: ManualSyncDoc,\n plan: CommitPlan,\n options?: CommitPlanOptions,\n): Promise<CommitPlanResult> {\n if (options?.validation === 'preflight') {\n return commitPlanPreflight(doc, plan);\n }\n\n const actual = encodeDocVersionMark(doc.versionMark());\n const expected = decodeDocVersionMark(plan.base_version);\n if (expected == null || doc.hasChangedSince(expected)) {\n return {\n kind: 'rejected',\n reason: 'version_mismatch',\n expected: plan.base_version,\n actual,\n };\n }\n\n await doc.replayJournal(plan.ops);\n return retryPlanPush(doc, plan.ops.length);\n}\n\n/**\n * Phase-2 path: scratch revalidation then real replay. Each entry is driven\n * through `replayJournal` alone so a ValidationError maps to a stable index;\n * integrity throws are not wrapped.\n */\nasync function commitPlanPreflight(doc: ManualSyncDoc, plan: CommitPlan): Promise<CommitPlanResult> {\n const scratch = createPlainMemoryAdapter(doc.snapshot());\n\n for (let index = 0; index < plan.ops.length; index++) {\n const entry = plan.ops[index];\n if (entry == null) continue;\n try {\n await replayJournal(scratch, [entry]);\n } catch (error) {\n if (error instanceof ValidationError) {\n return opConflict(index, entry.kind, error.message);\n }\n throw error;\n }\n }\n\n // Real replay: optimistic window may still collide; wrap ValidationError the\n // same way. Prior entries in this loop have already been written.\n for (let index = 0; index < plan.ops.length; index++) {\n const entry = plan.ops[index];\n if (entry == null) continue;\n try {\n await doc.replayJournal([entry]);\n } catch (error) {\n if (error instanceof ValidationError) {\n return opConflict(index, entry.kind, `real replay: ${error.message}`);\n }\n throw error;\n }\n }\n\n return retryPlanPush(doc, plan.ops.length);\n}\n\n/** Push an already-replayed plan again without replaying or re-running its version gate. */\nexport async function retryPlanPush(doc: ManualSyncDoc, opsApplied: number): Promise<CommitPlanResult> {\n const result = await doc.push();\n if (result.kind === 'ack' || result.kind === 'duplicate' || result.kind === 'nothing_to_push') {\n // A push can reveal that another peer wrote concurrently. Pull after the\n // durable verdict so the cached document does not serve a stale snapshot on\n // the next tool call; a pull failure cannot undo the acknowledged write.\n const reconciled = result.collaborated ? await doc.pull() : undefined;\n const warnings =\n reconciled != null && !reconciled.ok\n ? [{ kind: 'pull_failed' as const, message: reconciled.error.message }]\n : undefined;\n return {\n kind: 'committed',\n ops_applied: opsApplied,\n collaborated: result.collaborated,\n ...(warnings !== undefined ? { warnings } : {}),\n };\n }\n if (result.kind === 'rejected') {\n return {\n kind: 'rejected',\n reason: 'push_rejected',\n ...(result.code !== undefined ? { code: result.code } : {}),\n message: result.error?.message ?? 'mengine rejected the sandbox plan',\n };\n }\n return {\n kind: 'unconfirmed',\n reason: 'push_failed',\n ops_applied: opsApplied,\n message: result.error?.message ?? 'mengine push failed',\n };\n}\n\nfunction opConflict(index: number, op_kind: SemanticOpName, message: string): CommitPlanResult {\n return { kind: 'rejected', reason: 'op_conflict', index, op_kind, message };\n}\n","import { randomUUID } from 'node:crypto';\n\nimport {\n createMirrorVideoDocument,\n encodeDocVersionMark,\n ManualSyncDoc,\n MengineHttpClient,\n MengineHttpRequestError,\n toVideoDocument,\n type ManualSyncDocOptions,\n type VideoDocument,\n type VideoDraft,\n} from '@mengine/medeo-client';\n\nimport { renderCompactProjection } from './document/compact-projection.ts';\nimport type { EntityStoreSnapshot } from './entity/entity-contract.ts';\nimport { EntityHttpClient, MengineEntityHttpRequestError } from './entity/entity-http-client.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 { commitPlan, retryPlanPush, type CommitPlanOptions, 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 fetchImpl?: typeof fetch;\n /** @deprecated ManualSyncDoc has no SSE or reconnect loop. */\n sseReconnectDelayMs?: number;\n /** Defaults passed to runEditScript; each call may override them. */\n sandbox?: { timeoutMs?: number; memoryLimitMb?: number };\n /** Maximum cached plans; oldest plans are evicted (default 16). */\n maxPlans?: number;\n /** Maximum model-call version baselines retained across host contexts (default 128). */\n maxModelContexts?: number;\n}\n\nexport interface MedeoModelContextInput {\n /** Internal MEngine document id. This is host-supplied and never model-facing. */\n doc_id: string;\n /** Stable host conversation/session key used to compare consecutive model calls. */\n context_id: string;\n}\n\nexport interface MedeoModelContext {\n /** Complete MEngine-owned prompt: workflow, runtime state, and sandbox TypeScript interface. */\n prompt: string;\n document_version: string;\n updated_since_previous_model_call: boolean | null;\n}\n\nexport type MedeoToolInput =\n | { op: 'snapshot'; doc_id: string }\n | {\n op: 'run-edit-script';\n doc_id: string;\n script: string;\n inputs?: Record<string, unknown>;\n timeout_ms?: number;\n memory_limit_mb?: number;\n auto_commit?: boolean;\n }\n | {\n op: 'commit-plan';\n doc_id: string;\n plan_id: string;\n validation?: 'version' | 'preflight';\n };\n\nexport interface MedeoToolWarning {\n kind: 'pull_failed';\n message: string;\n}\n\nexport type EntityCommitResult =\n | {\n kind: 'committed';\n ops_applied: number;\n collaborated: false;\n entity_revision: number;\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: '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}\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}\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\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 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) {\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 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 === '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): string {\n const planId = randomUUID();\n plans.set(planId, { docId, plan });\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(docId: string, planId: string, plan: ChangePlan, result: MedeoCommitResult): 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 },\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(docId: string): Promise<EntityStoreSnapshot> {\n try {\n return await getEntityClient(docId).fetchState();\n } catch (error) {\n // Keep timeline-only edits compatible during a rolling deploy where the\n // document endpoint exists before the new entity-state route. Any entity\n // commit still fails explicitly against that route.\n if (error instanceof MengineEntityHttpRequestError && error.status === 404) {\n return { revision: 0, entities: [], relations: [] };\n }\n throw error;\n }\n }\n\n async function commitCachedPlan(\n docId: string,\n doc: ManualSyncDoc,\n plan: ChangePlan,\n validation?: 'version' | 'preflight',\n ) {\n if (plan.plan_kind === 'timeline') {\n const commitOptions: CommitPlanOptions | undefined = validation === undefined ? undefined : { validation };\n return await commitPlan(doc, plan, commitOptions);\n }\n if (validation === 'preflight') {\n throw new Error('validation=preflight applies only to timeline plans; entity plans use revision CAS');\n }\n if (plan.entity_rows === undefined) throw new Error('entity plan is missing its authoritative rows');\n return await commitEntityPlan(getEntityClient(docId), plan);\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 await observePull(doc);\n const documentVersion = encodeDocVersionMark(doc.versionMark());\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 return {\n ok: true,\n op: 'snapshot',\n doc_id: input.doc_id,\n version: encodeDocVersionMark(doc.versionMark()),\n preview: renderCompactProjection(doc.snapshot()),\n collaborated: pull.collaborated,\n ...(pull.warnings !== undefined ? { warnings: pull.warnings } : {}),\n };\n });\n }\n\n async function run(input: Extract<MedeoToolInput, { op: 'run-edit-script' }>): Promise<MedeoToolResult> {\n return runExclusive(input.doc_id, async (doc) => {\n assertNoPendingPush(input.doc_id);\n const [pull, entityState] = await Promise.all([observePull(doc), fetchEntityStateForSandbox(input.doc_id)]);\n const document: VideoDocument = doc.snapshot();\n const baseVersion = encodeDocVersionMark(doc.versionMark());\n const result = await runEditScript({\n document,\n baseVersion,\n entityState,\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);\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);\n recordPushResult(input.doc_id, planId, plan, commit);\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);\n recordPushResult(input.doc_id, input.plan_id, pending.plan, result);\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);\n recordPushResult(input.doc_id, input.plan_id, cached.plan, result);\n const warnings = mergeWarnings(pull.warnings, commitWarnings(result));\n return {\n ok: true,\n op: 'commit-plan',\n doc_id: input.doc_id,\n plan_id: input.plan_id,\n plan_kind: cached.plan.plan_kind,\n committed: result.kind === 'committed',\n result,\n collaborated: pull.collaborated || (result.kind === 'committed' && result.collaborated),\n ...(warnings !== undefined ? { warnings } : {}),\n };\n });\n }\n\n return {\n name: MEDEO_TOOL_NAME,\n description: MEDEO_TOOL_DESCRIPTION,\n parameters: MEDEO_TOOL_PARAMETERS,\n getModelContext,\n async handle(input: unknown): Promise<MedeoToolResult> {\n try {\n const parsed = parseInput(input);\n if (parsed.op === 'snapshot') return await snapshot(parsed);\n if (parsed.op === 'run-edit-script') return await run(parsed);\n return await commit(parsed);\n } catch (error) {\n const op = isRecord(input) && typeof input.op === 'string' ? (input.op as MedeoToolOp) : 'snapshot';\n return {\n ok: false,\n op,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n },\n async close(): Promise<void> {\n closed = true;\n await Promise.allSettled(documentTails.values());\n const opening = [...documents.values()];\n documents.clear();\n entityClients.clear();\n documentTails.clear();\n pendingPushes.clear();\n plans.clear();\n modelContextVersions.clear();\n const errors: unknown[] = [];\n for (const documentPromise of opening) {\n try {\n await documentPromise;\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length === 1) throw errors[0];\n if (errors.length > 1) throw new AggregateError(errors, 'failed to close medeo tool documents');\n },\n };\n}\n"],"mappings":";;;;;AA0EA,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;GACnB;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;IACX,OAAY,UAAU;IACtB,OAAO;KACL,IAAI;KACJ,OAAO;KACP,OAAO,EAAE,SAAS,mCAAmC,UAAU,IAAI;KACnE,SAAS;MACP,KAAK,IAAI,MAAM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K,SAAS;AAC9E;AAEA,eAAe,aAAa,UAAsC;CAChE,MAAM,OAAO,MAAM,SAAS,KAAK;CACjC,IAAI,KAAK,WAAW,GAAG,OAAO;CAC9B,IAAI;EACF,OAAO,KAAK,MAAM,IAAI;CACxB,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;;AC5JA,MAAa,uBAAuB;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;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;;;AC37BX,MAAa,yBAAyB;;;;;;;;;;;EAWpC,KAAK;AAEP,MAAM,6BAA6B;;;;;;;;EAQjC,KAAK;;AAQP,SAAgB,wBAAw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AAK,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"],"sources":["../src/sandbox/node-host.ts","../src/entity/entity-contract.ts","../src/entity/entity-http-client.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","export 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\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 | 'phonetic-script-provenance'\n | 'caption-provenance'\n | 'caption-alignment'\n | 'clip-anchor'\n | 'audio-script-render';\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 'phonetic-script-provenance',\n 'caption-provenance',\n 'caption-alignment',\n 'clip-anchor',\n 'audio-script-render',\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 interface EntityPayloadByKind {\n axvideo: BoundedDerivedSequencePayload;\n timeline: JsonObject;\n track: JsonObject & { hidden?: boolean; role?: string };\n clip: JsonObject;\n /** Asset-owned metadata. Peer media associations belong in physical-asset Relations. */\n asset: JsonObject;\n video: BoundedNativeSequencePayload;\n audio: BoundedNativeSequencePayload;\n voice: BoundedNativeSequencePayload;\n image: UnboundedConstantSequencePayload;\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 };\n viewport: JsonObject;\n 'audio-script': JsonObject & { segments: ScriptTextSegment[] };\n 'phonetic-script': JsonObject & { segments: ScriptTextSegment[] };\n caption: BoundedNativeSequencePayload;\n}\n\nexport interface SandboxEntity<K extends KnownEntityKind = KnownEntityKind> {\n entity_id: string;\n entity_kind: K;\n payload: EntityPayloadByKind[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: EntityPayloadByKind[K];\n };\n}[KnownEntityKind];\n\nexport interface UpdateEntityInput {\n entity_id: string;\n payload: JsonObject;\n}\n\nexport interface DeleteEntityInput {\n entity_id: string;\n}\n\nexport interface ImportAssetInput {\n asset_id: string;\n entity_id?: string;\n payload?: JsonObject;\n}\n\nexport type EmptyRelationKind =\n | 'timeline-track'\n | 'track-clip'\n | 'clip-marker'\n | 'marker-content'\n | 'axvideo-marker'\n | 'marker-timeline';\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: 'phonetic-script-provenance' | 'caption-provenance';\n metadata: JsonObject & { segmentAlignment: JsonValue };\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 LinkAudioScriptRenderRelationInput {\n relation_id?: string;\n output_entity_id: string;\n script_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 list(): SandboxEntity[];\n get(entityId: string): SandboxEntity | null;\n /** Return every explicitly imported Asset entity for a Memota asset id. */\n findByAssetId(assetId: string): SandboxEntity<'asset'>[];\n create(input: CreateEntityInput): string;\n /** Replace one Entity's owned payload without changing its identity or kind. */\n update(input: UpdateEntityInput): void;\n /** Delete an Entity only after all of its incident Relations have been explicitly unlinked. */\n delete(input: DeleteEntityInput): void;\n /** Import one physical asset without implying a one-to-one media Entity mapping. */\n importAsset(input: ImportAssetInput): 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 /** For physical-asset use sequence media as endpoint 0 and Asset as endpoint 1. */\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 audio-script-render(output,script) without positional endpoint ambiguity. */\n linkAudioScriptRender(input: LinkAudioScriptRenderRelationInput): 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 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 '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 '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 type CreateEntityInput = {',\n ' [K in KnownEntityKind]: {',\n ' entity_id?: string;',\n ' entity_kind: K;',\n ' payload: EntityPayloadByKind[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 'export interface EntityFacade {',\n ' list(): SandboxEntity[];',\n ' get(entityId: string): SandboxEntity | null;',\n ' /** Return every explicitly imported Asset entity for a Memota asset id. */',\n \" findByAssetId(assetId: string): SandboxEntity<'asset'>[];\",\n ' create(input: CreateEntityInput): string;',\n \" /** Replace one Entity's owned payload without changing its identity or kind. */\",\n ' update(input: UpdateEntityInput): void;',\n ' /** Delete an Entity only after all of its incident Relations have been explicitly unlinked. */',\n ' delete(input: DeleteEntityInput): void;',\n ' /** Import one physical asset without implying a one-to-one media Entity mapping. */',\n ' importAsset(input: ImportAssetInput): string;',\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 ' /** Asset-owned metadata. Peer media associations belong in physical-asset Relations. */',\n ' asset: JsonObject;',\n ' video: BoundedNativeSequencePayload;',\n ' audio: BoundedNativeSequencePayload;',\n ' voice: BoundedNativeSequencePayload;',\n ' image: UnboundedConstantSequencePayload;',\n \" 'sequence-marker': JsonObject & {\",\n ' sourceRange: {',\n ' start: number;',\n ' end: number;',\n ' };',\n ' targetRange?: {',\n ' start: number;',\n ' end: number;',\n ' };',\n ' duration:',\n ' | {',\n \" mode: 'from-source';\",\n ' }',\n ' | {',\n \" mode: 'fixed';\",\n ' value: number;',\n ' };',\n ' timeRemapping?: JsonValue;',\n ' anchorOffset?: number;',\n \" durationPolicy?: 'timeline';\",\n ' };',\n ' viewport: JsonObject;',\n \" 'audio-script': JsonObject & {\",\n ' segments: ScriptTextSegment[];',\n ' };',\n \" 'phonetic-script': JsonObject & {\",\n ' segments: ScriptTextSegment[];',\n ' };',\n ' caption: BoundedNativeSequencePayload;',\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 ImportAssetInput {',\n ' asset_id: string;',\n ' entity_id?: string;',\n ' payload?: JsonObject;',\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 \" | 'phonetic-script-provenance'\",\n \" | 'caption-provenance'\",\n \" | 'caption-alignment'\",\n \" | 'clip-anchor'\",\n \" | 'audio-script-render';\",\n 'export interface LinearClipSpeed {',\n \" readonly kind: 'linear';\",\n ' readonly rate: number;',\n ' readonly mode?: string;',\n '}',\n 'export interface LinkAudioScriptRenderRelationInput {',\n ' relation_id?: string;',\n ' output_entity_id: string;',\n ' script_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 '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: 'phonetic-script-provenance' | 'caption-provenance';\",\n ' metadata: JsonObject & {',\n ' segmentAlignment: JsonValue;',\n ' };',\n ' })',\n ' | (LinkRelationBase & {',\n \" relation_kind: 'caption-alignment';\",\n ' metadata: JsonObject & {',\n ' alignment: JsonValue;',\n ' };',\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 ' /** For physical-asset use sequence media as endpoint 0 and Asset as endpoint 1. */',\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 audio-script-render(output,script) without positional endpoint ambiguity. */',\n ' linkAudioScriptRender(input: LinkAudioScriptRenderRelationInput): 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 'export interface SandboxEntity<K extends KnownEntityKind = KnownEntityKind> {',\n ' entity_id: string;',\n ' entity_kind: K;',\n ' payload: EntityPayloadByKind[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 '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 '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 ' readonly voice: VoiceDescriptor;',\n '}',\n 'export interface VoiceoverCaptionFact {',\n ' /** Stable placed caption identity supplied by the materialized side effect. */',\n ' readonly captionClipEntityId: string;',\n ' readonly text: string;',\n ' readonly startMs: number;',\n ' readonly durationMs: number;',\n ' readonly style?: CaptionStyleFields;',\n '}',\n 'export interface VoiceoverTakeInput {',\n ' readonly timelineEntityId: string;',\n ' /** Stable placed speech identity, distinct from media.assetId. */',\n ' readonly voiceoverClipEntityId: string;',\n ' readonly hostClipEntityId: string;',\n ' readonly anchorOffset: number;',\n ' readonly media: VoiceMediaAssetFact;',\n ' /** Complete spoken text; the editor owns the deterministic local script segment identity. */',\n ' readonly scriptText: string;',\n ' readonly volume: number;',\n ' readonly captions: readonly VoiceoverCaptionFact[];',\n '}',\n 'export interface VoiceoverTakeResult {',\n ' readonly voiceoverClipEntityId: string;',\n ' readonly voiceEntityId: string;',\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 '}',\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: return the Entity/Relation state summary and opaque base version.\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, generated Relations and timeline edits belong in ONE plan. The sandbox has no network, storage or generation access. Pass recalled generation/asset facts through inputs. 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, reuse or create the appropriate media Entity and physical-asset Relation, then pass the media Entity id to edit.insertClip. A raw asset id or URL is not valid contentEntityId. Asset and media Entity identity are not one-to-one. Recall generation history and author known generated(output,input) relations in the same plan; do not invent an input for text-only generation. 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 and Memota asset facts are host-provided through inputs. Never invent an asset id, Entity kind, or peer Entity id.\nBefore importing an Asset, call entities.findByAssetId(assetId), inspect every match, and decide whether an existing Entity represents the intended logical asset. Multiple matches are valid; do not assume Asset↔media is one-to-one.\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.\nFor physical-asset authoring, use sequence media as endpoint_0_entity_id and Asset as endpoint_1_entity_id. For generated lineage, use linkGenerated so endpoint 0 is output and endpoint 1 is input. 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.\nVoice links to AudioScript through audio-script-render(output,script). Caption owns text/style and is placed through a Clip anchored to the Voice Clip; caption alignment/provenance agree with that Voice/AudioScript. BGM Audio keeps factual source duration and its Marker declares durationPolicy:'timeline'. External Asset identity and storageKey are distinct from the placed Clip identity. Never introduce a speech entity kind.\nCreate only the known entity kinds. On an empty document, explicitly create Timeline and Track(role='video_clip') and connect timeline-track before inserting a Clip. 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 generation lineage and asset facts. 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 { 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 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 interface MedeoToolWarning {\n kind: 'pull_failed';\n message: string;\n}\n\nexport type EntityCommitResult =\n | {\n kind: 'committed';\n ops_applied: number;\n collaborated: false;\n entity_revision: number;\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}\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}\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): string {\n const planId = randomUUID();\n plans.set(planId, { docId, plan });\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(docId: string, planId: string, plan: ChangePlan, result: MedeoCommitResult): 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 },\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(docId: string): Promise<EntityStoreSnapshot> {\n return await getEntityClient(docId).fetchState();\n }\n\n async function commitCachedPlan(\n docId: string,\n _doc: ManualSyncDoc,\n plan: ChangePlan,\n validation?: 'version' | 'preflight',\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 return await commitEntityPlan(getEntityClient(docId), plan);\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 [, entityState] = await Promise.all([observePull(doc), fetchEntityStateForSandbox(docId)]);\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, entityState] = await Promise.all([observePull(doc), fetchEntityStateForSandbox(input.doc_id)]);\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 = new EntityGraphHttpClient({\n docId: input.doc_id,\n httpOrigin: requiredContext(options.httpOrigin, input.doc_id, 'httpOrigin'),\n ...(options.authToken === undefined\n ? {}\n : { authToken: () => optionalContext(options.authToken, input.doc_id) }),\n ...(options.userId === undefined ? {} : { userId: () => optionalContext(options.userId, input.doc_id) }),\n ...(options.fetchImpl === undefined ? {} : { fetchImpl: options.fetchImpl }),\n });\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, entityState] = await Promise.all([observePull(doc), fetchEntityStateForSandbox(input.doc_id)]);\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);\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);\n recordPushResult(input.doc_id, planId, plan, commit);\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);\n recordPushResult(input.doc_id, input.plan_id, pending.plan, result);\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);\n recordPushResult(input.doc_id, input.plan_id, cached.plan, result);\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,qBAAq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AAM,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;AACF,EAAE,KAAK,IAAI;;;AC9hBX,MAAa,yBAAyB;;;;;;;;;;;;EAYpC,KAAK;AAEP,MAAM,6BAA6B;;;;;;;;;;;EAWjC,KAAK;;AAQP,SAAgB,wBAAwB,OAA6C;CACnF,MAAM,UACJ,MAAM,iCAAiC,OACnC,+BACA,OAAO,MAAM,6BAA6B;CAChD,OAAO;EACP,uBAAuB;;EAEvB,2BAA2B;;;sBAGP,KAAK,UAAU,MAAM,eAAe,EAAE;uCACrB,QAAQ;;;;;;EAM7C,4BAA4B;;EAE5B,KAAK;AACP;;;ACxDA,MAAa,kBAAkB;AAI/B,MAAM,sBAAsB;CAC1B,SAAS;EAAE,MAAM;EAAU,WAAW;CAAE;CACxC,MAAM;EAAE,MAAM;EAAU,MAAM;GAAC;GAAS;GAAS;GAAS;EAAO;CAAE;CACnE,YAAY;EAAE,MAAM;EAAW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