@mengine/medeo-client 1.2.1-alpha.5 → 1.2.1-alpha.7

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-ClBRZtLn.js";
3
- import { z } from "zod";
1
+ import { A as resolveSpeechOverlapByShiftingVideos, B as partUnionToDraft, C as solveVideoDocument, D as reassignSpeechesToVideoClipsByTime, E as fillMainTrackTimeGaps, F as safeDurationMs, H as videoDocumentMirrorSchema, I as DEFAULT_UNIT_TIME_MS, L as VIDEO_DOCUMENT_SCHEMA_VERSION, M as TIMELINE_SKELETON_DURATION_MS, N as isEmptyVideoClip, O as recalculateTimelineDuration, P as partDurationMs, R as effectiveVideoClipDurationMs, S as laneTrackId, T as arrangeMainTrackSeamlessly, U as base64ToBytes, V as recordEntries, W as bytesToBase64, _ 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 syncAggregatedClipsTimePosition, k as resolveAllSpeechOverlaps, 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 speedOf } from "./document-49OdvviW.js";
2
+ import { addSpeechesInputSchema, addVideoClipsInputSchema, adjustBgmVolumeInputSchema, adjustSpeechVolumeInputSchema, adjustVideoClipDurationInputSchema, adjustVideoClipVolumeInputSchema, changeSpeechScriptInputSchema, changeSpeechVoiceInputSchema, deleteBgmInputSchema, deleteSpeechesInputSchema, deleteVideoClipsInputSchema, 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;
@@ -1016,10 +445,6 @@ var SchemaValidator = class {
1016
445
  const snapshot = doc.snapshot();
1017
446
  for (const s of parsed.speeches) this.assertPartKind(snapshot, s.speech_id, "speech", "move_speeches");
1018
447
  }
1019
- validateMoveBgm(input, doc) {
1020
- this.parse(moveBgmInputSchema, input, "move_bgm_invalid_input");
1021
- if (doc.snapshot().tracks?.find((track) => track.parts_kind === "bgm")?.items?.[0] == null) throw new ValidationError("move_bgm_not_found", "document has no BGM item");
1022
- }
1023
448
  validateSetBgm(input, _doc) {
1024
449
  this.parse(setBgmInputSchema, input, "set_bgm_invalid_input");
1025
450
  }
@@ -1029,18 +454,6 @@ var SchemaValidator = class {
1029
454
  validateSetCaptionVisibility(input, _doc) {
1030
455
  this.parse(setCaptionVisibilityInputSchema, input, "set_caption_visibility_invalid_input");
1031
456
  }
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
457
  validateSetCaptionStyle(input, _doc) {
1045
458
  this.parse(setCaptionStyleInputSchema, input, "set_caption_style_invalid_input");
1046
459
  }
@@ -1067,20 +480,16 @@ var SchemaValidator = class {
1067
480
  for (const speech of assets.speeches) this.assertPartKind(snapshot, speech.speech_id, "speech", opName);
1068
481
  }
1069
482
  /**
1070
- * Anchored speeches may follow a video or BGM root. A null anchor is an
1071
- * explicit absolute speech root. Missing and wrong-kind parents are rejected.
483
+ * Each speech's `anchor_part_id` must point at a video clip that already
484
+ * exists. A relative speech anchored to a missing clip cannot be positioned
485
+ * by the projection and has no host to recover to (RFC 02 §4/§11.1), so the
486
+ * write must be rejected rather than landing a dangling reference. (Restores
487
+ * the dangling-reference guard the old `validateMaterializedPatch` carried;
488
+ * ADR 0009.)
1072
489
  */
1073
490
  assertAnchorsExist(assets, doc, opName) {
1074
491
  const snapshot = doc.snapshot();
1075
- for (const speech of assets.speeches) {
1076
- if (speech.anchor_part_id == null) continue;
1077
- const part = readPart(snapshot, speech.anchor_part_id);
1078
- if (part == null) throw new ValidationError(`${opName}_anchor_part_not_found`, `part_library has no parent`, { part_id: speech.anchor_part_id });
1079
- if (part.part_kind !== "video_clip" && part.part_kind !== "bgm") throw new ValidationError(`${opName}_anchor_wrong_part_kind`, `speech parent must be video_clip or bgm`, {
1080
- part_id: speech.anchor_part_id,
1081
- part_kind: part.part_kind
1082
- });
1083
- }
492
+ for (const speech of assets.speeches) this.assertPartKind(snapshot, speech.anchor_part_id, "video_clip", `${opName}_anchor`);
1084
493
  }
1085
494
  assertPartKind(snapshot, partId, kind, opName) {
1086
495
  const part = readPart(snapshot, partId);
@@ -1156,9 +565,11 @@ function readPartLibrary(draft) {
1156
565
  var SemanticEditor = class {
1157
566
  doc;
1158
567
  validator;
1159
- constructor(doc, validator = new SchemaValidator()) {
568
+ idFactory;
569
+ constructor(doc, validator = new SchemaValidator(), idFactory = generatePartId) {
1160
570
  this.doc = doc;
1161
571
  this.validator = validator;
572
+ this.idFactory = idFactory;
1162
573
  }
1163
574
  async moveVideoClips(input, options) {
1164
575
  this.validator.validateMoveVideoClips(input, this.doc);
@@ -1238,7 +649,7 @@ var SemanticEditor = class {
1238
649
  track.items ??= [];
1239
650
  let at = insertIndex;
1240
651
  for (const clip of input.clips) {
1241
- const partId = generatePartId("clip");
652
+ const partId = this.idFactory("clip");
1242
653
  setPart(draft, partId, { video_clip: {
1243
654
  id: partId,
1244
655
  kind: "video_clip",
@@ -1250,8 +661,7 @@ var SemanticEditor = class {
1250
661
  track.items.splice(at, 0, {
1251
662
  part_id: partId,
1252
663
  time_position: { mode: "sequential" },
1253
- fallback_abs_ms: void 0,
1254
- duration_override_ms: void 0
664
+ fallback_abs_ms: void 0
1255
665
  });
1256
666
  at += 1;
1257
667
  }
@@ -1286,7 +696,7 @@ var SemanticEditor = class {
1286
696
  const newItems = [];
1287
697
  const newClipIds = [];
1288
698
  for (const clip of input.new_clips) {
1289
- const partId = generatePartId("clip");
699
+ const partId = this.idFactory("clip");
1290
700
  setPart(draft, partId, { video_clip: {
1291
701
  id: partId,
1292
702
  kind: "video_clip",
@@ -1298,8 +708,7 @@ var SemanticEditor = class {
1298
708
  newItems.push({
1299
709
  part_id: partId,
1300
710
  time_position: { mode: "sequential" },
1301
- fallback_abs_ms: void 0,
1302
- duration_override_ms: void 0
711
+ fallback_abs_ms: void 0
1303
712
  });
1304
713
  newClipIds.push(partId);
1305
714
  }
@@ -1429,9 +838,8 @@ var SemanticEditor = class {
1429
838
  */
1430
839
  async addSpeeches(input, options) {
1431
840
  this.validator.validateAddSpeeches(input, this.doc);
1432
- const absByPartId = solveVideoDocument(this.doc.snapshot()).absByPartId;
1433
841
  this.doc.transact((draft) => {
1434
- writeSpeechAssets(draft, input, absByPartId);
842
+ writeSpeechAssets(draft, input);
1435
843
  }, audit("AddSpeeches", input, options));
1436
844
  }
1437
845
  /** Delete speeches with their captions; the subtree is removed (§9.2). Surviving lanes keep their facts. */
@@ -1449,60 +857,29 @@ var SemanticEditor = class {
1449
857
  */
1450
858
  async moveSpeeches(input, options) {
1451
859
  this.validator.validateMoveSpeeches(input, this.doc);
1452
- const snapshot = this.doc.snapshot();
1453
- const absByPartId = solveVideoDocument(snapshot).absByPartId;
1454
860
  this.doc.transact((draft) => {
1455
- const track = findLaneTrack(draft, "speech");
1456
861
  const ranges = mainTrackRanges(draft);
862
+ const track = findLaneTrack(draft, "speech");
1457
863
  for (const move of input.speeches) {
1458
864
  const item = (track?.items ?? []).find((it) => it?.part_id === move.speech_id);
1459
865
  if (item == null) continue;
1460
- const current = item.time_position;
1461
- if (current?.mode === "anchored") {
1462
- const parentStartMs = absByPartId.get(current.anchorPartId);
1463
- item.time_position = readPart(snapshot, current.anchorPartId)?.part_kind === "video_clip" ? relativePositionForAbs(ranges, move.new_start_ms) : parentStartMs == null ? {
1464
- mode: "absolute",
1465
- offsetMs: move.new_start_ms
1466
- } : {
1467
- mode: "anchored",
1468
- anchorPartId: current.anchorPartId,
1469
- offsetMs: Math.max(0, move.new_start_ms - parentStartMs)
1470
- };
1471
- } else item.time_position = {
1472
- mode: "absolute",
1473
- offsetMs: move.new_start_ms
1474
- };
866
+ item.time_position = relativePositionForAbs(ranges, move.new_start_ms);
1475
867
  item.fallback_abs_ms = move.new_start_ms;
1476
868
  }
1477
869
  }, audit("MoveSpeeches", input, options));
1478
870
  }
1479
- /** Move the BGM root; any speech/caption descendants follow through their anchors. */
1480
- async moveBgm(input, options) {
1481
- this.validator.validateMoveBgm(input, this.doc);
1482
- this.doc.transact((draft) => {
1483
- const item = findLaneTrack(draft, "bgm")?.items?.[0];
1484
- if (item == null) return;
1485
- item.time_position = {
1486
- mode: "absolute",
1487
- offsetMs: input.new_start_ms
1488
- };
1489
- item.fallback_abs_ms = void 0;
1490
- }, audit("MoveBgm", input, options));
1491
- }
1492
871
  /** Change a speech's script. Re-TTS runs upstream; the regenerated parts arrive materialized (no cascade). */
1493
872
  async changeSpeechScript(input, options) {
1494
873
  this.validator.validateChangeSpeechScript(input, this.doc);
1495
- const absByPartId = solveVideoDocument(this.doc.snapshot()).absByPartId;
1496
874
  this.doc.transact((draft) => {
1497
- writeSpeechAssets(draft, input, absByPartId);
875
+ writeSpeechAssets(draft, input);
1498
876
  }, audit("ChangeSpeechScript", input, options));
1499
877
  }
1500
878
  /** Change a speech's voice. Re-TTS runs upstream; the regenerated parts arrive materialized (no cascade). */
1501
879
  async changeSpeechVoice(input, options) {
1502
880
  this.validator.validateChangeSpeechVoice(input, this.doc);
1503
- const absByPartId = solveVideoDocument(this.doc.snapshot()).absByPartId;
1504
881
  this.doc.transact((draft) => {
1505
- writeSpeechAssets(draft, input, absByPartId);
882
+ writeSpeechAssets(draft, input);
1506
883
  }, audit("ChangeSpeechVoice", input, options));
1507
884
  }
1508
885
  /**
@@ -1544,8 +921,7 @@ var SemanticEditor = class {
1544
921
  mode: "absolute",
1545
922
  offsetMs: 0
1546
923
  },
1547
- fallback_abs_ms: void 0,
1548
- duration_override_ms: void 0
924
+ fallback_abs_ms: void 0
1549
925
  }];
1550
926
  }, audit("SetBgm", input, options));
1551
927
  }
@@ -1568,15 +944,6 @@ var SemanticEditor = class {
1568
944
  track.is_hidden = input.is_hidden;
1569
945
  }, audit("SetCaptionVisibility", input, options));
1570
946
  }
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
947
  /**
1581
948
  * Set the document-wide caption style. GLOBAL (no `caption_id`): the patch is
1582
949
  * merged onto EVERY caption part's `style`, mirroring the FE, which applies a
@@ -1741,7 +1108,7 @@ function normalizeSpeedShift(input) {
1741
1108
  * projection derives it on read. On re-TTS the speech id is preserved, so an
1742
1109
  * existing item is re-positioned rather than duplicated.
1743
1110
  */
1744
- function writeSpeechAssets(draft, assets, absByPartId) {
1111
+ function writeSpeechAssets(draft, assets) {
1745
1112
  const captionById = new Map(assets.captions.map((c) => [c.caption_id, c]));
1746
1113
  const speechTrack = ensureLaneTrack(draft, "speech");
1747
1114
  speechTrack.items ??= [];
@@ -1754,6 +1121,8 @@ function writeSpeechAssets(draft, assets, absByPartId) {
1754
1121
  }
1755
1122
  return captionItems;
1756
1123
  };
1124
+ const ranges = mainTrackRanges(draft);
1125
+ const hostStartMs = (anchorPartId) => ranges.find((r) => r.partId === anchorPartId)?.startMs;
1757
1126
  for (const speech of assets.speeches) {
1758
1127
  const priorCaptionIds = draft.part_library?.[speech.speech_id]?.speech?.caption_ids ?? [];
1759
1128
  const nextCaptionIds = new Set(speech.caption_ids);
@@ -1777,10 +1146,9 @@ function writeSpeechAssets(draft, assets, absByPartId) {
1777
1146
  voice: speech.voice,
1778
1147
  caption_ids: speech.caption_ids
1779
1148
  } });
1780
- const hostStart = speech.anchor_part_id == null ? void 0 : absByPartId.get(speech.anchor_part_id);
1781
- const speechAbs = speech.anchor_part_id == null ? speech.offset_ms : hostStart == null ? void 0 : hostStart + speech.offset_ms;
1782
- if (speech.anchor_part_id == null) placeAbsolute(speechTrack.items, speech.speech_id, speech.offset_ms);
1783
- else placeRelative(speechTrack.items, speech.speech_id, speech.anchor_part_id, speech.offset_ms, speechAbs);
1149
+ const hostStart = hostStartMs(speech.anchor_part_id);
1150
+ const speechAbs = hostStart == null ? void 0 : hostStart + speech.offset_ms;
1151
+ placeRelative(speechTrack.items, speech.speech_id, speech.anchor_part_id, speech.offset_ms, speechAbs);
1784
1152
  for (const captionId of speech.caption_ids) {
1785
1153
  const caption = captionById.get(captionId);
1786
1154
  if (caption == null) continue;
@@ -1822,26 +1190,7 @@ function placeRelative(items, partId, anchorPartId, offsetMs, fallbackAbsMs) {
1822
1190
  items.push({
1823
1191
  part_id: partId,
1824
1192
  time_position: timePosition,
1825
- fallback_abs_ms: fallbackAbsMs,
1826
- duration_override_ms: void 0
1827
- });
1828
- }
1829
- function placeAbsolute(items, partId, startMs) {
1830
- const timePosition = {
1831
- mode: "absolute",
1832
- offsetMs: Math.max(0, Math.round(startMs))
1833
- };
1834
- const existing = items.find((item) => item?.part_id === partId);
1835
- if (existing != null) {
1836
- existing.time_position = timePosition;
1837
- existing.fallback_abs_ms = void 0;
1838
- return;
1839
- }
1840
- items.push({
1841
- part_id: partId,
1842
- time_position: timePosition,
1843
- fallback_abs_ms: void 0,
1844
- duration_override_ms: void 0
1193
+ fallback_abs_ms: fallbackAbsMs
1845
1194
  });
1846
1195
  }
1847
1196
  /**
@@ -1967,6 +1316,111 @@ function deleteAnchoredSubtree(draft, clipId) {
1967
1316
  for (const speechId of anchored) deleteSpeechSubtree(draft, speechId);
1968
1317
  }
1969
1318
  //#endregion
1319
+ //#region src/editor/journal.ts
1320
+ /**
1321
+ * Wire a plain-memory adapter + editor that share a recording id factory, so
1322
+ * every mutating transact lands in `journal` with ordered `generated_ids`.
1323
+ */
1324
+ function createEditSandbox(document, options) {
1325
+ const adapter = createPlainMemoryAdapter(document, options);
1326
+ return {
1327
+ adapter,
1328
+ editor: new SemanticEditor(adapter, new SchemaValidator(), adapter.idFactory),
1329
+ journal: adapter.journal
1330
+ };
1331
+ }
1332
+ /**
1333
+ * Re-drive `doc` from a recorded journal, forcing each entry's `generated_ids`
1334
+ * through a queue-backed id factory. Never mints fresh ids: an empty queue on
1335
+ * demand throws `unrecorded id`; leftover ids after an entry throws
1336
+ * `unconsumed ids`. Legacy entries without `generated_ids` are treated as `[]`.
1337
+ */
1338
+ async function replayJournal(doc, journal) {
1339
+ const queue = [];
1340
+ const idFactory = (_prefix) => {
1341
+ const id = queue.shift();
1342
+ if (id == null) throw new Error("unrecorded id");
1343
+ return id;
1344
+ };
1345
+ const editor = new SemanticEditor(doc, new SchemaValidator(), idFactory);
1346
+ for (const entry of journal) {
1347
+ queue.push(...entry.generated_ids ?? []);
1348
+ await dispatchEntry(editor, entry);
1349
+ if (queue.length > 0) throw new Error("unconsumed ids");
1350
+ }
1351
+ }
1352
+ /** Dispatch one journal entry to the matching editor method; payload is passed through. */
1353
+ async function dispatchEntry(editor, entry) {
1354
+ const payload = entry.payload;
1355
+ const options = entry.intent != null ? { intent: entry.intent } : void 0;
1356
+ switch (entry.kind) {
1357
+ case "MoveVideoClips":
1358
+ await editor.moveVideoClips(payload, options);
1359
+ return;
1360
+ case "MoveVideoClipsByAnchor":
1361
+ await editor.moveVideoClipsByAnchor(payload, options);
1362
+ return;
1363
+ case "DeleteVideoClips":
1364
+ await editor.deleteVideoClips(payload, options);
1365
+ return;
1366
+ case "AddVideoClips":
1367
+ await editor.addVideoClips(payload, options);
1368
+ return;
1369
+ case "AdjustVideoClipVolume":
1370
+ await editor.adjustVideoClipVolume(payload, options);
1371
+ return;
1372
+ case "SetVideoClipSpeedShift":
1373
+ await editor.setVideoClipSpeedShift(payload, options);
1374
+ return;
1375
+ case "ReplaceVideoClipContent":
1376
+ await editor.replaceVideoClipContent(payload, options);
1377
+ return;
1378
+ case "ReplaceVideoClipSequence":
1379
+ await editor.replaceVideoClipSequence(payload, options);
1380
+ return;
1381
+ case "AdjustVideoClipDuration":
1382
+ await editor.adjustVideoClipDuration(payload, options);
1383
+ return;
1384
+ case "AddSpeeches":
1385
+ await editor.addSpeeches(payload, options);
1386
+ return;
1387
+ case "DeleteSpeeches":
1388
+ await editor.deleteSpeeches(payload, options);
1389
+ return;
1390
+ case "MoveSpeeches":
1391
+ await editor.moveSpeeches(payload, options);
1392
+ return;
1393
+ case "ChangeSpeechScript":
1394
+ await editor.changeSpeechScript(payload, options);
1395
+ return;
1396
+ case "ChangeSpeechVoice":
1397
+ await editor.changeSpeechVoice(payload, options);
1398
+ return;
1399
+ case "AdjustSpeechVolume":
1400
+ await editor.adjustSpeechVolume(payload, options);
1401
+ return;
1402
+ case "SetCaptionVisibility":
1403
+ await editor.setCaptionVisibility(payload, options);
1404
+ return;
1405
+ case "SetCaptionStyle":
1406
+ await editor.setCaptionStyle(payload, options);
1407
+ return;
1408
+ case "SetBgm":
1409
+ await editor.setBgm(payload, options);
1410
+ return;
1411
+ case "DeleteBgm":
1412
+ await editor.deleteBgm(payload, options);
1413
+ return;
1414
+ case "AdjustBgmVolume":
1415
+ await editor.adjustBgmVolume(payload, options);
1416
+ return;
1417
+ default: {
1418
+ const _exhaustive = entry.kind;
1419
+ throw new Error(`replayJournal: unsupported kind ${String(_exhaustive)}`);
1420
+ }
1421
+ }
1422
+ }
1423
+ //#endregion
1970
1424
  //#region src/editor/types.ts
1971
1425
  /** Runtime list of the frozen, implemented kinds (for guards / introspection). */
1972
1426
  const IMPLEMENTED_SEMANTIC_OP_KINDS = [
@@ -1982,11 +1436,9 @@ const IMPLEMENTED_SEMANTIC_OP_KINDS = [
1982
1436
  "AddSpeeches",
1983
1437
  "DeleteSpeeches",
1984
1438
  "MoveSpeeches",
1985
- "MoveBgm",
1986
1439
  "ChangeSpeechScript",
1987
1440
  "ChangeSpeechVoice",
1988
1441
  "AdjustSpeechVolume",
1989
- "ResizeCaption",
1990
1442
  "SetCaptionVisibility",
1991
1443
  "SetCaptionStyle",
1992
1444
  "SetBgm",
@@ -2163,6 +1615,18 @@ var ManualSyncDoc = class ManualSyncDoc {
2163
1615
  return fromVideoDocument(this.adapter.snapshot());
2164
1616
  }
2165
1617
  /**
1618
+ * Replay a deterministic sandbox journal into this document.
1619
+ *
1620
+ * The adapter stays private so callers cannot bypass the manual-sync
1621
+ * lifecycle; journal replay is the one host-side operation that needs the
1622
+ * adapter's transaction boundary and recorded id queue. Durability is still
1623
+ * explicit: call {@link push} after replay and report success only from its
1624
+ * verdict.
1625
+ */
1626
+ async replayJournal(journal) {
1627
+ await replayJournal(this.adapter, journal);
1628
+ }
1629
+ /**
2166
1630
  * Mark the document state the caller has just observed, for a later
2167
1631
  * {@link hasChangedSince}.
2168
1632
  *
@@ -2762,6 +2226,24 @@ var MengineDocSession = class {
2762
2226
  if (this.editorValue == null) throw new Error("mengine doc session is not started");
2763
2227
  return this.editorValue;
2764
2228
  }
2229
+ /**
2230
+ * Opaque version token of the local oplog (base64 `VersionVector.encode`).
2231
+ * Equality-comparable only: equal means no observed change (local or
2232
+ * remote-arrived) since the token was taken. Throws when not started.
2233
+ */
2234
+ version() {
2235
+ if (this.adapterValue == null) throw new Error("mengine doc session is not started");
2236
+ return bytesToBase64(this.adapterValue.doc.oplogVersion().encode());
2237
+ }
2238
+ /**
2239
+ * The live document adapter, exposed for journal replay (commit channel).
2240
+ * Replaying through it still goes SemanticEditor → Loro → mengine-server —
2241
+ * no write bypass. Typed by the narrow interface on purpose.
2242
+ */
2243
+ get documentAdapter() {
2244
+ if (this.adapterValue == null) throw new Error("mengine doc session is not started");
2245
+ return this.adapterValue;
2246
+ }
2765
2247
  /** Current document snapshot (read model). */
2766
2248
  snapshot() {
2767
2249
  if (this.adapterValue == null) throw new Error("mengine doc session is not started");
@@ -2872,4 +2354,4 @@ function serverCovers(serverVV, target) {
2872
2354
  return covers(server, target);
2873
2355
  }
2874
2356
  //#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 };
2357
+ 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, relativePositionForAbs, replayJournal, resolveAllSpeechOverlaps, resolveSpeechOverlapByShiftingVideos, safeDurationMs, schemas_exports as schemas, snapshotToPlain, solveVideoDocument, speedOf, syncAggregatedClipsTimePosition, toVideoDocument, validateVideoDocument, videoDocumentMirrorSchema, videoDocumentSchema, writeVideoDocumentToDraft };