@mulmoclaude/mulmoscript-plugin 4.4.0 → 4.5.1

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.
Files changed (45) hide show
  1. package/dist/contract-BHqxMUWm.cjs +82 -0
  2. package/dist/contract-BHqxMUWm.cjs.map +1 -0
  3. package/dist/contract-BnIl6w_f.js +53 -0
  4. package/dist/contract-BnIl6w_f.js.map +1 -0
  5. package/dist/core/contract.d.ts +80 -6
  6. package/dist/core/contract.d.ts.map +1 -1
  7. package/dist/core/definition.d.ts.map +1 -1
  8. package/dist/core/paths.d.ts +41 -0
  9. package/dist/core/paths.d.ts.map +1 -1
  10. package/dist/index.cjs +1 -1
  11. package/dist/index.js +1 -1
  12. package/dist/{plugin-BOq5YkTl.cjs → plugin-C5JC2lNR.cjs} +51 -1
  13. package/dist/plugin-C5JC2lNR.cjs.map +1 -0
  14. package/dist/{plugin-CAhxJ5WM.js → plugin-Jo8iGv4K.js} +40 -2
  15. package/dist/plugin-Jo8iGv4K.js.map +1 -0
  16. package/dist/server/dispatch.d.ts +0 -6
  17. package/dist/server/dispatch.d.ts.map +1 -1
  18. package/dist/server/ops.d.ts +29 -18
  19. package/dist/server/ops.d.ts.map +1 -1
  20. package/dist/server/types.d.ts +75 -2
  21. package/dist/server/types.d.ts.map +1 -1
  22. package/dist/server.cjs +468 -110
  23. package/dist/server.cjs.map +1 -1
  24. package/dist/server.js +468 -110
  25. package/dist/server.js.map +1 -1
  26. package/dist/style.css +30 -18
  27. package/dist/vue/View.vue.d.ts.map +1 -1
  28. package/dist/vue/composables/useDeckEditor.d.ts.map +1 -1
  29. package/dist/vue/index.d.ts +1 -1
  30. package/dist/vue/index.d.ts.map +1 -1
  31. package/dist/vue/subscription.d.ts +16 -0
  32. package/dist/vue/subscription.d.ts.map +1 -0
  33. package/dist/vue/transport.d.ts +16 -5
  34. package/dist/vue/transport.d.ts.map +1 -1
  35. package/dist/vue.cjs +110 -21
  36. package/dist/vue.cjs.map +1 -1
  37. package/dist/vue.js +110 -21
  38. package/dist/vue.js.map +1 -1
  39. package/package.json +11 -11
  40. package/dist/contract-BhN3yKJC.cjs +0 -36
  41. package/dist/contract-BhN3yKJC.cjs.map +0 -1
  42. package/dist/contract-CIt1ZAtt.js +0 -19
  43. package/dist/contract-CIt1ZAtt.js.map +0 -1
  44. package/dist/plugin-BOq5YkTl.cjs.map +0 -1
  45. package/dist/plugin-CAhxJ5WM.js.map +0 -1
@@ -0,0 +1,82 @@
1
+ //#region src/core/contract.ts
2
+ /** Plugin pubsub event name the host publishes generation events on
3
+ * (full channel: `plugin:<scope>:generation`). */
4
+ var GENERATION_EVENT = "generation";
5
+ /** Plugin pubsub event name for "this script changed on disk"
6
+ * (full channel: `plugin:<scope>:scriptChanged`). */
7
+ var SCRIPT_CHANGED_EVENT = "scriptChanged";
8
+ /**
9
+ * Whether a View watching `watching` should reload because of `event`.
10
+ *
11
+ * A pure rule rather than a condition inside the subscriber, because the case that matters is
12
+ * the one that is invisible when it is wrong: a View acting on the echo of its own write
13
+ * rebuilds the element the caret is in, on every keystroke.
14
+ */
15
+ var shouldReloadForScriptChange = (event, watching, ownOrigin, watchingRoot) => watching !== "" && event.filePath === watching && sameRoot(event.root, watchingRoot) && event.origin !== ownOrigin;
16
+ /**
17
+ * The one spelling of a root that every comparison and every key must use.
18
+ *
19
+ * It lives HERE, in the module both the server and the View import, because
20
+ * the server had its own copy and the browser side compared raw strings — so
21
+ * `publishGeneration` emitted `"repoA"` while a View watching `" repoA "`
22
+ * dropped every event of its own generation (CodeRabbit on #3015). A rule
23
+ * that two sides must agree on cannot live on one of the two sides.
24
+ *
25
+ * Trimmed, because the codebase's other opaque "which project root" reader —
26
+ * `readCommandScope` in `@mulmoclaude/core/remote-host` — trims its value and
27
+ * shares the "absent = the host's own root" convention. Without this,
28
+ * `" repoA "` is one root there and a different one here.
29
+ *
30
+ * A non-string reads as the default root rather than throwing. The type says
31
+ * that cannot happen, but this package is published and its callers include
32
+ * untyped JavaScript: a subscription whose `root()` returns `42` reached
33
+ * `.trim()` and threw from INSIDE a pubsub callback, where nothing catches it
34
+ * and the View simply stops updating (Codex P2 on #3015). The guard belongs
35
+ * here rather than at the three call sites, because a rule enforced by
36
+ * enumerating its callers is what this PR got wrong repeatedly.
37
+ */
38
+ var normalizeRoot = (root) => typeof root === "string" ? root.trim() : "";
39
+ /**
40
+ * Two roots are the same when they name the same one, with absent meaning the
41
+ * host's default (#3014).
42
+ *
43
+ * The identity of a script is the PAIR, not the path: `stories/deck.json` in
44
+ * two repositories is two files, and comparing paths alone would reload the
45
+ * View watching one because the other was saved. Absent normalises to the
46
+ * default so a pre-`root` event and a default-root watcher still match — that
47
+ * equivalence is what keeps every existing card working untouched.
48
+ */
49
+ var sameRoot = (a, b) => normalizeRoot(a) === normalizeRoot(b);
50
+ //#endregion
51
+ Object.defineProperty(exports, "GENERATION_EVENT", {
52
+ enumerable: true,
53
+ get: function() {
54
+ return GENERATION_EVENT;
55
+ }
56
+ });
57
+ Object.defineProperty(exports, "SCRIPT_CHANGED_EVENT", {
58
+ enumerable: true,
59
+ get: function() {
60
+ return SCRIPT_CHANGED_EVENT;
61
+ }
62
+ });
63
+ Object.defineProperty(exports, "normalizeRoot", {
64
+ enumerable: true,
65
+ get: function() {
66
+ return normalizeRoot;
67
+ }
68
+ });
69
+ Object.defineProperty(exports, "sameRoot", {
70
+ enumerable: true,
71
+ get: function() {
72
+ return sameRoot;
73
+ }
74
+ });
75
+ Object.defineProperty(exports, "shouldReloadForScriptChange", {
76
+ enumerable: true,
77
+ get: function() {
78
+ return shouldReloadForScriptChange;
79
+ }
80
+ });
81
+
82
+ //# sourceMappingURL=contract-BHqxMUWm.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract-BHqxMUWm.cjs","names":[],"sources":["../src/core/contract.ts"],"sourcesContent":["// Host-agnostic dispatch envelope for the presentMulmoScript View. The Vue\n// View is decoupled from any one host's REST surface: it calls\n// `useRuntime().dispatch({ kind, … })`, the host routes that to its\n// mulmoScript dispatch handler, and every response is an `{ ok: … }`\n// envelope so failures travel as data (no HTTP-status coupling, no\n// \"dispatch failed (500)\" prefixes in user-facing errors).\n//\n// Long-running generation (movie / PDF) is a single long-held dispatch that\n// resolves when the pipeline finishes; per-beat progress arrives on the\n// plugin pubsub channel (`GENERATION_EVENT`) instead of an SSE stream, which\n// also covers generations started elsewhere (background autoGenerateMovie,\n// another tab, the agent).\n\n/** One in-flight or per-beat generation notice, published on the plugin\n * pubsub `generation` channel and returned by the `pendingGenerations`\n * snapshot. Value strings mirror @mulmobridge/protocol's GENERATION_KINDS\n * so MulmoClaude's host bridge maps 1:1 without a lookup table. */\nexport interface MulmoScriptGenerationEvent {\n kind: \"beatImage\" | \"beatAudio\" | \"characterImage\" | \"movie\" | \"pdf\";\n /** Wire `stories/…` path of the script the generation belongs to. */\n filePath: string;\n /** Which stories root `filePath` is relative to (#3014). Absent = the\n * host's default root, which is every event this package emitted before\n * roots existed. */\n root?: string;\n /** beatIndex (as string) for beat*, character key for characterImage, \"\" for movie/pdf. */\n key: string;\n /** false = started, true = finished (reload the asset off disk). */\n done: boolean;\n /** Only set on done=true when the work failed. */\n error?: string;\n}\n\n/** Plugin pubsub event name the host publishes generation events on\n * (full channel: `plugin:<scope>:generation`). */\nexport const GENERATION_EVENT = \"generation\";\n\n/** Plugin pubsub event name for \"this script changed on disk\"\n * (full channel: `plugin:<scope>:scriptChanged`). */\nexport const SCRIPT_CHANGED_EVENT = \"scriptChanged\";\n\n/**\n * A script was written — by the agent, or by another View.\n *\n * `origin` is who wrote it. A View passes its own id on every write and ignores the echo of\n * its own: without that, a keystroke would round-trip through the server and reload the very\n * element the caret is in. An agent write carries no origin, so every View reloads.\n */\nexport interface MulmoScriptChangedEvent {\n filePath: string;\n /** Which stories root `filePath` is relative to (#3014). Absent = default. */\n root?: string;\n origin?: string;\n}\n\n/**\n * Whether a View watching `watching` should reload because of `event`.\n *\n * A pure rule rather than a condition inside the subscriber, because the case that matters is\n * the one that is invisible when it is wrong: a View acting on the echo of its own write\n * rebuilds the element the caret is in, on every keystroke.\n */\nexport const shouldReloadForScriptChange = (event: MulmoScriptChangedEvent, watching: string, ownOrigin: string, watchingRoot?: string): boolean =>\n watching !== \"\" && event.filePath === watching && sameRoot(event.root, watchingRoot) && event.origin !== ownOrigin;\n\n/** The default root: what a caller that names no root is asking for. */\nexport const DEFAULT_ROOT = \"\";\n\n/**\n * The one spelling of a root that every comparison and every key must use.\n *\n * It lives HERE, in the module both the server and the View import, because\n * the server had its own copy and the browser side compared raw strings — so\n * `publishGeneration` emitted `\"repoA\"` while a View watching `\" repoA \"`\n * dropped every event of its own generation (CodeRabbit on #3015). A rule\n * that two sides must agree on cannot live on one of the two sides.\n *\n * Trimmed, because the codebase's other opaque \"which project root\" reader —\n * `readCommandScope` in `@mulmoclaude/core/remote-host` — trims its value and\n * shares the \"absent = the host's own root\" convention. Without this,\n * `\" repoA \"` is one root there and a different one here.\n *\n * A non-string reads as the default root rather than throwing. The type says\n * that cannot happen, but this package is published and its callers include\n * untyped JavaScript: a subscription whose `root()` returns `42` reached\n * `.trim()` and threw from INSIDE a pubsub callback, where nothing catches it\n * and the View simply stops updating (Codex P2 on #3015). The guard belongs\n * here rather than at the three call sites, because a rule enforced by\n * enumerating its callers is what this PR got wrong repeatedly.\n */\nexport const normalizeRoot = (root: string | undefined): string => (typeof root === \"string\" ? root.trim() : DEFAULT_ROOT);\n\n/**\n * Two roots are the same when they name the same one, with absent meaning the\n * host's default (#3014).\n *\n * The identity of a script is the PAIR, not the path: `stories/deck.json` in\n * two repositories is two files, and comparing paths alone would reload the\n * View watching one because the other was saved. Absent normalises to the\n * default so a pre-`root` event and a default-root watcher still match — that\n * equivalence is what keeps every existing card working untouched.\n */\nexport const sameRoot = (a: string | undefined, b: string | undefined): boolean => normalizeRoot(a) === normalizeRoot(b);\n\ninterface BeatRef {\n filePath: string;\n beatIndex: number;\n}\n\ninterface CharacterRef {\n filePath: string;\n key: string;\n}\n\n/** Session tag for hosts that surface per-session generation indicators\n * (MulmoClaude's sidebar). Optional everywhere; hosts without sessions\n * ignore it. */\ninterface SessionTag {\n chatSessionId?: string | undefined;\n}\n\n/**\n * Which registered stories root the named script lives in (#3014).\n *\n * Intersected into the whole union below, so every dispatch that names a\n * `filePath` can name its root — a union member that could not would make\n * root-aware calls untypeable while the handler happily read `args.root`\n * off an untyped record (Codex P1 on #3015).\n */\ninterface RootTag {\n root?: string | undefined;\n}\n\nexport type MulmoScriptDispatchArgs = RootTag &\n (\n | ({ kind: \"save\" } & { filePath?: string; script?: unknown; filename?: string })\n | { kind: \"updateBeat\"; filePath: string; beatIndex: number; beat: unknown; origin?: string }\n | { kind: \"updateScript\"; filePath: string; script: unknown; origin?: string }\n | ({ kind: \"beatImage\" } & BeatRef)\n | ({ kind: \"beatAudio\" } & BeatRef)\n | ({ kind: \"beatMovie\" } & BeatRef)\n | ({ kind: \"renderBeat\" } & BeatRef & SessionTag & { force?: boolean })\n | ({ kind: \"generateBeatAudio\" } & BeatRef & SessionTag & { force?: boolean })\n | ({ kind: \"uploadBeatImage\" } & BeatRef & { imageData: string })\n | ({ kind: \"characterImage\" } & CharacterRef)\n | ({ kind: \"renderCharacter\" } & CharacterRef & SessionTag & { force?: boolean })\n | ({ kind: \"uploadCharacterImage\" } & CharacterRef & { imageData: string })\n | ({ kind: \"movieStatus\" } & { filePath: string })\n | ({ kind: \"pdfStatus\" } & { filePath: string })\n | ({ kind: \"generateMovie\" } & { filePath: string } & SessionTag)\n | ({ kind: \"generatePdf\" } & { filePath: string } & SessionTag)\n | { kind: \"pendingGenerations\"; filePath: string }\n );\n\nexport type MulmoScriptDispatchKind = MulmoScriptDispatchArgs[\"kind\"];\n\n/** Failure half of every dispatch response. `code` mirrors the phase-1\n * outcome codes so a host can log/telemetry on it; the View only reads\n * `error`. */\nexport interface DispatchFailure {\n ok: false;\n code?: \"bad_request\" | \"not_found\" | \"server_error\";\n error: string;\n}\n\nexport type DispatchEnvelope<T> = ({ ok: true } & T) | DispatchFailure;\n\n/** The success payload of each dispatch `kind`, BEFORE the root tag below is\n * applied. Not exported: `MulmoScriptDispatchResult` is the type callers use. */\ninterface DispatchResultPayloads {\n save: { script: Record<string, unknown>; filePath: string; message: string };\n updateBeat: Record<string, never>;\n updateScript: Record<string, never>;\n beatImage: { image: string | null };\n beatAudio: { audio: string | null };\n beatMovie: { moviePath: string | null };\n renderBeat: { image: string };\n generateBeatAudio: { audio: string };\n uploadBeatImage: { image: string };\n characterImage: { image: string | null };\n renderCharacter: { image: string };\n uploadCharacterImage: { image: string };\n movieStatus: { moviePath: string | null };\n pdfStatus: { pdfPath: string | null };\n generateMovie: { moviePath: string };\n generatePdf: { pdfPath: string };\n pendingGenerations: { pending: MulmoScriptGenerationEvent[] };\n}\n\n/**\n * Maps a dispatch `kind` to its success payload, every one of them carrying\n * the root it acted in.\n *\n * A host builds its cards from these results, and a card's identity is the\n * PAIR `(root, filePath)` — `stories/deck.json` exists in every registered\n * root. Without the root here, two repositories' identically-named decks\n * collapse onto one card, which is #3014's third collision point, and no\n * amount of fixing the host's identity function helps because the value never\n * arrives.\n *\n * `root` was threaded through the ARGS and the EVENTS in #3015 and not through\n * the results — the same shape that PR got wrong repeatedly: the comparison\n * widened while the path carrying the data to it did not. Applied as a mapped\n * type rather than field by field so a kind added later cannot be forgotten.\n *\n * Absent means the default root, so every pre-`root` card is unchanged.\n */\nexport type MulmoScriptDispatchResult = {\n [K in keyof DispatchResultPayloads]: DispatchResultPayloads[K] & RootTag;\n};\n"],"mappings":";;;AAmCA,IAAa,mBAAmB;;;AAIhC,IAAa,uBAAuB;;;;;;;;AAuBpC,IAAa,+BAA+B,OAAgC,UAAkB,WAAmB,iBAC/G,aAAa,MAAM,MAAM,aAAa,YAAY,SAAS,MAAM,MAAM,YAAY,KAAK,MAAM,WAAW;;;;;;;;;;;;;;;;;;;;;;;AA2B3G,IAAa,iBAAiB,SAAsC,OAAO,SAAS,WAAW,KAAK,KAAK,IAAA;;;;;;;;;;;AAYzG,IAAa,YAAY,GAAuB,MAAmC,cAAc,CAAC,MAAM,cAAc,CAAC"}
@@ -0,0 +1,53 @@
1
+ //#region src/core/contract.ts
2
+ /** Plugin pubsub event name the host publishes generation events on
3
+ * (full channel: `plugin:<scope>:generation`). */
4
+ var GENERATION_EVENT = "generation";
5
+ /** Plugin pubsub event name for "this script changed on disk"
6
+ * (full channel: `plugin:<scope>:scriptChanged`). */
7
+ var SCRIPT_CHANGED_EVENT = "scriptChanged";
8
+ /**
9
+ * Whether a View watching `watching` should reload because of `event`.
10
+ *
11
+ * A pure rule rather than a condition inside the subscriber, because the case that matters is
12
+ * the one that is invisible when it is wrong: a View acting on the echo of its own write
13
+ * rebuilds the element the caret is in, on every keystroke.
14
+ */
15
+ var shouldReloadForScriptChange = (event, watching, ownOrigin, watchingRoot) => watching !== "" && event.filePath === watching && sameRoot(event.root, watchingRoot) && event.origin !== ownOrigin;
16
+ /**
17
+ * The one spelling of a root that every comparison and every key must use.
18
+ *
19
+ * It lives HERE, in the module both the server and the View import, because
20
+ * the server had its own copy and the browser side compared raw strings — so
21
+ * `publishGeneration` emitted `"repoA"` while a View watching `" repoA "`
22
+ * dropped every event of its own generation (CodeRabbit on #3015). A rule
23
+ * that two sides must agree on cannot live on one of the two sides.
24
+ *
25
+ * Trimmed, because the codebase's other opaque "which project root" reader —
26
+ * `readCommandScope` in `@mulmoclaude/core/remote-host` — trims its value and
27
+ * shares the "absent = the host's own root" convention. Without this,
28
+ * `" repoA "` is one root there and a different one here.
29
+ *
30
+ * A non-string reads as the default root rather than throwing. The type says
31
+ * that cannot happen, but this package is published and its callers include
32
+ * untyped JavaScript: a subscription whose `root()` returns `42` reached
33
+ * `.trim()` and threw from INSIDE a pubsub callback, where nothing catches it
34
+ * and the View simply stops updating (Codex P2 on #3015). The guard belongs
35
+ * here rather than at the three call sites, because a rule enforced by
36
+ * enumerating its callers is what this PR got wrong repeatedly.
37
+ */
38
+ var normalizeRoot = (root) => typeof root === "string" ? root.trim() : "";
39
+ /**
40
+ * Two roots are the same when they name the same one, with absent meaning the
41
+ * host's default (#3014).
42
+ *
43
+ * The identity of a script is the PAIR, not the path: `stories/deck.json` in
44
+ * two repositories is two files, and comparing paths alone would reload the
45
+ * View watching one because the other was saved. Absent normalises to the
46
+ * default so a pre-`root` event and a default-root watcher still match — that
47
+ * equivalence is what keeps every existing card working untouched.
48
+ */
49
+ var sameRoot = (a, b) => normalizeRoot(a) === normalizeRoot(b);
50
+ //#endregion
51
+ export { shouldReloadForScriptChange as a, sameRoot as i, SCRIPT_CHANGED_EVENT as n, normalizeRoot as r, GENERATION_EVENT as t };
52
+
53
+ //# sourceMappingURL=contract-BnIl6w_f.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract-BnIl6w_f.js","names":[],"sources":["../src/core/contract.ts"],"sourcesContent":["// Host-agnostic dispatch envelope for the presentMulmoScript View. The Vue\n// View is decoupled from any one host's REST surface: it calls\n// `useRuntime().dispatch({ kind, … })`, the host routes that to its\n// mulmoScript dispatch handler, and every response is an `{ ok: … }`\n// envelope so failures travel as data (no HTTP-status coupling, no\n// \"dispatch failed (500)\" prefixes in user-facing errors).\n//\n// Long-running generation (movie / PDF) is a single long-held dispatch that\n// resolves when the pipeline finishes; per-beat progress arrives on the\n// plugin pubsub channel (`GENERATION_EVENT`) instead of an SSE stream, which\n// also covers generations started elsewhere (background autoGenerateMovie,\n// another tab, the agent).\n\n/** One in-flight or per-beat generation notice, published on the plugin\n * pubsub `generation` channel and returned by the `pendingGenerations`\n * snapshot. Value strings mirror @mulmobridge/protocol's GENERATION_KINDS\n * so MulmoClaude's host bridge maps 1:1 without a lookup table. */\nexport interface MulmoScriptGenerationEvent {\n kind: \"beatImage\" | \"beatAudio\" | \"characterImage\" | \"movie\" | \"pdf\";\n /** Wire `stories/…` path of the script the generation belongs to. */\n filePath: string;\n /** Which stories root `filePath` is relative to (#3014). Absent = the\n * host's default root, which is every event this package emitted before\n * roots existed. */\n root?: string;\n /** beatIndex (as string) for beat*, character key for characterImage, \"\" for movie/pdf. */\n key: string;\n /** false = started, true = finished (reload the asset off disk). */\n done: boolean;\n /** Only set on done=true when the work failed. */\n error?: string;\n}\n\n/** Plugin pubsub event name the host publishes generation events on\n * (full channel: `plugin:<scope>:generation`). */\nexport const GENERATION_EVENT = \"generation\";\n\n/** Plugin pubsub event name for \"this script changed on disk\"\n * (full channel: `plugin:<scope>:scriptChanged`). */\nexport const SCRIPT_CHANGED_EVENT = \"scriptChanged\";\n\n/**\n * A script was written — by the agent, or by another View.\n *\n * `origin` is who wrote it. A View passes its own id on every write and ignores the echo of\n * its own: without that, a keystroke would round-trip through the server and reload the very\n * element the caret is in. An agent write carries no origin, so every View reloads.\n */\nexport interface MulmoScriptChangedEvent {\n filePath: string;\n /** Which stories root `filePath` is relative to (#3014). Absent = default. */\n root?: string;\n origin?: string;\n}\n\n/**\n * Whether a View watching `watching` should reload because of `event`.\n *\n * A pure rule rather than a condition inside the subscriber, because the case that matters is\n * the one that is invisible when it is wrong: a View acting on the echo of its own write\n * rebuilds the element the caret is in, on every keystroke.\n */\nexport const shouldReloadForScriptChange = (event: MulmoScriptChangedEvent, watching: string, ownOrigin: string, watchingRoot?: string): boolean =>\n watching !== \"\" && event.filePath === watching && sameRoot(event.root, watchingRoot) && event.origin !== ownOrigin;\n\n/** The default root: what a caller that names no root is asking for. */\nexport const DEFAULT_ROOT = \"\";\n\n/**\n * The one spelling of a root that every comparison and every key must use.\n *\n * It lives HERE, in the module both the server and the View import, because\n * the server had its own copy and the browser side compared raw strings — so\n * `publishGeneration` emitted `\"repoA\"` while a View watching `\" repoA \"`\n * dropped every event of its own generation (CodeRabbit on #3015). A rule\n * that two sides must agree on cannot live on one of the two sides.\n *\n * Trimmed, because the codebase's other opaque \"which project root\" reader —\n * `readCommandScope` in `@mulmoclaude/core/remote-host` — trims its value and\n * shares the \"absent = the host's own root\" convention. Without this,\n * `\" repoA \"` is one root there and a different one here.\n *\n * A non-string reads as the default root rather than throwing. The type says\n * that cannot happen, but this package is published and its callers include\n * untyped JavaScript: a subscription whose `root()` returns `42` reached\n * `.trim()` and threw from INSIDE a pubsub callback, where nothing catches it\n * and the View simply stops updating (Codex P2 on #3015). The guard belongs\n * here rather than at the three call sites, because a rule enforced by\n * enumerating its callers is what this PR got wrong repeatedly.\n */\nexport const normalizeRoot = (root: string | undefined): string => (typeof root === \"string\" ? root.trim() : DEFAULT_ROOT);\n\n/**\n * Two roots are the same when they name the same one, with absent meaning the\n * host's default (#3014).\n *\n * The identity of a script is the PAIR, not the path: `stories/deck.json` in\n * two repositories is two files, and comparing paths alone would reload the\n * View watching one because the other was saved. Absent normalises to the\n * default so a pre-`root` event and a default-root watcher still match — that\n * equivalence is what keeps every existing card working untouched.\n */\nexport const sameRoot = (a: string | undefined, b: string | undefined): boolean => normalizeRoot(a) === normalizeRoot(b);\n\ninterface BeatRef {\n filePath: string;\n beatIndex: number;\n}\n\ninterface CharacterRef {\n filePath: string;\n key: string;\n}\n\n/** Session tag for hosts that surface per-session generation indicators\n * (MulmoClaude's sidebar). Optional everywhere; hosts without sessions\n * ignore it. */\ninterface SessionTag {\n chatSessionId?: string | undefined;\n}\n\n/**\n * Which registered stories root the named script lives in (#3014).\n *\n * Intersected into the whole union below, so every dispatch that names a\n * `filePath` can name its root — a union member that could not would make\n * root-aware calls untypeable while the handler happily read `args.root`\n * off an untyped record (Codex P1 on #3015).\n */\ninterface RootTag {\n root?: string | undefined;\n}\n\nexport type MulmoScriptDispatchArgs = RootTag &\n (\n | ({ kind: \"save\" } & { filePath?: string; script?: unknown; filename?: string })\n | { kind: \"updateBeat\"; filePath: string; beatIndex: number; beat: unknown; origin?: string }\n | { kind: \"updateScript\"; filePath: string; script: unknown; origin?: string }\n | ({ kind: \"beatImage\" } & BeatRef)\n | ({ kind: \"beatAudio\" } & BeatRef)\n | ({ kind: \"beatMovie\" } & BeatRef)\n | ({ kind: \"renderBeat\" } & BeatRef & SessionTag & { force?: boolean })\n | ({ kind: \"generateBeatAudio\" } & BeatRef & SessionTag & { force?: boolean })\n | ({ kind: \"uploadBeatImage\" } & BeatRef & { imageData: string })\n | ({ kind: \"characterImage\" } & CharacterRef)\n | ({ kind: \"renderCharacter\" } & CharacterRef & SessionTag & { force?: boolean })\n | ({ kind: \"uploadCharacterImage\" } & CharacterRef & { imageData: string })\n | ({ kind: \"movieStatus\" } & { filePath: string })\n | ({ kind: \"pdfStatus\" } & { filePath: string })\n | ({ kind: \"generateMovie\" } & { filePath: string } & SessionTag)\n | ({ kind: \"generatePdf\" } & { filePath: string } & SessionTag)\n | { kind: \"pendingGenerations\"; filePath: string }\n );\n\nexport type MulmoScriptDispatchKind = MulmoScriptDispatchArgs[\"kind\"];\n\n/** Failure half of every dispatch response. `code` mirrors the phase-1\n * outcome codes so a host can log/telemetry on it; the View only reads\n * `error`. */\nexport interface DispatchFailure {\n ok: false;\n code?: \"bad_request\" | \"not_found\" | \"server_error\";\n error: string;\n}\n\nexport type DispatchEnvelope<T> = ({ ok: true } & T) | DispatchFailure;\n\n/** The success payload of each dispatch `kind`, BEFORE the root tag below is\n * applied. Not exported: `MulmoScriptDispatchResult` is the type callers use. */\ninterface DispatchResultPayloads {\n save: { script: Record<string, unknown>; filePath: string; message: string };\n updateBeat: Record<string, never>;\n updateScript: Record<string, never>;\n beatImage: { image: string | null };\n beatAudio: { audio: string | null };\n beatMovie: { moviePath: string | null };\n renderBeat: { image: string };\n generateBeatAudio: { audio: string };\n uploadBeatImage: { image: string };\n characterImage: { image: string | null };\n renderCharacter: { image: string };\n uploadCharacterImage: { image: string };\n movieStatus: { moviePath: string | null };\n pdfStatus: { pdfPath: string | null };\n generateMovie: { moviePath: string };\n generatePdf: { pdfPath: string };\n pendingGenerations: { pending: MulmoScriptGenerationEvent[] };\n}\n\n/**\n * Maps a dispatch `kind` to its success payload, every one of them carrying\n * the root it acted in.\n *\n * A host builds its cards from these results, and a card's identity is the\n * PAIR `(root, filePath)` — `stories/deck.json` exists in every registered\n * root. Without the root here, two repositories' identically-named decks\n * collapse onto one card, which is #3014's third collision point, and no\n * amount of fixing the host's identity function helps because the value never\n * arrives.\n *\n * `root` was threaded through the ARGS and the EVENTS in #3015 and not through\n * the results — the same shape that PR got wrong repeatedly: the comparison\n * widened while the path carrying the data to it did not. Applied as a mapped\n * type rather than field by field so a kind added later cannot be forgotten.\n *\n * Absent means the default root, so every pre-`root` card is unchanged.\n */\nexport type MulmoScriptDispatchResult = {\n [K in keyof DispatchResultPayloads]: DispatchResultPayloads[K] & RootTag;\n};\n"],"mappings":";;;AAmCA,IAAa,mBAAmB;;;AAIhC,IAAa,uBAAuB;;;;;;;;AAuBpC,IAAa,+BAA+B,OAAgC,UAAkB,WAAmB,iBAC/G,aAAa,MAAM,MAAM,aAAa,YAAY,SAAS,MAAM,MAAM,YAAY,KAAK,MAAM,WAAW;;;;;;;;;;;;;;;;;;;;;;;AA2B3G,IAAa,iBAAiB,SAAsC,OAAO,SAAS,WAAW,KAAK,KAAK,IAAA;;;;;;;;;;;AAYzG,IAAa,YAAY,GAAuB,MAAmC,cAAc,CAAC,MAAM,cAAc,CAAC"}
@@ -6,6 +6,10 @@ export interface MulmoScriptGenerationEvent {
6
6
  kind: "beatImage" | "beatAudio" | "characterImage" | "movie" | "pdf";
7
7
  /** Wire `stories/…` path of the script the generation belongs to. */
8
8
  filePath: string;
9
+ /** Which stories root `filePath` is relative to (#3014). Absent = the
10
+ * host's default root, which is every event this package emitted before
11
+ * roots existed. */
12
+ root?: string;
9
13
  /** beatIndex (as string) for beat*, character key for characterImage, "" for movie/pdf. */
10
14
  key: string;
11
15
  /** false = started, true = finished (reload the asset off disk). */
@@ -28,6 +32,8 @@ export declare const SCRIPT_CHANGED_EVENT = "scriptChanged";
28
32
  */
29
33
  export interface MulmoScriptChangedEvent {
30
34
  filePath: string;
35
+ /** Which stories root `filePath` is relative to (#3014). Absent = default. */
36
+ root?: string;
31
37
  origin?: string;
32
38
  }
33
39
  /**
@@ -37,7 +43,43 @@ export interface MulmoScriptChangedEvent {
37
43
  * the one that is invisible when it is wrong: a View acting on the echo of its own write
38
44
  * rebuilds the element the caret is in, on every keystroke.
39
45
  */
40
- export declare const shouldReloadForScriptChange: (event: MulmoScriptChangedEvent, watching: string, ownOrigin: string) => boolean;
46
+ export declare const shouldReloadForScriptChange: (event: MulmoScriptChangedEvent, watching: string, ownOrigin: string, watchingRoot?: string) => boolean;
47
+ /** The default root: what a caller that names no root is asking for. */
48
+ export declare const DEFAULT_ROOT = "";
49
+ /**
50
+ * The one spelling of a root that every comparison and every key must use.
51
+ *
52
+ * It lives HERE, in the module both the server and the View import, because
53
+ * the server had its own copy and the browser side compared raw strings — so
54
+ * `publishGeneration` emitted `"repoA"` while a View watching `" repoA "`
55
+ * dropped every event of its own generation (CodeRabbit on #3015). A rule
56
+ * that two sides must agree on cannot live on one of the two sides.
57
+ *
58
+ * Trimmed, because the codebase's other opaque "which project root" reader —
59
+ * `readCommandScope` in `@mulmoclaude/core/remote-host` — trims its value and
60
+ * shares the "absent = the host's own root" convention. Without this,
61
+ * `" repoA "` is one root there and a different one here.
62
+ *
63
+ * A non-string reads as the default root rather than throwing. The type says
64
+ * that cannot happen, but this package is published and its callers include
65
+ * untyped JavaScript: a subscription whose `root()` returns `42` reached
66
+ * `.trim()` and threw from INSIDE a pubsub callback, where nothing catches it
67
+ * and the View simply stops updating (Codex P2 on #3015). The guard belongs
68
+ * here rather than at the three call sites, because a rule enforced by
69
+ * enumerating its callers is what this PR got wrong repeatedly.
70
+ */
71
+ export declare const normalizeRoot: (root: string | undefined) => string;
72
+ /**
73
+ * Two roots are the same when they name the same one, with absent meaning the
74
+ * host's default (#3014).
75
+ *
76
+ * The identity of a script is the PAIR, not the path: `stories/deck.json` in
77
+ * two repositories is two files, and comparing paths alone would reload the
78
+ * View watching one because the other was saved. Absent normalises to the
79
+ * default so a pre-`root` event and a default-root watcher still match — that
80
+ * equivalence is what keeps every existing card working untouched.
81
+ */
82
+ export declare const sameRoot: (a: string | undefined, b: string | undefined) => boolean;
41
83
  interface BeatRef {
42
84
  filePath: string;
43
85
  beatIndex: number;
@@ -52,7 +94,18 @@ interface CharacterRef {
52
94
  interface SessionTag {
53
95
  chatSessionId?: string | undefined;
54
96
  }
55
- export type MulmoScriptDispatchArgs = ({
97
+ /**
98
+ * Which registered stories root the named script lives in (#3014).
99
+ *
100
+ * Intersected into the whole union below, so every dispatch that names a
101
+ * `filePath` can name its root — a union member that could not would make
102
+ * root-aware calls untypeable while the handler happily read `args.root`
103
+ * off an untyped record (Codex P1 on #3015).
104
+ */
105
+ interface RootTag {
106
+ root?: string | undefined;
107
+ }
108
+ export type MulmoScriptDispatchArgs = RootTag & (({
56
109
  kind: "save";
57
110
  } & {
58
111
  filePath?: string;
@@ -116,7 +169,7 @@ export type MulmoScriptDispatchArgs = ({
116
169
  } & SessionTag) | {
117
170
  kind: "pendingGenerations";
118
171
  filePath: string;
119
- };
172
+ });
120
173
  export type MulmoScriptDispatchKind = MulmoScriptDispatchArgs["kind"];
121
174
  /** Failure half of every dispatch response. `code` mirrors the phase-1
122
175
  * outcome codes so a host can log/telemetry on it; the View only reads
@@ -129,9 +182,9 @@ export interface DispatchFailure {
129
182
  export type DispatchEnvelope<T> = ({
130
183
  ok: true;
131
184
  } & T) | DispatchFailure;
132
- /** Maps a dispatch `kind` to its success payload so the View's transport
133
- * can call `dispatch` without casts at every site. */
134
- export interface MulmoScriptDispatchResult {
185
+ /** The success payload of each dispatch `kind`, BEFORE the root tag below is
186
+ * applied. Not exported: `MulmoScriptDispatchResult` is the type callers use. */
187
+ interface DispatchResultPayloads {
135
188
  save: {
136
189
  script: Record<string, unknown>;
137
190
  filePath: string;
@@ -182,5 +235,26 @@ export interface MulmoScriptDispatchResult {
182
235
  pending: MulmoScriptGenerationEvent[];
183
236
  };
184
237
  }
238
+ /**
239
+ * Maps a dispatch `kind` to its success payload, every one of them carrying
240
+ * the root it acted in.
241
+ *
242
+ * A host builds its cards from these results, and a card's identity is the
243
+ * PAIR `(root, filePath)` — `stories/deck.json` exists in every registered
244
+ * root. Without the root here, two repositories' identically-named decks
245
+ * collapse onto one card, which is #3014's third collision point, and no
246
+ * amount of fixing the host's identity function helps because the value never
247
+ * arrives.
248
+ *
249
+ * `root` was threaded through the ARGS and the EVENTS in #3015 and not through
250
+ * the results — the same shape that PR got wrong repeatedly: the comparison
251
+ * widened while the path carrying the data to it did not. Applied as a mapped
252
+ * type rather than field by field so a kind added later cannot be forgotten.
253
+ *
254
+ * Absent means the default root, so every pre-`root` card is unchanged.
255
+ */
256
+ export type MulmoScriptDispatchResult = {
257
+ [K in keyof DispatchResultPayloads]: DispatchResultPayloads[K] & RootTag;
258
+ };
185
259
  export {};
186
260
  //# sourceMappingURL=contract.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"contract.d.ts","sourceRoot":"","sources":["../../src/core/contract.ts"],"names":[],"mappings":"AAaA;;;oEAGoE;AACpE,MAAM,WAAW,0BAA0B;IACzC,IAAI,EAAE,WAAW,GAAG,WAAW,GAAG,gBAAgB,GAAG,OAAO,GAAG,KAAK,CAAC;IACrE,qEAAqE;IACrE,QAAQ,EAAE,MAAM,CAAC;IACjB,2FAA2F;IAC3F,GAAG,EAAE,MAAM,CAAC;IACZ,oEAAoE;IACpE,IAAI,EAAE,OAAO,CAAC;IACd,kDAAkD;IAClD,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED;mDACmD;AACnD,eAAO,MAAM,gBAAgB,eAAe,CAAC;AAE7C;sDACsD;AACtD,eAAO,MAAM,oBAAoB,kBAAkB,CAAC;AAEpD;;;;;;GAMG;AACH,MAAM,WAAW,uBAAuB;IACtC,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;;;;GAMG;AACH,eAAO,MAAM,2BAA2B,GAAI,OAAO,uBAAuB,EAAE,UAAU,MAAM,EAAE,WAAW,MAAM,KAAG,OACpC,CAAC;AAE/E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AAO,EAAE,MAAM,CAAA;KAAE,CAAC;IACjC,kBAAkB,EAAE;QAAE,OAAO,EAAE,0BAA0B,EAAE,CAAA;KAAE,CAAC;CAC/D;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,MAAM,yBAAyB,GAAG;KACrC,CAAC,IAAI,MAAM,sBAAsB,GAAG,sBAAsB,CAAC,CAAC,CAAC,GAAG,OAAO;CACzE,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"definition.d.ts","sourceRoot":"","sources":["../../src/core/definition.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAExD,eAAO,MAAM,SAAS,uBAAuB,CAAC;AAM9C,eAAO,MAAM,eAAe,EAAE,cA4H7B,CAAC"}
1
+ {"version":3,"file":"definition.d.ts","sourceRoot":"","sources":["../../src/core/definition.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAExD,eAAO,MAAM,SAAS,uBAAuB,CAAC;AAM9C,eAAO,MAAM,eAAe,EAAE,cA0H7B,CAAC"}
@@ -1,3 +1,44 @@
1
+ /**
2
+ * The slice of `node:path` this rule needs.
3
+ *
4
+ * Injected with no default, and this module imports no `node:*` builtin: it is
5
+ * reached from the browser entry through `core/plugin`, so a `node:path`
6
+ * import here lands in the Vue bundle (Codex on #3017). The server passes its
7
+ * own `path`; tests pass `path.win32` to reach the case below.
8
+ */
9
+ export interface PathRules {
10
+ relative: (from: string, to: string) => string;
11
+ isAbsolute: (p: string) => boolean;
12
+ sep: string;
13
+ }
14
+ /**
15
+ * The wire ref for an absolute path inside a stories root, or `null` when it
16
+ * is not inside one.
17
+ *
18
+ * Pure, and taking its path rules as an argument, because the case that
19
+ * matters is unreachable on the machine this is written on. `path.relative`
20
+ * says "not under the base" in TWO ways and only one looks like an escape:
21
+ * `../…` is the familiar one, and across Windows DRIVES there is no relative
22
+ * path at all, so `relative("C:\\base", "D:\\x")` answers `"D:\\x"` —
23
+ * absolute, with no `..` for the escape check to catch. That minted
24
+ * `stories/D:/anything`, a wire ref that reads back as a DIFFERENT file, which
25
+ * is the substitution this function exists to refuse. Only Windows CI caught
26
+ * it; here there is one root and always a relative route (#3015 post-merge).
27
+ */
28
+ /**
29
+ * The path INSIDE a stories root that a wire path names, or null when it does
30
+ * not name one.
31
+ *
32
+ * The default root's FileOps is rooted one level up, at `<workspace>/artifacts`,
33
+ * so there the wire path and the FileOps path are the SAME string and nothing
34
+ * is stripped. A named root's FileOps is rooted at the stories directory
35
+ * itself — which is what a host naturally writes, having registered exactly
36
+ * that directory in `extraRoots` — so the `stories/` prefix has to come off,
37
+ * or the write lands in `<root>/stories/<rel>` while the read looks in
38
+ * `<root>/<rel>` and the two are different files (#3020 review H1).
39
+ */
40
+ export declare function storiesRelativePath(wirePath: string): string | null;
41
+ export declare function storyRefWithin(base: string, absolutePath: string, rules: PathRules): string | null;
1
42
  /** Lowercase-hyphen slug, capped, leading/trailing hyphens stripped; falls back
2
43
  * to `fallback` for empty/undefined/non-ASCII input. */
3
44
  export declare function slugify(title: string | undefined, fallback?: string): string;
@@ -1 +1 @@
1
- {"version":3,"file":"paths.d.ts","sourceRoot":"","sources":["../../src/core/paths.ts"],"names":[],"mappings":"AAgBA;yDACyD;AACzD,wBAAgB,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,EAAE,QAAQ,SAAsB,GAAG,MAAM,CAEzF;AAED;;0CAE0C;AAC1C,wBAAgB,aAAa,CAAC,UAAU,EAAE,MAAM,EAAE,GAAG,GAAE,IAAiB,GAAG,MAAM,CAEhF;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAUlE"}
1
+ {"version":3,"file":"paths.d.ts","sourceRoot":"","sources":["../../src/core/paths.ts"],"names":[],"mappings":"AAaA;;;;;;;GAOG;AACH,MAAM,WAAW,SAAS;IACxB,QAAQ,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,KAAK,MAAM,CAAC;IAC/C,UAAU,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC;IACnC,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;;;;;;;;;;;;GAaG;AACH;;;;;;;;;;;GAWG;AACH,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAInE;AAED,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,GAAG,MAAM,GAAG,IAAI,CAMlG;AAKD;yDACyD;AACzD,wBAAgB,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,EAAE,QAAQ,SAAsB,GAAG,MAAM,CAEzF;AAED;;0CAE0C;AAC1C,wBAAgB,aAAa,CAAC,UAAU,EAAE,MAAM,EAAE,GAAG,GAAE,IAAiB,GAAG,MAAM,CAEhF;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAUlE"}
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_plugin = require("./plugin-BOq5YkTl.cjs");
2
+ const require_plugin = require("./plugin-C5JC2lNR.cjs");
3
3
  exports.TOOL_DEFINITION = require_plugin.TOOL_DEFINITION;
4
4
  exports.TOOL_NAME = require_plugin.TOOL_NAME;
5
5
  exports.executeMulmoScript = require_plugin.executeMulmoScript;
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import { a as pluginCore, c as normalizeStoryPath, f as TOOL_DEFINITION, i as executeUpdateScript, l as slugify, n as executeMulmoScriptSave, o as validateUpdateBeatBody, p as TOOL_NAME, r as executeUpdateBeat, s as validateUpdateScriptBody, t as executeMulmoScript, u as storyFilePath } from "./plugin-CAhxJ5WM.js";
1
+ import { a as pluginCore, c as normalizeStoryPath, d as storyFilePath, h as TOOL_NAME, i as executeUpdateScript, l as slugify, m as TOOL_DEFINITION, n as executeMulmoScriptSave, o as validateUpdateBeatBody, r as executeUpdateBeat, s as validateUpdateScriptBody, t as executeMulmoScript } from "./plugin-Jo8iGv4K.js";
2
2
  export { TOOL_DEFINITION, TOOL_NAME, executeMulmoScript, executeMulmoScriptSave, executeUpdateBeat, executeUpdateScript, normalizeStoryPath, pluginCore, slugify, storyFilePath, validateUpdateBeatBody, validateUpdateScriptBody };
@@ -151,6 +151,44 @@ function errorMessage(err, fallback) {
151
151
  }
152
152
  //#endregion
153
153
  //#region src/core/paths.ts
154
+ /**
155
+ * The wire ref for an absolute path inside a stories root, or `null` when it
156
+ * is not inside one.
157
+ *
158
+ * Pure, and taking its path rules as an argument, because the case that
159
+ * matters is unreachable on the machine this is written on. `path.relative`
160
+ * says "not under the base" in TWO ways and only one looks like an escape:
161
+ * `../…` is the familiar one, and across Windows DRIVES there is no relative
162
+ * path at all, so `relative("C:\\base", "D:\\x")` answers `"D:\\x"` —
163
+ * absolute, with no `..` for the escape check to catch. That minted
164
+ * `stories/D:/anything`, a wire ref that reads back as a DIFFERENT file, which
165
+ * is the substitution this function exists to refuse. Only Windows CI caught
166
+ * it; here there is one root and always a relative route (#3015 post-merge).
167
+ */
168
+ /**
169
+ * The path INSIDE a stories root that a wire path names, or null when it does
170
+ * not name one.
171
+ *
172
+ * The default root's FileOps is rooted one level up, at `<workspace>/artifacts`,
173
+ * so there the wire path and the FileOps path are the SAME string and nothing
174
+ * is stripped. A named root's FileOps is rooted at the stories directory
175
+ * itself — which is what a host naturally writes, having registered exactly
176
+ * that directory in `extraRoots` — so the `stories/` prefix has to come off,
177
+ * or the write lands in `<root>/stories/<rel>` while the read looks in
178
+ * `<root>/<rel>` and the two are different files (#3020 review H1).
179
+ */
180
+ function storiesRelativePath(wirePath) {
181
+ const normalized = normalizeStoryPath(wirePath);
182
+ if (normalized === null) return null;
183
+ return normalized.slice(`${STORIES_DIR}/`.length);
184
+ }
185
+ function storyRefWithin(base, absolutePath, rules) {
186
+ const relative = rules.relative(base, absolutePath);
187
+ if (rules.isAbsolute(relative)) return null;
188
+ const rel = relative.split(rules.sep).join("/");
189
+ if (rel === ".." || rel.startsWith("../")) return null;
190
+ return rel ? `${STORIES_DIR}/${rel}` : STORIES_DIR;
191
+ }
154
192
  var STORIES_DIR = "stories";
155
193
  var STORY_FALLBACK_SLUG = "story";
156
194
  /** Lowercase-hyphen slug, capped, leading/trailing hyphens stripped; falls back
@@ -496,12 +534,24 @@ Object.defineProperty(exports, "slugify", {
496
534
  return slugify;
497
535
  }
498
536
  });
537
+ Object.defineProperty(exports, "storiesRelativePath", {
538
+ enumerable: true,
539
+ get: function() {
540
+ return storiesRelativePath;
541
+ }
542
+ });
499
543
  Object.defineProperty(exports, "storyFilePath", {
500
544
  enumerable: true,
501
545
  get: function() {
502
546
  return storyFilePath;
503
547
  }
504
548
  });
549
+ Object.defineProperty(exports, "storyRefWithin", {
550
+ enumerable: true,
551
+ get: function() {
552
+ return storyRefWithin;
553
+ }
554
+ });
505
555
  Object.defineProperty(exports, "validateUpdateBeatBody", {
506
556
  enumerable: true,
507
557
  get: function() {
@@ -515,4 +565,4 @@ Object.defineProperty(exports, "validateUpdateScriptBody", {
515
565
  }
516
566
  });
517
567
 
518
- //# sourceMappingURL=plugin-BOq5YkTl.cjs.map
568
+ //# sourceMappingURL=plugin-C5JC2lNR.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin-C5JC2lNR.cjs","names":["isRecord"],"sources":["../src/core/definition.ts","../../../common/dist/index.js","../src/core/paths.ts","../src/core/validate.ts","../src/core/plugin.ts"],"sourcesContent":["import type { ToolDefinition } from \"gui-chat-protocol\";\n\nexport const TOOL_NAME = \"presentMulmoScript\";\n\n// Single source of truth for the presentMulmoScript tool schema, shared by\n// MulmoClaude (host built-in shim re-exports this) and MulmoTerminal.\n// (Extracted byte-identical from the host definition; evolves here with the\n// package version.)\nexport const TOOL_DEFINITION: ToolDefinition = {\n type: \"function\",\n name: TOOL_NAME,\n description: `Save and present a MulmoScript story or presentation as a visual storyboard in the canvas.\n\nProvide EXACTLY ONE of \\`script\\` or \\`filePath\\`:\n\n1. **Create new** — pass \\`script\\` (full MulmoScript JSON). Server saves it to disk and presents it.\n2. **Re-display existing** — pass \\`filePath\\` (the \\`filePath\\` returned by a previous call, e.g. \"stories/my-story-1700000000000.json\"; it is resolved against the workspace's \\`artifacts/\\` directory, NOT the workspace root). Much cheaper than re-sending the full script. Use whenever the user wants to revisit a presentation that was already created in this workspace.\n3. **Edit one beat** — pass \\`filePath\\` PLUS \\`beatIndex\\` and \\`beat\\`. Replaces that one beat and presents the result. **Use this whenever the user asks to change part of an existing presentation** — re-sending the whole script instead wastes tokens and overwrites anything edited in the canvas meanwhile.\n\nOptional \\`autoGenerateMovie: true\\` kicks off movie generation in the background, so the final video is ready by the time the user opens the canvas. Movie generation is expensive (multiple image + audio API calls + video encoding) — only set this when the user has explicitly asked for the movie. Default \\`false\\`.\n\nProvider rules for new scripts:\n- \\`speechParams.speakers.<name>.provider\\`: \\`\"gemini\"\\` — pairs with Gemini voices like \\`\"Kore\"\\`, \\`\"Aoede\"\\`, \\`\"Puck\"\\`. Do NOT use \\`\"google\"\\` here — that routes to Google Cloud TTS, where Gemini-class voices fail with \"This voice requires a model name to be specified.\" unless an explicit \\`model\\` is set.\n- \\`imageParams.provider\\`: \\`\"google\"\\`\n- \\`movieParams.provider\\`: \\`\"google\"\\`\n- Do NOT add a top-level \\`provider\\` field to \\`speechParams\\` — provider belongs per-speaker only.\n\nRequired structure:\n\n{\n \"$mulmocast\": { \"version\": \"1.1\" },\n \"title\": \"The Life of a Star\",\n \"description\": \"A short educational explainer about stellar evolution\",\n \"lang\": \"en\",\n \"speechParams\": {\n \"speakers\": {\n \"Presenter\": {\n \"provider\": \"gemini\",\n \"voiceId\": \"Kore\",\n \"displayName\": { \"en\": \"Presenter\" }\n }\n }\n },\n \"imageParams\": { \"provider\": \"google\", \"model\": \"gemini-3.1-flash-image-preview\" },\n \"movieParams\": { \"provider\": \"google\", \"model\": \"veo-3.1-generate\" },\n \"beats\": [\n {\n \"speaker\": \"Presenter\",\n \"text\": \"Narration spoken aloud for this beat.\",\n \"imagePrompt\": \"Detailed description — AI generates the image\"\n },\n {\n \"speaker\": \"Presenter\",\n \"text\": \"Bullet point beat.\",\n \"image\": { \"type\": \"textSlide\", \"slide\": { \"title\": \"Slide Title\", \"bullets\": [\"Point one\", \"Point two\"] } }\n },\n {\n \"speaker\": \"Presenter\",\n \"text\": \"Markdown beat.\",\n \"image\": { \"type\": \"markdown\", \"markdown\": \"## Heading\\\\n\\\\nBody text here.\" }\n },\n {\n \"speaker\": \"Presenter\",\n \"text\": \"Chart beat — use for data, comparisons, trends.\",\n \"image\": { \"type\": \"chart\", \"title\": \"Chart Title\", \"chartData\": { \"type\": \"bar\", \"data\": { \"labels\": [\"A\", \"B\", \"C\"], \"datasets\": [{ \"label\": \"Series\", \"data\": [10, 20, 30] }] } } }\n },\n {\n \"speaker\": \"Presenter\",\n \"text\": \"Diagram beat — use for flows, architectures, relationships.\",\n \"image\": { \"type\": \"mermaid\", \"title\": \"Diagram Title\", \"code\": { \"kind\": \"text\", \"text\": \"graph TD\\\\n A[Start] --> B[Process] --> C[End]\" } }\n },\n {\n \"speaker\": \"Presenter\",\n \"text\": \"Rich interactive beat — use for custom layouts, animations, or anything that benefits from HTML/CSS.\",\n \"image\": { \"type\": \"html_tailwind\", \"html\": \"<div class=\\\\\"flex items-center justify-center h-full text-4xl font-bold text-blue-600\\\\\">Hello World</div>\" }\n },\n {\n \"speaker\": \"Presenter\",\n \"text\": \"AI video beat.\",\n \"moviePrompt\": \"Detailed description — AI generates the video clip\"\n }\n ]\n}\n\nBeat visual options (choose one per beat):\n- \"imagePrompt\": \"...\" → top-level string field — AI generates an image from the prompt\n- \"moviePrompt\": \"...\" → top-level string field — AI generates a video clip from the prompt\n- \"image\": { \"type\": \"textSlide\", \"slide\": { \"title\", \"subtitle\"?, \"bullets\"? } }\n- \"image\": { \"type\": \"markdown\", \"markdown\": \"...\" }\n- \"image\": { \"type\": \"chart\", \"title\": \"...\", \"chartData\": { \"type\": \"bar\"|\"line\"|\"pie\"|..., \"data\": { \"labels\": [...], \"datasets\": [...] } } } ← PREFER for data/numbers/comparisons. chartData is a full Chart.js config: labels/datasets go under \"data\", not at the top level.\n- \"image\": { \"type\": \"mermaid\", \"title\": \"...\", \"code\": { \"kind\": \"text\", \"text\": \"...\" } } ← PREFER for flows/diagrams/relationships\n- \"image\": { \"type\": \"html_tailwind\", \"html\": \"...\", \"script\"?: \"...\" } ← PREFER for rich layouts, animations, custom visuals\n\nIMPORTANT: \"imagePrompt\" and \"moviePrompt\" are plain string fields on the beat, NOT nested under \"image\".`,\n parameters: {\n type: \"object\",\n properties: {\n script: {\n type: \"object\",\n description:\n \"Complete MulmoScript JSON for a NEW presentation. Must include $mulmocast, speechParams, imageParams, movieParams, and beats array. Always populate the top-level 'description' field with a concise 1–2 sentence summary of the presentation. Do NOT pass alongside `filePath`.\",\n additionalProperties: true,\n },\n filename: {\n type: \"string\",\n description:\n \"Optional filename without extension. Defaults to a slug of the script title. Only meaningful with `script`; ignored when `filePath` is given.\",\n },\n filePath: {\n type: \"string\",\n description:\n \"Path of an EXISTING MulmoScript JSON file, as returned by a previous call (e.g. 'stories/my-story-1700000000000.json'). Resolved against the workspace's `artifacts/` directory, not the workspace root ('artifacts/stories/…' is also accepted). Use this to re-display a script previously saved in this workspace, instead of resending the full JSON. Do NOT pass alongside `script`.\",\n },\n beatIndex: {\n type: \"number\",\n description: \"0-based index of the beat to replace. Requires `filePath` and `beat`. Omit to re-display the script unchanged.\",\n },\n beat: {\n type: \"object\",\n description: \"The replacement beat, complete (it overwrites the old one — it is not merged). Requires `filePath` and `beatIndex`.\",\n additionalProperties: true,\n },\n autoGenerateMovie: {\n type: \"boolean\",\n description:\n \"When true, the server starts movie generation in the background after save/load. The user does NOT need to open the canvas — progress streams via the existing session channel. Default false. Only set true when the user has explicitly asked for the movie; generation is expensive.\",\n },\n },\n required: [],\n },\n};\n","// General-purpose runtime type guards, shared across the MulmoClaude host,\n// bridges, and plugins. This is a leaf package — pure and dependency-free — so\n// any tier can import it without creating an uphill edge.\n//\n// These originated as `server/utils/types.ts` (#504), which centralised 40+\n// hand-written inline `typeof x === \"object\"` checks. They are promoted here so\n// the same guards stop being re-hand-written in every bridge and plugin too.\n/** Narrow `unknown` to a plain object (not null, not array). */\nexport function isRecord(value) {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n/** Narrow `unknown` to any object (not null, arrays allowed).\n * Use `isRecord` when you need to access string keys. */\nexport function isObj(value) {\n return typeof value === \"object\" && value !== null;\n}\n/** Non-empty string after trimming whitespace. */\nexport function isNonEmptyString(value) {\n return typeof value === \"string\" && value.trim().length > 0;\n}\n/** Record whose values are all strings. */\nexport function isStringRecord(value) {\n if (!isRecord(value))\n return false;\n return Object.values(value).every((val) => typeof val === \"string\");\n}\n/** String array (every element is a string). */\nexport function isStringArray(value) {\n return Array.isArray(value) && value.every((val) => typeof val === \"string\");\n}\n/** An array of unknowns. Prefer this over a bare `Array.isArray` in typed code:\n * `Array.isArray(x: unknown)` narrows to `any[]`, silently reintroducing\n * `any`, whereas this keeps the element type `unknown`. */\nexport function isUnknownArray(value) {\n return Array.isArray(value);\n}\n/** Error-like object with a `code` property (e.g. Node.js fs errors). */\nexport function isErrorWithCode(value) {\n return isRecord(value) && typeof value.code === \"string\";\n}\n/** Check that a record has a specific key with a string value. */\nexport function hasStringProp(value, key) {\n return isRecord(value) && typeof value[key] === \"string\";\n}\n/** Check that a record has a specific key with a number value. */\nexport function hasNumberProp(value, key) {\n return isRecord(value) && typeof value[key] === \"number\";\n}\n/** Split a comma-separated env value into trimmed, non-empty entries.\n * `lowercase` folds case for identifiers compared case-insensitively\n * (JIDs, email addresses, hex pubkeys). Absent/empty input → empty list. */\nexport function parseCsvList(raw, opts) {\n return (raw ?? \"\")\n .split(\",\")\n .map((entry) => (opts?.lowercase ? entry.trim().toLowerCase() : entry.trim()))\n .filter(Boolean);\n}\n/** A comma-separated env value as a Set — the canonical allowlist shape,\n * where an empty set is the \"allow all\" sentinel (`set.size === 0`). */\nexport function parseCsvSet(raw, opts) {\n return new Set(parseCsvList(raw, opts));\n}\n/** Normalise an unknown thrown value into a human-readable string. Isomorphic\n * (host, bridges, plugins, Vue) — this is the single home for the helper that\n * #2217 could only consolidate for server code, since `@mulmoclaude/core/utils`\n * is server-only.\n *\n * A non-Error object with a non-empty string `details` (gRPC convention) or\n * `message` field surfaces that field — `details` wins — instead of the\n * `[object Object]` a bare `String(err)` would print; an empty-string field\n * falls through. `fallback` covers the error-boundary idiom where a thrown\n * non-Error should read as a descriptive message rather than `String(err)`\n * noise; omit it in logging contexts where `String(err)` is fine. */\nexport function errorMessage(err, fallback) {\n if (err instanceof Error)\n return err.message;\n if (hasStringProp(err, \"details\") && err.details)\n return err.details;\n if (hasStringProp(err, \"message\") && err.message)\n return err.message;\n if (fallback !== undefined)\n return fallback;\n return String(err);\n}\n/** `Date` → `YYYY-MM-DD` in UTC — for dates that must not shift with the\n * host's local timezone (tool-trace search dirs, API date keys). Isomorphic\n * single source (#2480): the host re-exports it from `server/utils/date.ts`,\n * x-plugin imports it directly. The `@receptron/task-scheduler` copy stays\n * local on purpose — that leaf package is published independently and kept\n * dependency-free. Wall-clock questions use the host's `toLocalIsoDate`. */\nexport function toUtcIsoDate(timestamp) {\n const year = timestamp.getUTCFullYear();\n const month = String(timestamp.getUTCMonth() + 1).padStart(2, \"0\");\n const day = String(timestamp.getUTCDate()).padStart(2, \"0\");\n return `${year}-${month}-${day}`;\n}\n// A Map, not an object literal: `{}[char]` reads through the prototype chain,\n// so a future caller widening the regex would silently get `[object Object]`\n// for keys like `constructor`.\nconst HTML_ESCAPES = new Map([\n [\"&\", \"&amp;\"],\n [\"<\", \"&lt;\"],\n [\">\", \"&gt;\"],\n ['\"', \"&quot;\"],\n [\"'\", \"&#39;\"],\n]);\n/** HTML-escape text destined for markup or an attribute value — the fixed\n * five-character map, nothing more. Lives here rather than in\n * `@mulmoclaude/core/wiki` (#2483) because `@mulmoclaude/markdown-utils` is a\n * leaf that core depends on and so cannot import back up; core/wiki\n * re-exports this, keeping its consumers' import path unchanged.\n *\n * Escaping `&` first is what makes a single pass safe — the entities this\n * introduces contain none of the other four characters, so nothing is\n * double-escaped. Not a sanitiser: it neither strips tags nor validates URLs. */\nexport function escapeHtml(value) {\n return value.replace(/[&<>\"']/g, (char) => HTML_ESCAPES.get(char) ?? char);\n}\n/** Split a JWS compact serialization into its three segments, or `null` when the\n * token isn't well-formed. Pure string work, so the Node bridges and the\n * Cloudflare Workers relay — which decode the segments differently (`Buffer` vs\n * `atob`) — can still share this one guard.\n *\n * A JWS compact serialization is EXACTLY three segments. Both a short token and\n * a longer one (a five-segment JWE, or an attacker appending `.junk`) are\n * rejected outright — never parsed from their first three segments, which would\n * let the signed input disagree with the token. */\nexport function splitJwtSegments(token) {\n const [headerSegment, payloadSegment, signatureSegment, ...extraSegments] = token.split(\".\");\n if (headerSegment === undefined || payloadSegment === undefined || signatureSegment === undefined)\n return null;\n if (extraSegments.length > 0)\n return null;\n return { headerSegment, payloadSegment, signatureSegment };\n}\nexport { scanEnvOptions, snakeToLowerCamel } from \"./envScan.js\";\n","// Path helpers for MulmoScript story artifacts. The generic build primitives\n// (slug + the `\"\"`/`.`/`..` traversal guard) live in the shared, browser-safe\n// `@mulmoclaude/core/artifacts` (#2405); only the story-specific wire-path\n// rules stay here.\n//\n// Path model: the stories directory lives at `<workspace>/artifacts/stories`\n// and the FileOps scope root is `<workspace>/artifacts`, so the\n// FileOps-relative path and the historical `stories/<name>.json` wire form\n// (which every mulmoScript endpoint keys on) are the SAME string. Stories are\n// NOT `YYYY/MM`-partitioned, so `storyFilePath` opts out of partitioning.\n\nimport { ARTIFACTS_ROOT, buildArtifactRelPath, hasUnsafePathSegment, slugifyArtifact } from \"@mulmoclaude/core/artifacts\";\n\n/**\n * The slice of `node:path` this rule needs.\n *\n * Injected with no default, and this module imports no `node:*` builtin: it is\n * reached from the browser entry through `core/plugin`, so a `node:path`\n * import here lands in the Vue bundle (Codex on #3017). The server passes its\n * own `path`; tests pass `path.win32` to reach the case below.\n */\nexport interface PathRules {\n relative: (from: string, to: string) => string;\n isAbsolute: (p: string) => boolean;\n sep: string;\n}\n\n/**\n * The wire ref for an absolute path inside a stories root, or `null` when it\n * is not inside one.\n *\n * Pure, and taking its path rules as an argument, because the case that\n * matters is unreachable on the machine this is written on. `path.relative`\n * says \"not under the base\" in TWO ways and only one looks like an escape:\n * `../…` is the familiar one, and across Windows DRIVES there is no relative\n * path at all, so `relative(\"C:\\\\base\", \"D:\\\\x\")` answers `\"D:\\\\x\"` —\n * absolute, with no `..` for the escape check to catch. That minted\n * `stories/D:/anything`, a wire ref that reads back as a DIFFERENT file, which\n * is the substitution this function exists to refuse. Only Windows CI caught\n * it; here there is one root and always a relative route (#3015 post-merge).\n */\n/**\n * The path INSIDE a stories root that a wire path names, or null when it does\n * not name one.\n *\n * The default root's FileOps is rooted one level up, at `<workspace>/artifacts`,\n * so there the wire path and the FileOps path are the SAME string and nothing\n * is stripped. A named root's FileOps is rooted at the stories directory\n * itself — which is what a host naturally writes, having registered exactly\n * that directory in `extraRoots` — so the `stories/` prefix has to come off,\n * or the write lands in `<root>/stories/<rel>` while the read looks in\n * `<root>/<rel>` and the two are different files (#3020 review H1).\n */\nexport function storiesRelativePath(wirePath: string): string | null {\n const normalized = normalizeStoryPath(wirePath);\n if (normalized === null) return null;\n return normalized.slice(`${STORIES_DIR}/`.length);\n}\n\nexport function storyRefWithin(base: string, absolutePath: string, rules: PathRules): string | null {\n const relative = rules.relative(base, absolutePath);\n if (rules.isAbsolute(relative)) return null;\n const rel = relative.split(rules.sep).join(\"/\");\n if (rel === \"..\" || rel.startsWith(\"../\")) return null;\n return rel ? `${STORIES_DIR}/${rel}` : STORIES_DIR;\n}\n\nconst STORIES_DIR = \"stories\";\nconst STORY_FALLBACK_SLUG = \"story\";\n\n/** Lowercase-hyphen slug, capped, leading/trailing hyphens stripped; falls back\n * to `fallback` for empty/undefined/non-ASCII input. */\nexport function slugify(title: string | undefined, fallback = STORY_FALLBACK_SLUG): string {\n return slugifyArtifact(title, fallback);\n}\n\n/** Build a fresh, collision-safe story path for a new script —\n * `stories/<slug>-<epoch-ms>.json`, valid as both the FileOps-relative\n * write path and the wire `filePath`. */\nexport function storyFilePath(slugSource: string, now: Date = new Date()): string {\n return buildArtifactRelPath({ dir: STORIES_DIR, title: slugSource, ext: \".json\", fallback: STORY_FALLBACK_SLUG, now, partitioned: false });\n}\n\n/**\n * Normalize a caller-supplied wire path to the canonical\n * `stories/<rel>` form, or null when it can't be trusted. Accepts the\n * canonical `stories/foo.json` convention, bare `foo.json` (the host route\n * historically allowed either), and the workspace-relative spelling\n * `artifacts/stories/foo.json` — the tool description called `filePath`\n * \"workspace-relative\" for a long time, so agents legitimately send it.\n * A leading `artifacts` segment is dropped only when `stories` follows;\n * a bare `artifacts/foo.json` keeps its historical meaning (a file named\n * `artifacts/foo.json` under the stories dir). Rejects absolute paths,\n * backslashes, and any empty / `.` / `..` segment — the lexical guard\n * before every `files.artifacts` read/write (FileOps re-checks\n * containment as defence-in-depth).\n */\nexport function normalizeStoryPath(filePath: string): string | null {\n if (filePath.length === 0 || filePath.includes(\"\\\\\")) return null;\n // Absolute POSIX path or Windows drive prefix.\n if (filePath.startsWith(\"/\") || /^[A-Za-z]:/.test(filePath)) return null;\n if (hasUnsafePathSegment(filePath)) return null;\n const segments = filePath.split(\"/\");\n const trimmed = segments[0] === ARTIFACTS_ROOT && segments[1] === STORIES_DIR ? segments.slice(1) : segments;\n const rest = trimmed[0] === STORIES_DIR ? trimmed.slice(1) : trimmed;\n if (rest.length === 0) return null;\n return [STORIES_DIR, ...rest].join(\"/\");\n}\n","// Body validators for the mulmoScript update endpoints, moved verbatim from\n// the host's `server/api/routes/mulmoScriptValidate.ts` so MulmoClaude and\n// MulmoTerminal share one definition of a \"valid script\" / \"valid beat\".\n//\n// The `@mulmocast/types` package exports zod schemas that mirror the\n// canonical MulmoScript / MulmoBeat shapes. The same schemas back client-side\n// edit-time validation in the presentMulmoScript View.\n\nimport { mulmoBeatSchema, mulmoScriptSchema } from \"@mulmocast/types\";\n\nexport type ValidationResult<T> = { ok: true; value: T } | { ok: false; error: string };\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction formatZodIssues(\n // Zod's `$ZodIssue.path` is `PropertyKey[]` (includes `symbol`).\n // Accept the wider type so callers can pass `safeParse().error.issues`\n // directly; stringify any non-string/number segments at format time.\n issues: readonly { message: string; path: readonly PropertyKey[] }[],\n): string {\n if (issues.length === 0) return \"invalid shape\";\n const head = issues\n .slice(0, 3)\n .map((i) => {\n const pathStr = i.path.length > 0 ? i.path.map((seg) => String(seg)).join(\".\") : \"<root>\";\n return `${pathStr}: ${i.message}`;\n })\n .join(\"; \");\n return issues.length > 3 ? `${head} (+${issues.length - 3} more)` : head;\n}\n\n/** Shared prelude: require an object body carrying a non-empty\n * `filePath`. On success returns the narrowed record + filePath so the\n * caller reads the remaining fields without re-narrowing. */\nfunction validateFilePathBody(body: unknown): ValidationResult<{ record: Record<string, unknown>; filePath: string }> {\n if (!isRecord(body)) {\n return { ok: false, error: \"body must be an object\" };\n }\n if (typeof body.filePath !== \"string\" || body.filePath === \"\") {\n return { ok: false, error: \"filePath must be a non-empty string\" };\n }\n return { ok: true, value: { record: body, filePath: body.filePath } };\n}\n\n/**\n * Validate the `update-script` request body. Returns the parsed,\n * schema-conformant script on success, or a human-readable error\n * suitable for sending back as a 400 response.\n */\nexport function validateUpdateScriptBody(body: unknown): ValidationResult<{\n filePath: string;\n script: unknown;\n}> {\n const base = validateFilePathBody(body);\n if (!base.ok) return base;\n const { record, filePath } = base.value;\n if (record.script === undefined) {\n return { ok: false, error: \"script is required\" };\n }\n const parsed = mulmoScriptSchema.safeParse(record.script);\n if (!parsed.success) {\n return {\n ok: false,\n error: `invalid script: ${formatZodIssues(parsed.error.issues)}`,\n };\n }\n return {\n ok: true,\n value: { filePath, script: parsed.data },\n };\n}\n\n/**\n * Validate the `update-beat` request body. `beatIndex` is allowed\n * to be any non-negative integer; the handler still bounds-checks\n * against the actual script length after reading the file.\n */\nexport function validateUpdateBeatBody(body: unknown): ValidationResult<{\n filePath: string;\n beatIndex: number;\n beat: unknown;\n}> {\n const base = validateFilePathBody(body);\n if (!base.ok) return base;\n const { record, filePath } = base.value;\n const beatIndex = record.beatIndex;\n if (typeof beatIndex !== \"number\" || !Number.isInteger(beatIndex) || beatIndex < 0) {\n return { ok: false, error: \"beatIndex must be a non-negative integer\" };\n }\n if (record.beat === undefined) {\n return { ok: false, error: \"beat is required\" };\n }\n const parsed = mulmoBeatSchema.safeParse(record.beat);\n if (!parsed.success) {\n return {\n ok: false,\n error: `invalid beat: ${formatZodIssues(parsed.error.issues)}`,\n };\n }\n return {\n ok: true,\n value: {\n filePath,\n beatIndex,\n beat: parsed.data,\n },\n };\n}\n","import type { ToolPluginCore, ToolResult } from \"gui-chat-protocol\";\nimport { mulmoScriptSchema } from \"@mulmocast/types\";\nimport { errorMessage } from \"@mulmoclaude/common\";\nimport { TOOL_DEFINITION } from \"./definition\";\nimport { normalizeStoryPath, storyFilePath } from \"./paths\";\nimport { validateUpdateBeatBody, validateUpdateScriptBody } from \"./validate\";\nimport type { MulmoScriptData, MulmoScriptExecuteContext, SaveMulmoScriptArgs } from \"./types\";\n\n/** Failure half of every outcome below. `code` preserves the hosts'\n * HTTP contract (bad_request → 400, not_found → 404) without the package\n * knowing anything about HTTP. */\nexport interface MulmoScriptFailure {\n ok: false;\n code: \"bad_request\" | \"not_found\";\n error: string;\n}\n\nexport type SaveMulmoScriptOutcome = ({ ok: true; message: string } & MulmoScriptData) | MulmoScriptFailure;\n\nexport type UpdateMulmoScriptOutcome = { ok: true } | MulmoScriptFailure;\n\nfunction badRequest(error: string): MulmoScriptFailure {\n return { ok: false, code: \"bad_request\", error };\n}\n\nfunction notFound(error: string): MulmoScriptFailure {\n return { ok: false, code: \"not_found\", error };\n}\n\nfunction stringifyScript(script: unknown): string {\n // 2-space indent matches the hosts' writeJsonAtomic convention so a\n // package-written script diffs cleanly against host-written ones.\n return JSON.stringify(script, null, 2);\n}\n\n/** Persist a new, schema-validated script under a fresh `stories/…` path. */\nasync function saveNewScript(context: MulmoScriptExecuteContext, script: unknown, filename: string | undefined, now: Date): Promise<SaveMulmoScriptOutcome> {\n const validation = mulmoScriptSchema.safeParse(script);\n if (!validation.success) {\n return badRequest(\"script is not a valid MulmoScript\");\n }\n const validatedScript = validation.data;\n // slugify drops `/`, `\\`, and `..`, so a hostile `filename` like\n // \"../../etc/passwd\" can never escape the stories dir — defense in\n // depth on top of FileOps' own containment check.\n const slugSource = filename ? filename.replace(/\\.json$/i, \"\") : validatedScript.title || \"untitled\";\n const filePath = storyFilePath(slugSource, now);\n await context.files.artifacts.write(filePath, stringifyScript(validatedScript));\n return { ok: true, script: validatedScript, filePath, message: `Saved MulmoScript to ${filePath}` };\n}\n\n/** Re-open an existing script: containment guard, existence, JSON parse,\n * schema validation — same acceptance rules as the save path so a script\n * this package saved can never be one it later refuses to load. */\nasync function loadExistingScript(context: MulmoScriptExecuteContext, filePath: string): Promise<SaveMulmoScriptOutcome> {\n if (!filePath.toLowerCase().endsWith(\".json\")) {\n return badRequest(\"filePath must point to a .json file\");\n }\n const storyPath = normalizeStoryPath(filePath);\n if (!storyPath) {\n return badRequest(\"Invalid filePath\");\n }\n if (!(await context.files.artifacts.exists(storyPath))) {\n return notFound(`File not found: ${filePath}`);\n }\n const raw = await context.files.artifacts.read(storyPath);\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n return badRequest(`Invalid JSON: ${errorMessage(err)}`);\n }\n const validation = mulmoScriptSchema.safeParse(parsed);\n if (!validation.success) {\n return badRequest(\"File is not a valid MulmoScript\");\n }\n return { ok: true, script: validation.data, filePath: storyPath, message: `Loaded MulmoScript from ${storyPath}` };\n}\n\n/**\n * Unified save-or-reopen for the presentMulmoScript tool call. `script`\n * (create new) and `filePath` (existing) are mutually exclusive. Never\n * throws on bad input — validation failures come back as discriminated\n * failures so host routes stay thin adapters. `autoGenerateMovie` is NOT\n * handled here: movie generation needs host backends (mulmocast/ffmpeg),\n * so hosts that support it trigger it from the returned `filePath`.\n */\nexport async function executeMulmoScriptSave(\n context: MulmoScriptExecuteContext,\n args: SaveMulmoScriptArgs,\n now: Date = new Date(),\n): Promise<SaveMulmoScriptOutcome> {\n const { script, filename, filePath, beatIndex, beat } = args ?? {};\n const hasScript = script !== undefined && script !== null;\n const hasFilePath = typeof filePath === \"string\" && filePath !== \"\";\n if (hasScript === hasFilePath) {\n return badRequest(\n hasScript ? \"Provide either `script` or `filePath`, not both.\" : \"Provide either `script` (new presentation) or `filePath` (existing presentation).\",\n );\n }\n if (!hasFilePath) return saveNewScript(context, script, typeof filename === \"string\" ? filename : undefined, now);\n\n // `filePath` + `beatIndex` + `beat` replaces one beat before displaying, so revising a single\n // slide does not mean re-sending a whole deck. Both halves are required together: an index\n // with no replacement, or a replacement with no index, is a caller mistake worth reporting\n // rather than silently ignoring — it would look like a successful edit that changed nothing.\n const wantsBeatEdit = beatIndex !== undefined || beat !== undefined;\n if (wantsBeatEdit) {\n if (beatIndex === undefined || beat === undefined) {\n return badRequest(\"`beatIndex` and `beat` go together — pass both to replace one beat, or neither to re-display.\");\n }\n const updated = await executeUpdateBeat(context, { filePath, beatIndex, beat });\n if (!updated.ok) return updated;\n }\n return loadExistingScript(context, filePath);\n}\n\n/** Resolve + guard a wire path for the update endpoints. */\nasync function resolveExistingStory(context: MulmoScriptExecuteContext, filePath: string): Promise<{ storyPath: string } | MulmoScriptFailure> {\n const storyPath = normalizeStoryPath(filePath);\n if (!storyPath) return badRequest(\"Invalid filePath\");\n if (!(await context.files.artifacts.exists(storyPath))) {\n return notFound(`File not found: ${filePath}`);\n }\n return { storyPath };\n}\n\n/** Overwrite one beat of an existing script (the View's per-beat source\n * editor). Validates the body shape + beat schema, bounds-checks the index\n * against the script on disk, and writes the whole file back. */\nexport async function executeUpdateBeat(context: MulmoScriptExecuteContext, body: unknown): Promise<UpdateMulmoScriptOutcome> {\n const validation = validateUpdateBeatBody(body);\n if (!validation.ok) return badRequest(validation.error);\n const { filePath, beatIndex, beat } = validation.value;\n\n const resolved = await resolveExistingStory(context, filePath);\n if (\"ok\" in resolved) return resolved;\n\n let script: { beats?: unknown[] };\n try {\n script = JSON.parse(await context.files.artifacts.read(resolved.storyPath));\n } catch (err) {\n return badRequest(`Invalid JSON: ${errorMessage(err)}`);\n }\n if (!Array.isArray(script.beats) || beatIndex >= script.beats.length) {\n return badRequest(\"Invalid beatIndex\");\n }\n script.beats[beatIndex] = beat;\n await context.files.artifacts.write(resolved.storyPath, stringifyScript(script));\n return { ok: true };\n}\n\n/** Overwrite the whole script (the View's full-source editor / deck-editor\n * auto-save). The body's `script` is schema-validated by\n * `validateUpdateScriptBody` before the write. */\nexport async function executeUpdateScript(context: MulmoScriptExecuteContext, body: unknown): Promise<UpdateMulmoScriptOutcome> {\n const validation = validateUpdateScriptBody(body);\n if (!validation.ok) return badRequest(validation.error);\n const { filePath, script } = validation.value;\n\n const resolved = await resolveExistingStory(context, filePath);\n if (\"ok\" in resolved) return resolved;\n\n await context.files.artifacts.write(resolved.storyPath, stringifyScript(script));\n return { ok: true };\n}\n\n/** ToolResult-shaped wrapper over `executeMulmoScriptSave` for runtime hosts\n * (e.g. MulmoTerminal's package loader), where the tool call resolves to a\n * ToolResult rather than an HTTP response. Failures are narrate-only\n * (message, no data) so the agent can self-correct. */\nexport async function executeMulmoScript(context: MulmoScriptExecuteContext, args: SaveMulmoScriptArgs): Promise<ToolResult<MulmoScriptData>> {\n const outcome = await executeMulmoScriptSave(context, args);\n if (!outcome.ok) {\n return {\n message: outcome.error,\n instructions: \"Acknowledge the error and retry with a valid `script` (new) or an existing `filePath`.\",\n };\n }\n // The tool schema advertises `autoGenerateMovie`, but movie generation\n // needs host backends (mulmocast/ffmpeg) this generic execute path\n // doesn't have — MulmoClaude honours the flag in its own save route.\n // Say so in the result rather than silently dropping the option, so the\n // agent doesn't tell the user a movie is on its way.\n const ignoredMovieNote = args.autoGenerateMovie === true ? \" (autoGenerateMovie is not supported by this host and was ignored)\" : \"\";\n return {\n message: `${outcome.message}${ignoredMovieNote}`,\n data: { script: outcome.script, filePath: outcome.filePath },\n instructions: \"Display the storyboard to the user.\",\n };\n}\n\n/** Non-Vue plugin core for runtime hosts that register the package directly.\n * MulmoClaude consumes only TOOL_DEFINITION + the execute functions in its\n * own routes, so it doesn't use this. */\nexport const pluginCore: ToolPluginCore<MulmoScriptData, MulmoScriptData, SaveMulmoScriptArgs> = {\n toolDefinition: TOOL_DEFINITION,\n execute: executeMulmoScript as unknown as ToolPluginCore<MulmoScriptData, MulmoScriptData, SaveMulmoScriptArgs>[\"execute\"],\n generatingMessage: \"Generating MulmoScript storyboard…\",\n isEnabled: () => true,\n};\n"],"mappings":";;;AAEA,IAAa,YAAY;AAMzB,IAAa,kBAAkC;CAC7C,MAAM;CACN,MAAM;CACN,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmFb,YAAY;EACV,MAAM;EACN,YAAY;GACV,QAAQ;IACN,MAAM;IACN,aACE;IACF,sBAAsB;GACxB;GACA,UAAU;IACR,MAAM;IACN,aACE;GACJ;GACA,UAAU;IACR,MAAM;IACN,aACE;GACJ;GACA,WAAW;IACT,MAAM;IACN,aAAa;GACf;GACA,MAAM;IACJ,MAAM;IACN,aAAa;IACb,sBAAsB;GACxB;GACA,mBAAmB;IACjB,MAAM;IACN,aACE;GACJ;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