@mengine/medeo-client 1.2.1-alpha.2 → 1.2.1-alpha.3

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/dist/index.js CHANGED
@@ -1,6 +1,5 @@
1
- import { t as __exportAll } from "./chunk-D7D4PA-g.js";
2
- import { A as TIMELINE_SKELETON_DURATION_MS, B as base64ToBytes, C as reassignSpeechesToVideoClipsByTime, D as resolveAnchoredClipsTimePosition, E as resolveAllSpeechOverlaps, F as VIDEO_DOCUMENT_SCHEMA_VERSION, I as effectiveVideoClipDurationMs, L as partUnionToDraft, M as partDurationMs, N as safeDurationMs, O as resolveSpeechOverlapByShiftingVideos, P as DEFAULT_UNIT_TIME_MS, R as recordEntries, S as fillMainTrackTimeGaps, T as recoverOrphanedSpeechAnchorsByTime, V as bytesToBase64, _ as findLaneTrack, a as buildInitialVideoDocument, b as cascadeAfterVideoClipChanges, c as fromVideoDocument, d as assertValidVideoDocument, f as validateVideoDocument, g as ensureLaneTrack, h as LANE_KINDS_IN_STACK_ORDER, i as readVideoDocumentFromDraft, j as isEmptyVideoClip, k as syncAggregatedClipsTimePosition, l as toVideoDocument, m as videoDocumentSchema, n as createMirrorVideoDocument, o as buildSpeechHostMap, p as partUnionSchema, r as createMirrorVideoDocumentAdapter, s as derivePositionFromAbs, t as MirrorVideoDocumentAdapter, u as VideoDocumentValidationError, v as laneTrackId, w as recalculateTimelineDuration, x as arrangeMainTrackSeamlessly, y as solveVideoDocument, z as videoDocumentMirrorSchema } from "./document-C5KDvMMR.js";
3
- import { z } from "zod";
1
+ import { A as resolveAllSpeechOverlaps, B as effectiveVideoClipDurationMs, C as solveVideoDocument, D as reassignSpeechesToVideoClipsByTime, E as fillMainTrackTimeGaps, F as isEmptyVideoClip, G as base64ToBytes, H as partUnionToDraft, I as partDurationMs, K as bytesToBase64, L as safeDurationMs, M as resolveSpeechOverlapByShiftingVideos, N as syncAggregatedClipsTimePosition, O as recalculateTimelineDuration, P as TIMELINE_SKELETON_DURATION_MS, R as DEFAULT_UNIT_TIME_MS, S as laneTrackId, T as arrangeMainTrackSeamlessly, U as recordEntries, V as speedOf, W as videoDocumentMirrorSchema, _ as partUnionSchema, a as createMirrorVideoDocument, b as ensureLaneTrack, c as readVideoDocumentFromDraft, d as derivePositionFromAbs, f as fromVideoDocument, g as validateVideoDocument, h as assertValidVideoDocument, i as MirrorVideoDocumentAdapter, j as resolveAnchoredClipsTimePosition, k as recoverOrphanedSpeechAnchorsByTime, l as buildInitialVideoDocument, m as VideoDocumentValidationError, n as createPlainMemoryAdapter, o as createMirrorVideoDocumentAdapter, p as toVideoDocument, r as generatePartId, s as writeVideoDocumentToDraft, t as PlainMemoryAdapter, u as buildSpeechHostMap, v as videoDocumentSchema, w as cascadeAfterVideoClipChanges, x as findLaneTrack, y as LANE_KINDS_IN_STACK_ORDER, z as VIDEO_DOCUMENT_SCHEMA_VERSION } from "./document-vV4IbKWB.js";
2
+ import { addSpeechesInputSchema, addVideoClipsInputSchema, adjustBgmVolumeInputSchema, adjustSpeechVolumeInputSchema, adjustVideoClipDurationInputSchema, adjustVideoClipVolumeInputSchema, changeSpeechScriptInputSchema, changeSpeechVoiceInputSchema, deleteBgmInputSchema, deleteSpeechesInputSchema, deleteVideoClipsInputSchema, moveBgmInputSchema, moveSpeechesInputSchema, moveVideoClipsByAnchorInputSchema, moveVideoClipsInputSchema, replaceVideoClipContentInputSchema, replaceVideoClipSequenceInputSchema, setBgmInputSchema, setCaptionStyleInputSchema, setCaptionVisibilityInputSchema, setVideoClipSpeedShiftInputSchema, t as schemas_exports } from "./schemas.js";
4
3
  import { LoroDoc, VersionVector } from "loro-crdt";
5
4
  import { ClientServerSynchronizer, DocManager } from "@mengine/sync";
6
5
  import { DisposableSet, EventBus, Task } from "@mengine/utils";
@@ -218,576 +217,6 @@ function findSseFrameBoundary(buffer) {
218
217
  return Math.min(lf, crlf);
219
218
  }
220
219
  //#endregion
221
- //#region src/editor/id-gen.ts
222
- /**
223
- * Part-id generation, aligned with the online ecosystem.
224
- *
225
- * The authoritative online producers — agent-harness (`@harness/shared`
226
- * `genObjId`) and director.v2 (`common/obj_id.py` `gen_obj_id`) — both mint part
227
- * ids as `` `${prefix}_${ulid()}` ``, and real captured drafts use exactly that
228
- * shape (`clip_…` / `spe_…` / `cap_…` / `bgm_…`, each a 26-char ULID). The engine
229
- * previously emitted `vc_<base36 timestamp><6 random>`, a different prefix AND a
230
- * different encoding — the sole cross-repo id divergence. This module removes it
231
- * by emitting the same `<prefix>_<ULID>` bytes.
232
- *
233
- * The ULID is generated inline (Crockford Base32, 48-bit time + 80-bit random)
234
- * rather than pulling the `ulid` npm package: the randomness class matches the
235
- * old generator (both `Math.random`-based) and it keeps `@mengine/medeo-client`
236
- * dependency-free for a purely mechanical id string. Part ids only need to be
237
- * unique and lexicographically time-sortable, which this satisfies.
238
- */
239
- /** Crockford Base32 alphabet (no I, L, O, U), per the ULID spec. */
240
- const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
241
- const TIME_LEN = 10;
242
- const RANDOM_LEN = 16;
243
- function encodeTime(now) {
244
- let out = "";
245
- let ms = now;
246
- for (let i = TIME_LEN - 1; i >= 0; i--) {
247
- const mod = ms % 32;
248
- out = CROCKFORD[mod] + out;
249
- ms = (ms - mod) / 32;
250
- }
251
- return out;
252
- }
253
- function encodeRandom() {
254
- let out = "";
255
- for (let i = 0; i < RANDOM_LEN; i++) out += CROCKFORD[Math.floor(Math.random() * 32)];
256
- return out;
257
- }
258
- /** A 26-char Crockford Base32 ULID (10-char time + 16-char random). */
259
- function ulid() {
260
- return encodeTime(Date.now()) + encodeRandom();
261
- }
262
- function generatePartId(prefix) {
263
- return `${prefix}_${ulid()}`;
264
- }
265
- //#endregion
266
- //#region src/editor/schemas/shared.ts
267
- const clipIdSchema = z.string().min(1).describe("The clip part ID on the timeline");
268
- const clipIdsSchema = z.array(clipIdSchema).min(1).refine((ids) => new Set(ids).size === ids.length, { message: "Duplicate clip IDs are not allowed" }).describe("List of clip part IDs (no duplicates allowed)");
269
- const mediaIdSchema = z.string().min(1).describe("The media asset ID");
270
- const speechIdSchema = z.string().min(1).describe("The speech part ID on the timeline");
271
- const timelineMsSchema = z.number().int().min(0).describe("Time position in milliseconds on the timeline (>= 0)");
272
- const positiveMsSchema = z.number().int().positive().describe("Duration in milliseconds (> 0)");
273
- const volumeSchema = z.number().min(-60).max(20).describe("Volume in decibels (-60.0 to 20.0; 0.0 = original, -60 = mute, +20 = max)");
274
- const speechIdsSchema = z.array(speechIdSchema).min(1).refine((ids) => new Set(ids).size === ids.length, { message: "Duplicate speech IDs are not allowed" }).describe("List of speech part IDs (no duplicates allowed)");
275
- const tangentHandleSchema = z.object({
276
- x: z.number().finite(),
277
- y: z.number().finite()
278
- }).describe("Bezier tangent handle (x, y)");
279
- const speedKeyframeSchema = z.object({
280
- position: z.number().min(0).max(1),
281
- rate: z.number().min(0),
282
- in_tangent: tangentHandleSchema.optional(),
283
- out_tangent: tangentHandleSchema.optional()
284
- }).describe("A speed keyframe: normalized position (0..1), rate, optional tangents");
285
- /**
286
- * A clip's playback-speed fact, the only thing `SetVideoClipSpeedShift` writes.
287
- * Mirrors the IDL `SpeedShift`: `category` is `linear` | `curve`, and `config`
288
- * is a discriminated union — `{ linear: { speed } }` for a constant multiplier
289
- * (the multiplier projection reads at `config.linear.speed`) or `{ curve: {
290
- * keyframes } }` for a Bezier-controlled variable speed (RFC 02 / `reference/16`
291
- * §0). Exactly one of `linear` / `curve` is present.
292
- */
293
- const speedShiftSchema = z.object({
294
- category: z.enum(["linear", "curve"]),
295
- mode: z.string(),
296
- config: z.union([z.object({ linear: z.object({ speed: z.number().finite().positive() }) }), z.object({ curve: z.object({ keyframes: z.array(speedKeyframeSchema).min(2) }) })])
297
- }).describe("Speed shift: linear multiplier or Bezier curve, mirroring the IDL shape");
298
- const voiceSchema = z.object({
299
- id: z.string().min(1),
300
- name: z.string()
301
- }).describe("TTS voice summary attached to a speech");
302
- //#endregion
303
- //#region src/editor/schemas/speech-assets.ts
304
- /**
305
- * The materialized TTS result shared by `AddSpeeches` / `ChangeSpeechScript` /
306
- * `ChangeSpeechVoice` (see `results/phase-4-side-effect-payload-contract.md`
307
- * §1/§2). The side effect (TTS/ASR + billing) runs upstream; the op receives the
308
- * stable speech + caption parts and writes them as authoritative facts. No
309
- * cascade runs on write — the projection derives absolute positions on read.
310
- *
311
- * `anchor_part_id` states the root relationship explicitly: a video/BGM id
312
- * creates an anchored speech; `null` creates an absolute audio root.
313
- * `offset_ms` is relative to the anchor or absolute for a root. Captions always
314
- * anchor to their speech via `start_ms`.
315
- */
316
- const speechAssetSchema = z.object({
317
- speech_id: speechIdSchema.describe("The speech part ID (= side-effect speech_parts[].id)"),
318
- anchor_part_id: z.string().min(1).nullable().describe("Video/BGM parent part ID, or null when the speech itself is the root"),
319
- offset_ms: timelineMsSchema.describe("Relative offset from the parent, or absolute start for a root speech"),
320
- audio_storage_key: z.string().min(1),
321
- duration_ms: positiveMsSchema,
322
- audio_script: z.string(),
323
- volume: volumeSchema,
324
- voice: voiceSchema,
325
- origin_speech_id: z.string().min(1),
326
- caption_ids: z.array(z.string().min(1)).describe("Caption part IDs owned by this speech")
327
- });
328
- const captionAssetSchema = z.object({
329
- caption_id: z.string().min(1).describe("The caption part ID (= side-effect created_caption_parts[].id)"),
330
- speech_part_id: speechIdSchema.describe("The owning speech part ID"),
331
- text: z.string(),
332
- start_ms: timelineMsSchema.describe("Offset within the host speech (caption.abs = speech.abs + start_ms)"),
333
- duration_ms: positiveMsSchema
334
- });
335
- /** A materialized speech-subtree write (speeches + their captions). */
336
- const speechAssetsSchema = z.object({
337
- speeches: z.array(speechAssetSchema).min(1).describe("Materialized speech parts to write"),
338
- captions: z.array(captionAssetSchema).describe("Materialized caption parts owned by the speeches")
339
- });
340
- //#endregion
341
- //#region src/editor/schemas/add-speeches.ts
342
- /**
343
- * Add speeches (and their captions). TTS runs upstream; the stable speech /
344
- * caption parts arrive materialized (see `speech-assets.ts`). The op writes the
345
- * parts and each speech's `{ mode:'anchored', anchorPartId, offsetMs }` fact
346
- * verbatim — no write-time host-picking, no cascade (RFC 02 §4). The projection
347
- * derives absolute positions on read.
348
- */
349
- const addSpeechesInputSchema = speechAssetsSchema.describe("Materialized speeches + captions to add");
350
- //#endregion
351
- //#region src/editor/schemas/add-video-clips.ts
352
- /**
353
- * Add video clips to a track. Each clip's duration facts are separated so a
354
- * single number is never overloaded (RFC 02 / `reference/16` §0b):
355
- *
356
- * - `media_duration_ms` is the source media's intrinsic full length (a resource
357
- * fact, written to the part);
358
- * - `play_in` / `play_out` are the optional trim window into that media; when
359
- * omitted the whole media is used (`play_in=0`, `play_out=media_duration_ms`).
360
- *
361
- * The clip's effective timeline duration is derived by the projection from the
362
- * trim window and `speed_shift` — it is never an input here.
363
- */
364
- const addVideoClipsInputSchema = z.object({
365
- clips: z.array(z.object({
366
- media_id: mediaIdSchema.describe("The media asset ID for the video clip"),
367
- start_ms: timelineMsSchema.optional().describe("Absolute start time in milliseconds on the timeline"),
368
- media_duration_ms: positiveMsSchema.describe("The source media's intrinsic full length in ms"),
369
- play_in: timelineMsSchema.optional().describe("Trim window start in the media (default 0)"),
370
- play_out: positiveMsSchema.optional().describe("Trim window end in the media (default media_duration_ms)"),
371
- track_id: z.string().min(1).optional().describe("Target track ID (optional, defaults to main track)")
372
- })).min(1).describe("List of video clips to create"),
373
- before_clip_id: z.string().min(1).optional().describe("Insert new clips before this clip ID"),
374
- after_clip_id: z.string().min(1).optional().describe("Insert new clips after this clip ID")
375
- }).superRefine((data, ctx) => {
376
- if (data.before_clip_id != null && data.after_clip_id != null) {
377
- ctx.addIssue({
378
- code: z.ZodIssueCode.custom,
379
- message: "Cannot provide both before_clip_id and after_clip_id"
380
- });
381
- return;
382
- }
383
- const hasRelative = data.before_clip_id != null || data.after_clip_id != null;
384
- for (let i = 0; i < data.clips.length; i++) {
385
- const clip = data.clips[i];
386
- if (hasRelative && clip.start_ms != null) ctx.addIssue({
387
- code: z.ZodIssueCode.custom,
388
- message: `clips[${i}].start_ms must not be provided when using before_clip_id or after_clip_id`,
389
- path: [
390
- "clips",
391
- i,
392
- "start_ms"
393
- ]
394
- });
395
- if (!hasRelative && clip.start_ms == null) ctx.addIssue({
396
- code: z.ZodIssueCode.custom,
397
- message: `clips[${i}].start_ms is required when not using relative positioning`,
398
- path: [
399
- "clips",
400
- i,
401
- "start_ms"
402
- ]
403
- });
404
- const playIn = clip.play_in ?? 0;
405
- const playOut = clip.play_out ?? clip.media_duration_ms;
406
- if (playOut > clip.media_duration_ms) ctx.addIssue({
407
- code: z.ZodIssueCode.custom,
408
- message: `clips[${i}].play_out ${playOut}ms exceeds media_duration_ms ${clip.media_duration_ms}ms`,
409
- path: [
410
- "clips",
411
- i,
412
- "play_out"
413
- ]
414
- });
415
- if (playIn >= playOut) ctx.addIssue({
416
- code: z.ZodIssueCode.custom,
417
- message: `clips[${i}].play_in ${playIn}ms must be less than play_out ${playOut}ms`,
418
- path: [
419
- "clips",
420
- i,
421
- "play_in"
422
- ]
423
- });
424
- }
425
- });
426
- //#endregion
427
- //#region src/editor/schemas/adjust-bgm-volume.ts
428
- const adjustBgmVolumeInputSchema = z.object({ bgm: z.array(z.object({
429
- bgm_id: clipIdSchema.describe("The bgm part ID to adjust volume for"),
430
- volume: volumeSchema.describe("Volume in decibels (-60.0 to 20.0; 0.0 = original)")
431
- })).min(1).describe("List of bgm parts with their new volume settings") });
432
- //#endregion
433
- //#region src/editor/schemas/adjust-speech-volume.ts
434
- const adjustSpeechVolumeInputSchema = z.object({ speeches: z.array(z.object({
435
- speech_id: speechIdSchema.describe("The speech part ID to adjust volume for"),
436
- volume: volumeSchema.describe("Volume in decibels (-60.0 to 20.0; 0.0 = original)")
437
- })).min(1).describe("List of speeches with their new volume settings") });
438
- //#endregion
439
- //#region src/editor/schemas/adjust-video-clip-duration.ts
440
- /**
441
- * Re-trim existing video clips (the user-facing "adjust duration" gesture is a
442
- * trim of the source window). The new `play_in` / `play_out` are the facts; the
443
- * effective timeline duration is derived from them and the clip's `speed_shift`,
444
- * and the change reflows downstream clips, speeches, and the timeline inside the
445
- * op's transaction (no caller-materialized cascade).
446
- */
447
- const adjustVideoClipDurationInputSchema = z.object({ clips: z.array(z.object({
448
- clip_id: clipIdSchema.describe("The video clip part ID to re-trim"),
449
- play_in: timelineMsSchema.describe("New trim window start in the source media"),
450
- play_out: positiveMsSchema.describe("New trim window end in the source media")
451
- })).min(1).describe("Video clips with their new trim windows") });
452
- //#endregion
453
- //#region src/editor/schemas/adjust-video-clip-volume.ts
454
- const adjustVideoClipVolumeInputSchema = z.object({ clips: z.array(z.object({
455
- clip_id: clipIdSchema.describe("The video clip part ID to adjust volume for"),
456
- volume: volumeSchema.describe("Volume in decibels (-60.0 to 20.0; 0.0 = original)")
457
- })).min(1).describe("List of video clips with their new volume settings") });
458
- //#endregion
459
- //#region src/editor/schemas/change-speech.ts
460
- /**
461
- * Change a speech's script or voice. Both re-run TTS upstream and return the
462
- * regenerated speech / caption parts in the same materialized shape as
463
- * `AddSpeeches` (`speech-assets.ts`); the op upserts them by id (the speech part
464
- * id is preserved across a re-TTS), re-seats at `start_ms`, and reflows. Old
465
- * caption parts no longer owned by the speech are removed via `caption_ids`.
466
- */
467
- const changeSpeechScriptInputSchema = speechAssetsSchema.describe("Regenerated speeches + captions (new script)");
468
- const changeSpeechVoiceInputSchema = speechAssetsSchema.describe("Regenerated speeches + captions (new voice)");
469
- //#endregion
470
- //#region src/editor/schemas/delete-bgm.ts
471
- /**
472
- * Remove the document BGM. Pure document edit: clears the bgm lane and removes
473
- * the bgm part. Takes no input (a document holds at most one bgm); an empty
474
- * object keeps the op signature uniform with the rest.
475
- */
476
- const deleteBgmInputSchema = z.object({}).describe("Remove the document BGM (no parameters)");
477
- //#endregion
478
- //#region src/editor/schemas/delete-speeches.ts
479
- /**
480
- * Delete speeches with their captions. Pure document edit (no side effect): the
481
- * op removes each speech part, cascade-deletes the captions it owns (via
482
- * `caption_ids` / `speech_part_id`), drops their track items, and reflows.
483
- */
484
- const deleteSpeechesInputSchema = z.object({ speech_ids: speechIdsSchema.describe("Speech part IDs to delete (their captions cascade-delete)") });
485
- //#endregion
486
- //#region src/editor/schemas/delete-video-clips.ts
487
- /**
488
- * How a delete handles the anchored subtree (speeches anchored to a deleted clip,
489
- * and their captions) — a delete-op policy, not a data-model field (reference/17
490
- * §6). `cascade` (default) removes the subtree; `detach` keeps the direct
491
- * anchored children, re-pinning them to `absolute` so they stay on the timeline.
492
- */
493
- const anchoredDeletePolicySchema = z.enum(["cascade", "detach"]);
494
- const deleteVideoClipsInputSchema = z.object({
495
- clip_ids: clipIdsSchema.describe("List of video clip part IDs to delete from the main track"),
496
- on_anchored: anchoredDeletePolicySchema.optional().describe("How to treat anchored children (default cascade)")
497
- });
498
- //#endregion
499
- //#region src/editor/schemas/move-speeches.ts
500
- /**
501
- * Move speeches in time. Pure document edit: the op re-seats each speech at its
502
- * new absolute `start_ms`; the cascade reassigns it to the host video clip,
503
- * resolves overlaps, and reflows. Captions follow their speech.
504
- */
505
- const moveSpeechesInputSchema = z.object({ speeches: z.array(z.object({
506
- speech_id: speechIdSchema.describe("The speech part ID to move"),
507
- new_start_ms: timelineMsSchema.describe("New absolute start time on the timeline")
508
- })).min(1).describe("Speeches to move to new positions") });
509
- //#endregion
510
- //#region src/editor/schemas/move-bgm.ts
511
- const moveBgmInputSchema = z.object({ new_start_ms: timelineMsSchema.describe("New absolute BGM start on the timeline") });
512
- //#endregion
513
- //#region src/editor/schemas/move-video-clips-by-anchor.ts
514
- /**
515
- * Where the moved block lands on the main track.
516
- *
517
- * A discriminated union rather than two optional `before_clip_id` /
518
- * `after_clip_id` fields (the shape `addVideoClips` had to use, because there the
519
- * two modes share a whole clip description): here the alternatives carry nothing
520
- * in common, so making them mutually exclusive *by type* removes three runtime
521
- * `superRefine` checks that would otherwise have to be written and tested.
522
- *
523
- * `track_start` is an explicit member, not the absence of an anchor. The
524
- * agent-harness mutation this maps from treats "neither anchor given" as
525
- * "move to the front" (`applyBatchMoveVideoClips` falls back to `insertIndex = 0`),
526
- * which is a default buried in a tool description. Requiring the caller to name
527
- * that intent keeps a forgotten field from silently reordering the timeline.
528
- */
529
- const moveAnchorSchema = z.discriminatedUnion("position", [
530
- z.object({
531
- position: z.literal("before"),
532
- clip_id: clipIdSchema.describe("The moved block lands immediately before this clip")
533
- }),
534
- z.object({
535
- position: z.literal("after"),
536
- clip_id: clipIdSchema.describe("The moved block lands immediately after this clip")
537
- }),
538
- z.object({ position: z.literal("track_start") })
539
- ]).describe("Where the moved block lands: before/after a reference clip, or at the head of the track");
540
- /**
541
- * What happens to the speeches anchored to the clips being moved.
542
- *
543
- * - `follow` keeps each speech anchored where it is, so it travels with its clip
544
- * to the new position. In the anchored model this is the *no-op* branch: a
545
- * speech's authoritative fact is `{ anchorPartId, offsetMs }` and its absolute
546
- * time is derived on read from the host's position, so moving the host moves
547
- * the speech with no write to the speech at all.
548
- * - `keep_absolute` preserves each speech's current absolute landing instead, then
549
- * re-anchors it to whichever clip now covers that time (RFC 02 §9.1/§11.1). This
550
- * is the branch that costs an extra pass, and the one the FE timeline uses.
551
- *
552
- * **Required, with no default**, matching `deleteVideoClips` and
553
- * `replaceVideoClipSequence`. The two branches decide which picture the user's
554
- * narration ends up over, which is too consequential to infer from a missing
555
- * field — and neither branch is "safe enough" to be the implicit one.
556
- */
557
- const movedClipAnchoredPolicySchema = z.enum(["follow", "keep_absolute"]);
558
- /**
559
- * Reorder a set of main-track clips relative to a reference clip.
560
- *
561
- * Distinct from `moveVideoClips`, which positions clips by absolute time
562
- * (`new_start_ms`) and is what the FE timeline dispatches after a drag. Main-track
563
- * clips are `sequential`-positioned, so absolute time is not authoritative state
564
- * there (RFC 02 §4/§7): `moveVideoClips` has to *guess* an index back out of the
565
- * time it was handed, whereas an anchor already is the ordinal fact being changed.
566
- * Keeping them separate also isolates blast radius — this method can diverge on
567
- * speech policy without touching the FE path.
568
- *
569
- * `clip_ids` need not be contiguous. They move as one block, keeping their
570
- * relative order, which is the agent-harness `batch_move_video_clips` contract.
571
- */
572
- const moveVideoClipsByAnchorInputSchema = z.object({
573
- clip_ids: clipIdsSchema.describe("Clips to move as one block, keeping their relative order. Need not be contiguous on the track."),
574
- anchor: moveAnchorSchema,
575
- on_anchored: movedClipAnchoredPolicySchema.describe("What happens to speeches anchored to the moved clips (required — see the policy doc)")
576
- });
577
- //#endregion
578
- //#region src/editor/schemas/move-video-clips.ts
579
- const moveVideoClipsInputSchema = z.object({ clips: z.array(z.object({
580
- clip_id: clipIdSchema.describe("The video clip part ID to move"),
581
- new_start_ms: timelineMsSchema.describe("New absolute start time in milliseconds on the timeline"),
582
- new_track_id: z.string().min(1).optional().describe("Target track ID to move the clip to (optional)")
583
- })).min(1).describe("List of video clips to move to new positions") });
584
- //#endregion
585
- //#region src/editor/schemas/replace-video-clip-content.ts
586
- /**
587
- * Replace the media backing existing video clips. The media import runs upstream
588
- * (Director); its stable result — the new media id, intrinsic length, and the
589
- * reset trim window — arrives materialized (see
590
- * `results/phase-4-side-effect-payload-contract.md` §4). Director resets
591
- * `play_in=0` / `play_out=media_duration_ms` and clears `speed_shift` on
592
- * replacement. The clip `part_id`s (hence their track items) are unchanged; the
593
- * editor reflows the main track from the new effective durations.
594
- */
595
- const replaceVideoClipContentInputSchema = z.object({ clips: z.array(z.object({
596
- clip_id: clipIdSchema.describe("Existing video clip part ID to re-point"),
597
- origin_media_id: mediaIdSchema.describe("The new media asset ID"),
598
- media_duration_ms: positiveMsSchema.describe("The new media's intrinsic full length"),
599
- play_in: timelineMsSchema.describe("Trim window start in the new media (usually 0)"),
600
- play_out: positiveMsSchema.describe("Trim window end in the new media (usually = media_duration_ms)"),
601
- volume: volumeSchema
602
- })).min(1).describe("Video clips whose media is being replaced") });
603
- //#endregion
604
- //#region src/editor/schemas/replace-video-clip-sequence.ts
605
- /**
606
- * What happens to the speeches anchored to the clips being replaced.
607
- *
608
- * - `remap` re-anchors each surviving speech to the new clip in the SAME POSITION
609
- * of the sequence, keeping its offset — old[i]'s children become new[i]'s
610
- * children. An old clip with no counterpart (fewer new clips than old) has its
611
- * subtree deleted, because there is nothing left to anchor to.
612
- * - `cascade` deletes every anchored speech (and its captions) outright, like
613
- * `deleteVideoClips`.
614
- *
615
- * **Required, with no default.** The two branches differ in whether the user's
616
- * narration survives, and the agent tool that drives this op makes its
617
- * `preserve_speeches` flag required for that reason. A default here would let a
618
- * caller that forgot the field silently delete speech.
619
- */
620
- const anchoredReplacePolicySchema = z.enum(["remap", "cascade"]);
621
- /**
622
- * Replace a contiguous run of main-track clips with a new run.
623
- *
624
- * A composite of delete + insert that cannot be expressed as the two ops in
625
- * sequence, because the anchored speeches have to survive *across* the swap: with
626
- * `remap` they are re-anchored positionally, which needs both the old and the new
627
- * ids in the same transaction (ADR 0009 — the cascade stays in the editor, callers
628
- * never re-wire anchors themselves).
629
- *
630
- * Duration facts follow `addVideoClips`: `media_duration_ms` is the source's
631
- * intrinsic length and the trim window defaults to the whole media. The effective
632
- * timeline duration is derived by the projection, never an input.
633
- *
634
- * `media_id` is optional: omitting it creates a **deliberate empty placeholder
635
- * clip** (`origin_media_id: ''`) — structure with no picture. This is the only op
636
- * that can produce one, and it is authoritative state, unlike the gap fillers the
637
- * read-side solve mints (which never enter the document).
638
- */
639
- const replaceVideoClipSequenceInputSchema = z.object({
640
- old_clip_ids: clipIdsSchema.describe("The clips being replaced: a contiguous main-track run, listed in timeline order"),
641
- new_clips: z.array(z.object({
642
- media_id: mediaIdSchema.optional().describe("The replacement media asset ID. Omit to create an empty placeholder clip."),
643
- media_duration_ms: positiveMsSchema.describe("The source media's intrinsic full length in ms"),
644
- play_in: timelineMsSchema.optional().describe("Trim window start in the media (default 0)"),
645
- play_out: positiveMsSchema.optional().describe("Trim window end in the media (default media_duration_ms)")
646
- })).min(1).describe("The replacement clips, in the order they take on the track"),
647
- on_anchored: anchoredReplacePolicySchema.describe("What happens to speeches anchored to the replaced clips (required — see the policy doc)")
648
- }).superRefine((data, ctx) => {
649
- for (let i = 0; i < data.new_clips.length; i++) {
650
- const clip = data.new_clips[i];
651
- const playIn = clip.play_in ?? 0;
652
- const playOut = clip.play_out ?? clip.media_duration_ms;
653
- if (playOut > clip.media_duration_ms) ctx.addIssue({
654
- code: z.ZodIssueCode.custom,
655
- message: `new_clips[${i}].play_out ${playOut}ms exceeds media_duration_ms ${clip.media_duration_ms}ms`,
656
- path: [
657
- "new_clips",
658
- i,
659
- "play_out"
660
- ]
661
- });
662
- if (playIn >= playOut) ctx.addIssue({
663
- code: z.ZodIssueCode.custom,
664
- message: `new_clips[${i}].play_in ${playIn}ms must be less than play_out ${playOut}ms`,
665
- path: [
666
- "new_clips",
667
- i,
668
- "play_in"
669
- ]
670
- });
671
- }
672
- });
673
- //#endregion
674
- //#region src/editor/schemas/resize-caption.ts
675
- /** Resize one caption placement without changing its cue/source duration. */
676
- const resizeCaptionInputSchema = z.object({
677
- caption_id: z.string().min(1),
678
- duration_ms: z.number().finite().positive()
679
- });
680
- //#endregion
681
- //#region src/editor/schemas/set-bgm.ts
682
- /**
683
- * Set the document BGM. The media's stable result (storage key) arrives
684
- * materialized from upstream (see
685
- * `results/phase-4-side-effect-payload-contract.md` §3). The op upserts the bgm
686
- * part and seats it on the bgm lane; its effective length is always the whole
687
- * timeline, derived by the projection on read — so there is no `duration_ms`
688
- * input or fact (RFC 02 / `reference/16` §0b). A `bgm_id` lets the op replace an
689
- * existing bgm part by id.
690
- */
691
- const setBgmInputSchema = z.object({
692
- bgm_id: z.string().min(1).describe("The bgm part ID to write"),
693
- audio_storage_key: z.string().min(1),
694
- origin_media_id: mediaIdSchema,
695
- volume: volumeSchema
696
- });
697
- //#endregion
698
- //#region src/editor/schemas/set-caption-style.ts
699
- /**
700
- * Set the caption visual style. GLOBAL by design: the style applies to every
701
- * caption part in the document — it carries NO `caption_id`. This mirrors the FE,
702
- * whose caption-style store (`caption-style.ts:persistCaptionStylePatch`) iterates
703
- * ALL captions and writes the same normalized style to each; the product has a
704
- * single document-wide caption style, not per-caption styling.
705
- *
706
- * Every field is optional and maps to a `CaptionStyle` attribute (snake_case
707
- * IDL). A field present in the input is written to every caption; a field ABSENT
708
- * from the input is left untouched on each caption (the editor merges the patch
709
- * onto each caption's existing style — this is a value edit, not a full-style
710
- * replace, so a partial patch such as "recolor only" does not wipe font size).
711
- *
712
- * Pure document edit, no cascade — captions keep their positions; only the style
713
- * sub-map of each caption part changes.
714
- */
715
- const setCaptionStyleInputSchema = z.object({
716
- font_id: z.string().min(1).optional().describe("Font ID referencing a font from the font library"),
717
- font_size: z.number().positive().optional().describe("Font size in points"),
718
- font_color: z.string().min(1).optional().describe("Font color as hex string, e.g. \"#FFFFFF\""),
719
- font_weight: z.number().int().optional().describe("Numeric font weight, e.g. 400 or 700"),
720
- entrance_animation: z.string().optional().describe("Entrance animation preset ID, e.g. \"fade\" or \"none\""),
721
- entrance_animation_duration_ms: z.number().min(0).optional().describe("Entrance animation duration in ms"),
722
- stroke_color: z.string().min(1).optional().describe("Outline/stroke color as hex string, e.g. \"#000000\""),
723
- stroke_width: z.number().min(0).optional().describe("Outline/stroke width in pixels"),
724
- position_x: z.number().optional().describe("Caption center X as a fraction (0.0 to 1.0)"),
725
- position_y: z.number().optional().describe("Caption center Y as a fraction (0.0 to 1.0)")
726
- }).describe("Document-wide caption style patch (no caption_id; applies to every caption)");
727
- //#endregion
728
- //#region src/editor/schemas/set-caption-visibility.ts
729
- /**
730
- * Toggle caption visibility (the caption track's `is_hidden` flag). Pure
731
- * document edit, no cascade — captions keep their positions; only the lane's
732
- * hidden flag changes.
733
- */
734
- const setCaptionVisibilityInputSchema = z.object({ is_hidden: z.boolean().describe("Whether the caption track is hidden") });
735
- //#endregion
736
- //#region src/editor/schemas/set-video-clip-speed-shift.ts
737
- /**
738
- * Set the playback speed of existing video clips. Per the speed-shift decision
739
- * (`reference/16` §0): the op writes only the `speed_shift` fact — it does NOT
740
- * store an effective `duration_ms` (projection derives it from the trim window /
741
- * speed) and does NOT scale anchored speeches' relative offsets (offsets stay
742
- * put; the cascade reflows absolute positions). A `null` speed_shift clears the
743
- * speed back to original (1×).
744
- */
745
- const setVideoClipSpeedShiftInputSchema = z.object({ clips: z.array(z.object({
746
- clip_id: clipIdSchema.describe("The video clip part ID to set speed for"),
747
- speed_shift: speedShiftSchema.nullable().describe("The new speed setting, or null to reset to 1×")
748
- })).min(1).describe("Video clips with their new speed settings") });
749
- //#endregion
750
- //#region src/editor/schemas/index.ts
751
- var schemas_exports = /* @__PURE__ */ __exportAll({
752
- addSpeechesInputSchema: () => addSpeechesInputSchema,
753
- addVideoClipsInputSchema: () => addVideoClipsInputSchema,
754
- adjustBgmVolumeInputSchema: () => adjustBgmVolumeInputSchema,
755
- adjustSpeechVolumeInputSchema: () => adjustSpeechVolumeInputSchema,
756
- adjustVideoClipDurationInputSchema: () => adjustVideoClipDurationInputSchema,
757
- adjustVideoClipVolumeInputSchema: () => adjustVideoClipVolumeInputSchema,
758
- anchoredDeletePolicySchema: () => anchoredDeletePolicySchema,
759
- anchoredReplacePolicySchema: () => anchoredReplacePolicySchema,
760
- changeSpeechScriptInputSchema: () => changeSpeechScriptInputSchema,
761
- changeSpeechVoiceInputSchema: () => changeSpeechVoiceInputSchema,
762
- clipIdSchema: () => clipIdSchema,
763
- clipIdsSchema: () => clipIdsSchema,
764
- deleteBgmInputSchema: () => deleteBgmInputSchema,
765
- deleteSpeechesInputSchema: () => deleteSpeechesInputSchema,
766
- deleteVideoClipsInputSchema: () => deleteVideoClipsInputSchema,
767
- mediaIdSchema: () => mediaIdSchema,
768
- moveAnchorSchema: () => moveAnchorSchema,
769
- moveBgmInputSchema: () => moveBgmInputSchema,
770
- moveSpeechesInputSchema: () => moveSpeechesInputSchema,
771
- moveVideoClipsByAnchorInputSchema: () => moveVideoClipsByAnchorInputSchema,
772
- moveVideoClipsInputSchema: () => moveVideoClipsInputSchema,
773
- movedClipAnchoredPolicySchema: () => movedClipAnchoredPolicySchema,
774
- positiveMsSchema: () => positiveMsSchema,
775
- replaceVideoClipContentInputSchema: () => replaceVideoClipContentInputSchema,
776
- replaceVideoClipSequenceInputSchema: () => replaceVideoClipSequenceInputSchema,
777
- resizeCaptionInputSchema: () => resizeCaptionInputSchema,
778
- setBgmInputSchema: () => setBgmInputSchema,
779
- setCaptionStyleInputSchema: () => setCaptionStyleInputSchema,
780
- setCaptionVisibilityInputSchema: () => setCaptionVisibilityInputSchema,
781
- setVideoClipSpeedShiftInputSchema: () => setVideoClipSpeedShiftInputSchema,
782
- speechAssetsSchema: () => speechAssetsSchema,
783
- speechIdSchema: () => speechIdSchema,
784
- speechIdsSchema: () => speechIdsSchema,
785
- speedShiftSchema: () => speedShiftSchema,
786
- timelineMsSchema: () => timelineMsSchema,
787
- voiceSchema: () => voiceSchema,
788
- volumeSchema: () => volumeSchema
789
- });
790
- //#endregion
791
220
  //#region src/editor/snapshot-utils.ts
792
221
  function isMap(value) {
793
222
  return value instanceof Map;
@@ -1029,18 +458,6 @@ var SchemaValidator = class {
1029
458
  validateSetCaptionVisibility(input, _doc) {
1030
459
  this.parse(setCaptionVisibilityInputSchema, input, "set_caption_visibility_invalid_input");
1031
460
  }
1032
- validateResizeCaption(input, doc) {
1033
- const parsed = this.parse(resizeCaptionInputSchema, input, "resize_caption_invalid_input");
1034
- const snapshot = doc.snapshot();
1035
- this.assertPartKind(snapshot, parsed.caption_id, "caption", "resize_caption");
1036
- if (snapshot.tracks?.find((track) => track.parts_kind === "caption")?.items?.find((row) => row.part_id === parsed.caption_id) == null) throw new ValidationError("resize_caption_placement_not_found", `caption_id "${parsed.caption_id}" is not placed on the caption track`, { caption_id: parsed.caption_id });
1037
- const cueDuration = snapshot.part_library?.[parsed.caption_id]?.caption?.initial_duration_ms ?? 0;
1038
- if (parsed.duration_ms < cueDuration) throw new ValidationError("resize_caption_below_cue", `duration_ms ${parsed.duration_ms} is shorter than cue duration ${cueDuration}`, {
1039
- caption_id: parsed.caption_id,
1040
- duration_ms: parsed.duration_ms,
1041
- cue_duration_ms: cueDuration
1042
- });
1043
- }
1044
461
  validateSetCaptionStyle(input, _doc) {
1045
462
  this.parse(setCaptionStyleInputSchema, input, "set_caption_style_invalid_input");
1046
463
  }
@@ -1156,9 +573,11 @@ function readPartLibrary(draft) {
1156
573
  var SemanticEditor = class {
1157
574
  doc;
1158
575
  validator;
1159
- constructor(doc, validator = new SchemaValidator()) {
576
+ idFactory;
577
+ constructor(doc, validator = new SchemaValidator(), idFactory = generatePartId) {
1160
578
  this.doc = doc;
1161
579
  this.validator = validator;
580
+ this.idFactory = idFactory;
1162
581
  }
1163
582
  async moveVideoClips(input, options) {
1164
583
  this.validator.validateMoveVideoClips(input, this.doc);
@@ -1238,7 +657,7 @@ var SemanticEditor = class {
1238
657
  track.items ??= [];
1239
658
  let at = insertIndex;
1240
659
  for (const clip of input.clips) {
1241
- const partId = generatePartId("clip");
660
+ const partId = this.idFactory("clip");
1242
661
  setPart(draft, partId, { video_clip: {
1243
662
  id: partId,
1244
663
  kind: "video_clip",
@@ -1250,8 +669,7 @@ var SemanticEditor = class {
1250
669
  track.items.splice(at, 0, {
1251
670
  part_id: partId,
1252
671
  time_position: { mode: "sequential" },
1253
- fallback_abs_ms: void 0,
1254
- duration_override_ms: void 0
672
+ fallback_abs_ms: void 0
1255
673
  });
1256
674
  at += 1;
1257
675
  }
@@ -1286,7 +704,7 @@ var SemanticEditor = class {
1286
704
  const newItems = [];
1287
705
  const newClipIds = [];
1288
706
  for (const clip of input.new_clips) {
1289
- const partId = generatePartId("clip");
707
+ const partId = this.idFactory("clip");
1290
708
  setPart(draft, partId, { video_clip: {
1291
709
  id: partId,
1292
710
  kind: "video_clip",
@@ -1298,8 +716,7 @@ var SemanticEditor = class {
1298
716
  newItems.push({
1299
717
  part_id: partId,
1300
718
  time_position: { mode: "sequential" },
1301
- fallback_abs_ms: void 0,
1302
- duration_override_ms: void 0
719
+ fallback_abs_ms: void 0
1303
720
  });
1304
721
  newClipIds.push(partId);
1305
722
  }
@@ -1544,8 +961,7 @@ var SemanticEditor = class {
1544
961
  mode: "absolute",
1545
962
  offsetMs: 0
1546
963
  },
1547
- fallback_abs_ms: void 0,
1548
- duration_override_ms: void 0
964
+ fallback_abs_ms: void 0
1549
965
  }];
1550
966
  }, audit("SetBgm", input, options));
1551
967
  }
@@ -1568,15 +984,6 @@ var SemanticEditor = class {
1568
984
  track.is_hidden = input.is_hidden;
1569
985
  }, audit("SetCaptionVisibility", input, options));
1570
986
  }
1571
- /** Resize the caption placement window; cue/source duration stays immutable. */
1572
- async resizeCaption(input, options) {
1573
- this.validator.validateResizeCaption(input, this.doc);
1574
- this.doc.transact((draft) => {
1575
- const item = findLaneTrack(draft, "caption")?.items?.find((row) => row.part_id === input.caption_id);
1576
- if (item == null) return;
1577
- item.duration_override_ms = input.duration_ms;
1578
- }, audit("ResizeCaption", input, options));
1579
- }
1580
987
  /**
1581
988
  * Set the document-wide caption style. GLOBAL (no `caption_id`): the patch is
1582
989
  * merged onto EVERY caption part's `style`, mirroring the FE, which applies a
@@ -1822,8 +1229,7 @@ function placeRelative(items, partId, anchorPartId, offsetMs, fallbackAbsMs) {
1822
1229
  items.push({
1823
1230
  part_id: partId,
1824
1231
  time_position: timePosition,
1825
- fallback_abs_ms: fallbackAbsMs,
1826
- duration_override_ms: void 0
1232
+ fallback_abs_ms: fallbackAbsMs
1827
1233
  });
1828
1234
  }
1829
1235
  function placeAbsolute(items, partId, startMs) {
@@ -1840,8 +1246,7 @@ function placeAbsolute(items, partId, startMs) {
1840
1246
  items.push({
1841
1247
  part_id: partId,
1842
1248
  time_position: timePosition,
1843
- fallback_abs_ms: void 0,
1844
- duration_override_ms: void 0
1249
+ fallback_abs_ms: void 0
1845
1250
  });
1846
1251
  }
1847
1252
  /**
@@ -1967,6 +1372,114 @@ function deleteAnchoredSubtree(draft, clipId) {
1967
1372
  for (const speechId of anchored) deleteSpeechSubtree(draft, speechId);
1968
1373
  }
1969
1374
  //#endregion
1375
+ //#region src/editor/journal.ts
1376
+ /**
1377
+ * Wire a plain-memory adapter + editor that share a recording id factory, so
1378
+ * every mutating transact lands in `journal` with ordered `generated_ids`.
1379
+ */
1380
+ function createEditSandbox(document, options) {
1381
+ const adapter = createPlainMemoryAdapter(document, options);
1382
+ return {
1383
+ adapter,
1384
+ editor: new SemanticEditor(adapter, new SchemaValidator(), adapter.idFactory),
1385
+ journal: adapter.journal
1386
+ };
1387
+ }
1388
+ /**
1389
+ * Re-drive `doc` from a recorded journal, forcing each entry's `generated_ids`
1390
+ * through a queue-backed id factory. Never mints fresh ids: an empty queue on
1391
+ * demand throws `unrecorded id`; leftover ids after an entry throws
1392
+ * `unconsumed ids`. Legacy entries without `generated_ids` are treated as `[]`.
1393
+ */
1394
+ async function replayJournal(doc, journal) {
1395
+ const queue = [];
1396
+ const idFactory = (_prefix) => {
1397
+ const id = queue.shift();
1398
+ if (id == null) throw new Error("unrecorded id");
1399
+ return id;
1400
+ };
1401
+ const editor = new SemanticEditor(doc, new SchemaValidator(), idFactory);
1402
+ for (const entry of journal) {
1403
+ queue.push(...entry.generated_ids ?? []);
1404
+ await dispatchEntry(editor, entry);
1405
+ if (queue.length > 0) throw new Error("unconsumed ids");
1406
+ }
1407
+ }
1408
+ /** Dispatch one journal entry to the matching editor method; payload is passed through. */
1409
+ async function dispatchEntry(editor, entry) {
1410
+ const payload = entry.payload;
1411
+ const options = entry.intent != null ? { intent: entry.intent } : void 0;
1412
+ switch (entry.kind) {
1413
+ case "MoveVideoClips":
1414
+ await editor.moveVideoClips(payload, options);
1415
+ return;
1416
+ case "MoveVideoClipsByAnchor":
1417
+ await editor.moveVideoClipsByAnchor(payload, options);
1418
+ return;
1419
+ case "DeleteVideoClips":
1420
+ await editor.deleteVideoClips(payload, options);
1421
+ return;
1422
+ case "AddVideoClips":
1423
+ await editor.addVideoClips(payload, options);
1424
+ return;
1425
+ case "AdjustVideoClipVolume":
1426
+ await editor.adjustVideoClipVolume(payload, options);
1427
+ return;
1428
+ case "SetVideoClipSpeedShift":
1429
+ await editor.setVideoClipSpeedShift(payload, options);
1430
+ return;
1431
+ case "ReplaceVideoClipContent":
1432
+ await editor.replaceVideoClipContent(payload, options);
1433
+ return;
1434
+ case "ReplaceVideoClipSequence":
1435
+ await editor.replaceVideoClipSequence(payload, options);
1436
+ return;
1437
+ case "AdjustVideoClipDuration":
1438
+ await editor.adjustVideoClipDuration(payload, options);
1439
+ return;
1440
+ case "AddSpeeches":
1441
+ await editor.addSpeeches(payload, options);
1442
+ return;
1443
+ case "DeleteSpeeches":
1444
+ await editor.deleteSpeeches(payload, options);
1445
+ return;
1446
+ case "MoveSpeeches":
1447
+ await editor.moveSpeeches(payload, options);
1448
+ return;
1449
+ case "MoveBgm":
1450
+ await editor.moveBgm(payload, options);
1451
+ return;
1452
+ case "ChangeSpeechScript":
1453
+ await editor.changeSpeechScript(payload, options);
1454
+ return;
1455
+ case "ChangeSpeechVoice":
1456
+ await editor.changeSpeechVoice(payload, options);
1457
+ return;
1458
+ case "AdjustSpeechVolume":
1459
+ await editor.adjustSpeechVolume(payload, options);
1460
+ return;
1461
+ case "SetCaptionVisibility":
1462
+ await editor.setCaptionVisibility(payload, options);
1463
+ return;
1464
+ case "SetCaptionStyle":
1465
+ await editor.setCaptionStyle(payload, options);
1466
+ return;
1467
+ case "SetBgm":
1468
+ await editor.setBgm(payload, options);
1469
+ return;
1470
+ case "DeleteBgm":
1471
+ await editor.deleteBgm(payload, options);
1472
+ return;
1473
+ case "AdjustBgmVolume":
1474
+ await editor.adjustBgmVolume(payload, options);
1475
+ return;
1476
+ default: {
1477
+ const _exhaustive = entry.kind;
1478
+ throw new Error(`replayJournal: unsupported kind ${String(_exhaustive)}`);
1479
+ }
1480
+ }
1481
+ }
1482
+ //#endregion
1970
1483
  //#region src/editor/types.ts
1971
1484
  /** Runtime list of the frozen, implemented kinds (for guards / introspection). */
1972
1485
  const IMPLEMENTED_SEMANTIC_OP_KINDS = [
@@ -1986,7 +1499,6 @@ const IMPLEMENTED_SEMANTIC_OP_KINDS = [
1986
1499
  "ChangeSpeechScript",
1987
1500
  "ChangeSpeechVoice",
1988
1501
  "AdjustSpeechVolume",
1989
- "ResizeCaption",
1990
1502
  "SetCaptionVisibility",
1991
1503
  "SetCaptionStyle",
1992
1504
  "SetBgm",
@@ -2163,6 +1675,18 @@ var ManualSyncDoc = class ManualSyncDoc {
2163
1675
  return fromVideoDocument(this.adapter.snapshot());
2164
1676
  }
2165
1677
  /**
1678
+ * Replay a deterministic sandbox journal into this document.
1679
+ *
1680
+ * The adapter stays private so callers cannot bypass the manual-sync
1681
+ * lifecycle; journal replay is the one host-side operation that needs the
1682
+ * adapter's transaction boundary and recorded id queue. Durability is still
1683
+ * explicit: call {@link push} after replay and report success only from its
1684
+ * verdict.
1685
+ */
1686
+ async replayJournal(journal) {
1687
+ await replayJournal(this.adapter, journal);
1688
+ }
1689
+ /**
2166
1690
  * Mark the document state the caller has just observed, for a later
2167
1691
  * {@link hasChangedSince}.
2168
1692
  *
@@ -2762,6 +2286,24 @@ var MengineDocSession = class {
2762
2286
  if (this.editorValue == null) throw new Error("mengine doc session is not started");
2763
2287
  return this.editorValue;
2764
2288
  }
2289
+ /**
2290
+ * Opaque version token of the local oplog (base64 `VersionVector.encode`).
2291
+ * Equality-comparable only: equal means no observed change (local or
2292
+ * remote-arrived) since the token was taken. Throws when not started.
2293
+ */
2294
+ version() {
2295
+ if (this.adapterValue == null) throw new Error("mengine doc session is not started");
2296
+ return bytesToBase64(this.adapterValue.doc.oplogVersion().encode());
2297
+ }
2298
+ /**
2299
+ * The live document adapter, exposed for journal replay (commit channel).
2300
+ * Replaying through it still goes SemanticEditor → Loro → mengine-server —
2301
+ * no write bypass. Typed by the narrow interface on purpose.
2302
+ */
2303
+ get documentAdapter() {
2304
+ if (this.adapterValue == null) throw new Error("mengine doc session is not started");
2305
+ return this.adapterValue;
2306
+ }
2765
2307
  /** Current document snapshot (read model). */
2766
2308
  snapshot() {
2767
2309
  if (this.adapterValue == null) throw new Error("mengine doc session is not started");
@@ -2872,4 +2414,4 @@ function serverCovers(serverVV, target) {
2872
2414
  return covers(server, target);
2873
2415
  }
2874
2416
  //#endregion
2875
- export { DEFAULT_UNIT_TIME_MS, IMPLEMENTED_SEMANTIC_OP_KINDS, LANE_KINDS_IN_STACK_ORDER, ManualSyncDoc, MedeoHttpDocStorage, MemoryDocStorage, MengineAckFailedError, MengineDocSession, MengineHttpClient, MengineHttpRequestError, MenginePushRejectedError, MirrorVideoDocumentAdapter, SchemaValidator, SemanticEditor, TIMELINE_SKELETON_DURATION_MS, VIDEO_DOCUMENT_SCHEMA_VERSION, ValidationError, VideoDocumentValidationError, arrangeMainTrackSeamlessly, assertValidVideoDocument, base64ToBytes, buildInitialVideoDocument, buildSpeechHostMap, bytesToBase64, cascadeAfterVideoClipChanges, createMirrorVideoDocument, createMirrorVideoDocumentAdapter, decodeDocVersionMark, derivePositionFromAbs, encodeDocVersionMark, ensureLaneTrack, fillMainTrackTimeGaps, findLaneTrack, fromVideoDocument, generatePartId, getAt, hostForAbsMs, isEmptyVideoClip, isImplementedSemanticOpKind, isMap, laneTrackId, mainTrackRanges, partDurationMs, partUnionSchema, readMainTrackItems, readMengineEventStream, readPart, readPartDurationMs, readVideoDocumentFromDraft, reassignSpeechesToVideoClipsByTime, recalculateTimelineDuration, recoverOrphanedSpeechAnchorsByTime, relativePositionForAbs, resolveAllSpeechOverlaps, resolveAnchoredClipsTimePosition, resolveSpeechOverlapByShiftingVideos, safeDurationMs, schemas_exports as schemas, snapshotToPlain, solveVideoDocument, syncAggregatedClipsTimePosition, toVideoDocument, validateVideoDocument, videoDocumentMirrorSchema, videoDocumentSchema };
2417
+ export { DEFAULT_UNIT_TIME_MS, IMPLEMENTED_SEMANTIC_OP_KINDS, LANE_KINDS_IN_STACK_ORDER, ManualSyncDoc, MedeoHttpDocStorage, MemoryDocStorage, MengineAckFailedError, MengineDocSession, MengineHttpClient, MengineHttpRequestError, MenginePushRejectedError, MirrorVideoDocumentAdapter, PlainMemoryAdapter, SchemaValidator, SemanticEditor, TIMELINE_SKELETON_DURATION_MS, VIDEO_DOCUMENT_SCHEMA_VERSION, ValidationError, VideoDocumentValidationError, arrangeMainTrackSeamlessly, assertValidVideoDocument, base64ToBytes, buildInitialVideoDocument, buildSpeechHostMap, bytesToBase64, cascadeAfterVideoClipChanges, createEditSandbox, createMirrorVideoDocument, createMirrorVideoDocumentAdapter, createPlainMemoryAdapter, decodeDocVersionMark, derivePositionFromAbs, effectiveVideoClipDurationMs, encodeDocVersionMark, ensureLaneTrack, fillMainTrackTimeGaps, findLaneTrack, fromVideoDocument, generatePartId, getAt, hostForAbsMs, isEmptyVideoClip, isImplementedSemanticOpKind, isMap, laneTrackId, mainTrackRanges, partDurationMs, partUnionSchema, readMainTrackItems, readMengineEventStream, readPart, readPartDurationMs, readVideoDocumentFromDraft, reassignSpeechesToVideoClipsByTime, recalculateTimelineDuration, recoverOrphanedSpeechAnchorsByTime, relativePositionForAbs, replayJournal, resolveAllSpeechOverlaps, resolveAnchoredClipsTimePosition, resolveSpeechOverlapByShiftingVideos, safeDurationMs, schemas_exports as schemas, snapshotToPlain, solveVideoDocument, speedOf, syncAggregatedClipsTimePosition, toVideoDocument, validateVideoDocument, videoDocumentMirrorSchema, videoDocumentSchema, writeVideoDocumentToDraft };