@mengine/medeo-client 1.0.1-alpha.2 → 1.1.0

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.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- import { t as index_d_exports } from "./index-6e5cbdM3.js";
2
- import { $ as VideoClipPart, A as TrackItemDraft, B as derivePositionFromAbs, C as isImplementedSemanticOpKind, D as PartIdFactory, E as ValidationError, F as assertValidVideoDocument, G as PartKind, H as toVideoDocument, I as validateVideoDocument, J as Timeline, K as PartUnion, L as DerivedItemPosition, M as VideoDocumentMirrorSchema, N as videoDocumentMirrorSchema, O as generatePartId, P as VideoDocumentValidationError, Q as VIDEO_DOCUMENT_SCHEMA_VERSION, R as SpeechHostMap, S as SemanticOpKind, T as SnapshotReadable, U as BgmPart, V as fromVideoDocument, W as CaptionPart, X as TrackItem, Y as Track, Z as TrackItemTimePosition, _ as SemanticOpName, a as PlainMemoryAdapter, at as effectiveVideoClipDurationMs, b as ImplementedSemanticOpKind, c as MirrorVideoDocumentAdapter, ct as CaptionPart$1, d as createMirrorVideoDocumentAdapter, dt as SpeedShift, et as VideoDocument, f as writeVideoDocumentToDraft, ft as Timeline$1, g as SemanticOpInput, h as SemanticEditor, i as JournalEntry, it as VideoDraft, j as VideoDocumentDraft, k as TrackDraft, l as MirrorVideoDocumentOptions, lt as CaptionStyle, m as SemanticDocumentAdapter, mt as TrackItem$1, n as videoDocumentSchema, nt as VideoDocumentValidationIssue, o as PlainMemoryAdapterOptions, ot as speedOf, p as CommitOptions, pt as Track$1, q as SpeechPart, r as readVideoDocumentFromDraft, rt as VideoDocumentValidationIssueCode, s as createPlainMemoryAdapter, st as Attachment, t as partUnionSchema, tt as VideoDocumentSchemaVersion, u as createMirrorVideoDocument, ut as PartAggregation, v as TransactAudit, w as SchemaValidator, x as PlannedSemanticOpKind, y as IMPLEMENTED_SEMANTIC_OP_KINDS, z as buildSpeechHostMap } from "./index-DRUGsbm2.js";
1
+ import { $ as VideoDocumentValidationIssue, A as assertValidVideoDocument, B as BgmPart, C as index_d_exports, D as VideoDocumentMirrorSchema, E as VideoDocumentDraft, F as SpeechHostMap, G as Timeline, H as PartKind, I as buildSpeechHostMap, J as TrackItemTimePosition, K as Track, L as derivePositionFromAbs, M as InitialDocumentFacts, N as buildInitialVideoDocument, O as videoDocumentMirrorSchema, P as DerivedItemPosition, Q as VideoDocumentSchemaVersion, R as fromVideoDocument, S as ValidationError, T as TrackItemDraft, U as PartUnion, V as CaptionPart, W as SpeechPart, X as VideoClipPart, Y as VIDEO_DOCUMENT_SCHEMA_VERSION, Z as VideoDocument, _ as PlannedSemanticOpKind, a as MirrorVideoDocumentOptions, at as CaptionStyle, b as SchemaValidator, c as CommitOptions, ct as Timeline$1, d as SemanticEditor, et as VideoDocumentValidationIssueCode, f as SemanticOpInput, g as ImplementedSemanticOpKind, h as IMPLEMENTED_SEMANTIC_OP_KINDS, i as MirrorVideoDocumentAdapter, it as CaptionPart$1, j as validateVideoDocument, k as VideoDocumentValidationError, l as OpActor, lt as Track$1, m as TransactAudit, n as videoDocumentSchema, nt as VideoDraftPartUnion, o as createMirrorVideoDocument, ot as PartAggregation, p as SemanticOpName, q as TrackItem, r as readVideoDocumentFromDraft, rt as Attachment, s as createMirrorVideoDocumentAdapter, st as SpeedShift, t as partUnionSchema, tt as VideoDraft, u as SemanticDocumentAdapter, ut as TrackItem$1, v as SemanticOpKind, w as TrackDraft, x as SnapshotReadable, y as isImplementedSemanticOpKind, z as toVideoDocument } from "./index-BUKA3L7o.js";
3
2
  import { PeerID } from "loro-crdt";
4
3
  import { DocState } from "@mengine/sync";
5
4
  import { BaseDocStorage, Connection, DocDiff, DocSnapshotRecord, DocStorage, DocStorageOptions, DocUpdate, DocUpdateRecord } from "@mengine/storage";
@@ -25,6 +24,16 @@ interface MengineUpdateMeta {
25
24
  semantic_op: string | null;
26
25
  payload: unknown;
27
26
  intent: string | null;
27
+ /**
28
+ * Who authored the op, as recorded in the Loro commit message (see `OpActor`).
29
+ * Null for writes with no acting user — bootstrap, repair — and for Changes
30
+ * written before attribution existed. Self-reported by the authoring client;
31
+ * the server does not verify it against the request identity.
32
+ */
33
+ actor: {
34
+ user_id: string;
35
+ role: string;
36
+ } | null;
28
37
  message: string | null;
29
38
  parse_error: boolean;
30
39
  peer: string;
@@ -99,6 +108,26 @@ declare class MengineHttpRequestError extends Error {
99
108
  readonly payload: unknown;
100
109
  constructor(status: number, payload: unknown);
101
110
  }
111
+ /**
112
+ * A push the server refused on its merits (`kind: 'rejected'`), as opposed to a
113
+ * transport failure. Carries the server's machine `code` so callers can branch on
114
+ * *why* rather than on an HTTP status:
115
+ *
116
+ * - `missing_dependency` (server answers 409) — retryable: the update depends on
117
+ * ops the server log lacks, so catching up and re-exporting resolves it.
118
+ * - `corrupt_update` (server answers 422) — never valid, retrying cannot help.
119
+ *
120
+ * Distinct from {@link MengineHttpRequestError} (transport/status-level failure)
121
+ * and from a raw `fetch` rejection (network down): the three are separate classes
122
+ * so a caller can tell "the server said no" from "the server never answered".
123
+ */
124
+ declare class MenginePushRejectedError extends Error {
125
+ readonly code: string;
126
+ readonly serverMessage: string;
127
+ readonly serverVersion: MengineDocumentVersion | undefined;
128
+ readonly status: number | undefined;
129
+ constructor(code: string, serverMessage: string, serverVersion: MengineDocumentVersion | undefined, status: number | undefined);
130
+ }
102
131
  declare class MengineHttpClient {
103
132
  private readonly options;
104
133
  private readonly fetchImpl;
@@ -113,7 +142,24 @@ declare class MengineHttpClient {
113
142
  sync(fromVV?: Uint8Array): Promise<MengineSyncResponse>;
114
143
  /** Audit trail: extracted metadata per accepted update, in log order. */
115
144
  audit(): Promise<MengineAuditResponse>;
116
- pushUpdate(update: Uint8Array, baseVersion?: unknown): Promise<MenginePushUpdateResponse>;
145
+ /**
146
+ * Append one Loro update to the server log.
147
+ *
148
+ * Resolves for both accepted outcomes and hands the verdict back verbatim —
149
+ * `ack` (appended, `update_seq` allocated) and `duplicate` (already known, no
150
+ * row appended). A `duplicate` is NOT an error, but it is also not an ack: it
151
+ * means the bytes contributed nothing, so a caller waiting for its own write to
152
+ * land must be able to tell them apart. Hence the verdict is returned rather
153
+ * than collapsed into `void`.
154
+ *
155
+ * Rejections raise {@link MenginePushRejectedError} carrying the server's
156
+ * machine `code`. The server answers them with 409/422, so the failure arrives
157
+ * as a non-ok response; this method re-reads the parsed body to recover `code` /
158
+ * `server_version` instead of leaving the caller a bare status. Transport-level
159
+ * failures stay {@link MengineHttpRequestError}, and a dead network keeps
160
+ * surfacing as the underlying `fetch` rejection.
161
+ */
162
+ pushUpdate(update: Uint8Array): Promise<MenginePushUpdateResponse>;
117
163
  eventsUrl(): string;
118
164
  headers(): Headers;
119
165
  fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
@@ -131,23 +177,33 @@ interface MengineEventStreamOptions {
131
177
  }
132
178
  declare function readMengineEventStream(options: MengineEventStreamOptions): Promise<void>;
133
179
  //#endregion
134
- //#region src/editor/journal.d.ts
180
+ //#region src/editor/id-gen.d.ts
135
181
  /**
136
- * Wire a plain-memory adapter + editor that share a recording id factory, so
137
- * every mutating transact lands in `journal` with ordered `generated_ids`.
182
+ * Part-id generation, aligned with the online ecosystem.
183
+ *
184
+ * The authoritative online producers — agent-harness (`@harness/shared`
185
+ * `genObjId`) and director.v2 (`common/obj_id.py` `gen_obj_id`) — both mint part
186
+ * ids as `` `${prefix}_${ulid()}` ``, and real captured drafts use exactly that
187
+ * shape (`clip_…` / `spe_…` / `cap_…` / `bgm_…`, each a 26-char ULID). The engine
188
+ * previously emitted `vc_<base36 timestamp><6 random>`, a different prefix AND a
189
+ * different encoding — the sole cross-repo id divergence. This module removes it
190
+ * by emitting the same `<prefix>_<ULID>` bytes.
191
+ *
192
+ * The ULID is generated inline (Crockford Base32, 48-bit time + 80-bit random)
193
+ * rather than pulling the `ulid` npm package: the randomness class matches the
194
+ * old generator (both `Math.random`-based) and it keeps `@mengine/medeo-client`
195
+ * dependency-free for a purely mechanical id string. Part ids only need to be
196
+ * unique and lexicographically time-sortable, which this satisfies.
138
197
  */
139
- declare function createEditSandbox(document: VideoDocument, options?: PlainMemoryAdapterOptions): {
140
- adapter: PlainMemoryAdapter;
141
- editor: SemanticEditor;
142
- journal: readonly JournalEntry[];
143
- };
144
198
  /**
145
- * Re-drive `doc` from a recorded journal, forcing each entry's `generated_ids`
146
- * through a queue-backed id factory. Never mints fresh ids: an empty queue on
147
- * demand throws `unrecorded id`; leftover ids after an entry throws
148
- * `unconsumed ids`. Legacy entries without `generated_ids` are treated as `[]`.
199
+ * Online part-id semantic prefixes. `clip` (video clip) is the only value the
200
+ * engine currently mints (see `addVideoClips`); the rest are declared so the
201
+ * type documents the shared vocabulary and guards against reintroducing the old
202
+ * `vc`/`sp`/`cp`/`bg` names. Speech/caption/bgm ids arrive pre-minted in op
203
+ * payloads, so the engine never generates them itself.
149
204
  */
150
- declare function replayJournal(doc: SemanticDocumentAdapter, journal: readonly JournalEntry[]): Promise<void>;
205
+ type PartIdPrefix = 'clip' | 'spe' | 'cap' | 'bgm' | 'ti';
206
+ declare function generatePartId(prefix: PartIdPrefix): string;
151
207
  //#endregion
152
208
  //#region src/editor/snapshot-utils.d.ts
153
209
  /** Main-track item identity read from a raw snapshot (only `part_id` is needed). */
@@ -171,6 +227,355 @@ declare function readPart(snapshot: unknown, partId: string): (Record<string, un
171
227
  part_kind?: PartKind;
172
228
  }) | null;
173
229
  //#endregion
230
+ //#region src/manual-sync/types.d.ts
231
+ /**
232
+ * Opaque marker for "the document state I last looked at".
233
+ *
234
+ * Deliberately not a number. Under mengine there is no monotonic document
235
+ * version to compare: `meta.version` is stamped once at legacy ingest and then
236
+ * frozen, and the server's `update_seq` counts every writer's pushes, so neither
237
+ * can answer "has this document changed since I last read it". The answer comes
238
+ * from comparing version vectors.
239
+ *
240
+ * Opaque means: no arithmetic, no ordering, no comparison other than handing it
241
+ * back to {@link ManualSyncDoc.hasChangedSince}. Two version vectors are only
242
+ * partially ordered — concurrent ones are neither greater nor equal, and Loro's
243
+ * own `compare` returns `undefined` for them — so `mark1 > mark2` or sorting a
244
+ * list of marks has no meaning to get wrong.
245
+ *
246
+ * Persisting one IS supported, via {@link encodeDocVersionMark} /
247
+ * {@link decodeDocVersionMark}. Storing an opaque blob and reading it back does
248
+ * not order or compute anything, and callers that compare across turns (rather
249
+ * than within one process) need it: the legacy integer version this replaces was
250
+ * itself persisted between agent turns.
251
+ */
252
+ interface DocVersionMark {
253
+ readonly __brand: 'mengine-doc-version-mark';
254
+ /** Encoded oplog `VersionVector` at the moment the mark was taken. */
255
+ readonly encoded: Uint8Array;
256
+ }
257
+ /** Why a `pull()` did not complete. Mirrors the push failure taxonomy. */
258
+ type PullFailureReason = 'failed';
259
+ /**
260
+ * Result of a `pull()`.
261
+ *
262
+ * `ok: false` is a first-class outcome, not an exception: per the M2/A ruling a
263
+ * failed pull must not hard-fail the tool call, matching legacy's tolerance for
264
+ * read failures (`getDraftVersion` swallows to null, `DraftVersionDetector`
265
+ * catches and skips). The caller decides whether to proceed on a possibly-stale
266
+ * document, so the degradation has to be visible in the return value.
267
+ */
268
+ type PullResult = {
269
+ ok: true; /** True when the pull actually advanced the local document. */
270
+ changed: boolean;
271
+ } | {
272
+ ok: false;
273
+ reason: PullFailureReason;
274
+ error: Error;
275
+ };
276
+ /**
277
+ * What the server did with a `push()`.
278
+ *
279
+ * The first four mirror the server's verdict taxonomy (see `PushOutcomeKind`);
280
+ * `nothing_to_push` is a local short-circuit — no request was made because the
281
+ * document holds no ops the server lacks.
282
+ */
283
+ type PushResultKind = 'ack' | 'duplicate' | 'rejected' | 'failed' | 'nothing_to_push';
284
+ /**
285
+ * Result of a `push()`.
286
+ *
287
+ * `collaborated` is the load-bearing field. The legacy Drizzle path fails loudly
288
+ * on concurrent writes (`Optimistic lock failed`); mengine merges silently by
289
+ * design (M0/S2 accepted CRDT merge semantics). Migrating without surfacing this
290
+ * would replace a path that reports conflicts with one that hides them, so every
291
+ * successful push says whether the server held ops the local document did not.
292
+ *
293
+ * Its meaning is "the server has ops you don't", NOT "there was a conflict" — the
294
+ * same user's other browser tab counts. It is therefore suitable for driving a
295
+ * re-pull and for informing the caller, but not for raising an alarm on its own.
296
+ */
297
+ interface PushResult {
298
+ kind: PushResultKind;
299
+ /** Server-allocated sequence number; only present for `ack`. */
300
+ updateSeq?: number | undefined;
301
+ /** Whether the server held ops the local document lacked. See above. */
302
+ collaborated: boolean;
303
+ /** Server machine code for `rejected` (`missing_dependency` / `corrupt_update`). */
304
+ code?: string | undefined;
305
+ /** Underlying error for `rejected` / `failed`. */
306
+ error?: Error | undefined;
307
+ }
308
+ //#endregion
309
+ //#region src/manual-sync/doc-version-mark.d.ts
310
+ /**
311
+ * Encode a {@link DocVersionMark} for storage or transport.
312
+ *
313
+ * The mark stays opaque across the round trip — the string is not a version
314
+ * number and must not be compared, ordered, or parsed. Its only use is
315
+ * {@link decodeDocVersionMark} followed by `hasChangedSince`.
316
+ *
317
+ * Callers that persist this should know the encoded length grows with the number
318
+ * of peers that have ever written to the document (one counter each), and the FE
319
+ * mints a fresh peer per page load. Still small in practice (a few hundred bytes
320
+ * for dozens of peers), but it grows with document age rather than size; version
321
+ * vector compaction is deferred to a later phase.
322
+ */
323
+ declare function encodeDocVersionMark(mark: DocVersionMark): string;
324
+ /**
325
+ * Rebuild a mark from {@link encodeDocVersionMark}'s output.
326
+ *
327
+ * Returns `undefined` for input this did not produce (a legacy integer version,
328
+ * a truncated value, an empty string). That is the honest answer — "I cannot
329
+ * establish what you last saw" — and callers should treat it as "no baseline"
330
+ * rather than as "unchanged". Decoding does not validate the bytes as a version
331
+ * vector; `hasChangedSince` reports "changed" for an undecodable mark, which is
332
+ * the conservative direction.
333
+ */
334
+ declare function decodeDocVersionMark(encoded: string): DocVersionMark | undefined;
335
+ //#endregion
336
+ //#region src/manual-sync/manual-sync-doc.d.ts
337
+ interface ManualSyncDocOptions {
338
+ client: MengineHttpClient;
339
+ /**
340
+ * Peer id for this writer. Every writer needs a distinct one: two writers
341
+ * sharing a peer and branching from the same base emit identical
342
+ * `(peer, counter)` pairs, the server classifies the second as `duplicate` and
343
+ * drops it, and the write is silently lost. Callers mint a random one (see the
344
+ * harness's `mintHarnessPeerId`).
345
+ */
346
+ peerId?: PeerID;
347
+ }
348
+ /**
349
+ * Agent-facing document with explicit `pull()` / `push()` over one Loro
350
+ * document, with no background sync (ADR 0015 D1–D4).
351
+ *
352
+ * It deliberately does NOT reuse `MengineDocSession`'s stack. That stack —
353
+ * SSE + local `DocStorage` + `ClientServerSynchronizer` + `DocManager` — is
354
+ * correct for a browser editor and actively wrong here:
355
+ *
356
+ * - Its retry backoff lands *outside* the tool-call lifetime, so a write can
357
+ * settle seconds after the tool already told the LLM what happened.
358
+ * - It has no durable local queue in the harness, so pending pushes die with the
359
+ * process — that is lost data, reported as success.
360
+ * - Agent semantics require the document to change only at points the agent can
361
+ * name. If it converged on its own between tool calls, "what state was this
362
+ * decision based on" would be unanswerable, and a remote change could land
363
+ * mid-edit.
364
+ *
365
+ * What replaces the whole background job queue is one variable: the **watermark**,
366
+ * the version the server has confirmed. `push()` exports `{mode:'update', from:
367
+ * watermark}` and only advances it on a confirmed verdict, so a failed push is
368
+ * retried implicitly — the next push carries both the failed ops and any new
369
+ * ones, in one blob. No queue, no timer, no retry bookkeeping.
370
+ *
371
+ * Two non-obvious properties of that watermark, both verified against a real
372
+ * server in the ADR 0015 spike:
373
+ *
374
+ * - It can legitimately *lead* the local document (it carries other peers'
375
+ * counters). Exporting `from` a leading watermark does not error; the blob
376
+ * correctly contains only the local peer's new ops. So a collaborative merge
377
+ * does not force a pull before pushing.
378
+ * - Therefore every emptiness/coverage test must be one-directional containment,
379
+ * never equality. See {@link covers}.
380
+ *
381
+ * Lifecycle: one `LoroDoc` per document, shared across agent loops with a
382
+ * refcount held by the caller's session registry. Rebuilding the doc per tool
383
+ * call would mint a new peer each time and permanently inflate the document's
384
+ * version vector for every future reader.
385
+ *
386
+ * Not thread-safe by design and it does not need to be: harness tool calls run
387
+ * serially (`execToolCalls` is a `for` + `await`).
388
+ */
389
+ declare class ManualSyncDoc {
390
+ private readonly client;
391
+ private readonly doc;
392
+ private readonly adapter;
393
+ readonly editor: SemanticEditor;
394
+ /**
395
+ * The version the server is known to hold. Starts empty (nothing confirmed)
396
+ * and only ever moves forward on a verdict that proves the server took our ops.
397
+ */
398
+ private watermark;
399
+ private constructor();
400
+ /**
401
+ * Open an existing server document.
402
+ *
403
+ * Fetches the snapshot up front rather than starting empty and converging: the
404
+ * agent's first act is to read the document, so there is no useful state before
405
+ * the snapshot lands. This also fails fast and loudly on a document that does
406
+ * not exist, instead of `MengineDocSession.waitForContent()`'s behavior of
407
+ * waiting forever for content that will never arrive.
408
+ */
409
+ static open(options: ManualSyncDocOptions): Promise<ManualSyncDoc>;
410
+ /** Current document read model (authoritative shape). */
411
+ snapshot(): VideoDocument;
412
+ /**
413
+ * The Loro peer this document writes as.
414
+ *
415
+ * Exposed because the peer is an externally-meaningful fact, not an internal
416
+ * detail: it is the identity every op this document emits is attributed to, and
417
+ * callers mint it under rules of their own (the harness reserves a range so a
418
+ * peer id alone says "Agent wrote this"). Being able to read it back means those
419
+ * rules can be verified against the live document rather than against whatever
420
+ * was passed to the constructor.
421
+ */
422
+ editorPeerId(): PeerID;
423
+ /** Current document projected to the legacy `VideoDraft` read shape. */
424
+ draft(): VideoDraft;
425
+ /**
426
+ * Mark the document state the caller has just observed, for a later
427
+ * {@link hasChangedSince}.
428
+ *
429
+ * This pair replaces the legacy integer-version comparison that
430
+ * `DraftVersionDetector` used to tell the LLM "the draft was modified
431
+ * externally, reload before editing". Under mengine `meta.version` never
432
+ * changes, so that detector would go permanently silent; comparing version
433
+ * vectors restores the same capability.
434
+ *
435
+ * Same capability, not a stronger one: like the legacy detector, this only
436
+ * reports what changed between two moments the caller chose to sample.
437
+ */
438
+ versionMark(): DocVersionMark;
439
+ /**
440
+ * Has the document moved since `mark` was taken?
441
+ *
442
+ * Reports any advance, whoever caused it — including this document's own edits.
443
+ * The caller decides what is interesting: a detector sampling once per turn is
444
+ * asking "did anything happen", and its own edits legitimately count.
445
+ */
446
+ hasChangedSince(mark: DocVersionMark): boolean;
447
+ /**
448
+ * Fetch and merge everything the server has that this document lacks.
449
+ *
450
+ * Must run *before* the editor on each tool call. `SemanticEditor` validates
451
+ * against the local document, so editing a stale one validates against a world
452
+ * that no longer exists: the ADR 0015 spike confirmed that without pull-first
453
+ * an edit to a clip another writer had already deleted passes validation and is
454
+ * accepted by the server. Pulling afterwards cannot undo that.
455
+ *
456
+ * A failure is returned, not thrown — a transient network blip must not make
457
+ * the tool unusable (M2/A ruling; legacy tolerates read failures the same way).
458
+ * The caller proceeds on a possibly-stale document knowingly.
459
+ */
460
+ pull(): Promise<PullResult>;
461
+ /**
462
+ * Push every local op the server has not confirmed, and report the verdict.
463
+ *
464
+ * The return value is the durability answer a tool needs before claiming
465
+ * success: only `ack` / `duplicate` mean the server holds the ops. This is why
466
+ * this class exists rather than an ack-waiter — with a direct call, "did it
467
+ * land" is simply the result.
468
+ *
469
+ * `duplicate` counts as durable: the bytes added nothing *because* the server
470
+ * already had them.
471
+ */
472
+ push(): Promise<PushResult>;
473
+ /** Decode a wire `server_vv`, tolerating absence/corruption (never throws). */
474
+ private serverVVFrom;
475
+ }
476
+ //#endregion
477
+ //#region src/storage/medeo-http-doc-storage.d.ts
478
+ interface MedeoHttpDocStorageOptions {
479
+ docId: string;
480
+ client: MengineHttpClient;
481
+ sseReconnectDelayMs?: number;
482
+ readonlyMode?: boolean;
483
+ }
484
+ /**
485
+ * What the server did with one pushed update, as observed by this storage.
486
+ *
487
+ * `ack` / `duplicate` mirror the server verdict. `rejected` is a refusal on the
488
+ * merits (carrying the machine `code`: `missing_dependency` is retryable after
489
+ * catch-up, `corrupt_update` never is). `failed` is everything else — transport
490
+ * error, non-2xx status, dead network — i.e. the server's answer is unknown.
491
+ *
492
+ * The four are kept distinct because the recovery differs per case, and because
493
+ * the whole point of M1 is that a caller can tell "written" from "not written".
494
+ */
495
+ type PushOutcomeKind = 'ack' | 'duplicate' | 'rejected' | 'failed';
496
+ interface PushOutcome {
497
+ kind: PushOutcomeKind;
498
+ /** Server-allocated sequence number; only present for `ack`. */
499
+ updateSeq?: number | undefined;
500
+ /**
501
+ * The server oplog version vector *after* handling this push (`ack` and
502
+ * `duplicate` both carry it; encoded `VersionVector`).
503
+ *
504
+ * This is what an "is my write durable" waiter keys on, and it is deliberately
505
+ * the ONLY correlation handle here. An earlier revision also carried the pushed
506
+ * bytes so a waiter could match its own update; that was removed because byte
507
+ * identity is not a reliable match — the same ops can reach the server either
508
+ * as the individual blob the push job carried or as a merged
509
+ * `export({from: serverVV})` blob produced by the synchronizer's sync path.
510
+ * Version coverage is reliable, and it makes `duplicate` satisfy a waiter
511
+ * correctly: the bytes appended nothing precisely because the server already
512
+ * held them. Offering both invited the wrong one.
513
+ */
514
+ serverVV?: Uint8Array | undefined;
515
+ /** Server machine code for `rejected` (e.g. `missing_dependency`). */
516
+ code?: string | undefined;
517
+ /** The underlying error for `rejected` / `failed`. */
518
+ error?: Error | undefined;
519
+ }
520
+ /**
521
+ * Adapts the mengine-server HTTP/SSE protocol to the engine `DocStorage`
522
+ * contract so `ClientServerSynchronizer` can treat it as a remote peer.
523
+ *
524
+ * Deliberately thin (mirrors the socket `DocStorage` in the playground): it
525
+ * forwards live SSE updates and exposes a version-vector diff, and keeps NO
526
+ * sync state of its own.
527
+ *
528
+ * - `getDocDiff(docId, knownVersion)` pulls the server-computed VV-diff via
529
+ * `GET /sync?from=<vv>` — the synchronizer passes the real `doc.version()`, so
530
+ * the response carries exactly the ops the doc is missing. `getDoc` (full
531
+ * `/snapshot`) stays for cold start, when the caller holds no version yet.
532
+ * - `pushDocUpdate` forwards a Loro update; the server appends it.
533
+ * - `subscribeDocUpdate` registers a callback for live SSE updates. It does no
534
+ * catch-up and keeps no cursor: after an SSE drop the connection reports a
535
+ * status change, and the synchronizer re-runs its cycle to catch up via
536
+ * `getDocDiff(doc.version())`. `LoroDoc.import` is idempotent (OpId/VV), so
537
+ * re-forwarded or echoed updates are harmless.
538
+ *
539
+ * It is bound to a single `docId` because `MengineHttpClient` is per-document.
540
+ */
541
+ declare class MedeoHttpDocStorage implements DocStorage {
542
+ private readonly options;
543
+ readonly connection: Connection;
544
+ private readonly client;
545
+ private readonly docId;
546
+ private readonly events;
547
+ constructor(options: MedeoHttpDocStorageOptions);
548
+ get isReadonly(): boolean;
549
+ getDoc(docId: string): Promise<DocSnapshotRecord | null>;
550
+ getDocDiff(docId: string, knownVersion?: Uint8Array): Promise<DocDiff | null>;
551
+ /**
552
+ * Forward one update to the server.
553
+ *
554
+ * The `DocStorage` contract returns `void`, so the server's verdict cannot be
555
+ * the return value — it is published on {@link subscribePushOutcome} instead,
556
+ * for BOTH outcomes and failures. That channel is what makes the push
557
+ * observable; previously the verdict was read and dropped, so a `duplicate`
558
+ * (bytes contributed nothing) was indistinguishable from a successful write.
559
+ *
560
+ * The error is still rethrown after being published: the synchronizer treats a
561
+ * throw as "retry this cycle", and swallowing it here would strand the update.
562
+ * Publishing is therefore additive observability, not error handling.
563
+ */
564
+ pushDocUpdate(update: DocUpdate, _origin: unknown): Promise<void>;
565
+ /**
566
+ * Observe the server's verdict for every pushed update, including failures.
567
+ *
568
+ * This is the loud channel the `void`-returning `DocStorage.pushDocUpdate`
569
+ * cannot express. Consumers that need "did my write land" (the agent's
570
+ * tool-level ack wait) subscribe here.
571
+ */
572
+ subscribePushOutcome(callback: (outcome: PushOutcome) => void): () => void;
573
+ deleteDoc(_docId: string): Promise<void>;
574
+ subscribeDocUpdate(callback: (update: DocUpdate, origin: unknown) => void): () => void;
575
+ private assertDocId;
576
+ private emitUpdate;
577
+ }
578
+ //#endregion
174
579
  //#region src/session/types.d.ts
175
580
  /**
176
581
  * Local storage contract the runtime depends on. Aliased to the engine
@@ -185,6 +590,34 @@ interface MengineDocSessionUpdateEvent {
185
590
  source: 'remote' | 'local';
186
591
  snapshot: VideoDocument;
187
592
  }
593
+ /**
594
+ * Raised by {@link MengineDocSession.waitForServerAck} when the local edits it
595
+ * was asked to confirm were not acknowledged as durable.
596
+ *
597
+ * Named `...AckFailed`, not `...AckTimeout`: two of the three `reason` values are
598
+ * not timeouts, and the earlier name made callers reach for a retry-after-delay
599
+ * that is wrong for `rejected`.
600
+ *
601
+ * The distinction the caller needs is "was it written": if this throws, treat the
602
+ * write as NOT durable. `reason` says which failure it was, and `code` carries the
603
+ * server's machine code when the push was rejected on its merits:
604
+ *
605
+ * - `timeout` — no verdict within the deadline. Ambiguous by nature: the push may
606
+ * still land later. The caller should surface it as unconfirmed, not as "failed".
607
+ * - `rejected` — the server refused. `missing_dependency` is retryable after
608
+ * catch-up; `corrupt_update` never is.
609
+ * - `failed` — transport/network failure; the server's answer is unknown.
610
+ */
611
+ declare class MengineAckFailedError extends Error {
612
+ readonly reason: 'timeout' | 'rejected' | 'failed';
613
+ readonly code: string | undefined;
614
+ readonly cause: Error | undefined;
615
+ constructor(reason: 'timeout' | 'rejected' | 'failed', code: string | undefined, cause: Error | undefined, message: string);
616
+ }
617
+ interface WaitForServerAckOptions {
618
+ /** Deadline in ms. Rejects with reason `timeout` when it elapses. */
619
+ timeoutMs?: number;
620
+ }
188
621
  interface MengineDocSessionOptions {
189
622
  docId: string;
190
623
  client: MengineHttpClient;
@@ -230,7 +663,44 @@ declare class MengineDocSession {
230
663
  private adapterValue;
231
664
  private editorValue;
232
665
  private started;
666
+ /**
667
+ * Latest server oplog version seen on a push outcome. Lets `waitForServerAck`
668
+ * return without waiting when the server is already known to cover the local
669
+ * doc (e.g. nothing was edited since the last confirmed push).
670
+ */
671
+ private serverVVValue;
233
672
  constructor(options: MengineDocSessionOptions);
673
+ /**
674
+ * Observe every push verdict, including `duplicate` and failures.
675
+ *
676
+ * Exposed so a host can log/meter the four outcomes (rfc/05 §3 asks for
677
+ * explicit ack/rejected semantics). Most callers want the higher-level
678
+ * {@link waitForServerAck} instead.
679
+ */
680
+ subscribePushOutcome(callback: (outcome: PushOutcome) => void): () => void;
681
+ /**
682
+ * Resolve once the server has durably accepted the local document state as of
683
+ * *now* — the capability an Agent tool needs to answer "did my edit land?"
684
+ * before reporting success.
685
+ *
686
+ * Call it right after the editor ops whose durability matters. It snapshots the
687
+ * local doc's current version and resolves on the first push outcome whose
688
+ * `serverVV` covers that version, i.e. the server log is at least as advanced as
689
+ * the local doc was when this was called.
690
+ *
691
+ * Version coverage, not byte identity, is the acceptance test — for two reasons:
692
+ * the ops may reach the server inside a merged blob rather than as the exact
693
+ * bytes a push job carried, and a `duplicate` verdict then correctly satisfies
694
+ * the wait (the bytes appended nothing *because* the server already had them).
695
+ * A `rejected` / `failed` outcome rejects immediately with that reason rather
696
+ * than burning the whole timeout, since neither will resolve by waiting.
697
+ *
698
+ * Returns early when the server is already known to be current, so a caller
699
+ * with nothing outstanding does not block.
700
+ *
701
+ * @throws {MengineAckFailedError} on timeout, rejection, or transport failure.
702
+ */
703
+ waitForServerAck(options?: WaitForServerAckOptions): Promise<void>;
234
704
  /**
235
705
  * The editor for local edits. Each op method validates, writes, and commits
236
706
  * itself as one SemanticOp (single commit carrying its audit message), so
@@ -238,18 +708,6 @@ declare class MengineDocSession {
238
708
  * step. The committed change drives DocManager's local-update push.
239
709
  */
240
710
  get editor(): SemanticEditor;
241
- /**
242
- * Opaque version token of the local oplog (base64 `VersionVector.encode`).
243
- * Equality-comparable only: equal means no observed change (local or
244
- * remote-arrived) since the token was taken. Throws when not started.
245
- */
246
- version(): string;
247
- /**
248
- * The live document adapter, exposed for journal replay (commit channel).
249
- * Replaying through it still goes SemanticEditor → Loro → mengine-server —
250
- * no write bypass. Typed by the narrow interface on purpose.
251
- */
252
- get documentAdapter(): SemanticDocumentAdapter;
253
711
  /** Current document snapshot (read model). */
254
712
  snapshot(): VideoDocument;
255
713
  /**
@@ -277,51 +735,6 @@ declare class MengineDocSession {
277
735
  private hasContent;
278
736
  }
279
737
  //#endregion
280
- //#region src/storage/medeo-http-doc-storage.d.ts
281
- interface MedeoHttpDocStorageOptions {
282
- docId: string;
283
- client: MengineHttpClient;
284
- sseReconnectDelayMs?: number;
285
- readonlyMode?: boolean;
286
- }
287
- /**
288
- * Adapts the mengine-server HTTP/SSE protocol to the engine `DocStorage`
289
- * contract so `ClientServerSynchronizer` can treat it as a remote peer.
290
- *
291
- * Deliberately thin (mirrors the socket `DocStorage` in the playground): it
292
- * forwards live SSE updates and exposes a version-vector diff, and keeps NO
293
- * sync state of its own.
294
- *
295
- * - `getDocDiff(docId, knownVersion)` pulls the server-computed VV-diff via
296
- * `GET /sync?from=<vv>` — the synchronizer passes the real `doc.version()`, so
297
- * the response carries exactly the ops the doc is missing. `getDoc` (full
298
- * `/snapshot`) stays for cold start, when the caller holds no version yet.
299
- * - `pushDocUpdate` forwards a Loro update; the server appends it.
300
- * - `subscribeDocUpdate` registers a callback for live SSE updates. It does no
301
- * catch-up and keeps no cursor: after an SSE drop the connection reports a
302
- * status change, and the synchronizer re-runs its cycle to catch up via
303
- * `getDocDiff(doc.version())`. `LoroDoc.import` is idempotent (OpId/VV), so
304
- * re-forwarded or echoed updates are harmless.
305
- *
306
- * It is bound to a single `docId` because `MengineHttpClient` is per-document.
307
- */
308
- declare class MedeoHttpDocStorage implements DocStorage {
309
- private readonly options;
310
- readonly connection: Connection;
311
- private readonly client;
312
- private readonly docId;
313
- private readonly events;
314
- constructor(options: MedeoHttpDocStorageOptions);
315
- get isReadonly(): boolean;
316
- getDoc(docId: string): Promise<DocSnapshotRecord | null>;
317
- getDocDiff(docId: string, knownVersion?: Uint8Array): Promise<DocDiff | null>;
318
- pushDocUpdate(update: DocUpdate, _origin: unknown): Promise<void>;
319
- deleteDoc(_docId: string): Promise<void>;
320
- subscribeDocUpdate(callback: (update: DocUpdate, origin: unknown) => void): () => void;
321
- private assertDocId;
322
- private emitUpdate;
323
- }
324
- //#endregion
325
738
  //#region src/storage/memory-doc-storage.d.ts
326
739
  /**
327
740
  * Runtime-neutral local `DocStorage` backed by in-process memory.
@@ -530,6 +943,25 @@ interface SolvedVideoDocument {
530
943
  aggregations: PartAggregation[];
531
944
  durationMs: number;
532
945
  partLibrary: Record<string, PartUnion>;
946
+ /**
947
+ * Part ids of the gap fillers this solve minted.
948
+ *
949
+ * They exist only inside the solve: gap filling needs them so the clips after a
950
+ * gap land at the right absolute time, but they are not authoritative state and
951
+ * the read view does not carry them (see `fromVideoDocument`).
952
+ *
953
+ * Reported as ids rather than left for the caller to detect, because the caller
954
+ * *cannot* detect them. The obvious predicate — `origin_media_id === ''` — also
955
+ * matches an empty clip a writer placed on purpose (`batch_replace_video_clip_sequence`
956
+ * documents "Omit to create an empty clip placeholder"), and those are
957
+ * authoritative parts that must survive the projection. The mint callback is the
958
+ * only place that knows the difference.
959
+ *
960
+ * Note this deliberately excludes the fillers that gap filling *extended* rather
961
+ * than minted (`fillMainTrackTimeGaps` cases 1 and 2): those are authoritative
962
+ * empty clips already in `part_library`, and only their length is derived.
963
+ */
964
+ derivedFillerPartIds: Set<string>;
533
965
  }
534
966
  /**
535
967
  * Solve a `VideoDocument` (authoritative, position-only) into its derived
@@ -539,13 +971,48 @@ interface SolvedVideoDocument {
539
971
  declare function solveVideoDocument(document: VideoDocument): SolvedVideoDocument;
540
972
  /** The named container a secondary lane lives in. */
541
973
  type SecondaryLane = 'speech' | 'caption' | 'bgm';
974
+ /** A lane's track kind: the `video_clip` main lane plus the three secondary lanes. */
975
+ type LaneKind = SecondaryLane | 'video_clip';
976
+ /**
977
+ * The four lanes in top-to-bottom stack order — the order a `tracks` list holds
978
+ * them in (see {@link laneRank}).
979
+ *
980
+ * Exported so a document can be seeded with all four lanes up front. That seed is
981
+ * not cosmetic: {@link ensureLaneTrack} is find-then-mint over a `LoroMovableList`,
982
+ * so two concurrent writers that each mint the same absent lane both keep their
983
+ * row, and the merged document holds two tracks for one lane. For the main lane
984
+ * that is fatal — `videoDocumentSchema` allows at most one `video_clip` track, so
985
+ * the merged document stops being projectable at all, symmetrically on both
986
+ * replicas. Pre-seeding every lane makes `ensureLaneTrack` always take its find
987
+ * branch, which removes the race by construction rather than by detection.
988
+ *
989
+ * What closes the race is that a track with the lane's `parts_kind` EXISTS — the
990
+ * lookup is by kind, not by id. So a seed is only safe if it covers every lane:
991
+ * a partial seed leaves the uncovered lanes exactly as exposed as before.
992
+ */
993
+ declare const LANE_KINDS_IN_STACK_ORDER: readonly LaneKind[];
994
+ /**
995
+ * The conventional track id for a lane (`main_track`, `<kind>_track`). Shared by
996
+ * the up-front seed and {@link ensureLaneTrack}'s lazy mint so a document's lane
997
+ * ids do not depend on which of the two created the track.
998
+ *
999
+ * Ids are cosmetic to the merge itself — lane lookup goes by `parts_kind`, so
1000
+ * drifting them apart would not reopen the concurrent-mint race. They matter to
1001
+ * readers that address a lane by id (the FE editor's panes, fixtures), which is
1002
+ * why there is one convention rather than two.
1003
+ */
1004
+ declare function laneTrackId(kind: LaneKind): string;
542
1005
  /**
543
1006
  * Locate a lane's track row in the single `tracks` list by kind, minting an empty
544
1007
  * row in lane-stacking order if absent (reference/17 §4: lane = `parts_kind`).
545
1008
  * Ops use this to write authoritative items onto the right lane. The track id
546
- * mirrors the seed convention (`<kind>_track`).
1009
+ * comes from {@link laneTrackId}, shared with the up-front seed.
1010
+ *
1011
+ * The mint branch is a concurrency hazard, not a convenience: see
1012
+ * {@link LANE_KINDS_IN_STACK_ORDER}. A document seeded with all four lanes never
1013
+ * reaches it.
547
1014
  */
548
- declare function ensureLaneTrack(draft: VideoDocumentDraft, kind: SecondaryLane | 'video_clip'): TrackDraft;
1015
+ declare function ensureLaneTrack(draft: VideoDocumentDraft, kind: LaneKind): TrackDraft;
549
1016
  /** Find a secondary lane's track row without minting it. */
550
1017
  declare function findLaneTrack(draft: VideoDocumentDraft, kind: SecondaryLane): TrackDraft | undefined;
551
1018
  //#endregion
@@ -592,4 +1059,4 @@ declare function hostForAbsMs(ranges: MainClipRange[], absMs: number): MainClipR
592
1059
  */
593
1060
  declare function relativePositionForAbs(ranges: MainClipRange[], absMs: number): TrackItemTimePosition;
594
1061
  //#endregion
595
- export { type Aggregation, type Attachment, type BgmPart, type CaptionPart, type CaptionStyle, type CommitOptions, type DerivedItemPosition, type DocStorageLike, IMPLEMENTED_SEMANTIC_OP_KINDS, type ImplementedSemanticOpKind, type JournalEntry, type MainClipRange, type MakeEmptyPart, MedeoHttpDocStorage, type MedeoHttpDocStorageOptions, MemoryDocStorage, type MengineAuditEntry, type MengineAuditResponse, MengineDocSession, type MengineDocSessionOptions, type MengineDocSessionUpdateEvent, type MengineDocumentVersion, type MengineEventStreamOptions, MengineHttpClient, type MengineHttpClientOptions, MengineHttpRequestError, type MenginePushResponse, type MenginePushUpdateResponse, type MengineRejectedResponse, type MengineSnapshotResponse, type MengineSseUpdateEvent, type MengineSyncResponse, type MengineUpdateMeta, MirrorVideoDocumentAdapter, type MirrorVideoDocumentOptions, type PartAggregation, type PartIdFactory, type PartKind, type PartUnion, PlainMemoryAdapter, type PlainMemoryAdapterOptions, type PlannedSemanticOpKind, SchemaValidator, type SemanticDocumentAdapter, SemanticEditor, type SemanticOpInput, type SemanticOpKind, type SemanticOpName, type SnapshotReadable, type SolvedVideoDocument, type SpeechHostMap, type SpeechPart, type SpeedShift, TIMELINE_SKELETON_DURATION_MS, type Timeline, type TimelineDoc, type TimelineItem, type Track, type TrackDraft, type TrackItem, type TrackItemDraft, type TrackItemTimePosition, type TransactAudit, VIDEO_DOCUMENT_SCHEMA_VERSION, ValidationError, type VideoClipPart, type VideoDocument, type VideoDocumentDraft, type VideoDocumentMirrorSchema, type VideoDocumentSchemaVersion, VideoDocumentValidationError, type VideoDocumentValidationIssue, type VideoDocumentValidationIssueCode, type VideoDraft, type CaptionPart$1 as VideoDraftCaptionPart, type Timeline$1 as VideoDraftTimeline, type Track$1 as VideoDraftTrack, type TrackItem$1 as VideoDraftTrackItem, arrangeMainTrackSeamlessly, assertValidVideoDocument, base64ToBytes, buildSpeechHostMap, bytesToBase64, cascadeAfterVideoClipChanges, createEditSandbox, createMirrorVideoDocument, createMirrorVideoDocumentAdapter, createPlainMemoryAdapter, derivePositionFromAbs, effectiveVideoClipDurationMs, ensureLaneTrack, fillMainTrackTimeGaps, findLaneTrack, fromVideoDocument, generatePartId, getAt, hostForAbsMs, isEmptyVideoClip, isImplementedSemanticOpKind, isMap, mainTrackRanges, partDurationMs, partUnionSchema, readMainTrackItems, readMengineEventStream, readPart, readPartDurationMs, readVideoDocumentFromDraft, reassignSpeechesToVideoClipsByTime, recalculateTimelineDuration, relativePositionForAbs, replayJournal, resolveAllSpeechOverlaps, resolveSpeechOverlapByShiftingVideos, safeDurationMs, index_d_exports as schemas, snapshotToPlain, solveVideoDocument, speedOf, syncAggregatedClipsTimePosition, toVideoDocument, validateVideoDocument, videoDocumentMirrorSchema, videoDocumentSchema, writeVideoDocumentToDraft };
1062
+ export { type Aggregation, type Attachment, type BgmPart, type CaptionPart, type CaptionStyle, type CommitOptions, type DerivedItemPosition, type DocStorageLike, type DocVersionMark, IMPLEMENTED_SEMANTIC_OP_KINDS, type ImplementedSemanticOpKind, type InitialDocumentFacts, LANE_KINDS_IN_STACK_ORDER, type LaneKind, type MainClipRange, type MakeEmptyPart, ManualSyncDoc, type ManualSyncDocOptions, MedeoHttpDocStorage, type MedeoHttpDocStorageOptions, MemoryDocStorage, MengineAckFailedError, type MengineAuditEntry, type MengineAuditResponse, MengineDocSession, type MengineDocSessionOptions, type MengineDocSessionUpdateEvent, type MengineDocumentVersion, type MengineEventStreamOptions, MengineHttpClient, type MengineHttpClientOptions, MengineHttpRequestError, MenginePushRejectedError, type MenginePushResponse, type MenginePushUpdateResponse, type MengineRejectedResponse, type MengineSnapshotResponse, type MengineSseUpdateEvent, type MengineSyncResponse, type MengineUpdateMeta, MirrorVideoDocumentAdapter, type MirrorVideoDocumentOptions, type OpActor, type PartAggregation, type PartKind, type PartUnion, type PlannedSemanticOpKind, type PullFailureReason, type PullResult, type PushOutcome, type PushOutcomeKind, type PushResult, type PushResultKind, SchemaValidator, type SemanticDocumentAdapter, SemanticEditor, type SemanticOpInput, type SemanticOpKind, type SemanticOpName, type SnapshotReadable, type SolvedVideoDocument, type SpeechHostMap, type SpeechPart, type SpeedShift, TIMELINE_SKELETON_DURATION_MS, type Timeline, type TimelineDoc, type TimelineItem, type Track, type TrackDraft, type TrackItem, type TrackItemDraft, type TrackItemTimePosition, type TransactAudit, VIDEO_DOCUMENT_SCHEMA_VERSION, ValidationError, type VideoClipPart, type VideoDocument, type VideoDocumentDraft, type VideoDocumentMirrorSchema, type VideoDocumentSchemaVersion, VideoDocumentValidationError, type VideoDocumentValidationIssue, type VideoDocumentValidationIssueCode, type VideoDraft, type CaptionPart$1 as VideoDraftCaptionPart, type VideoDraftPartUnion, type Timeline$1 as VideoDraftTimeline, type Track$1 as VideoDraftTrack, type TrackItem$1 as VideoDraftTrackItem, type WaitForServerAckOptions, 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, relativePositionForAbs, resolveAllSpeechOverlaps, resolveSpeechOverlapByShiftingVideos, safeDurationMs, index_d_exports as schemas, snapshotToPlain, solveVideoDocument, syncAggregatedClipsTimePosition, toVideoDocument, validateVideoDocument, videoDocumentMirrorSchema, videoDocumentSchema };