@vosjs/cli 0.78.0 → 0.79.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +87 -12
  2. package/dist/{assetManifest-S6H5F2VE.js → assetManifest-U25FJER6.js} +3 -3
  3. package/dist/{chunk-ZSJEISKL.js → chunk-4ZUHEXUX.js} +9 -4
  4. package/dist/chunk-4ZUHEXUX.js.map +1 -0
  5. package/dist/{chunk-B4U4URE3.js → chunk-J3KHIZCH.js} +466 -412
  6. package/dist/chunk-J3KHIZCH.js.map +1 -0
  7. package/dist/{chunk-RUDDBHQ7.js → chunk-OWYOJB7K.js} +5 -1
  8. package/dist/chunk-OWYOJB7K.js.map +1 -0
  9. package/dist/{chunk-INRUYQ6J.js → chunk-TWAP4BKR.js} +2299 -1412
  10. package/dist/chunk-TWAP4BKR.js.map +1 -0
  11. package/dist/{chunk-JYCW4EOA.js → chunk-Z6TLHRFQ.js} +2 -2
  12. package/dist/cli.js +9 -8
  13. package/dist/cli.js.map +1 -1
  14. package/dist/index.d.ts +13 -4
  15. package/dist/index.js +5 -5
  16. package/dist/manifest-VTOIEUHJ.js +8 -0
  17. package/dist/{run-TIFM3ZHI.js → run-UKWKAGDK.js} +5 -5
  18. package/dist/{shotList-SCA234OS.js → shotList-EE3S5LVF.js} +34 -7
  19. package/dist/shotList-EE3S5LVF.js.map +1 -0
  20. package/package.json +3 -3
  21. package/schema/actions.schema.json +298 -13
  22. package/schema/doc.schema.json +37 -1
  23. package/skills/VERSION +1 -1
  24. package/skills/launch-kit/SKILL.md +6 -1
  25. package/skills/product-video/SKILL.md +7 -0
  26. package/skills/vos-authoring/SKILL.md +8 -1
  27. package/skills/vos-create/SKILL.md +5 -0
  28. package/skills/vos-cut/SKILL.md +8 -0
  29. package/skills/vos-footage/SKILL.md +4 -0
  30. package/skills/vos-migrate/SKILL.md +4 -0
  31. package/dist/chunk-B4U4URE3.js.map +0 -1
  32. package/dist/chunk-INRUYQ6J.js.map +0 -1
  33. package/dist/chunk-RUDDBHQ7.js.map +0 -1
  34. package/dist/chunk-ZSJEISKL.js.map +0 -1
  35. package/dist/manifest-6DJSPKVH.js +0 -8
  36. package/dist/shotList-SCA234OS.js.map +0 -1
  37. /package/dist/{assetManifest-S6H5F2VE.js.map → assetManifest-U25FJER6.js.map} +0 -0
  38. /package/dist/{chunk-JYCW4EOA.js.map → chunk-Z6TLHRFQ.js.map} +0 -0
  39. /package/dist/{manifest-6DJSPKVH.js.map → manifest-VTOIEUHJ.js.map} +0 -0
  40. /package/dist/{run-TIFM3ZHI.js.map → run-UKWKAGDK.js.map} +0 -0
package/README.md CHANGED
@@ -124,7 +124,7 @@ vos score film --track fresh-focus --at m1:share --dry-run # a catalog slug, a
124
124
  vos score film --track ./theme.wav --at 12 --gain 0.4 # a local file (copied into film/music/), output seconds
125
125
  ```
126
126
 
127
- The track is decoded (mediabunny in Node for PCM; a compressed track in the headless browser) and measured as a short-term loudness curve, a 1 s window every 0.5 s: K-weighted LUFS (BS.1770) for mono and stereo audio, RMS dBFS otherwise, and the output says which. Its strongest swell is the largest sustained rise to a peak (at least 3 dB, holding within 3 dB of the peak for 1.5 s), measured once the track has established its level: a rise starts no earlier than 5 s after the track first comes within 12 dB of its median level, and from no lower than that, so a fade in from silence at the top is the track starting, never its swell; it lands where it ARRIVES, within 1 dB of the peak. `--at` is where it should land: a step (its id, `step:<index>` by its index, `<media>:<step>` for another media's), resolved through the cut exactly as an anchored caption is, or output seconds. The clip's `in` is set so the swell plays there, `start` is 0, `out` is `in` plus the film's length, with `--gain` (0.5), `--fade-out` (1.5 s) and, whenever the track is entered mid-song (`in` > 0), a 0.8 s fade-in (`--fade-in` sets it, 0 for none); when the track cannot both hold the swell there and cover the film, the clamp is said in words. Without `--at` the track starts at its first moment above its median level. A second run replaces the clip; `--dry-run` writes nothing and prints the swell, the offset and the curve as one line of blocks (`--json` carries every point).
127
+ The track is decoded (mediabunny in Node for PCM; a compressed track in the headless browser) and measured as a short-term loudness curve, a 1 s window every 0.5 s: K-weighted LUFS (BS.1770) for mono and stereo audio, RMS dBFS otherwise, and the output says which. Its strongest swell is the largest sustained rise to a peak (at least 3 dB, holding within 3 dB of the peak for 1.5 s), measured once the track has established its level: a rise starts no earlier than 5 s after the track first comes within 12 dB of its median level, and from no lower than that, so a fade in from silence at the top is the track starting, never its swell; it lands where it ARRIVES, within 1 dB of the peak. `--at` is where it should land: a step (its id, `step:<index>` by its index, `<media>:<step>` for another media's), resolved through the cut exactly as an anchored caption is, or output seconds. The clip's `in` is set so the swell plays there, `start` is 0, `out` is `in` plus the film's length, with `--gain` (0.5), `--fade-out` (1.5 s) and, whenever the track is entered mid-song (`in` > 0), a 0.8 s fade-in (`--fade-in` sets it, 0 for none); when the track cannot both hold the swell there and cover the film, the clamp is said in words. Without `--at` the track starts at its first moment above its median level. A second run replaces the clip; `--dry-run` writes nothing and prints the swell, the offset and the curve as one line of blocks (`--json` carries every point). The clip carries what the track measures (`loudness`, below) and a loudness target, `normalize: -16` (`--normalize <lufs>` sets another, `--normalize off` none), with `--gain` a trim on the target: a catalog track, mastered at about -16 LUFS, plays at the default 0.5 as it did before it had a target, and a file of your own lands at the same level.
128
128
 
129
129
  **No browser here?** A cloud agent, a CI runner or a chat host records on vos.so instead: the same script goes up, the fleet records, plans and lands the take as a private vos with its doc and its digest, and the take comes home into `--out` with its media, the directory every other verb reads.
130
130
 
@@ -136,7 +136,7 @@ What travels: the script, the viewport, every `--header` value (a preview's bypa
136
136
 
137
137
  | Verb | Flags |
138
138
  | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
139
- | `record` | `--actions <file>` (or positional) `--url` `--out take` `--strict` `--dry-run` `--allow-wall` `--keep-frames` `--storage-state <file>` or `--session <name>` `--header name=value`... `--confirm <id>`... `--browser-arg=<switch>`... `--max-duration <s>` `--background <slug\|url\|none>` `--hosted` (record on vos.so; with `--title` `--folder <id>`) |
139
+ | `record` | `--actions <file>` (or positional) `--url` `--out take` `--strict` `--dry-run` `--allow-wall` `--keep-frames` `--storage-state <file>` or `--session <name>` `--header name=value`... `--confirm <id>`... `--browser-arg=<switch>`... `--max-duration <s>` `--ready dom\|networkidle` `--background <slug\|url\|none>` `--hosted` (record on vos.so; with `--title` `--folder <id>`) |
140
140
  | `create` | The `record` flags plus the render flags (`--width` `--height` `--fps` `--format` `--parallel` `--draft` `--frame` `--set`), no `--range`. With `--strict` an incomplete recording exits 2 before anything is rendered |
141
141
  | `plan` | `--fresh` (discard the current plan) `--reuse` `--from <doc.json>` (defaults to `<take>/doc.prev.json`) `--style <doc.json\|take\|vosId>` `--with <doc.json\|take\|vosId>[@end\|@start\|@step:<id>\|@<seconds>]` (a template, repeatable) `--background` `--motion` (re-propose the motion) `--headline` `--kicker` `--launch` `--brand` `--music` `--entrance` `--transitions slide\|fade\|scale\|none` `--end-card on\|none\|<ref>` `--captions` (bare: the step captions, anchored; `none`: no beat captions) `--clicks` `--release` |
142
142
  | `digest` | `--out <take>/digest` `--full 960` `--crop 640` (image long edges, the token budget) `--no-frames` `--transcript <file>` (Whisper-shaped segments merged as `said`) `--style <ref>` (report a reference document's style fields) |
@@ -144,21 +144,24 @@ What travels: the script, the viewport, every `--header` value (a preview's bypa
144
144
  | `render` | `--width` `--height` `--fps` `--format webm\|mp4` `--parallel N` (1..16 sessions) `--range a..b` (output seconds; keeps its audio) `--draft` `--frame <kind>` `--background` `--set …`; `out` defaults to `<take>/out.<format>` |
145
145
  | `ingest` | `<video>` (positional) `--cursor <trace.zip\|steps.jsonl\|cursor.csv>` `--out take` `--offset <ms>` `--viewport WxH` `--background <slug\|url\|none>`; a `.zip` is a Playwright trace, `.jsonl`/`.json` are records (or a Playwright `.trace` by its lines), `.csv` is `t,x,y,type` |
146
146
  | `join` | `<take> <take\|file.mp4>...` (positional, in order) `--out <dir>` `--force` (replace a take directory) `--captions` (land the step captions, anchored) `--mute <file>`... (leave a file's own sound out) |
147
- | `score` | `<take>` `--track <slug\|file>` `--at <step id\|step:<index>\|media:step\|seconds>` `--gain 0..1` (0.5) `--fade-in <s>` (0.8 when entered mid-song) `--fade-out <s>` (1.5) `--dry-run` |
147
+ | `score` | `<take>` `--track <slug\|file>` `--at <step id\|step:<index>\|media:step\|seconds>` `--gain 0..1` (0.5) `--normalize <lufs\|off>` (-16) `--fade-in <s>` (0.8 when entered mid-song) `--fade-out <s>` (1.5) `--dry-run` |
148
+ | `audio` | `measure <take>` (write every audio clip's `loudness`, the fact a `normalize` target plays it to) |
148
149
  | `open` | `--studio <url>` (the studio; `https://vos.so` by default, `VOS_ORIGIN` moves it) `--print` (print the URL, do not launch a browser) |
149
150
 
151
+ **When the take starts.** Step 1 runs once the first page is ready, and by default that means it has stopped changing: after `load`, the page must make no DOM change for 800 ms, at most 8 s (`ready: "dom"`). Network idle is the opt-in (`"ready": "networkidle"` in `actions.json`, or `--ready networkidle`), at most 45 s, because a page that holds a socket open or keeps an analytics beacon going never goes network-idle and every take of it would start after the whole timeout. The same mode opens a `setup` step's `goto`, the page after the setup, and an `await`'s reload. The done event says how the first load settled, `ready: { mode, ms, capped }`; `capped` is a page still changing at the cap (an animation, a ticker), recorded anyway, and `navTimeout: true` now means only that network idle was asked for and never came.
152
+
150
153
  **The wall check.** Once the first navigation settles, and before a frame is captured, `record`, `create` and `--dry-run` ask whether the recorder landed where it was sent. A take that met a sign-in instead is refused with exit 4 and a sentence (`asked for /dashboard, landed on /login: no session for app.acme.com`): the asked URL answered 401 or 403, the recorder was sent to an identity provider or a sign-in path, or the page is a sign-in form (one password field, or a one-time-code field) rendered in place. A redirect somewhere else with no sign-in in sight, which is what a site that shows strangers a public page looks like, is refused under `--strict` and in a rehearsal, and said as a warning otherwise. The check runs before a re-record clears anything, so a session that expired since the last take never costs the footage it failed to replace. The way past a wall is a session: `--storage-state <file>`, minted from the test auth the project already has wherever that exists. `--allow-wall` records the page anyway (a video OF a sign-in page is a legitimate take), and the take's `meta.wall` and its digest then say so.
151
154
 
152
155
  **`vos session`: takeover mode, local.** A production app behind an emailed code, SSO, a passkey or a CAPTCHA has no form to script and no test auth to mint from, so a person signs in once and the recorder reuses that session:
153
156
 
154
157
  ```bash
155
- vos session open https://app.acme.com --name acme # a plain Chrome window opens; sign in, quit it (⌘Q on a Mac, closing the window is not quitting)
158
+ vos session open https://app.acme.com --name acme # a plain Chrome window opens; sign in, set the account up, close the window (or press Enter)
156
159
  vos session check acme --url https://app.acme.com/dashboard # does it still open the page? exit 0, or 4
157
160
  vos record --actions actions.json --out take --session acme --strict
158
161
  vos session list · vos session rm acme
159
162
  ```
160
163
 
161
- `open` runs the SYSTEM Chrome as an ordinary child process on a profile under `~/.config/vos/sessions/<name>`, with no automation switch and no debugging pipe, so a sign-in that refuses automated browsers (Google's) goes through, and it waits for the window to EXIT, because Chrome writes its cookie store when it quits and not before. It then prints what the session holds as counts and dates (`holds cookies for app.acme.com (7), accounts.google.com (12); newest expires in 29 days`), never a value, and `--json` does not either. `check` reads the session through the same Chrome and, with `--url`, asks the wall check whether the page still opens signed in: a session that expired says so in words with the command to sign in again, and exits 4. `record --session` records in that profile; it is one door and `--storage-state` is the other, never both.
164
+ `open` runs the SYSTEM Chrome as an ordinary child process on a profile under `~/.config/vos/sessions/<name>`, with no automation switch and no debugging pipe, so a sign-in that refuses automated browsers (Google's) goes through, and it waits for the person to finish, however they finish: the last window closed, Chrome quit (⌘Q), or Enter in the terminal. It never finishes on a sign-in it sees, because the person often is not done (a second factor or a single sign-on hop lands later, and the workspace picked and the demo data made in that window are what every take on the session finds). Chrome writes its cookie store when it quits, so a closed window or Enter quits that Chrome, by its process id (never by name: the everyday Chrome is the same app), and only then is the session read. The window is watched from outside the browser: a debugging endpoint, even one that only lists tabs, makes Chrome tell every page `navigator.webdriver === true`, which is what a sign-in that refuses automated browsers reads. So it counts the window's page renderers in the process table (they all exit when the last window closes, while a minimized window or one on another desktop keeps its own), and reads the profile's cookie store for counts only, saying `app.acme.com set 12 cookies (analytics not counted)` when the host's own cookies change, leaving out measurement cookies a stranger's visit sets too (`_ga*`, `_gid`, `ph_*`, `g_state`, `ajs_*`, `_fbp`, `_hj*`, `__stripe_*` and the like); Chrome commits that store about every thirty seconds, so the line lags a little, and it needs Node 22.5 or later, staying quiet before. A cookie count is never called a sign-in. Once the session is saved, `open` checks it the way `check --url` does: the URL opens headless on the saved profile AND for a stranger (a fresh, empty profile), through the wall check. Walled on the profile is `NOT signed in: https://app.acme.com/projects sends a stranger to /login …` with the command to try again (exit 4); open on the profile and walled for the stranger is `signed in: https://app.acme.com/projects opens as you`; open for both is `can't tell: … opens the same for a stranger`, a warning (exit 4 under `--strict`), because a public page proves nothing; and a sign-in page (`/login`, `/signin`, an identity provider) is not opened at all, since a stranger reaches it too. Name a page only a signed-in person sees. Only a session that passed is offered for recording. It also prints what the session holds as counts and dates (`holds cookies for app.acme.com (7), accounts.google.com (12); newest expires in 29 days`), never a value, and `--json` does not either. `check` reads the session through the same Chrome and, with `--url`, asks the wall check whether the page still opens signed in: a session that expired says so in words with the command to sign in again, and exits 4. `record --session` records in that profile; it is one door and `--storage-state` is the other, never both.
162
165
 
163
166
  Measured before this was written: a profile plain Chrome signed in reopens signed in ONLY under the system Chrome with the real keychain. Playwright's bundled Chromium keeps its own keychain entry and can never decrypt Chrome's cookies, so every reader of a session here is the system Chrome (`VOS_BROWSER_PATH` overrides it) with Playwright's `--use-mock-keychain` removed. Two things `check` says because they cost real runs: an app whose session cookie has no expiry leaves nothing to reuse once the window closes, and a Chrome that was killed rather than quit never wrote its store.
164
167
 
@@ -188,7 +191,9 @@ It writes `<out>/look.png` (the viewport; `--out look` by default) and lists eve
188
191
 
189
192
  **`--header name=value`**, repeatable: a request header on every request the recording browser makes, the way past a preview deployment protected by a bypass header alone (`--header x-vercel-protection-bypass=$TOKEN`). The rehearsal's `Next:` line carries it.
190
193
 
191
- **What the frame shows.** Getting past a login puts the account's own data in the picture, and asking for a demo account does not hold that line: a person asked to sign in signs in as themselves. So the recorder looks. After the page opens and after every step it reads the text visible in the viewport and reports the KIND of thing it saw and where, never the string: an email address (one on `example.com` or a `.test`, `.example`, `.invalid` or `.localhost` domain is demo data and is not reported), something shaped like an API key or a JWT, a card number that passes the Luhn check, a masked card's visible tail. They land in `meta.exposures[]` (`step`, `kind`, `selector`, `rect`, `seen`), in the `record` and `create` done events, at the end of a rehearsal (before anything is recorded), as warnings in `vos validate <take>`, and in the digest's `take.exposures`. They warn; they do not fail a take, because a product may legitimately show addresses. The `selector` reaches that element and no other, so it can be pasted into a mask.
194
+ **The sound a page plays.** The recorder captures frames, so sound the product makes (a voice preview, a video playing in the page) would be lost. It watches every `<video>` and `<audio>` the page plays, in the page and its same-origin frames, `new Audio()` included: each one heard (not muted, volume above 0) lands in `meta.media[]` as `{ step, src, tag, duration, volume, intervals: [{ at, from, to }] }`, footage seconds `at` while it played media seconds `from`..`to`, split wherever an `await` took the camera away; one that played muted is listed with `muted: true` and no intervals. At the end of the take each heard source is fetched with the page's own cookies (a `blob:` or `data:` inside the page) into `page-sound/`, and the plan places one audio clip per interval at the output time the footage reaches it, `source: "page"`, at the element's volume. An auto speed span over a heard stretch is dropped, or the footage would race ahead of the sound. A re-plan, and `plan --reuse` after a re-record, replace only the `page` clips. A source that cannot be fetched is said, and its entry carries `fetchError` instead of `file`. A hosted take records `meta.media` and places nothing, since it has nowhere to keep the file. Web Audio a page synthesizes is not heard.
195
+
196
+ **What the frame shows.** Getting past a login puts the account's own data in the picture, and asking for a demo account does not hold that line: a person asked to sign in signs in as themselves. So the recorder looks. After the page opens and after every step it reads the text visible in the viewport and reports the KIND of thing it saw and where, never the string: an email address (one on `example.com` or a `.test`, `.example`, `.invalid` or `.localhost` domain is demo data and is not reported), something shaped like an API key or a JWT, a card number that passes the Luhn check, a masked card's visible tail. They land in `meta.exposures[]` (`step`, `kind`, `selector`, `rect`, `seen`), in the `record` and `create` done events, at the end of a rehearsal (before anything is recorded), as warnings in `vos validate <take>`, and in the digest's `take.exposures`. They warn; they do not fail a take, because a product may legitimately show addresses. The `selector` reaches that element and no other, so it can be pasted into a mask. Beside them the scan keeps two NOTICES, information that is never a warning, never in `exposures` and never a `--strict` failure: the signed-in account's own name, read conservatively from where apps say whose account it is (a "Signed in as …" or "Welcome back, …" line, an account menu's label, or the name-like words on the account menu's own button, the one holding the avatar; a name-like label on an avatar is reported as what MAY be the name, and a control's generic label, "Account menu" or "Profile settings", never is), with every place in the frame it showed; and a list of the account's recent items (a "Recents", "Recent" or "History" heading over three or more links) with the one-line `mask` that hides it. They land in `meta.notices[]` (`step`, `kind`: `account-name` with `places` and `sure`, or `personal-list` with `heading`, `selector`, `rect`, `items`; `seen`), the `record` and `create` done events, the end of a rehearsal, and a `noticed` section of `vos validate <take>`. The name itself is never printed, not even inside a selector: a line reads `the account's name (3 places, as the page opened): …`.
192
197
 
193
198
  **`mask`** in `actions.json` hides a selector BEFORE the first frame is captured and keeps it hidden across navigations and re-renders, so the real value is never in a frame, never in the recording, never pushed:
194
199
 
@@ -201,7 +206,7 @@ It writes `<out>/look.png` (the viewport; `--out look` by default) and lists eve
201
206
 
202
207
  `as: "blur"` (the default) blurs the element; `as: "text"` swaps its words, which reads as a product where a blur reads as a redaction. Use `text` for IDENTIFIERS (an email, a name, an account id), never for product copy or numbers: the video stays true to the product. A form control is always blurred, since writing into an input would change what the app submits. A mask whose selector reached no element hid nothing, so it fails `--strict` and a rehearsal (exit 2) and is named; `meta.masks[]` records each mask's `hits`.
203
208
 
204
- **Rehearse before you record.** `vos record … --dry-run` runs every step against the real page, in order, because a later selector usually exists only after an earlier click. Nothing is captured and nothing is written: the pointer lands instead of travelling, every pause is cut to a beat, and the take directory beside it keeps its footage, its cut and its script exactly as they were (a real re-record moves `doc.json` aside; a rehearsal does not). Selector lookups keep their whole timeout, so a miss here is a miss in the take. It prints each step with the rect it resolved, in capture px, which are the rects a pin or `vos callout --step` reads, and exits 2 on any miss (a first load that never went network-idle is only a note). A step that spends is hovered and never pressed, so an `expect` or `await` after it is not waited on (`not waited: it follows #N (guarded, not pressed)`) and counts as resolved. Add `--dry-run` to the exact command you were about to run; `--storage-state` and `--browser-arg=` apply to it too, and the `Next:` line it prints carries them, so the command it hands you records what it rehearsed. The page's own console errors are said one line each, cut short, with a repeat counted (`[page error ×4]`) rather than printed again; `--verbose` prints every one whole, and the `--json` done event carries them all as `pageErrors` (`{ text, count }`).
209
+ **Rehearse before you record.** `vos record … --dry-run` runs every step against the real page, in order, because a later selector usually exists only after an earlier click. Nothing is captured and nothing is written: the pointer lands instead of travelling, every pause is cut to a beat, and the take directory beside it keeps its footage, its cut and its script exactly as they were (a real re-record moves `doc.json` aside; a rehearsal does not). Selector lookups keep their whole timeout, so a miss here is a miss in the take. It prints each step with the rect it resolved, in capture px, which are the rects a pin or `vos callout --step` reads, and exits 2 on any miss (a first load that never went network-idle is only a note; a rehearsal captures no frames, so it says nothing of dead time). A step that spends is hovered and never pressed, so an `expect` or `await` after it is not waited on (`not waited: it follows #N (guarded, not pressed)`) and counts as resolved. Add `--dry-run` to the exact command you were about to run; `--storage-state` and `--browser-arg=` apply to it too, and the `Next:` line it prints carries them, so the command it hands you records what it rehearsed. The page's own console errors are said one line each, cut short, with a repeat counted (`[page error ×4]`) rather than printed again; `--verbose` prints every one whole, and the `--json` done event carries them all as `pageErrors` (`{ text, count }`).
205
210
 
206
211
  **The planners read the flow's own structure.** On a scripted take the step timeline is a planner input: a `wait` step between the first and the last doing step, or a hover's dwell, in which the digest's activity measured nothing moving is proposed at 2× (`speedParams.stillRate`; the opening and closing waits are the clip's establishing and resting beats and stay at 1×), the presses inside one step (a click and the dialog it opened, a drag's presses) are one zoom while their targets share a window, and a park before the first step (the cursor arriving on the logo) is never a dwell. Manual and rejected spans stay as they are.
207
212
 
@@ -246,6 +251,7 @@ take/
246
251
  doc.json ProjectDoc, the editable cut
247
252
  doc.prev.json the previous cut, kept by a re-record for `vos plan --reuse`
248
253
  outputs/ the files `download` steps kept, listed in meta.json's outputs
254
+ page-sound/ the sound the page played during the take, listed in meta.json's media
249
255
  vos.json hosted tracking (vos id + base version), written by push, fetch and pull
250
256
  stills/ `vos frames` output + stills.json
251
257
  digest/ `vos digest` output: digest.json, <id>.full.png, <id>.crop.png, sheet.png
@@ -284,7 +290,54 @@ A re-record replaces the footage, the cursor track, the frames, `outputs/` and e
284
290
  }
285
291
  ```
286
292
 
287
- Eight verbs: `wait`, `hover` (`ms` 700, the dwell), `click` (`ms` the settle after the press, 150), `type` (`delayMs` 40 per key, paced by the clock; `focus: false` skips the focusing click; `replace: true` selects the field's value first so the typing replaces it; `at: "end" | "start"` puts the caret there before the first character, for a code editor line; `ms` the settle after, 150), `press` (one named key, `Escape`, `Enter`, `Tab`, `Backspace`, `Delete`, the arrows, `Home`, `End`, `PageUp`, `PageDown`, `Space`, recorded as a typing ping where the pointer is or on `selector` with no click, so an Escape closes what a click opened and an Enter submits what was typed without a second click ringing on the field; `ms` the settle, 150), `scroll` (`ms` the settle, 200), `move`, `drag` (press, move, release: a range input, a canvas element, a timeline clip; `ms` the travel, 700). The recorder's pace is the script's: a gesture is driven by the clock, so a page that answers each pointer sample slowly costs samples, never seconds, and the only pauses are the ones the script names (`wait`, a hover's dwell, a settle). `vos record` ends with a pace line, what the script asked, what the gestures added, what the page cost, and the steps that ran slow, and the `--json` done event carries it as `pace`. Every step takes an optional unique `id`; give steps ids so a span anchored to a step survives script edits and `vos plan --reuse` can follow it, and so a layer can name the element a step touched (`overlays[].pin.step`; the recorder keeps each hover, click, type and drag step's element rect on `meta.steps[].rect`). **The take carries its payload**: every step keeps the page it left (`meta.steps[].url`, origin and path), and a step with `read: "<selector>"` keeps that element's words once the step has settled (`meta.steps[].text`, at most 2 KB; on a click, what the click opened: the URL a share button minted, the code a dialog printed), so a layer quotes the take instead of a replay of the flow. Because the CLI issues every input itself, the cursor track is synthesized with exact coordinates, exact timing and fresh element rects, which is what powers element-aware auto-zoom and click effects downstream. The schema is [`schema/actions.schema.json`](./schema/actions.schema.json); `vos validate actions.json` checks a script without running anything.
293
+ Nine verbs: `wait`, `hover` (`ms` 700, the dwell), `click` (`ms` the settle after the press, 150; `count: 2 | 3` for a double or triple click, `button: "right" | "middle"`, `modifiers` held for the press), `type` (`delayMs` 40 per key, paced by the clock; `focus: false` skips the focusing click; `replace: true` selects the field's value first so the typing replaces it; `at: "end" | "start"` puts the caret there before the first character, for a code editor line; `ms` the settle after, 150), `press` (one named key, `Escape`, `Enter`, `Tab`, `Backspace`, `Delete`, the arrows, `Home`, `End`, `PageUp`, `PageDown`, `Space`, recorded as a typing ping where the pointer is or on `selector` with no click, so an Escape closes what a click opened and an Enter submits what was typed without a second click ringing on the field; or `keys`, a chord, a plain key or a sequence, below; `ms` the settle, 150), `scroll` (`ms` the settle, 200), `move`, `drag` (press, move, release: a range input, a canvas element, a timeline clip; `ms` the travel, 700; `modifiers` and `path`, below), `paste` (below). The recorder's pace is the script's: a gesture is driven by the clock, so a page that answers each pointer sample slowly costs samples, never seconds, and the only pauses are the ones the script names (`wait`, a hover's dwell, a settle). `vos record` ends with a pace line, what the script asked, what the gestures added, what the page cost, and the steps that ran slow, and the `--json` done event carries it as `pace`. Every step takes an optional unique `id`; give steps ids so a span anchored to a step survives script edits and `vos plan --reuse` can follow it, and so a layer can name the element a step touched (`overlays[].pin.step`; the recorder keeps each hover, click, type and drag step's element rect on `meta.steps[].rect`). **The take carries its payload**: every step keeps the page it left (`meta.steps[].url`, origin and path), and a step with `read: "<selector>"` keeps that element's words once the step has settled (`meta.steps[].text`, at most 2 KB; on a click, what the click opened: the URL a share button minted, the code a dialog printed), so a layer quotes the take instead of a replay of the flow. Because the CLI issues every input itself, the cursor track is synthesized with exact coordinates, exact timing and fresh element rects, which is what powers element-aware auto-zoom and click effects downstream. The schema is [`schema/actions.schema.json`](./schema/actions.schema.json); `vos validate actions.json` checks a script without running anything.
294
+
295
+ **Canvas gestures**: what a whiteboard, a design tool or a timeline is recorded with.
296
+
297
+ ```json
298
+ {
299
+ "settle": true,
300
+ "steps": [
301
+ { "do": "press", "keys": "r" },
302
+ { "do": "drag", "x": 200, "y": 160, "tx": 420, "ty": 300 },
303
+ { "do": "press", "keys": ["v", "Escape"] },
304
+ {
305
+ "do": "drag",
306
+ "selector": ".shape",
307
+ "tx": 600,
308
+ "ty": 300,
309
+ "modifiers": ["Alt"]
310
+ },
311
+ { "do": "drag", "path": "signature.json" },
312
+ {
313
+ "do": "drag",
314
+ "path": [
315
+ [300, 400],
316
+ [340, 420],
317
+ [380, 400]
318
+ ],
319
+ "ms": 500
320
+ },
321
+ { "do": "click", "selector": "text=Title", "count": 2 },
322
+ { "do": "click", "selector": ".layer", "button": "right" },
323
+ { "do": "click", "x": 640, "y": 420, "modifiers": ["Shift"] },
324
+ { "do": "click", "x": 300, "y": 260, "count": 2 },
325
+ { "do": "paste", "file": "logo.svg" },
326
+ { "do": "press", "keys": "Mod+Z" }
327
+ ]
328
+ }
329
+ ```
330
+
331
+ - **`press` `keys`** takes a chord (`"Shift+D"`, `"Meta+Shift+z"`, `"Mod+Z"`: `Mod` is Meta on macOS and Control elsewhere, wherever the browser runs), a plain key (`"r"`, a tool's shortcut) or a sequence (`["v", "Escape"]`, 150 ms apart). A key is a single character, a named key (`Escape`, `ArrowLeft`, `Space`), `F1` to `F24`, or a code (`KeyA`, `Digit1`); the modifiers are `Shift`, `Control`, `Alt`, `Meta`, `Mod`. Each key is a typing ping on the cursor track, when and where, never which key. The older `key` form still works.
332
+ - **`drag` `modifiers`** (`Alt`, `Shift`, `Meta`, `Control`, `Mod`) are held from the press to the release: Alt-drag to duplicate, Shift to constrain.
333
+ - **`drag` `path`** draws: viewport points inline (`[x, y]`, `[x, y, tMs]`, `[x, y, tMs, pressure]` or `{ "x", "y", "t", "pressure" }`, every point timed or none), or a file beside the actions file by a plain name (`"path": "loop.json"`, an array of points or `{ "points": [...] }`). The pointer travels to the first point, presses there, moves through every later point in order and releases at the last, replayed by the points' own times, or evenly over `ms` when they carry none. Every point is sent: a page that answers slowly makes the stroke late (an overrun, below), never a different stroke. A point that carries `pressure` draws the whole path with a pen, so the page's pointer events carry that pressure; without, the mouse draws it. A path takes no `selector`, `x`, `y`, `tx` or `ty`. The cursor track holds the press, every point and the release. The take keeps its script self-contained: a path a file held is written inline (with its times and pressure) in the take's `actions.json`, so the push embeds it, a fetch writes it back and a hosted take runs it, and a re-record draws the same strokes with the file gone; `--hosted` sends a path file's points inline too.
334
+ - **`click` `count`** 2 or 3 is a real double or triple click (that many presses inside the platform's double-click interval, each with its click count); `button` presses the right or middle one; `modifiers` (`Alt`, `Shift`, `Meta`, `Control`, `Mod`) are held for the press and released after it (a Shift-click adds to a selection). Every press is a down and an up on the cursor track.
335
+ - **`click` and `hover` at a point**: `x` and `y` (viewport CSS px) instead of a `selector`, for a spot no element names: a place on a canvas, a handle, empty space to click on to focus or deselect. The cursor track carries the press at that point with no element rect, so the planner treats it as a point. A drawn shape's DOM box is not always where it is drawn (an arrow's container sits at its anchor), so a point is often the truer target on a canvas.
336
+ - **`paste`** puts `text`, or a `file` beside the actions file (an image, an SVG, a text file; at most 10 MB), on the clipboard and pastes it the way a person's ⌘V does, into `selector` (clicked first) or where the focus is. The browser's own clipboard holds the item (a headless browser keeps its own, so this machine's clipboard is untouched), and the recorder presses the platform's paste chord, so the page gets a trusted keydown and a trusted `paste` event, and a page that reads `navigator.clipboard.read()` itself finds the item there. An SVG rides as its markup too. An IMAGE file is dispatched in the page with its own bytes instead (the focused element gets a `paste` event holding the file, and `navigator.clipboard.read` answers it for that paste only: shortly after it is first read, or after 3 s unread, the browser's own reads come back, so a later paste goes through the real clipboard), because the browser's clipboard re-encodes a picture and drops what it carries, a screenshot's density among it, so a 2x capture would land at twice its size; the log says which path ran, and that those events are untrusted. Words keep the trusted path, and fall back to the same dispatch in the page when the browser refuses them. A paste is a typing ping, never its contents. The take keeps a pasted file beside its script as `paste-<name>`, and its `actions.json` names the copy, so the take re-records on this machine with the original gone. A pushed take carries its script but not a pasted file, so a script fetched from vos.so that pastes a file needs that file put beside it again, and says so.
337
+ - **`settle: true`** on a gesture step (or at the top of the script, for every one; a step's `settle: false` opts out) waits after the gesture until the page has made no DOM change and painted no new frame for 300 ms, counted from the page's last change (a page already still for longer goes on at once), at most 4 s: a heavy canvas that falls behind under load finishes the last stroke before the next one starts. `meta.steps[].settleMs` says how long it waited, and a page still changing at the cap is said in the log. A rehearsal captures no frames, so there it waits on the DOM alone.
338
+ - **Overruns**: a gesture the script paces (a straight drag's travel, a path's timing, typing, a key sequence, whose plan holds each key's round trip as well as its gaps) that took more than a fifth longer than planned, and at least 100 ms longer, is reported: `meta.steps[].overrunMs`, `overruns: [{ step, id, do, plannedMs, tookMs, overrunMs }]` in the done event, and one line (`3 steps ran 2.1× slower than scripted (…): the page could not keep up; add settle or raise ms`).
339
+
340
+ A hosted take (`--hosted`) refuses a `paste` (a fleet browser has no clipboard) and a `path` read from a file (the script travels alone; write the points inline).
288
341
 
289
342
  Three steps that are not gestures, and a guard:
290
343
 
@@ -311,10 +364,13 @@ Three steps that are not gestures, and a guard:
311
364
 
312
365
  - **`expect`** checks the page on camera, with no cursor move: exactly one of `selector` (visible; with `enabled: true | false`, enabled or disabled), `text` (some visible text contains it) or `gone` (no longer visible), waiting up to `timeout` seconds (5). A condition that never holds is a skip with its reason (`#10 expect: 'text=Generate video' stayed disabled for 5 s`), and `--strict` turns it into exit 2. Separately, every `click` asks whether its target is disabled: the press still happens, and the done event lists it under `disabled: [{ step, id, selector }]`, the rehearsal marks it, and `--strict` fails on it.
313
366
  - **`await`** waits OFF CAMERA for something slow: a render, a generated result, a deploy. The capture stops, the cursor clock stops with it, and `until` (`{ selector }`, `{ text }` or `{ gone }`) is polled every `poll` seconds (2) for up to `timeout` (600), reloading the page between looks with `reload: true` (after a reload the recorder lets the page settle, no DOM change for 0.8 s, and wants the condition on two reads in a row, so a list drawn after the network went quiet cannot end the wait early). When it holds, the capture resumes, so the footage runs straight from the moment before the wait to the moment after: no gap, no frozen stretch. The cut is recorded in `meta.skips[]` (`{ step, id, at, ms }`: `at` the footage second of the cut, `ms` the wall time that did not reach the footage) and on the step's `meta.steps[]` entry (`offCameraMs`), and the planned `doc.json` starts a segment at every `at`. On timeout, `onTimeout: "fail"` (the default) stops the take there with exit 1 and a sentence naming the step and the time it waited, keeping the footage up to it; `"continue"` resumes and marks the skip `timedOut`. A rehearsal waits for real and prints how long it took, which is how you learn the timing. A wait that holds within 250 ms cut nothing and records no skip or segment boundary (the step still reports it). A predicate that may already be true before the action (an older item with the same text, a spinner not yet shown) holds at once: wait for something only the new result has. Under `--json` an await reports `{ event: "await", step, id, phase: "start" }`, a `phase: "wait"` heartbeat with `elapsedMs` every 30 s, and `phase: "end"` with `ms`.
367
+
368
+ **Every step is bounded, and says when it runs.** A page that stops answering (a busy loop, a renderer stuck after a reload the page made itself) would leave a step waiting on it for good, so every call the recorder makes into the page is held to the step's own bound: an `expect` its `timeout` plus 5 s, an `await` its `timeout` plus 30 s, a `download` its 30 s plus 30 s, any other step its planned time plus 30 s. A step that runs into its bound ends as a skip whose reason carries the real time it took (`the page stopped answering: this expect ran 6 s, past its bound of 6 s`); under `--strict`, and always in a rehearsal, the take stops there, keeping the footage up to it. Under `--json` every step reports `{ event: "step", phase: "start", i, id, do }` as it begins and `phase: "end"` with `ms` (and `skipped`, `hung`) as it ends, so a slow take is never minutes of silence.
369
+
314
370
  - **`download`** keeps a file the page makes, in the take's `outputs/`: `selector` clicks a control and waits up to 30 s for the browser's download (the name the page sends in `Content-Disposition`); `src` names a `<video>`, `<audio>` or `<img>` (any selector the other steps take: `video >> nth=0`, `text=…`) and fetches its `currentSrc` with the page's own cookies. `as` names the file (a plain file name: no path separator, no `..`); absent, the page's name is used, made plain and unique. Each file is listed in `meta.outputs[]` (`{ step, id, name, bytes, contentType }`). A download that never arrives is a skip with its reason. A rehearsal fetches the file and keeps nothing.
315
371
  - **`"guard": "spend"`** marks a `click`, `press` or `type` that costs something real: credits, a purchase, a message sent. It needs an `id`. `vos record --dry-run` moves the pointer to its target and never presses it (`#9 generate: guarded (spend), hovered, not pressed`); `vos record` presses it only when the command names it with `--confirm <id>` (repeatable), and otherwise refuses before capturing anything, naming the step and the flag (under `--json` also as `{ event: "refused", reason, step, id }`). The done event's `confirmed` and the step's `meta.steps[].confirmed` say which guarded steps were pressed.
316
372
 
317
- `vos actions script` says these too: `Check that … is enabled`, `Wait until … (off camera: pause the recording meanwhile)`, `Download …`, and a guarded step is marked as one that spends.
373
+ `vos actions script` says these too: `Check that … is enabled`, `Wait until … (off camera: pause the recording meanwhile)`, `Download …`, `Press ⌘/Ctrl+Z`, `Press v then Escape`, `Hold Alt/Option and drag …`, `Draw the stroke in loop.json, in one press`, `Double-click …`, `Copy the file logo.svg, then paste it (⌘/Ctrl+V)`, and a guarded step is marked as one that spends.
318
374
 
319
375
  Verified the flow in agent-browser already? `vos actions from-agent-browser steps.jsonl [--out actions.json] [--url] [--viewport WxH]` writes the script from that walk (each command kept beside its `--json` result, the batch record shape; refs resolve through the last `snapshot -i`), and names every step the recorder cannot follow rather than dropping it.
320
376
 
@@ -346,6 +402,25 @@ Not sure of a selector? `vos look <url>` (with the take's `--session` or `--stor
346
402
 
347
403
  **Audio.** `doc.audio` clips (music, effects, `key` a take-directory file or a URL) are mixed with gain, fade and loop envelopes and muxed into every full render: Opus for webm, AAC (Opus fallback) for mp4. Audio forces single-flight (`--parallel` is ignored with a note); a `--range` render keeps its audio.
348
404
 
405
+ **Loudness as a target.** `gain` is 0..1, so it cannot lift a quiet file; a clip may say how loud it should play instead: `normalize`, an integrated loudness in LUFS from -30 to -6 (`-16` sits a score under speech without burying it). The lowering plays the clip at `10^((normalize - lufs) / 20) × gain`, which may exceed 1, from what the file measures, a FACT stored beside the clip and written by tooling, never by hand:
406
+
407
+ ```json
408
+ {
409
+ "id": "score",
410
+ "key": "music/theme.wav",
411
+ "gain": 1,
412
+ "normalize": -16,
413
+ "loudness": {
414
+ "lufs": -24.3,
415
+ "peakDb": -9.1,
416
+ "at": "2026-10-22T10:04:00.000Z",
417
+ "src": "music/theme.wav"
418
+ }
419
+ }
420
+ ```
421
+
422
+ `vos audio measure <take>` decodes every clip's file and writes its `loudness`: BS.1770 integrated loudness (K-weighted, gated) over the whole file and its sample peak, by the meter `vos check-video` reads a render with. `vos score` writes it for the score and `vos join` for the sound it adds. The gain is CAPPED, never limited: no target puts the file's sample peak above -1 dBFS, none lifts more than +24 dB, and `vos validate` says when a cap holds a clip under its target. A target applies only while `loudness.src` is the clip's own `key`, so a clip pointed at another file plays at its gain alone until it is measured again (`vos validate` warns: measure it: `vos audio measure <take>`); a document with no target lowers byte for byte as before. `vos push` and `vos pull --media` move `loudness.src` with the key when a file is uploaded or brought home.
423
+
349
424
  **Background.** `doc.frame.backgroundMedia` puts a looping video or a still behind the card: `{ "kind": "video", "key": "<url or /file>", "duration": 10, "dim": 0.2 }`. Time is output-anchored modulo `duration`, so trims and speed never retime the ambience; `dim` is a black scrim for legibility; `frame.parallax` (0..1, 0.6 reads well) counter-pans it with the zoom and `backgroundMedia.blur` softens it in design px. The hand-picked set is `GET https://vos.so/api/backdrops` (no auth): copy `key` from a row's `urls["1080p"]`, `duration` from the row, and `frame.background` from its `ground`. Drawn under the card, outside the zoom, fail-open to the CSS `frame.background`.
350
425
 
351
426
  **Checking what rendered.** A still is only proof of what it shows. `vos frames --at-zooms` reads every zoom span on every media of the take through the cut to the output time it plays (a span the cut keeps none of is skipped and named), stills its apex, and stills the same time again with the zooms off (`--set zoom=[]`): a zoom whose frame matches its zoom-off twin did not render, and it is said, `zoom z3 at 4.50s did not render (its frame matches the zoom-off frame)`, with the twin kept beside it. Each zoom entry in `stills.json` and the `--json` done event carries `zoomId`, `media` when it is not the primary, `rendered` and `difference` (the mean absolute difference from the twin over a small grayscale, 0..1). `vos check-video <file>` checks the rendered file itself, decoding it in the browser the CLI already drives: duration, bytes, codecs, resolution and frame rate; full-frame scene changes (a large change that stands out from the frames around it, or a smaller one over at least a quarter of the frame that stands alone, as when a camera jumps between two views of one dark picture; a zoom, a pan or a cross-fade is neither), with the count per 5 s and a warning when any 5 s holds more than one; loudness per ITU-R BS.1770 (short-term every 3 s, integrated, the sample peak), with a warning below -23 LUFS (too quiet for a feed) or above -9, and a silent track named; and the first and last frames as PNGs, with a warning when either is near-uniform, an empty or faded open or close.
@@ -374,7 +449,7 @@ vos brand https://your.app --out BRAND.md # the brand kit,
374
449
 
375
450
  ## The vos.so loop
376
451
 
377
- Everything that runs on your machine is open source; [vos.so](https://vos.so) is the hosted platform: a studio for the human half of an edit, version history with a typed changelog, a shelf of projects and recipes. All vos.so traffic lives behind one client: one origin (`VOS_ORIGIN`, default `https://vos.so`; `--origin` per call), one credential ladder (`--key`, then `VOS_API_KEY`, then `~/.config/vos/credentials`, written by `vos login`; a `vos_rg_` remix grant is just a key), one tracking file (`vos.json` beside the artifact). Credentials are never printed. Keys can never publish: pushes are private, and humans publish on vos.so.
452
+ Everything that runs on your machine is open source; [vos.so](https://vos.so) is the hosted platform: a studio for the human half of an edit, version history with a typed changelog, a shelf of projects and recipes. All vos.so traffic lives behind one client: one origin (`VOS_ORIGIN`, default `https://vos.so`; `--origin` per call), one credential ladder (`--key`, then `VOS_API_KEY`, then `~/.config/vos/credentials`, written by `vos login` with the origin it was minted for; a `vos_rg_` remix grant is just a key), one tracking file (`vos.json` beside the artifact). Credentials are never printed, and the stored one is sent only to the origin it was minted for (a file written before the origin line is `https://vos.so`'s): a command aimed at another origin sends no key and says so, so pass `--key` or `VOS_API_KEY` for it, or `vos login --origin <it>`. Keys can never publish: pushes are private, and humans publish on vos.so.
378
453
 
379
454
  ```bash
380
455
  vos login [--key <k>] [--label <name>] [--no-browser] # browser sign-in: a code and a vos.so/cli/auth URL, a human approves, the key stores itself
@@ -402,7 +477,7 @@ vos assets ls [--kind <kind>] [--q <text>] [--sort size] | usage | why <id> #
402
477
  vos recipe push <FILE.md> --folder <slug> | --asset <id> # the one recipe write: create, or replace in place
403
478
  ```
404
479
 
405
- `push` is polymorphic by a deterministic sniff, never a flag: a take directory (a `doc.json` carrying `source`) pushes recording and document through the take pipeline; a `config.json` (or a directory holding one) pushes the program, and a `doc.json` beside it that carries `program` (a program document: overlays, objects, audio, speed, tween edits, its own length; `program.config` omitted on disk) rides along, lint-gated. `fetch` and `pull` write a program document back the same way. `pull` takes `--since <versionId>` (walk the changelog from that base instead of the tracked one) and `--check` (print what changed and stop: nothing on disk moves) on both paths. A program push LANDS where `vos.json` says: a directory that tracks a vos iterates it, so the fetch, edit, check, push, pull loop needs no flags, and making something separate from the same config is the explicit `--remix-of` door. Program pushes take `--vos`, `--title`, `--slug`, `--desc`, `--tags`, `--folder`, `--remix-of`, `--base`, `--label`, `--note`, `--override <id>` (repeatable) and `--claimable`; take pushes take `--title`, `--label`, `--note`, `--folder`, `--override`, `--yes` and `--claimable`. Both take `--wait`. A new vos pushed without `--folder` lands unfiled, at the root of the shelf, and the done line says so. `--folder` takes a project on your own shelf (its slug or id) or anyone's project by its address, `<handle>/<slug>` as its page on vos.so names it: the server answers where the push lands, CONTINUING that project when the key is its owner's and otherwise STARTING the person's own from it (a private project made once, named after it, with the recipes they may read copied in, never its videos). The push says which.
480
+ `push` is polymorphic by a deterministic sniff, never a flag: a take directory (a `doc.json` carrying `source`) pushes recording and document through the take pipeline; a `config.json` (or a directory holding one) pushes the program, and a `doc.json` beside it that carries `program` (a program document: overlays, objects, audio, speed, tween edits, its own length; `program.config` omitted on disk) rides along, lint-gated. `fetch` and `pull` write a program document back the same way. `pull` takes `--since <versionId>` (walk the changelog from that base instead of the tracked one) and `--check` (print what changed and stop: nothing on disk moves) on both paths. A program push LANDS where `vos.json` says: a directory that tracks a vos iterates it, so the fetch, edit, check, push, pull loop needs no flags, and making something separate from the same config is the explicit `--remix-of` door. Program pushes take `--vos`, `--title`, `--slug`, `--desc`, `--tags`, `--folder`, `--remix-of`, `--base`, `--label`, `--note`, `--override <id>` (repeatable) and `--claimable`; take pushes take `--title`, `--label`, `--note`, `--folder`, `--override`, `--yes`, `--bake` and `--claimable`. Both take `--wait`. A take push first asks the platform which `@vosjs/studio-core` it renders with (`GET /api/engine`, public, `{ studioCore, core }`) and refuses (exit 2), before anything uploads, a take that uses a field newer than it: the program a push compiles plays right, but the platform's studio lowers the stored document again with its own release, so it would show an anchored caption at its fallback start or play a clip with a loudness target at its gain, and every version saved from the studio would keep it that way. `--bake` sends a copy any renderer plays: every such field the take uses, said in what an older release reads (an anchored caption at the start it plays at in this cut with its `{elapsed}` filled, a loudness target as its gain, up to 1), whatever the platform answered, behind, current or nothing at all, and it never touches `doc.json`. The table of fields and their releases is `DOC_FEATURES` in `@vosjs/studio-core`. A platform that cannot say (no such endpoint, a refusal, no answer in 2 s) is warned of and pushed to. A new vos pushed without `--folder` lands unfiled, at the root of the shelf, and the done line says so. `--folder` takes a project on your own shelf (its slug or id) or anyone's project by its address, `<handle>/<slug>` as its page on vos.so names it: the server answers where the push lands, CONTINUING that project when the key is its owner's and otherwise STARTING the person's own from it (a private project made once, named after it, with the recipes they may read copied in, never its videos). The push says which.
406
481
 
407
482
  **A program's files are declared, never typed into a function.** `config.json` names each file it uses in `assets` (`"assets": { "logo": { "ref": "./logo.png", "kind": "image" }, "shots": { "ref": ["./shots/1.png", "./shots/2.png"] } }`) and reads `ctx.assets.logo`, or `"$assets.logo"` in an element, object or font. On disk a `ref` is a path in the config's own directory or below, so `vos render`, `vos still` and `vos preview` serve the file to the page from disk. A path that climbs out of that directory (`../`, an absolute path, a link that points away) is not served and not uploaded, and a config loaded from a URL reads no local file: a program's code runs in a page, and what the page is served the program can send anywhere. `vos push` uploads each local file (content-addressed, so a re-push sends nothing: pictures, SVG, video, sound, `.glb` models, fonts and HDR environments) and what it stores names the hosted file as `asset:<id>`, the one spelling the platform resolves for every render; the config on disk keeps its paths. A file an element names as `src` or a font names as `url` is lifted into the manifest on the way (the element then names `"$assets.<name>"`), and a path in `data` that is a file beside the config is uploaded and rewritten to the hosted file's path, so every place a program can name a file crosses. A file typed inside a function cannot be rewritten: `vos push` says so, with the manifest line to write. `vos fetch --media` brings a program's hosted files home under `assets/` and re-points the manifest at them (`assets/.hosted.json` remembers which hosted file each one is, so a later fetch replaces one that changed); without `--media` the manifest keeps `asset:<id>` and a local render reads each file with your key. `vos check` says when a `"$assets.<name>"` names nothing, when a declared path is not a file, and when a function names a hosted file in code instead of the manifest: a file named only in code does not load on a render of a private program and does not follow a remix. A `--claimable` push carries them too, through the claim's own upload session (below).
408
483
 
@@ -432,7 +507,7 @@ vos push /tmp/take --label "$TAG launch" --yes --json # VOS_API_KEY as a r
432
507
  - **Output.** Logs on stderr, results on stdout. `--json` turns every verb into NDJSON events ending with `{"event":"done",…}`.
433
508
  - **`vos <verb> --help`** prints that verb's usage lines and exits 0 (it used to be a usage error).
434
509
  - **Exit codes.** 0 ok, 1 error, 2 usage (including `--strict` failures), 3 no browser found, 4 the recorder met a wall (a sign-in, or under `--strict` a redirect away from the asked page) and nothing was recorded or cleared. `--json` carries the verdict as a `wall` event (`kind`, `level`, `asked`, `landed`, `refused`).
435
- - **`--strict`** on `record` and `create` (agents: always): a skipped step (a selector that never appeared, an `expect` that never held, a download that never came), a click on a disabled control, an `await` that timed out, or a take that hit `--max-duration` exits 2 and lists `skipped[]`, `disabled[]` (and `capped`) in the done event. A first load that never reaches network idle is a warning, `navTimeout: true` in the done event, never a strict failure: many real apps hold a socket open and never go network-idle. The default is lenient (exit 0, `skipped[]` still reported) for exploratory runs.
510
+ - **`--strict`** on `record` and `create` (agents: always): a skipped step (a selector that never appeared, an `expect` that never held, a download that never came), a click on a disabled control, an `await` that timed out, or a take that hit `--max-duration` exits 2 and lists `skipped[]`, `disabled[]` (and `capped`) in the done event. A first load that never settles is a note, never a strict failure: `ready.capped` in the done event, and `navTimeout: true` when `ready: "networkidle"` was asked for and never came (many real apps hold a socket open and never go network-idle, which is why the default waits for the DOM instead). The default is lenient (exit 0, `skipped[]` still reported) for exploratory runs.
436
511
  - **`--max-duration <s>`** on `record` and `create` defaults to the hosted recording cap, read live from `GET /api/limits` (2 s, fail-open to 30 min when the origin is unreachable): the capture stops there and the done event says so. Cut the flow rather than raising the cap; the platform refuses a longer take.
437
512
  - **`create`** is the one-shot verb: record, auto-plan and render in one command and one browser session. The take directory still lands on disk, so the full loop (frames, edit `doc.json`, re-render) stays open afterwards.
438
513
  - **`vos validate <thing>`** takes an `actions.json`, a take directory, a program directory (`config.json`, plus its program document when present), or a `kit.json`; exit 1 on any problem.
@@ -4,12 +4,12 @@ import {
4
4
  localManifestRefs,
5
5
  pullManifest,
6
6
  uploadManifest
7
- } from "./chunk-ZSJEISKL.js";
8
- import "./chunk-B4U4URE3.js";
7
+ } from "./chunk-4ZUHEXUX.js";
8
+ import "./chunk-J3KHIZCH.js";
9
9
  export {
10
10
  hostedLiteralWarnings,
11
11
  localManifestRefs,
12
12
  pullManifest,
13
13
  uploadManifest
14
14
  };
15
- //# sourceMappingURL=assetManifest-S6H5F2VE.js.map
15
+ //# sourceMappingURL=assetManifest-U25FJER6.js.map
@@ -3,6 +3,7 @@ import {
3
3
  MEDIA_HEAD_BYTES,
4
4
  TAKE_MEDIA_EXTENSIONS,
5
5
  apiJson,
6
+ bearerFor,
6
7
  extensionFor,
7
8
  hostedAssetId,
8
9
  localFile,
@@ -13,7 +14,7 @@ import {
13
14
  writeFileSafe,
14
15
  writeFileSafeSync,
15
16
  writeSyncState
16
- } from "./chunk-B4U4URE3.js";
17
+ } from "./chunk-J3KHIZCH.js";
17
18
 
18
19
  // src/plugin/assetManifest.ts
19
20
  import { existsSync as existsSync3, readFileSync, realpathSync, rmSync } from "fs";
@@ -115,7 +116,9 @@ async function prepareReRecord(dir) {
115
116
  join(dir, "stills"),
116
117
  join(dir, "digest"),
117
118
  // What the last run's download steps kept: this run downloads again.
118
- join(dir, "outputs")
119
+ join(dir, "outputs"),
120
+ // The sound the last run's page played: this run hears it again.
121
+ join(dir, "page-sound")
119
122
  ]) {
120
123
  await rm(stale, { recursive: true, force: true });
121
124
  }
@@ -410,6 +413,7 @@ function docAudioRefs(doc, keep = isTakeRelativeKey) {
410
413
  where: `audio ${clip.id}`,
411
414
  key: clip.key,
412
415
  set: (next) => {
416
+ if (clip.loudness?.src === clip.key) clip.loudness.src = next;
413
417
  clip.key = next;
414
418
  }
415
419
  });
@@ -487,7 +491,7 @@ function downloadPlan(ctx, url) {
487
491
  async function downloadMedia(ctx, url, target) {
488
492
  const plan = downloadPlan(ctx, url);
489
493
  const res = await fetch(plan.url, {
490
- headers: plan.bearer && ctx.key ? { authorization: `Bearer ${ctx.key}` } : {}
494
+ headers: plan.bearer ? bearerFor(ctx.key, plan.url) : {}
491
495
  });
492
496
  if (!res.ok || !res.body) {
493
497
  throw new Error(
@@ -735,6 +739,7 @@ export {
735
739
  docOverlayRefs,
736
740
  docLayerRefs,
737
741
  docMediaRefs,
742
+ docAudioRefs,
738
743
  uploadDocRefs,
739
744
  readMediaHead,
740
745
  pullMedia,
@@ -745,4 +750,4 @@ export {
745
750
  pullManifest,
746
751
  hostedLiteralWarnings
747
752
  };
748
- //# sourceMappingURL=chunk-ZSJEISKL.js.map
753
+ //# sourceMappingURL=chunk-4ZUHEXUX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/plugin/assetManifest.ts","../src/plugin/pathName.ts","../src/plugin/media.ts","../src/plugin/take.ts","../src/plugin/uploadAsset.ts"],"sourcesContent":["/**\n * A program's declared files (`config.assets`) crossing to and from vos.so.\n *\n * On disk a manifest names files beside the config (`./logo.png`), so a\n * program renders offline and reads like the repository it lives in. On the\n * platform a manifest names hosted assets (`asset:<id>`), the one spelling\n * the platform resolves for every surface: a private file reaches a render\n * page, a remix brings its files along, and a file a program still plays is\n * never collected. A push is the crossing one way, `vos fetch --media` the\n * other; neither rewrites the other side's spelling in place.\n */\nimport { existsSync, readFileSync, realpathSync, rmSync } from 'node:fs'\nimport { join, relative } from 'node:path'\nimport { hostedAssetId, localFile, manifestRefs } from '../programAssets'\nimport { safePathName } from './pathName'\nimport { writeFileSafeSync } from './safeWrite'\nimport { downloadMedia, uploadDocRefs } from './media'\nimport type { DocMediaRef } from './media'\nimport type { UploadTarget } from './uploadAsset'\n\ntype Manifest = Record<string, { ref: string | string[] }>\n\nconst isUrl = (ref: string) => /^(https?:|data:|blob:)/.test(ref)\n\n/** The origins whose `/api/assets/<id>/file` is a hosted file of ours. */\nconst homeOrigins = (origin: string) => [\n origin,\n 'https://vos.so',\n 'https://www.vos.so',\n]\n\n/** `assets/.hosted.json`: which hosted file each file brought home is. */\nconst HOME_INDEX = '.hosted.json'\n\n/** A deep copy of the manifest, so a caller's rewrite never reaches disk. */\nfunction cloneManifest(config: Record<string, unknown>): Manifest {\n return JSON.parse(JSON.stringify(config.assets ?? {})) as Manifest\n}\n\nfunction setRef(\n manifest: Manifest,\n name: string,\n index: number | null,\n next: string,\n): void {\n const decl = manifest[name]\n if (index === null) decl.ref = next\n else (decl.ref as string[])[index] = next\n}\n\nconst where = (name: string, index: number | null) =>\n index === null ? `assets.${name}` : `assets.${name}[${index}]`\n\n/**\n * Upload the manifest's local files and point every entry at its hosted\n * asset as `asset:<id>`; a hosted file spelled as a URL takes the same\n * spelling. `config.assets` is REPLACED on the object (the file on disk is\n * untouched), so everything composed from it afterwards carries the hosted\n * refs. Uploads are content-addressed: a re-push sends nothing.\n */\nexport async function uploadManifest(\n config: Record<string, unknown>,\n dir: string,\n target: UploadTarget,\n log: (line: string) => void,\n): Promise<{ uploaded: number }> {\n const refs = manifestRefs(config)\n if (refs.length === 0) return { uploaded: 0 }\n const manifest = cloneManifest(config)\n const local: DocMediaRef[] = []\n for (const { name, index, ref } of refs) {\n const hosted = hostedAssetId(ref, homeOrigins(target.origin))\n if (hosted) {\n setRef(manifest, name, index, `asset:${hosted}`)\n continue\n }\n if (isUrl(ref)) continue\n // A push uploads what the manifest names, so it holds the same line a\n // render does: only a file inside the program's own directory.\n const found = localFile(ref, dir)\n if ('refused' in found) {\n throw new Error(`${where(name, index)} names ${ref}, ${found.refused}`)\n }\n local.push({\n where: where(name, index),\n // The upload helper reads keys against the directory.\n key: relative(realpathSync(dir), found.file),\n set: (url) => {\n const id = hostedAssetId(url, homeOrigins(target.origin))\n setRef(manifest, name, index, id ? `asset:${id}` : url)\n },\n })\n }\n await uploadDocRefs(local, dir, target, log)\n config.assets = manifest\n return { uploaded: local.length }\n}\n\n/** The manifest entries that are still files on this machine. */\nexport function localManifestRefs(config: Record<string, unknown>): string[] {\n return manifestRefs(config)\n .filter(({ ref }) => !isUrl(ref) && !hostedAssetId(ref, homeOrigins('')))\n .map(({ name, index }) => where(name, index))\n}\n\n/**\n * Bring a fetched program's hosted files home: each `asset:<id>` lands as\n * `assets/<name>.<ext>` beside the config (the bytes choose the extension)\n * and its entry is re-pointed at that file.\n *\n * A file already there is kept only when it IS that hosted file\n * (`assets/.hosted.json` remembers which id each one came from). Kept by\n * name alone, a second fetch after someone changed `logo` left the old\n * picture under the new manifest, and the next push stored the old one\n * again without a word.\n *\n * Returns the rewritten manifest, or null when nothing in it is hosted.\n */\nexport async function pullManifest(\n ctx: { origin: string; key: string | null },\n dir: string,\n config: Record<string, unknown>,\n log: (line: string) => void,\n): Promise<{ assets: Manifest; files: string[] } | null> {\n const home = homeOrigins(ctx.origin)\n const hosted = manifestRefs(config).filter(({ ref }) =>\n hostedAssetId(ref, home),\n )\n if (hosted.length === 0) return null\n const manifest = cloneManifest(config)\n const indexPath = join(dir, 'assets', HOME_INDEX)\n let index: Record<string, string> = {}\n try {\n const parsed: unknown = JSON.parse(readFileSync(indexPath, 'utf8'))\n if (parsed && typeof parsed === 'object') {\n index = parsed as Record<string, string>\n }\n } catch {\n // no index yet: nothing here is known to be a hosted file\n }\n const files: string[] = []\n for (const { name, index: at, ref } of hosted) {\n const id = hostedAssetId(ref, home)!\n // The manifest name is the config's word and becomes a file name here,\n // so it is held to a plain path segment (the asset id stands in).\n const stem = safePathName(at === null ? name : `${name}-${at}`, id)\n const known = Object.keys(index).find(\n (f) => f === stem || f.startsWith(`${stem}.`),\n )\n let file: string\n if (\n known &&\n index[known] === id &&\n existsSync(join(dir, 'assets', known))\n ) {\n file = `assets/${known}`\n } else {\n // A different hosted file under this name: the old copy goes first,\n // or a changed extension would leave both lying side by side.\n if (known) {\n rmSync(join(dir, 'assets', known), { force: true })\n delete index[known]\n }\n const got = await downloadMedia(ctx, `/api/assets/${id}/file`, {\n dir,\n subdir: 'assets',\n stem,\n fallbackExt: '',\n describe: `${where(name, at)} (asset ${id})`,\n notFoundHint: 'a private file needs a content key of its owner',\n })\n file = got.file\n index[file.slice('assets/'.length)] = id\n log(\n ` ${file} ← ${where(name, at)}, asset ${id} (${Math.round(got.bytes / 1024)} kB)`,\n )\n }\n files.push(file)\n setRef(manifest, name, at, `./${file}`)\n }\n writeFileSafeSync(indexPath, JSON.stringify(index, null, 2) + '\\n')\n return { assets: manifest, files }\n}\n\nconst HOSTED_FILE_LITERAL =\n /(?:asset:|\\/api\\/assets\\/)([0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})/g\nconst FUNCTION_FIELDS = ['setup', 'createContent', 'createTimeline', 'onFrame']\n\n/**\n * A hosted file named inside a function instead of in the manifest. The\n * platform cannot give a string in code a URL per surface, so the file does\n * not reach a render of a private program and does not follow a remix.\n * One line per function and file, in words that say the fix.\n */\nexport function hostedLiteralWarnings(\n config: Record<string, unknown>,\n): string[] {\n const out: string[] = []\n const scan = (label: string, src: unknown) => {\n if (typeof src !== 'string') return\n const seen = new Set<string>()\n for (const m of src.matchAll(HOSTED_FILE_LITERAL)) {\n if (seen.has(m[1])) continue\n seen.add(m[1])\n out.push(\n `${label} names hosted file ${m[1]} in code. Declare it instead: \"assets\": { \"name\": { \"ref\": \"asset:${m[1]}\" } }, and read ctx.assets.name, so it loads on every render and follows a remix`,\n )\n }\n }\n for (const field of FUNCTION_FIELDS) scan(field, config[field])\n const stack = Array.isArray(config.stack) ? config.stack : []\n for (const entry of stack as Record<string, unknown>[]) {\n for (const field of ['setup', 'createContent', 'onFrame']) {\n scan(`stack.${String(entry.id)}.${field}`, entry[field])\n }\n }\n return out\n}\n","/**\n * A name the server chose (a slug, a title, a file name) as a path segment\n * on this disk. The server's word is never trusted as a path: a separator,\n * a `..`, a control character or a leading dot is dropped, everything else\n * collapses to `[A-Za-z0-9._-]`, and a name with nothing left falls back to\n * the id, which is ours to shape.\n */\nexport function safePathName(\n name: string | undefined,\n fallback: string,\n): string {\n const cleaned = (name ?? '')\n // eslint-disable-next-line no-control-regex\n .replace(/[\\u0000-\\u001f\\u007f]/g, '')\n .split(/[\\\\/]/)\n .filter((part) => part !== '' && part !== '.' && part !== '..')\n .join('-')\n .replace(/[^A-Za-z0-9._-]+/g, '-')\n .replace(/^[.-]+/, '')\n .replace(/-+$/, '')\n .slice(0, 80)\n if (cleaned) return cleaned\n const id = fallback.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^[.-]+/, '')\n return id || 'file'\n}\n","import { isKeyedOverlay } from '@vosjs/studio-core'\n/**\n * A hosted take comes home: download the recording (and the\n * mic/cam sidecars when the doc carries them) beside a pulled doc.json, and\n * re-anchor the doc's keys to the local files, so `vos digest`, `frames` and\n * `render` run on a pulled take exactly as on a local one. Also writes the\n * take-dir markers (meta.json, cursor.json) from the doc when absent, so the\n * directory IS a take directory to every other verb.\n *\n * Same consent shape as the upload direction: nothing moves without the verb\n * the user ran (`--media`). A file already on disk is kept, never re-fetched.\n */\nimport { createHash } from 'node:crypto'\nimport { createWriteStream, existsSync } from 'node:fs'\nimport {\n mkdir,\n open,\n readFile,\n readdir,\n rename,\n rm,\n stat,\n} from 'node:fs/promises'\nimport { basename, dirname, join } from 'node:path'\nimport { Readable } from 'node:stream'\nimport { pipeline } from 'node:stream/promises'\nimport { localFile } from '../programAssets'\nimport { refuseSymlink, writeFileSafe } from './safeWrite'\nimport { takeMediaFiles, writeJson } from './take'\nimport {\n MEDIA_HEAD_BYTES,\n extensionFor,\n nameForType,\n resolveMediaType,\n} from './container'\nimport { uploadAsset } from './uploadAsset'\nimport { bearerFor, writeSyncState } from './platform'\nimport type { UploadTarget, UploadedAsset } from './uploadAsset'\nimport type {\n AudioClip,\n ObjectClip,\n OverlayClip,\n ProjectDoc,\n} from '@vosjs/studio-core'\n\n/** The names the recorders write their sidecars under. */\nexport const MIC_NAME = 'mic.webm'\nexport const CAM_NAME = 'cam.webm'\n\n/**\n * A take's own media: the stem each one lives under, and the container to\n * assume when the bytes that come back say nothing. The EXTENSION is not part\n * of the identity — a pulled recording wears whatever its hosted asset holds.\n */\nconst SOURCE_MEDIA = [\n { key: 'videoKey', stem: 'recording', fallbackExt: '.webm' },\n { key: 'micKey', stem: 'mic', fallbackExt: '.webm' },\n { key: 'camKey', stem: 'cam', fallbackExt: '.webm' },\n] as const\n\n/** A take-relative media key: neither a URL, a blob, nor a hosted asset path. */\nexport function isTakeRelativeKey(key: string | undefined): key is string {\n // `media:<id>` names a document media (a layer that shows one); the media\n // itself rides the upload door, so the reference is never a file.\n return (\n !!key &&\n !/^(https?:|blob:|data:|media:|\\/\\/)/.test(key) &&\n !key.startsWith('/api/')\n )\n}\n\n/** The file a take-relative key names, under the take directory. */\nexport const takeRelativeFile = (key: string): string => key.replace(/^\\/+/, '')\n\nexport interface DocMediaRef {\n /** Where the key lives, in words (for a log line). */\n where: string\n key: string\n /** Replace the key in the document. */\n set: (next: string) => void\n}\n\n/**\n * A take's own sidecars, when they are local files: the voice (`micKey`)\n * and the webcam (`camKey`). A push used to DROP them (\"local-only\"), while\n * `vos fetch --media` writes them beside the take as `mic.webm` and\n * `cam.webm`: fetch, then push, and the voice and the webcam were gone from\n * the hosted take, in one log line nobody reads.\n */\nexport function sourceSidecarRefs(\n doc: ProjectDoc,\n keep: (key: string | undefined) => boolean = isTakeRelativeKey,\n): DocMediaRef[] {\n const out: DocMediaRef[] = []\n for (const [field, where] of [\n ['micKey', 'mic track'],\n ['camKey', 'cam track'],\n ] as const) {\n const key = doc.source[field]\n if (!key || !keep(key)) continue\n out.push({\n where,\n key,\n set: (next) => {\n doc.source[field] = next\n },\n })\n }\n return out\n}\n\n/** The 3D props a document places: each names a model file (a GLB). */\nexport function docObjectRefs(\n doc: { objects?: ObjectClip[] },\n keep: (key: string | undefined) => boolean = isTakeRelativeKey,\n): DocMediaRef[] {\n const out: DocMediaRef[] = []\n for (const clip of doc.objects ?? []) {\n const asset = clip.asset as { kind?: string; key?: string }\n if (asset.kind !== 'gltf' || !keep(asset.key)) continue\n out.push({\n where: `object ${clip.id}`,\n key: asset.key as string,\n set: (next) => {\n asset.key = next\n },\n })\n }\n return out\n}\n\n/** The picture and video layers a document places, by key. */\nexport function docOverlayRefs(\n doc: { overlays?: OverlayClip[] },\n keep: (key: string | undefined) => boolean = isTakeRelativeKey,\n): DocMediaRef[] {\n const out: DocMediaRef[] = []\n for (const clip of doc.overlays ?? []) {\n // An HTML layer has no key: its content IS its source. Its only files are\n // the faces it brings (`fonts`), each a url the page fetches, so a face\n // still beside the document crosses like any other layer file.\n if (clip.kind === 'html') {\n for (const [i, font] of (clip.fonts ?? []).entries()) {\n if (!keep(font.url)) continue\n out.push({\n where: `overlay ${clip.id} font ${i}`,\n key: font.url,\n set: (next) => {\n font.url = next\n },\n })\n }\n continue\n }\n if (!isKeyedOverlay(clip) || !keep(clip.key)) continue\n out.push({\n where: `overlay ${clip.id}`,\n key: clip.key,\n set: (next) => {\n clip.key = next\n },\n })\n }\n return out\n}\n\n/**\n * The shared layers either kind of document carries, as files: picture and\n * video overlays, 3D props, and added sound. A program document has no\n * recording, frame or end card, so this is all it can name; a take reads\n * the same three through `docMediaRefs`.\n */\nexport function docLayerRefs(\n doc: {\n overlays?: OverlayClip[]\n objects?: ObjectClip[]\n audio?: AudioClip[]\n },\n keep: (key: string | undefined) => boolean = isTakeRelativeKey,\n): DocMediaRef[] {\n return [\n ...docOverlayRefs(doc, keep),\n ...docObjectRefs(doc, keep),\n ...docAudioRefs(doc, keep),\n ]\n}\n\n/**\n * Every media key a document carries beside its recording, mic and cam:\n * image and video overlay clips (a poster's mark), 3D props, the end card's\n * mark, a background image or loop, added sound. The recording's own keys\n * are `KEYS` and handled by their own path. A push rehosts these; a pull\n * brings them home.\n */\nexport function docMediaRefs(\n doc: ProjectDoc,\n keep: (key: string | undefined) => boolean = isTakeRelativeKey,\n): DocMediaRef[] {\n const out: DocMediaRef[] = []\n // The take's OTHER media (concat): each recording, and its sidecars,\n // rides the upload door like the primary's; a pull brings them home.\n for (const m of doc.media ?? []) {\n if (keep(m.videoKey))\n out.push({\n where: `media ${m.id}`,\n key: m.videoKey,\n set: (next) => {\n m.videoKey = next\n },\n })\n const mic = m.micKey\n if (mic && keep(mic))\n out.push({\n where: `media ${m.id} mic`,\n key: mic,\n set: (next) => {\n m.micKey = next\n },\n })\n const cam = m.camKey\n if (cam && keep(cam))\n out.push({\n where: `media ${m.id} cam`,\n key: cam,\n set: (next) => {\n m.camKey = next\n },\n })\n }\n out.push(...docOverlayRefs(doc, keep))\n // A prop's model was never walked: a take with a GLB pushed a document\n // whose object keyed a file only the pusher's disk held.\n out.push(...docObjectRefs(doc, keep))\n const mark = doc.endCard?.mark\n if (mark && keep(mark.key))\n out.push({\n where: 'end card mark',\n key: mark.key,\n set: (next) => {\n mark.key = next\n },\n })\n const bg = doc.frame.backgroundMedia\n if (bg && keep(bg.key))\n out.push({\n where: 'background',\n key: bg.key,\n set: (next) => {\n bg.key = next\n },\n })\n out.push(...docAudioRefs(doc, keep))\n return out\n}\n\n/**\n * The sound a document adds (`doc.audio`: a score, a voice-over, an effect),\n * for either kind of document. A take reads it through `docMediaRefs`; a\n * program document, which has no recording or frame, reads it here. A\n * catalog track is an absolute URL and is never walked.\n */\nexport function docAudioRefs(\n doc: { audio?: AudioClip[] },\n keep: (key: string | undefined) => boolean = isTakeRelativeKey,\n): DocMediaRef[] {\n const out: DocMediaRef[] = []\n for (const clip of doc.audio ?? []) {\n if (!keep(clip.key)) continue\n out.push({\n where: `audio ${clip.id}`,\n key: clip.key,\n set: (next) => {\n // The same bytes under a new name (uploaded, or brought home): a\n // measurement taken for the old name holds for the new one.\n if (clip.loudness?.src === clip.key) clip.loudness.src = next\n clip.key = next\n },\n })\n }\n return out\n}\n\n/**\n * Upload the files a document names and point its keys at the hosted\n * assets. Each file rides the content-addressed upload door, so a re-push\n * reuses it; the bytes name the type, and the uploaded filename is corrected\n * to match so the asset is never self-contradictory. A key whose file is\n * missing is said and left as it is (the hosted render will 404 on it,\n * honestly). Take pushes and program pushes share it.\n */\nexport async function uploadDocRefs(\n refs: DocMediaRef[],\n dir: string,\n target: UploadTarget,\n log: (line: string) => void,\n): Promise<void> {\n for (const ref of refs) {\n // The key names a file in the take directory or below, never outside\n // it: a fetched or pasted document is not trusted with the disk.\n const local = localFile(takeRelativeFile(ref.key), dir)\n if ('refused' in local) {\n log(\n `warning ${ref.where}: ${ref.key} is not beside the document, so it was not uploaded`,\n )\n continue\n }\n const file = local.file\n const media = await readFile(file)\n const mediaHash = createHash('sha256').update(media).digest('hex')\n const { type } = resolveMediaType({\n head: media.subarray(0, MEDIA_HEAD_BYTES),\n filename: file,\n })\n const name = nameForType(basename(file), type)\n if (name !== basename(file)) {\n log(` ${ref.where}: ${basename(file)} holds ${type} — sent as ${name}`)\n }\n let put: UploadedAsset\n try {\n put = await uploadAsset(target, new Uint8Array(media), {\n filename: name,\n contentType: type,\n contentHash: mediaHash,\n })\n } catch (e) {\n throw new Error(\n `${ref.where} upload failed: ${e instanceof Error ? e.message : String(e)}`,\n )\n }\n ref.set(put.url)\n log(\n ` ${ref.where}: ${ref.key} → asset ${put.id}${put.reused ? ' (reused)' : ''}`,\n )\n for (const note of put.notes) log(` ${ref.where}: ${note}`)\n }\n}\n\n// The extension↔type table and the byte sniffer live in `container.ts`; these\n// stay the door every media caller already knows.\nexport { extensionFor, mediaContentType } from './container'\n\n/** An asset file URL (relative `/api/assets/{id}/file` or absolute). */\nexport function assetIdOf(url: string | undefined): string | null {\n if (!url) return null\n const m = /\\/api\\/assets\\/([A-Za-z0-9_-]+)\\/file/.exec(url)\n return m ? m[1] : null\n}\n\nexport interface MediaPullResult {\n downloaded: { file: string; assetId: string; bytes: number }[]\n kept: string[]\n /** Every hosted file now beside the take, downloaded or kept: its path\n * here and the address it came from. */\n hosted: { file: string; url: string }[]\n}\n\n/** The first bytes of a file, enough for every container signature. */\nexport async function readMediaHead(file: string): Promise<Uint8Array> {\n const handle = await open(file, 'r')\n try {\n const buf = Buffer.alloc(MEDIA_HEAD_BYTES)\n const { bytesRead } = await handle.read(buf, 0, MEDIA_HEAD_BYTES, 0)\n return new Uint8Array(buf.subarray(0, bytesRead))\n } finally {\n await handle.close()\n }\n}\n\nexport interface DownloadTarget {\n dir: string\n /** Directory under the take dir, when the file is filed away. */\n subdir?: string\n /** The name without its extension — the extension is the BYTES' to choose. */\n stem: string\n /** The container to assume when the bytes say nothing. */\n fallbackExt: string\n /** What is being fetched, in words, for an error or a log line. */\n describe: string\n /** Added to a 404, where the reason is usually the credential. */\n notFoundHint?: string\n}\n\n/**\n * One media file, brought home under the name its BYTES earn.\n *\n * Streamed to a `.part` sibling first, then sniffed and renamed, so a take\n * never holds a file whose extension lies — whatever the server declared, and\n * whatever the hosted asset happened to be called. A push of a pulled take\n * re-uploads that file, so a wrong name here becomes a wrong Content-Type on\n * the asset, and a render that dies inside the video element.\n */\n/**\n * Where a document key is fetched from, and whether the content key rides\n * along. The key goes ONLY to the configured origin: a hosted file named\n * as a file-door address on some other host is read from the home door by\n * its id, and any other URL is fetched bare, so a stranger's document\n * can never send the reader's credential elsewhere.\n */\nexport function downloadPlan(\n ctx: { origin: string },\n url: string,\n): { url: string; bearer: boolean } {\n const home = new URL(ctx.origin).origin\n if (!/^https?:/.test(url)) return { url: `${home}${url}`, bearer: true }\n let abs: URL\n try {\n abs = new URL(url)\n } catch {\n return { url, bearer: false }\n }\n if (abs.origin === home) return { url: abs.href, bearer: true }\n const id = assetIdOf(url)\n if (id) return { url: `${home}/api/assets/${id}/file`, bearer: true }\n return { url: abs.href, bearer: false }\n}\n\nexport async function downloadMedia(\n ctx: { origin: string; key: string | null },\n url: string,\n target: DownloadTarget,\n): Promise<{ file: string; bytes: number }> {\n const plan = downloadPlan(ctx, url)\n const res = await fetch(plan.url, {\n headers: plan.bearer ? bearerFor(ctx.key, plan.url) : {},\n })\n if (!res.ok || !res.body) {\n throw new Error(\n `download of ${target.describe} failed (${res.status})${\n res.status === 404 && target.notFoundHint\n ? ` — ${target.notFoundHint}`\n : ''\n }`,\n )\n }\n const into = target.subdir ? join(target.dir, target.subdir) : target.dir\n const partial = join(into, `${target.stem}.part`)\n await mkdir(dirname(partial), { recursive: true })\n // A link already at the path would carry the bytes wherever it points.\n await refuseSymlink(partial)\n try {\n await pipeline(\n Readable.fromWeb(res.body as never),\n createWriteStream(partial),\n )\n const { type } = resolveMediaType({\n head: await readMediaHead(partial),\n declared: res.headers.get('content-type'),\n filename: `${target.stem}${target.fallbackExt}`,\n })\n const name = `${target.stem}${extensionFor(type) || target.fallbackExt}`\n await refuseSymlink(join(into, name))\n await rename(partial, join(into, name))\n const file = target.subdir ? `${target.subdir}/${name}` : name\n return { file, bytes: (await stat(join(target.dir, file))).size }\n } finally {\n // A rename leaves nothing behind; a failed transfer must not.\n await rm(partial, { force: true })\n }\n}\n\nexport async function pullMedia(\n ctx: { origin: string; key: string | null },\n dir: string,\n doc: ProjectDoc,\n log: (line: string) => void,\n): Promise<MediaPullResult> {\n const result: MediaPullResult = { downloaded: [], kept: [], hosted: [] }\n for (const { key, stem, fallbackExt } of SOURCE_MEDIA) {\n const url = doc.source[key]\n const assetId = assetIdOf(url)\n if (!assetId) continue\n // A file already here is kept whatever container it wears, so a second\n // pull never re-fetches and never leaves two of the same footage.\n const present = takeMediaFiles(dir, stem)[0]\n if (present) {\n result.kept.push(basename(present))\n result.hosted.push({ file: basename(present), url: url! })\n doc.source[key] = basename(present)\n continue\n }\n const got = await downloadMedia(ctx, url!, {\n dir,\n stem,\n fallbackExt,\n describe: stem,\n notFoundHint: 'a private recording needs a content key of its owner',\n })\n result.downloaded.push({ file: got.file, assetId, bytes: got.bytes })\n log(` ${got.file} ← asset ${assetId} (${Math.round(got.bytes / 1024)} kB)`)\n result.hosted.push({ file: got.file, url: url! })\n doc.source[key] = got.file\n }\n // The document's other media (a poster's mark, a pasted ground): a hosted\n // asset comes home under media/<assetId>.<ext> and the key re-anchors to\n // it, so the pulled poster renders and re-pushes as a whole.\n for (const ref of docMediaRefs(doc, (k) => assetIdOf(k) !== null)) {\n const assetId = assetIdOf(ref.key)!\n const existing = existsSync(join(dir, 'media'))\n ? (await readdir(join(dir, 'media'))).find(\n (f) => f === assetId || f.startsWith(`${assetId}.`),\n )\n : undefined\n if (existing) {\n const file = `media/${existing}`\n result.kept.push(file)\n result.hosted.push({ file, url: ref.key })\n ref.set(file)\n continue\n }\n const got = await downloadMedia(ctx, ref.key, {\n dir,\n subdir: 'media',\n stem: assetId,\n // A type with no extension here (an svg served as such) keeps the bare\n // asset id, exactly as before.\n fallbackExt: '',\n describe: `${ref.where} (${ref.key})`,\n })\n result.downloaded.push({ file: got.file, assetId, bytes: got.bytes })\n log(\n ` ${got.file} ← ${ref.where}, asset ${assetId} (${Math.round(got.bytes / 1024)} kB)`,\n )\n result.hosted.push({ file: got.file, url: ref.key })\n ref.set(got.file)\n }\n // The take-dir markers: meta.json and cursor.json live on the doc for a\n // hosted take; write them out so loadTake() recognizes the directory.\n const metaPath = join(dir, 'meta.json')\n if (!existsSync(metaPath)) await writeJson(metaPath, doc.source.meta, true)\n const cursorPath = join(dir, 'cursor.json')\n if (!existsSync(cursorPath)) await writeJson(cursorPath, doc.source.cursor)\n await writeFileSafe(join(dir, 'doc.json'), JSON.stringify(doc, null, 2))\n return result\n}\n\n/** The sha256 of a file beside the take, hex. */\nexport async function fileSha256(file: string): Promise<string> {\n return createHash('sha256')\n .update(await readFile(file))\n .digest('hex')\n}\n\n/**\n * Write what a pull brought home into vos.json (`hostedMedia`): each file's\n * path here, the address it came from, and its sha256 now. A claimable push\n * of the take names those originals instead of uploading, and only while\n * the bytes are the ones that were fetched.\n */\nexport async function recordHostedMedia(\n dir: string,\n vosId: string,\n pulled: MediaPullResult,\n): Promise<void> {\n if (pulled.hosted.length === 0) return\n const hostedMedia: Record<string, { ref: string; sha256: string }> = {}\n for (const { file, url } of pulled.hosted) {\n hostedMedia[file] = { ref: url, sha256: await fileSha256(join(dir, file)) }\n }\n writeSyncState(dir, { vosId, hostedMedia })\n}\n","/**\n * The take directory — the CLI's unit of work, human-inspectable on purpose:\n * take/\n * recording.webm encoded footage (CFR; .mp4 when a pull brought it home\n * in that container, so readers RESOLVE the name)\n * frames/ raw screencast JPEGs + frames.json (kept for re-encode)\n * cursor.json synthesized CursorTrack\n * meta.json RecordingMeta (producer: 'cli')\n * actions.json the script that produced it (replay recipe)\n * doc.json ProjectDoc — the agent-editable surface\n */\nimport { mkdir, readFile, rename, rm } from 'node:fs/promises'\nimport { existsSync, readdirSync, statSync } from 'node:fs'\nimport { writeFileSafe } from './safeWrite'\nimport { basename, join } from 'node:path'\nimport { TAKE_MEDIA_EXTENSIONS } from './container'\nimport type { CursorTrack, ProjectDoc, RecordingMeta } from '@vosjs/studio-core'\nimport type { ActionsFile } from './actions'\n\n/** The name `record` writes its footage under — its encoder emits WebM. */\nexport const RECORDING_NAME = 'recording.webm'\n\n/**\n * A take's own media under `dir`, whatever container it came home in.\n *\n * `record` writes WebM, but a PULLED take wears the container its hosted asset\n * actually holds, so nothing may spell `recording.webm` at a read site: a take\n * whose footage is mp4 must still render, digest and push. Ordered by\n * `TAKE_MEDIA_EXTENSIONS`, so the answer is deterministic if a stale sibling\n * survives.\n */\nexport function takeMediaFiles(dir: string, stem: string): string[] {\n return TAKE_MEDIA_EXTENSIONS.map((ext) => join(dir, `${stem}${ext}`)).filter(\n (file) => existsSync(file),\n )\n}\n\n/**\n * The one file a take's media stem names, falling back to what `record` would\n * write — so a caller can `existsSync` the answer and get an honest\n * \"no footage here\" rather than a path that never existed.\n */\nexport function takeMediaFile(\n dir: string,\n stem: string,\n fallback: string,\n): string {\n return takeMediaFiles(dir, stem)[0] ?? join(dir, fallback)\n}\n\n/** The previous cut, preserved by a re-record. */\nexport const PREV_DOC_NAME = 'doc.prev.json'\n\nexport interface TakePaths {\n dir: string\n recording: string\n /** The recording's bare filename — what a doc key or a served URL spells. */\n recordingName: string\n framesDir: string\n framesIndex: string\n cursor: string\n meta: string\n actions: string\n doc: string\n}\n\nexport function takePaths(dir: string): TakePaths {\n const recording = takeMediaFile(dir, 'recording', RECORDING_NAME)\n return {\n dir,\n recording,\n recordingName: basename(recording),\n framesDir: join(dir, 'frames'),\n framesIndex: join(dir, 'frames.json'),\n cursor: join(dir, 'cursor.json'),\n meta: join(dir, 'meta.json'),\n actions: join(dir, 'actions.json'),\n doc: join(dir, 'doc.json'),\n }\n}\n\nexport async function ensureTakeDir(dir: string): Promise<TakePaths> {\n const p = takePaths(dir)\n await mkdir(p.framesDir, { recursive: true })\n return p\n}\n\n/**\n * Drop the screencast JPEGs once the recording they were encoded into is on\n * disk. They are the bulk of a take (one hero take: 437 MB of a 452 MB\n * directory) and nothing needs them afterwards: the digest reads frames\n * from them WHEN PRESENT and from the video otherwise, which is the path\n * every pulled take already runs on. Refuses unless the recording exists and\n * has bytes, so a failed encode never costs the only copy of the footage.\n * Returns the bytes freed, 0 when it left everything alone.\n */\nexport async function dropScreencastFrames(p: TakePaths): Promise<number> {\n if (!existsSync(p.recording) || statSync(p.recording).size === 0) return 0\n if (!existsSync(p.framesDir)) return 0\n let freed = 0\n for (const name of readdirSync(p.framesDir)) {\n try {\n freed += statSync(join(p.framesDir, name)).size\n } catch {\n // a file gone between the listing and the stat frees nothing\n }\n }\n await rm(p.framesDir, { recursive: true, force: true })\n await rm(p.framesIndex, { force: true })\n return freed\n}\n\n/**\n * Re-record into an existing take WITHOUT destroying the cut (the\n * re-render loop's first rung; `rm -rf` here is what made \"re-renders on the\n * next version\" a false claim). What the old footage produced is cleared\n * (recording, cursor, meta, raw frames, stills/, digest/ — all derived and\n * regenerable); what the human's work lives in survives: `doc.json` moves to\n * `doc.prev.json` — the explicit reuse base `vos plan --reuse` re-anchors\n * onto the new recording — and `actions.json` + `vos.json` stay put. The doc\n * is MOVED, never left in place: a doc.json embeds its footage's cursor and\n * meta (`doc.source`), so leaving it beside new footage would be a document\n * lying about its source, and the auto-plan after recording would replan\n * from the OLD cursor. Returns what was kept, for the terminal to say.\n */\nexport async function prepareReRecord(\n dir: string,\n): Promise<{ prevDoc: boolean; kept: string[] }> {\n const p = takePaths(dir)\n const kept: string[] = []\n let prevDoc = false\n if (existsSync(p.doc)) {\n await rename(p.doc, join(dir, PREV_DOC_NAME))\n prevDoc = true\n kept.push(PREV_DOC_NAME)\n }\n if (existsSync(p.actions)) kept.push('actions.json')\n if (existsSync(join(dir, 'vos.json'))) kept.push('vos.json')\n for (const stale of [\n // Every container, not just the one `record` writes: a pulled take's\n // footage may be mp4, and a survivor would outrank the new recording.\n ...takeMediaFiles(dir, 'recording'),\n ...takeMediaFiles(dir, 'mic'),\n ...takeMediaFiles(dir, 'cam'),\n p.cursor,\n p.meta,\n p.framesIndex,\n p.framesDir,\n join(dir, 'stills'),\n join(dir, 'digest'),\n // What the last run's download steps kept: this run downloads again.\n join(dir, 'outputs'),\n // The sound the last run's page played: this run hears it again.\n join(dir, 'page-sound'),\n ]) {\n await rm(stale, { recursive: true, force: true })\n }\n return { prevDoc, kept }\n}\n\nexport async function readJson<T>(file: string): Promise<T> {\n return JSON.parse(await readFile(file, 'utf8')) as T\n}\n\nexport async function writeJson(\n file: string,\n value: unknown,\n pretty = false,\n): Promise<void> {\n await writeFileSafe(\n file,\n pretty ? JSON.stringify(value, null, 2) : JSON.stringify(value),\n )\n}\n\nexport interface TakeData {\n paths: TakePaths\n cursor: CursorTrack\n meta: RecordingMeta\n actions: ActionsFile | null\n doc: ProjectDoc | null\n}\n\n/** Load a take directory; cursor+meta are required, doc/actions optional. */\nexport async function loadTake(dir: string): Promise<TakeData> {\n const paths = takePaths(dir)\n if (!existsSync(paths.meta)) {\n throw new Error(\n `${dir} is not a take directory (missing meta.json) — run record first`,\n )\n }\n const meta = await readJson<RecordingMeta>(paths.meta)\n const cursor = existsSync(paths.cursor)\n ? await readJson<CursorTrack>(paths.cursor)\n : []\n const actions = existsSync(paths.actions)\n ? await readJson<ActionsFile>(paths.actions)\n : null\n const doc = existsSync(paths.doc)\n ? await readJson<ProjectDoc>(paths.doc)\n : null\n return { paths, cursor, meta, actions, doc }\n}\n","/**\n * Uploading a file to vos.so: one door, for every kind and every size.\n *\n * The file is declared first, sent as parts, and sealed. Three reasons it\n * is never one request:\n *\n * - A request body has a ceiling the platform does not set and cannot\n * raise from inside a handler: the edge refuses anything past it before\n * the request arrives, with its own error page rather than a worded\n * refusal. A screen recording of any real length clears that ceiling.\n * - Everything the platform may refuse a file for (its kind, its size, a\n * daily rate, the account's storage) is weighed at the declaring call,\n * before a byte moves, so a refusal costs nothing and arrives in words.\n * - The declaring call is content-addressed: the same bytes pushed twice\n * are recognised and never re-sent, which is what keeps an iterating\n * push from re-uploading a take on every round.\n *\n * The part size is NOT decided here. The platform returns it from the\n * declaring call, so the split can change server-side without a CLI\n * release.\n *\n * What the file IS comes back from the sealing call: the platform reads\n * the stored bytes and answers its kind, the name it is stored under and\n * anything worth saying about it. Nothing here decides what is accepted;\n * `GET /api/limits` lists the kinds and their caps.\n */\nimport { apiJson } from './platform'\nimport type { ApiResult } from './platform'\n\n/** Attempts per part. A part commits nothing until the upload is sealed,\n * so it is always safe to send again. */\nconst PART_ATTEMPTS = 3\n\nexport interface PartPlan {\n /** Part numbers are 1-based. */\n partNumber: number\n start: number\n /** One past the last byte. */\n end: number\n}\n\n/**\n * The slices to send, in order. Every part but the last is exactly\n * `partBytes`; the last is the remainder. The platform holds each part to\n * exactly this length, so the split has to agree with the size that was\n * declared — which is why `partBytes` comes from the platform rather than\n * from a constant here.\n */\nexport function planParts(totalBytes: number, partBytes: number): PartPlan[] {\n if (totalBytes <= 0 || partBytes <= 0) return []\n const parts: PartPlan[] = []\n for (let start = 0; start < totalBytes; start += partBytes) {\n parts.push({\n partNumber: parts.length + 1,\n start,\n end: Math.min(start + partBytes, totalBytes),\n })\n }\n return parts\n}\n\nexport interface UploadedAsset {\n id: string\n /** The path a document names the file by. */\n url: string\n size: number\n /** The platform already had these exact bytes; nothing was sent. */\n reused: boolean\n /** What the bytes are, as the platform read them (video, audio, image,\n * vector, model, font, hdr, recipe, captions). */\n kind: string\n /** The name it is stored under: the extension follows the bytes. */\n filename: string\n /** The frontmatter summary of a recipe, a picture's size, a clip's codec. */\n metadata: Record<string, unknown> | null\n /** What the platform did to the file or wants said about it. */\n notes: string[]\n /** The reference a program's manifest takes. */\n ref: string\n /** Seconds, for what plays. */\n duration: number | null\n}\n\nexport interface UploadTarget {\n origin: string\n /** The bearer: a content key, or a claimable push's session token. */\n key: string\n /**\n * The door's path. The account's by default; a claimable push sends its\n * files through `/api/claim/uploads/files`, which speaks the same\n * protocol under its session token.\n */\n door?: string\n}\n\nexport interface UploadOptions {\n filename: string\n /** Only a hint: the platform types a file by its bytes. It settles the\n * one thing bytes cannot, a WebM that holds sound alone. */\n contentType?: string\n /** sha256 hex — the platform dedupes on it, per owner. */\n contentHash: string\n /** The take's length, so a refusal for one past the hosted cap arrives\n * before anything is sent. The platform measures the file either way. */\n durationSeconds?: number\n /** Parts landed, for a caller that reports a long upload's progress. */\n onPart?: (done: number, total: number) => void\n /** File the asset into one of the caller's folders. */\n folderId?: string\n /**\n * `library`: a file added to keep (`vos asset push`, a recipe).\n * `attached` (the default): a file a document is about to name, which\n * the platform collects if nothing ever does.\n */\n intent?: 'library' | 'attached'\n /**\n * Where the file came from, as the uploader states it: kept beside the\n * file and shown with it. The platform does not check it.\n */\n provenance?: { sourceUrl?: string; license?: string; attribution?: string }\n}\n\nfunction failed(what: string, r: ApiResult): Error {\n const detail = typeof r.body.error === 'string' ? r.body.error : ''\n const hint = typeof r.body.hint === 'string' ? ` ${r.body.hint}` : ''\n return new Error(`${what} (${r.status})${detail ? `: ${detail}${hint}` : ''}`)\n}\n\nfunction asAsset(\n body: Record<string, unknown>,\n reused: boolean,\n): UploadedAsset {\n const asset = (body.asset ?? {}) as Record<string, unknown>\n return {\n id: String(asset.id),\n url: String(asset.fileUrl),\n size: typeof asset.size === 'number' ? asset.size : 0,\n reused,\n kind: typeof asset.kind === 'string' ? asset.kind : '',\n filename: typeof asset.filename === 'string' ? asset.filename : '',\n metadata:\n asset.metadata && typeof asset.metadata === 'object'\n ? (asset.metadata as Record<string, unknown>)\n : null,\n notes: Array.isArray(body.notes)\n ? body.notes.filter((n): n is string => typeof n === 'string')\n : [],\n ref:\n typeof asset.ref === 'string' ? asset.ref : `asset:${String(asset.id)}`,\n duration: typeof asset.duration === 'number' ? asset.duration : null,\n }\n}\n\n/** Worth sending again: the platform was busy or briefly unreachable. A\n * refusal is a decision and will read the same on a second try. */\nfunction transient(status: number): boolean {\n return status >= 500 || status === 429\n}\n\nconst wait = (ms: number) => new Promise((r) => setTimeout(r, ms))\n\n/** Upload one file as an owned asset: declare it, send its parts, seal it. */\nexport async function uploadAsset(\n target: UploadTarget,\n bytes: Uint8Array,\n opts: UploadOptions,\n): Promise<UploadedAsset> {\n // Declare it first. Every quota is weighed here, before a byte moves, so\n // a refusal costs nothing and arrives in words — and the dedupe answers\n // here too, which is what makes re-pushing a hosted take free.\n const door = target.door ?? '/api/assets/uploads'\n const begun = await apiJson(target.origin, door, {\n method: 'POST',\n key: target.key,\n body: {\n filename: opts.filename,\n ...(opts.contentType ? { contentType: opts.contentType } : {}),\n size: bytes.length,\n sha256: opts.contentHash,\n ...(opts.durationSeconds && opts.durationSeconds > 0\n ? { durationSeconds: opts.durationSeconds }\n : {}),\n ...(opts.folderId ? { folderId: opts.folderId } : {}),\n ...(opts.intent ? { intent: opts.intent } : {}),\n },\n })\n if (begun.status !== 201 && begun.status !== 200) {\n throw failed('upload failed', begun)\n }\n // The platform already holds these bytes: nothing to send.\n if (begun.body.asset) return asAsset(begun.body, true)\n\n const uploadId = String(begun.body.uploadId)\n const partBytes = Number(begun.body.partBytes)\n if (!Number.isFinite(partBytes) || partBytes <= 0) {\n throw new Error('upload failed: the platform returned no part size')\n }\n const parts = planParts(bytes.length, partBytes)\n const etags: { partNumber: number; etag: string }[] = []\n\n try {\n for (const part of parts) {\n const chunk = bytes.subarray(part.start, part.end)\n let sent: ApiResult | null = null\n for (let attempt = 1; attempt <= PART_ATTEMPTS; attempt++) {\n try {\n sent = await apiJson(\n target.origin,\n `${door}/${uploadId}/parts/${part.partNumber}`,\n {\n method: 'PUT',\n key: target.key,\n headers: {\n 'Content-Type': 'application/octet-stream',\n 'Content-Length': String(chunk.length),\n },\n raw: chunk,\n },\n )\n } catch (networkError) {\n // Dropped connection, a sleeping machine: worth another try.\n if (attempt === PART_ATTEMPTS) throw networkError\n await wait(500 * 2 ** (attempt - 1))\n continue\n }\n if (sent.status === 200) break\n if (!transient(sent.status) || attempt === PART_ATTEMPTS) {\n throw failed(`part ${part.partNumber} failed`, sent)\n }\n await wait(500 * 2 ** (attempt - 1))\n }\n if (!sent || sent.status !== 200) {\n throw new Error(`part ${part.partNumber} failed`)\n }\n etags.push({\n partNumber: Number(sent.body.partNumber),\n etag: String(sent.body.etag),\n })\n opts.onPart?.(etags.length, parts.length)\n }\n\n // Sealing is where the platform reads the file. A refusal here means\n // the bytes are not what the name said, and it has already taken them\n // back out.\n const sealed = await apiJson(\n target.origin,\n `${door}/${uploadId}/complete`,\n {\n method: 'POST',\n key: target.key,\n body: {\n parts: etags,\n ...(opts.provenance ? { provenance: opts.provenance } : {}),\n },\n },\n )\n if (sealed.status !== 201 && sealed.status !== 200) {\n throw failed('upload failed', sealed)\n }\n // The platform hashes what it stored: bytes this account already held\n // come back as the file it had, whatever was declared.\n return asAsset(sealed.body, sealed.body.reused === true)\n } catch (err) {\n // Hand the parts back rather than leaving them held server-side.\n await apiJson(target.origin, `${door}/${uploadId}`, {\n method: 'DELETE',\n key: target.key,\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EA,IAAM,sBACJ;AACF,IAAM,kBAAkB,CAAC,SAAS,iBAAiB,kBAAkB,SAAS;AAQvE,SAAS,sBACd,QACU;AACV,QAAM,MAAgB,CAAC;AACvB,QAAM,OAAO,CAAC,OAAe,QAAiB;AAC5C,QAAI,OAAO,QAAQ,SAAU;AAC7B,UAAM,OAAO,oBAAI,IAAY;AAC7B,eAAW,KAAK,IAAI,SAAS,mBAAmB,GAAG;AACjD,UAAI,KAAK,IAAI,EAAE,CAAC,CAAC,EAAG;AACpB,WAAK,IAAI,EAAE,CAAC,CAAC;AACb,UAAI;AAAA,QACF,GAAG,KAAK,sBAAsB,EAAE,CAAC,CAAC,qEAAqE,EAAE,CAAC,CAAC;AAAA,MAC7G;AAAA,IACF;AAAA,EACF;AACA,aAAW,SAAS,gBAAiB,MAAK,OAAO,OAAO,KAAK,CAAC;AAC9D,QAAM,QAAQ,MAAM,QAAQ,OAAO,KAAK,IAAI,OAAO,QAAQ,CAAC;AAC5D,aAAW,SAAS,OAAoC;AACtD,eAAW,SAAS,CAAC,SAAS,iBAAiB,SAAS,GAAG;AACzD,WAAK,SAAS,OAAO,MAAM,EAAE,CAAC,IAAI,KAAK,IAAI,MAAM,KAAK,CAAC;AAAA,IACzD;AAAA,EACF;AACA,SAAO;AACT;","names":["existsSync","join","existsSync","mkdir","readFile","rename","rm","basename","join","where","readFile","basename","join","mkdir","rename","rm","existsSync","join","existsSync"]}