@lalalic/markcut 3.2.45 → 3.2.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -390,3 +390,13 @@ then supply `--itt`, `--vtt` and `--agent` (or `MARKCUT_ITT_CLI`,
390
390
  `MARKCUT_VTT_CLI` and `MARKCUT_AGENT_CLI`). See `markcut vision --help`
391
391
  and `markcut --show-clis` for the supported placeholders. Markcut does not
392
392
  choose or manage a browser/model provider.
393
+
394
+ ### Independent preview and mobile delivery
395
+
396
+ `markcut.preview` and the standalone `markcut preview` CLI compile immutable
397
+ video revisions and expose the review player. The provider does **not** send
398
+ APNs notifications, manage Relay Invocations, or change Task state. When called
399
+ through Neo MCP, Neo's `markcut.preview` federation wrapper optionally binds
400
+ a Relay execution, watches compilation, persists the mobile review request,
401
+ and sends the iPhone notification. Standalone Markcut usage does not require
402
+ Neo Mobile or Agents Relay.
package/bin/markcut CHANGED
@@ -6,16 +6,25 @@ import { fileURLToPath } from "node:url";
6
6
  const __filename = fileURLToPath(import.meta.url);
7
7
  const __dirname = dirname(__filename);
8
8
  const root = resolve(__dirname, "..");
9
- if (process.argv[2] === "preview" && process.argv.includes("--delivery")) {
10
- const index=process.argv.indexOf("--delivery");
11
- if (process.argv[index+1] !== "event") {
12
- console.error("CLI review delivery supports only --delivery event; omit --delivery for the native preview.");
13
- process.exit(1);
9
+ if (process.argv[2] === "preview") {
10
+ const argv=process.argv.slice(2);
11
+ const optionIndex=argv.indexOf("--delivery");
12
+ const explicit=optionIndex>=0;
13
+ const delivery=explicit ? argv[optionIndex+1] : "text";
14
+ if(explicit && delivery!=="text" && delivery!=="event"){
15
+ console.error("Preview delivery must be text or event.");process.exit(1);
16
+ }
17
+ // Markdown previews compile independently; Neo owns optional mobile review delivery.
18
+ // JSON previews retain their existing local-only renderer.
19
+ const markdown=argv[1]?.toLowerCase().endsWith('.md');
20
+ if(explicit || markdown){
21
+ const eventArgs=explicit ? argv : ['preview',argv[1],'--delivery','text'];
22
+ const entry=resolve(root,'src','mcp','mobile-review-cli.mjs');
23
+ const deliveryResult=spawnSync(process.execPath,[entry,...eventArgs],{stdio:'inherit'});
24
+ if(deliveryResult.error)console.error(deliveryResult.error.message);
25
+ if(deliveryResult.status!==0)process.exit(deliveryResult.status??1);
26
+ if(explicit)process.exit(0);
14
27
  }
15
- const entry=resolve(root,"src","mcp","mobile-review-cli.mjs");
16
- const result=spawnSync(process.execPath,[entry,...process.argv.slice(2)],{stdio:"inherit"});
17
- if(result.error)console.error(result.error.message);
18
- process.exit(result.status??1);
19
28
  }
20
29
  if (process.argv[2] === "queue") {
21
30
  const result = spawnSync(process.execPath, [resolve(root, "src", "queue-worker.mjs"), ...process.argv.slice(3)], { stdio: "inherit" });
@@ -50,10 +50,10 @@ See [docs/markdown-strict-descriptive.md](docs/markdown-strict-descriptive.md) f
50
50
  ```bash
51
51
  markcut render <file.json|.md> [--output path]
52
52
  markcut preview <file.json|.md> [--edit] [--label] [--port 3001]
53
- markcut preview <file.md> --delivery event --event-template /absolute/event.json [--phone-url http://17.local:9223/mcp]
53
+ markcut preview <file.md> --delivery event --event-template /absolute/event.json
54
54
  ```
55
55
 
56
- For Codex/terminal event delivery, `preview --delivery event` uses the hosted MCP compiler and an **asynchronous** Neo Mobile human review, rather than the local interactive browser. The `--event-template` file must follow Relay's canonical `task.interactive_decision` Contract. See `skills/markcut/references/mobile-event-preview-cli.md`. Only `text` (native preview) and `event` (phone-review route) are supported.
56
+ For Codex/terminal event delivery, `preview --delivery event` uses the hosted MCP compiler and stores the review on Neo Master. Neo Master sends an APNs notification; Neo Mobile fetches the request when opened and publishes an **asynchronous** Event after human review. Every hosted MCP Preview also sends a phone notification, independently of the result-delivery mode. Text-only previews without a Relay Event Template are read-only on phone. The `--event-template` file must follow Relay's canonical `task.interactive_decision` Contract. See `skills/markcut/references/mobile-event-preview-cli.md`. Only `text` (native preview) and `event` (phone-review route) are supported.
57
57
 
58
58
  ## Project structure
59
59
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lalalic/markcut",
3
- "version": "3.2.45",
3
+ "version": "3.2.47",
4
4
  "description": "Markdown-to-video engine. Describe scenes in markdown, get a rendered video.",
5
5
  "bin": {
6
6
  "markcut": "bin/markcut"
@@ -16,7 +16,7 @@ Markcut turns a Markdown video definition into a compiled stream tree and a play
16
16
  | Quickly assess story structure | `markcut preview <file> --storyboard` (placeholder media, not a final-video quality check). |
17
17
  | Watch a native work-in-progress video | `markcut preview <file>`; test real visuals, sound, and seeking. |
18
18
  | Ask a person to review in ChatGPT | Call the available `markcut.preview({path})` tool; handle revision-specific feedback and approval. |
19
- | Ask for human review from Codex/terminal via iPhone | Use `markcut preview <video.md> --delivery event --event-template <relay-event.json>` on Neo Master. The CLI queues the video in Neo Mobile Review Inbox; the phone sends the review Event when the person submits. |
19
+ | Ask for human review from Codex/terminal via iPhone | Use `markcut preview <video.md> --delivery event --event-template <relay-event.json>` on Neo Master. Neo Master stores the Preview and APNs notifies iPhone; the phone publishes the Event when the person submits. |
20
20
  | Deliver a finished MP4 | `markcut render <file> --output <path>`; inspect the resulting video and sound. |
21
21
  | Visualize a route or trip | Use a Markdown `map` stream; load [route/map reference](docs/map-dynamic-camera.md). |
22
22
 
@@ -57,7 +57,7 @@ Asset paths are relative to the Markdown document. A `prompt` without `src` asks
57
57
  1. **Structure gate:** `npx @lalalic/markcut verify video.md`, then `npx @lalalic/markcut preview video.md --storyboard` when rapid scene review is useful. Storyboard placeholders do not verify generated media or final audio.
58
58
  2. **Playback gate:** `npx @lalalic/markcut preview video.md`. Play and seek representative scenes; check black tails, media loading, narration, BGM, subtitles, route movement, and timing. For browser failures, load [Preview Troubleshooting](references/preview-troubleshooting.md) on demand.
59
59
  3. **Human review gate:** Use Neo's `markcut.preview({path: "/absolute/path/video.md"})` when the user wants the hosted ChatGPT video player. This is **not** the CLI preview. The tool compiles/publishes a revision for playback; it does not rewrite the source. Comments with `decision: changes_requested` require editing that Markdown and calling `markcut.preview` again. `decision: approved` applies **only** to the identified revision/content hash; never apply an old approval to changed content. Follow [Review Contract](review.md) for actual video assessment.
60
- 4. **Codex / terminal human-review gate:** `npx @lalalic/markcut preview /absolute/video.md --delivery event --event-template /absolute/relay-event.json` on Neo Master. The Event Template must match Relay's canonical `task.interactive_decision` Contract (`type`, `source`, `data.interactive.{jobId,taskId,executionId,invocationId}` only, without review-result fields). The CLI reuses the MCP compiler, publishes immutable preview assets, discovers the nearby `neox` phone by Bonjour (`--phone-url http://<phone>.local:9223/mcp` or `NEOX_MCP_URL` if discovery is unavailable), then submits `review.request` to that phone. Exit receipt `review_requested` confirms only that **the iPhone inbox accepted the request**; human decisions arrive asynchronously on Events Bus. If the app is suspended/offline, CLI fails visibly; **there is no background delivery queue or automatic text fallback**. Do not claim approval or Relay worker continuation from the receipt. For retries with an uncertain phone acknowledgment, pass a stable `--request-id UUID`. See [Codex/mobile review CLI](references/mobile-event-preview-cli.md).
60
+ 4. **Codex / terminal human-review gate:** `npx @lalalic/markcut preview /absolute/video.md --delivery event --event-template /absolute/relay-event.json` on Neo Master. The Event Template must match Relay's canonical `task.interactive_decision` Contract (`type`, `source`, `data.interactive.{jobId,taskId,executionId,invocationId}` only, without review-result fields). The CLI reuses the MCP compiler, publishes immutable preview assets, persists the review request on Neo Master and dispatches an APNs notification through the existing Neo Mobile provider. Exit receipt `review_requested` confirms only that **the iPhone inbox accepted the request**; human decisions arrive asynchronously on Events Bus. The phone need not be online. APNs delivery is best-effort; Neo Mobile synchronizes persisted requests on foreground. There is no automatic text fallback. Do not claim approval or Relay worker continuation from the receipt. For retries with an uncertain phone acknowledgment, pass a stable `--request-id UUID`. See [Codex/mobile review CLI](references/mobile-event-preview-cli.md).
61
61
  5. **Delivery gate:** `npx @lalalic/markcut render video.md --output out/video.mp4`. Confirm the MP4 exists and examine playback, including the final audio and subtitles. A valid Markdown file, compile success, or hosted-player resource alone is not proof of a finished video.
62
62
 
63
63
  If the user asks only for a script or structure, stop at the requested stage. Do not trigger expensive generation or claim final video delivery without a requested rendered artifact. A project-specific agent owns its own editorial or approval decisions; Markcut supplies authoring, playback and revision capabilities.
@@ -26,8 +26,8 @@ markcut verify /absolute/video.md
26
26
  markcut preview /absolute/video.md --delivery event --event-template /tmp/review-event.json
27
27
  ```
28
28
 
29
- The CLI auto-discovers the `neox` `_mcp._tcp` service on the local network. Override if necessary with `--phone-url http://<trusted-phone>.local:9223/mcp` or `NEOX_MCP_URL`. Options: `--title`, `--group-id`, `--group-title`, `--request-id <UUID>`, `--timeout-ms`.
29
+ The CLI submits to Neo Master’s durable review inbox. The existing APNs provider notifies the registered iPhone; the phone syncs outstanding reviews when opened or when a push arrives. **There is no phone MCP dependency.** Options: `--title`, `--group-id`, `--group-title`, `--request-id <UUID>`, `--timeout-ms`.
30
30
 
31
- It starts the same detached Markcut MCP compile worker, waits for an immutable revision, and calls the phone's `review.request`. On phone acceptance it prints JSON, including `status: "review_requested"`, `requestId`, `contentHash`, and `revisionId`. It **does not wait for a human decision**. The phone must have the Neo app running and reachable; offline delivery is not supported by this CLI. A rejected/missing ACK exits nonzero. If reattempting after an uncertain ACK, supply the **same** request UUID to avoid duplicate phone requests. Phone users can inspect the compiled scenes and submit `approved` or `changes_requested`, which publishes `task.interactive_decision` through the existing authenticated Events MCP. The Event's `data.interactive` includes the exact reviewed hash, scene/timestamp comments, and idempotency key.
31
+ It starts the same detached Markcut MCP compile worker, waits for an immutable revision, and calls the phone's `review.request`. On phone acceptance it prints JSON, including `status: "review_requested"`, `requestId`, `contentHash`, and `revisionId`. It **does not wait for a human decision**. The phone can be offline or Neo can be suspended. The Master stores the review, with APNs as a best-effort wake-up hint. A rejected/missing ACK exits nonzero. If reattempting after an uncertain ACK, supply the **same** request UUID to avoid duplicate phone requests. Phone users can inspect the compiled scenes and submit `approved` or `changes_requested`, which publishes `task.interactive_decision` through the existing authenticated Events MCP. The Event's `data.interactive` includes the exact reviewed hash, scene/timestamp comments, and idempotency key.
32
32
 
33
33
  Relay's Event receiver and Graph decide whether to resume/revise the original Task. **A successful phone enqueue is not a human approval or a resumed Codex thread.** Do not mark the Task complete until a real human decision was correlated to the correct immutable revision and the downstream workflow actually completed. For a local browser-only preview, omit `--delivery event` and use normal `markcut preview`.
@@ -2,7 +2,7 @@
2
2
 
3
3
  **Library:** Markcut (`markcut.preview` and Neo Mobile review clients)
4
4
  **Created:** 2026-11-05
5
- **Status:** Implemented — Text/Event MCP and Neo Mobile, plus headless Codex CLI Event submission
5
+ **Status:** Implemented — uniform Master-to-iPhone Preview delivery; independent Text/Event Review Result delivery
6
6
  **Decision:** Use exactly two delivery modes, `text` and `event`. No callback registry, callback dispatcher, or Markcut-owned Relay workflow.
7
7
 
8
8
  ## Goal and boundaries
@@ -11,7 +11,8 @@ Let the same Markcut Preview player collect human review decisions, scene/timest
11
11
 
12
12
  - `text` (default): send the Review Result to the opening Agent conversation using the existing MCP App `ui/message` route.
13
13
  - `event`: the caller supplies an event template to the Markcut Provider. On Submit, the Preview UI fills the review-only fields and publishes it through the existing authorized Events MCP tool. The event consumer (Relay or another application) decides what to do next.
14
- - Neo Mobile supports the same two modes and the same Review Result. It uses its already authenticated Neo MCP connection for event delivery and its existing Agent-turn route for text delivery.
14
+ - **Preview request delivery is independent from result delivery.** Every successful `markcut.preview` hosted MCP invocation and every Codex CLI Event Preview stores an immutable request in Neo Master's durable APNs review inbox. Apple receives only a request ID as a notification. iPhone fetches the request via authenticated `review.push.pending` on foreground/notification tap. No inbound iPhone MCP is needed.
15
+ - Neo Mobile uses the caller-bound Event Template to fill standard `data.interactive` decision/feedback and publishes through the already authenticated Events MCP connection. It calls `review.push.complete` after transport acceptance. A default ChatGPT Text Preview without an owning thread is mirrored on iPhone **for viewing only**; its text Review Result continues in the ChatGPT UI. Do not synthesize unauthorized Relay event identity.
15
16
  - Do not add `callback`, a callback dispatcher, a Markcut review inbox, or direct Relay SQLite/Graph access inside Markcut.
16
17
 
17
18
  ## User stories and acceptance scenarios
@@ -38,10 +39,10 @@ Let the same Markcut Preview player collect human review decisions, scene/timest
38
39
 
39
40
  ### US-4: Trigger Event-mode Preview from Codex CLI (P1)
40
41
 
41
- 1. Given a current Relay execution and a caller-authored JSON Event Template, when Codex runs `markcut preview <video.md> --delivery event --event-template <file.json>`, the CLI must validate the template, compile/publish the same immutable Markcut Preview assets as the MCP provider, then enqueue a native `review.request` on Neo Mobile.
42
- 2. The CLI discovers Neo Mobile's current `_mcp._tcp` Bonjour service (or uses the explicit `--phone-url` / `NEOX_MCP_URL`), then requires a verifiable `{accepted:true,id:requestId}` phone receipt. It returns `review_requested` with the immutable revision hash. No ChatGPT iframe or callback registry is involved.
42
+ 1. Given a current Relay execution and a caller-authored JSON Event Template, when Codex runs `markcut preview <video.md> --delivery event --event-template <file.json>`, the CLI validates the template, compiles/publishes the same immutable Markcut Preview assets as the MCP provider, then persists a review request on Neo Master.
43
+ 2. The CLI and hosted MCP compiler use the same Neo Master push adapter; CLI requires `{stored:true,requestId}` from the durable queue. APNs `accepted` is optional and does not prove phone delivery. No direct phone URL, ChatGPT iframe, or callback registry is involved.
43
44
  3. The CLI exits after mobile receipt, rather than waiting for human action. User submission on iPhone publishes the canonical `task.interactive_decision` using the frozen template. **Event Bus transport acceptance is not Relay Graph completion or Codex continuation.**
44
- 4. If the phone is asleep, unavailable, or its app is not listening, report delivery failure explicitly. The current CLI is foreground-phone-only; offline durable delivery/APNs are a separate feature. Do not fall back to a chat message.
45
+ 4. The iPhone may be asleep or offline; the request remains on Master even if APNs rejects the notification. App foreground/notification taps synchronize the pending list. Failed durable storage is an explicit error, never a success receipt or text fallback.
45
46
  5. On retry after an uncertain ACK, reuse the same mobile `--request-id` (UUID) so the phone can deduplicate the request. Never repurpose an old revision's approval to a changed source.
46
47
 
47
48
  ## Public contract (proposed)
@@ -130,13 +131,16 @@ Relay's canonical Event Contract is at `agents-relay/skills/agents-relay/contrac
130
131
  - **FR-010**: Preserve review and approval scope per exact immutable revision. A new video revision requires fresh human approval; an Agent review cannot substitute for it.
131
132
  - **FR-011**: Make submission failures visible and retryable, with no success banner until an actual accepted receipt. Do not change delivery modes automatically on failure.
132
133
  - **FR-012**: Text is the existing Agent conversation path; Event is exclusively the canonical Relay `task.interactive_decision`. Old Markcut-specific event types are rejected. Existing Neo Mobile legacy storage fields do not define an additional public delivery mode.
133
- - **FR-013**: Provide a headless `markcut preview --delivery event` CLI for Codex and terminal agents, using the same publisher/compiler, and enqueue the request through the phone's `review.request` MCP. Validate the caller-owned template and require an actual phone receipt.
134
+ - **FR-013**: Provide a headless `markcut preview --delivery event` CLI for Codex and terminal agents, using the same publisher/compiler, and persist through Neo Master `review.push.notify`. Validate the caller-owned template and require a durable Master receipt.
135
+ - **FR-014**: Preview delivery must be performed once on successful compilation for every Markcut MCP/CLI Preview, independent from result Text/Event mode. APNs notification contains only the request UUID, not the Event Template; Master stores the full immutable request and supports authenticated pending/complete operations. An offline phone must be able to fetch outstanding reviews later.
136
+ - **FR-015**: Neo Mobile `review.push.complete` follows successful Events MCP result submission. Replay after completed human review must not restore an obsolete pending request.
134
137
 
135
138
  ## Ownership and downstream behavior
136
139
 
137
- - **Markcut Provider**: compiles/publishes immutable media, binds review delivery metadata, validates preview revision state, provides review template to clients.
140
+ - **Markcut Provider and CLI**: compile/publish immutable media and deliver every Preview request to Neo Master (APNs notifier), independently of any user result.
138
141
  - **Markcut Preview UI**: gathers comments and decision, fills review fields, dispatches either text or event, displays honest receipt/failure state.
139
- - **Neo Mobile**: displays the same review/revision, submits through its authenticated Neo MCP connection, retains offline retry state.
142
+ - **Neo Master/APNs**: persist pending Preview requests and notify Apple with the request ID. Provide authenticated `pending`/`complete` API; do not claim APNs acceptance as iPhone receipt.
143
+ - **Neo Mobile**: synchronizes stored requests into its local Inbox, shows the same immutable revision, submits result Event through authenticated Neo MCP, then acknowledges completion. Offline local feedback retry remains.
140
144
  - **Caller/Event consumer**: owns authorization, durable business processing, any Relay Event → original Producer Agent continuation, rereview, workflow transitions, and video delivery. `task.interactive_decision` is Relay human-interaction input, **not** Relay task-completion authority. No alternate or legacy review event type is accepted by the Preview provider.
141
145
 
142
146
  ## Edge cases and compatibility
@@ -167,6 +171,6 @@ Relay's canonical Event Contract is at `agents-relay/skills/agents-relay/contrac
167
171
 
168
172
  - Markcut's MCP tool supports both `text` and canonical Relay `event` delivery. The hosted Review UI and the Neo Mobile Event requester use the immutable `data.interactive` field names.
169
173
  - Codex/terminal users can now call `markcut preview <video.md> --delivery event --event-template <file.json>`; this route starts the same hosted-preview compiler and sends the accepted revision to Neo Mobile using its `review.request` MCP, without invoking a ChatGPT iframe.
170
- - The first Codex CLI → physical iPhone 17 → Events Bus test (isolated Job `999999993`) returned `review_requested` and accepted the Event Template. The iPhone Review Inbox displayed the request and the phone submitted `changes_requested` with precise revision metadata, producing one persisted `task.interactive_decision`. This proves the transport and mobile UI paths, **not** real Relay Graph job continuation.
171
- - The CLI requires the Neo app's MCP listener to be reachable; at present this means the app needs to be active. An offline phone queue or APNs-mediated durable review request delivery remains a separate feature.
174
+ - The earlier direct-phone Codex CLI → physical iPhone 17 → Events Bus test (isolated Job `999999993`) returned `review_requested` and accepted the Event Template. The iPhone Review Inbox displayed the request and the phone submitted `changes_requested` with precise revision metadata, producing one persisted `task.interactive_decision`. This proves the transport and mobile UI paths, **not** real Relay Graph job continuation.
175
+ - The CLI does not call the phone's MCP server. Master holds pending reviews durably; APNs notification is a best-effort alert. A reachable Master is required to persist the review, but the phone can be offline.
172
176
  - Events Bus assigns the transport `event_id`; the mobile review result carries a stable `data.interactive.idempotencyKey`, and Relay consumes the canonical Task event. Code-level Graph/worker continuation verification remains owned by Relay.
@@ -180,8 +180,11 @@ async function trackOperation(data){
180
180
  if(!response.ok)throw new Error('HTTP '+response.status);
181
181
  const progress=await response.json();
182
182
  if(generation!==operationGeneration)return;
183
- if(progress.state==='ready'&&progress.result){renderRevision({...progress.result,requestedPath:data.requestedPath||data.path,
184
- requestId:progress.result.requestId||data.requestId,review:progress.result.review||data.review,relay:data.relay});return;}
183
+ if(progress.state==='ready'&&progress.result){
184
+ await renderRevision({...progress.result,requestedPath:data.requestedPath||data.path,
185
+ requestId:progress.result.requestId||data.requestId,review:progress.result.review||data.review,relay:data.relay});
186
+ return;
187
+ }
185
188
  if(progress.state==='failed'){reviewReadonly(true,'Compilation failed: '+progress.error);return;}
186
189
  const elapsed=Math.round((Date.now()-(progress.startedAt||Date.now()))/1000);
187
190
  status.textContent='Compiling · '+(progress.stage||'working')+' · '+elapsed+'s';
@@ -15,8 +15,11 @@ try{
15
15
  const result=await ensureVideoPreview(path,{onProgress:update});
16
16
  update("publishing");
17
17
  publishPreviewRevision(requestedPath,{...result,requestedPath});
18
- writeOperation(id,{id,state:"ready",stage:"complete",startedAt,updatedAt:Date.now(),requestedPath,result:{...result,requestedPath,requestId:id,review,relay:JSON.parse(relayText)}});
18
+ // Markcut is a pure preview provider. The Neo MCP wrapper owns mobile delivery.
19
+ writeOperation(id,{id,state:"ready",stage:"complete",startedAt,updatedAt:Date.now(),requestedPath,
20
+ result:{...result,requestedPath,requestId:id,review,relay:JSON.parse(relayText)}});
21
+
19
22
  }catch(e){
20
- writeOperation(id,{id,state:"failed",stage:"failed",startedAt,updatedAt:Date.now(),requestedPath,error:e?.message||String(e)});
23
+ writeOperation(id,{id,state:"failed",stage:"failed",startedAt,updatedAt:Date.now(),requestedPath,review,relay:JSON.parse(relayText||"null"),error:e?.message||String(e)});
21
24
  process.exitCode=1;
22
25
  }
@@ -1,111 +1,35 @@
1
1
  #!/usr/bin/env node
2
- /** Codex/terminal human-review bridge. The phone publishes the caller-owned Event after Submit. */
3
- import {spawn} from 'node:child_process';
4
- import {randomUUID} from 'node:crypto';
2
+ /** Standalone terminal preview compiler. Notification is owned by the Neo MCP wrapper. */
5
3
  import {readFileSync} from 'node:fs';
6
- import {basename,join,resolve} from 'node:path';
4
+ import {join,resolve} from 'node:path';
7
5
  import {pathToFileURL} from 'node:url';
8
6
  import {normalizeReviewConfig} from './review-delivery.mjs';
9
7
 
10
8
  const delay = ms => new Promise(done => setTimeout(done,ms));
11
- const UUID = /^[a-f0-9-]{36}$/i;
12
9
 
13
10
  export function parseEventPreviewOptions(argv) {
14
- if (argv[0] !== 'preview' || !argv[1] || argv[1].startsWith('--')) throw new Error('Usage: markcut preview <file.md> --delivery event --event-template <file.json> [--phone-url <url>]');
15
- const allowed=new Set(['--delivery','--event-template','--phone-url','--title','--group-id','--group-title','--request-id','--timeout-ms']);
11
+ if (argv[0] !== 'preview' || !argv[1] || argv[1].startsWith('--')) throw new Error('Usage: markcut preview <file.md> --delivery event --event-template <file.json>');
12
+ const allowed=new Set(['--delivery','--event-template','--timeout-ms']);
16
13
  const options={file:resolve(argv[1])};
17
14
  for(let i=2;i<argv.length;i+=2){
18
15
  const flag=argv[i],value=argv[i+1];
19
16
  if(!allowed.has(flag) || !value || value.startsWith('--'))throw new Error('Missing or unsupported preview event flag: '+flag);
20
- const key={'--delivery':'delivery','--event-template':'eventTemplatePath','--phone-url':'phoneUrl','--title':'title','--group-id':'groupId','--group-title':'groupTitle','--request-id':'requestId','--timeout-ms':'timeoutMs'}[flag];
17
+ const key={'--delivery':'delivery','--event-template':'eventTemplatePath','--timeout-ms':'timeoutMs'}[flag];
21
18
  if(Object.hasOwn(options,key))throw new Error('Duplicate flag: '+flag);
22
19
  options[key]=value;
23
20
  }
24
- if(options.delivery!=='event' || !options.eventTemplatePath)throw new Error('Event delivery and --event-template file are required');
25
- if(options.requestId && !UUID.test(options.requestId))throw new Error('--request-id must be a UUID');
21
+ if(!['text','event'].includes(options.delivery) || (options.delivery==='event')!==Boolean(options.eventTemplatePath))
22
+ throw new Error('Event delivery requires --event-template; Text delivery must omit it');
26
23
  const limit=options.timeoutMs===undefined ? 300000 : Number(options.timeoutMs);
27
24
  if(!Number.isSafeInteger(limit) || limit<1000 || limit>1800000)throw new Error('--timeout-ms must be 1000..1800000');
28
25
  options.timeoutMs=limit;
29
26
  return options;
30
27
  }
31
28
 
32
- export function phoneUrlFromDnsSdText(text){
33
- const m=text.match(/can be reached at ([a-z0-9._-]+):([0-9]{1,5})\b/i);
34
- if(!m)return null;
35
- const host=m[1].replace(/\.+$/,'');
36
- if(!host.endsWith('.local') || Number(m[2])<1 || Number(m[2])>65535)return null;
37
- return `http://${host}:${m[2]}/mcp`;
38
- }
39
-
40
- export async function discoverPhoneUrl(timeoutMs=4000){
41
- return await new Promise((resolveDiscovery,rejectDiscovery)=>{
42
- const proc=spawn('dns-sd',['-L','neox','_mcp._tcp','local'],{stdio:['ignore','pipe','pipe']});
43
- let output='',settled=false;
44
- const done=(error,value)=>{
45
- if(settled)return;settled=true;clearTimeout(timeout);proc.kill('SIGTERM');
46
- if(error)rejectDiscovery(error);else resolveDiscovery(value);
47
- };
48
- const timeout=setTimeout(()=>done(new Error('Neo Mobile not discoverable; launch Neo on iPhone or provide --phone-url')),timeoutMs);
49
- proc.stdout.on('data',c=>{output+=String(c);if(output.length>8192)output=output.slice(-8192);const url=phoneUrlFromDnsSdText(output);if(url)done(null,url);});
50
- proc.stderr.on('data',c=>{output+=String(c);});
51
- proc.on('error',e=>done(e));
52
- proc.on('exit',()=>done(new Error('Neo Mobile Bonjour discovery stopped before resolution')));
53
- });
54
- }
55
-
56
- export function validatePhoneUrl(input){
57
- const u=new URL(input);
58
- if(u.username || u.password || u.search || u.hash || u.pathname!=='/mcp')throw new Error('Phone MCP URL must have only /mcp path');
59
- const h=u.hostname.toLowerCase();
60
- const local=h==='localhost'||h.endsWith('.local')||h==='127.0.0.1'||h.startsWith('10.')||h.startsWith('192.168.')||
61
- /^172\.(1[6-9]|2[0-9]|3[01])\./.test(h);
62
- if((u.protocol!=='http:' || !local) && u.protocol!=='https:')throw new Error('Phone MCP URL must be local HTTP or HTTPS');
63
- return u.toString();
64
- }
65
-
66
- export function buildMobileReviewRequest(operation,template,options={}){
67
- const config=normalizeReviewConfig({delivery:'event',eventTemplate:template});
68
- const result=operation.result;
69
- if(operation.state!=='ready' || !result || !/^[a-f0-9]{64}$/.test(result.contentHash||'') ||
70
- !result.revisionId || !result.id)throw new Error('Compiled preview is not ready');
71
- const details=config.eventTemplate.data.interactive;
72
- const id=options.requestId??operation.id;
73
- if(!UUID.test(id))throw new Error('Invalid review request identity');
74
- const title=options.title?.trim() || basename(options.file??result.requestedPath??'Preview','.md');
75
- return {
76
- id,contentHash:result.contentHash,revisionId:result.revisionId,previewId:result.id,
77
- title,groupId:options.groupId ?? `job/${details.jobId}/task/${details.taskId}`,
78
- groupTitle:options.groupTitle ?? title,jobId:details.jobId,
79
- delivery:'event',eventTemplate:config.eventTemplate,
80
- };
81
- }
82
-
83
- export async function sendMobileReviewRequest(phoneUrl,request,{fetchImpl=fetch}={}){
84
- const url=validatePhoneUrl(phoneUrl);
85
- const payload={jsonrpc:'2.0',id:1,method:'tools/call',params:{name:'review.request',arguments:request}};
86
- let lastError;
87
- for(let attempt=0;attempt<2;attempt++){
88
- try{
89
- const response=await fetchImpl(url,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload),signal:AbortSignal.timeout(9000)});
90
- if(!response.ok)throw new Error(`Phone MCP returned HTTP ${response.status}`);
91
- const body=await response.json();
92
- if(body.error || body.result?.isError)throw new Error('Phone MCP rejected review.request');
93
- const text=body.result?.content?.find(item=>item.type==='text')?.text;
94
- let receipt;
95
- try{receipt=JSON.parse(text);}catch{throw new Error('Phone MCP returned no structured review receipt');}
96
- if(receipt.accepted!==true || receipt.id!==request.id)throw new Error('Phone rejected the review request: '+String(text).slice(0,130));
97
- return receipt;
98
- }catch(e){lastError=e;if(attempt===0)await delay(400);}
99
- }
100
- throw lastError;
101
- }
102
-
103
29
  export async function runMobilePreview(argv){
104
30
  const opts=parseEventPreviewOptions(argv);
105
- const template=JSON.parse(readFileSync(resolve(opts.eventTemplatePath),'utf8'));
106
- const config=normalizeReviewConfig({delivery:'event',eventTemplate:template});
107
- // Check phone reachability before starting potentially expensive compilation.
108
- const phoneUrl=validatePhoneUrl(opts.phoneUrl || process.env.NEOX_MCP_URL || await discoverPhoneUrl());
31
+ const config=opts.delivery==='event' ? normalizeReviewConfig({delivery:'event',
32
+ eventTemplate:JSON.parse(readFileSync(resolve(opts.eventTemplatePath),'utf8'))}) : {delivery:'text'};
109
33
  const [{startCompileOperation},{EXPORT_ROOT}]=await Promise.all([
110
34
  import('./compile-operation.mjs'),import('./remote-assets.mjs'),
111
35
  ]);
@@ -120,17 +44,15 @@ export async function runMobilePreview(argv){
120
44
  await delay(300);
121
45
  }
122
46
  if(state?.state!=='ready')throw new Error('Preview compile timed out; operation '+operation.operationId);
123
- const request=buildMobileReviewRequest(state,config.eventTemplate,{...opts,file:opts.file});
124
- const receipt=await sendMobileReviewRequest(phoneUrl,request);
125
- return {accepted:receipt.accepted,duplicate:receipt.duplicate===true,
126
- status:'review_requested',operationId:operation.operationId,requestId:request.id,
127
- contentHash:request.contentHash,revisionId:request.revisionId,jobId:request.jobId,
128
- delivery:'event',phone:'Neo Mobile'};
47
+ return {status:'preview_ready',operationId:operation.operationId,requestId:state.result.requestId,
48
+ contentHash:state.result.contentHash,revisionId:state.result.revisionId,
49
+ ...(config.delivery==='event' ? {jobId:config.eventTemplate.data.interactive.jobId} : {}),
50
+ delivery:config.delivery,notification:'not_requested'};
129
51
  }
130
52
 
131
53
  if(process.argv[1] && import.meta.url===pathToFileURL(resolve(process.argv[1])).href){
132
54
  runMobilePreview(process.argv.slice(2)).then(result=>console.log(JSON.stringify(result))).catch(error=>{
133
- console.error('Markcut mobile event preview failed: '+(error?.message||error));
55
+ console.error('Markcut preview compilation failed: '+(error?.message||error));
134
56
  process.exitCode=1;
135
57
  });
136
58
  }
@@ -9,7 +9,7 @@ import { externalizePreviewMedia, publicOrigin, resolveMountedFile, resolvePrevi
9
9
  import {fingerprintInputs} from "./source-fingerprint.mjs";
10
10
 
11
11
  export const TOOL_NAME = "markcut.preview";
12
- export const RESOURCE_URI = "ui://markcut/video-preview-v43.html";
12
+ export const RESOURCE_URI = "ui://markcut/video-preview-v44.html";
13
13
  const PREVIEW_VERSION = RESOURCE_URI.match(/video-preview-(v\d+)/)?.[1] ?? "unknown";
14
14
  // Legacy entrypoints remain registered, but serve the current implementation.
15
15
  export const LEGACY_RESOURCE_URIS = [
@@ -51,6 +51,7 @@ export const LEGACY_RESOURCE_URIS = [
51
51
  "ui://markcut/video-preview-v40.html",
52
52
  "ui://markcut/video-preview-v41.html",
53
53
  "ui://markcut/video-preview-v42.html",
54
+ "ui://markcut/video-preview-v43.html",
54
55
  "ui://markcut/video-preview-v39.html",
55
56
  "ui://markcut/video-preview-v38.html",
56
57
  ];
@@ -66,7 +66,7 @@ Commands:
66
66
  preview <file.json|.md> Open player with live preview
67
67
  --delivery event Headless human review via Neo Mobile (requires .md)
68
68
  --event-template <file.json> Relay task.interactive_decision envelope from current Task
69
- --phone-url <url> Neo Mobile HTTP MCP (optional; Bonjour autodiscovery)
69
+ (No phone URL) Neo Master stores and notifies through APNs
70
70
  --title <text> Optional title displayed in Review Inbox
71
71
  --group-id <id> Stable video group; later revisions supersede earlier ones
72
72
  --request-id <uuid> Stable mobile request UUID for retry after uncertain ACK
@@ -1,62 +1,12 @@
1
- import {describe,it,expect,vi} from 'vitest';
2
- import {randomUUID} from 'node:crypto';
3
- import {
4
- parseEventPreviewOptions,phoneUrlFromDnsSdText,validatePhoneUrl,
5
- buildMobileReviewRequest,sendMobileReviewRequest,
6
- } from '../src/mcp/mobile-review-cli.mjs';
7
- const hash='a'.repeat(64);
8
- const eventTemplate={type:'task.interactive_decision',source:'job/j1/task/producer/execution/e1',data:{
9
- interactive:{jobId:'j1',taskId:'producer',executionId:'e1',invocationId:'review-req-1'},
10
- }};
11
- const id=randomUUID();
12
- const operation={id,state:'ready',result:{id:hash,contentHash:hash,revisionId:hash,requestedPath:'/tmp/preview.md'}};
1
+ import {describe,it,expect} from 'vitest';
2
+ import {parseEventPreviewOptions} from '../src/mcp/mobile-review-cli.mjs';
13
3
 
14
- describe('Codex CLI event preview to Neo Mobile',()=>{
15
- it('requires an explicit event template and rejects incomplete or unexpected flags',()=>{
16
- expect(parseEventPreviewOptions(['preview','video.md','--delivery','event','--event-template','template.json']).delivery).toBe('event');
17
- expect(()=>parseEventPreviewOptions(['preview','video.md','--delivery','event'])).toThrow(/event-template/);
18
- expect(()=>parseEventPreviewOptions(['preview','video.md','--delivery','callback','--event-template','template.json'])).toThrow();
19
- expect(()=>parseEventPreviewOptions(['preview','video.md','--delivery','event','--event-template','t.json','--other','x'])).toThrow();
20
- expect(()=>parseEventPreviewOptions(['preview','video.md','--delivery','event','--event-template','t.json','--request-id','bad'])).toThrow();
21
- });
22
- it('finds Neo Mobile from Bonjour but only permits trusted local HTTP or HTTPS MCP addresses',()=>{
23
- const dns='18:45:31 neox._mcp._tcp.local. can be reached at 17.local.:9223 (interface 11)';
24
- expect(phoneUrlFromDnsSdText(dns)).toBe('http://17.local:9223/mcp');
25
- expect(phoneUrlFromDnsSdText('unrelated service')).toBeNull();
26
- expect(validatePhoneUrl('http://10.0.0.241:9223/mcp')).toBe('http://10.0.0.241:9223/mcp');
27
- expect(()=>validatePhoneUrl('http://example.org:9223/mcp')).toThrow();
28
- expect(()=>validatePhoneUrl('http://17.local:9223/mcp?target=evil')).toThrow();
29
- });
30
- it('constructs the immutable revision request with the caller-owned template',()=>{
31
- const request=buildMobileReviewRequest(operation,eventTemplate,{requestId:id,file:'/tmp/preview.md'});
32
- expect(request).toMatchObject({id,contentHash:hash,revisionId:hash,previewId:hash,
33
- delivery:'event',groupId:'job/j1/task/producer',jobId:'j1',title:'preview',
34
- eventTemplate:{type:'task.interactive_decision',source:eventTemplate.source,data:{interactive:{invocationId:'review-req-1'}}}});
35
- expect(request.eventTemplate.data.interactive).not.toHaveProperty('decision');
36
- expect(()=>buildMobileReviewRequest(operation,{...eventTemplate,type:'markcut.review.submitted'},{})).toThrow();
37
- expect(()=>buildMobileReviewRequest({...operation,result:{...operation.result,contentHash:'old'}},eventTemplate,{})).toThrow();
38
- });
39
- it('sends review.request to the phone and requires its accepted matching receipt',async()=>{
40
- const request=buildMobileReviewRequest(operation,eventTemplate,{requestId:id});
41
- const fakeFetch=vi.fn(async (_url,opts)=>{
42
- const sent=JSON.parse(opts.body);
43
- expect(sent).toMatchObject({method:'tools/call',params:{name:'review.request',arguments:request}});
44
- return {ok:true,json:async()=>({result:{content:[{type:'text',text:JSON.stringify({accepted:true,duplicate:false,id})}]}})};
45
- });
46
- expect(await sendMobileReviewRequest('http://17.local:9223/mcp',request,{fetchImpl:fakeFetch})).toEqual({accepted:true,duplicate:false,id});
47
- expect(fakeFetch).toHaveBeenCalledTimes(1);
48
- });
49
- it('reuses the same request identity on uncertain transport retries and refuses false success',async()=>{
50
- const request=buildMobileReviewRequest(operation,eventTemplate,{requestId:id});
51
- const stable=[];
52
- const fakeFetch=vi.fn(async(_url,opts)=>{
53
- stable.push(JSON.parse(opts.body).params.arguments.id);
54
- if(stable.length===1)throw new Error('lost ACK');
55
- return {ok:true,json:async()=>({result:{content:[{type:'text',text:JSON.stringify({accepted:true,duplicate:true,id})}]}})};
56
- });
57
- expect((await sendMobileReviewRequest('http://17.local:9223/mcp',request,{fetchImpl:fakeFetch})).duplicate).toBe(true);
58
- expect(stable).toEqual([id,id]);
59
- const reject=vi.fn(async()=>({ok:true,json:async()=>({result:{content:[{type:'text',text:'Error: invalid review request'}]}})}));
60
- await expect(sendMobileReviewRequest('http://17.local:9223/mcp',request,{fetchImpl:reject})).rejects.toThrow(/no structured review receipt/);
61
- });
4
+ describe('Standalone Markcut CLI preview (notification belongs to Neo)',()=>{
5
+ it('accepts externally supplied event templates without a phone or APNs URL',()=>{
6
+ expect(parseEventPreviewOptions(['preview','video.md','--delivery','event','--event-template','template.json']).delivery).toBe('event');
7
+ expect(()=>parseEventPreviewOptions(['preview','video.md','--delivery','event'])).toThrow();
8
+ expect(()=>parseEventPreviewOptions(['preview','video.md','--delivery','event','--event-template','a','--phone-url','http://phone'])).toThrow();
9
+ expect(parseEventPreviewOptions(['preview','video.md','--delivery','text']).delivery).toBe('text');
10
+ expect(()=>parseEventPreviewOptions(['preview','video.md','--delivery','text','--event-template','a'])).toThrow();
11
+ });
62
12
  });