Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.
TypeScript agentic-aiaiai-agentsai-videocompilerdslffmpeggenerative-aillmmarkup-languagemonorepoplugin-systemprogramming-languagetext-to-videotypescriptvideovideo-automationvideo-clonevideo-editingvideo-generation
merge: integrate upload lifecycle fixes and restore Quickstart demonstrations
kashorin88c3deab5bcb
diff --cc docs/guide/develop.mdindex 661520bf,f270a657..2a322a87--- a/docs/guide/develop.md+++ b/docs/guide/develop.md@@@ -53,7 -55,7 +53,7 @@@ hypit| Guide | Topic ||---|---|| [Hypit Skill Architecture](./skill.md) | Route entry points, tools, handoffs and durable JSON state |--| [Package architecture](./packages.md) | The five layers, dependency rules, package anatomy, facets |++| [Package architecture](./packages.md) | Layers, dependency rules, package anatomy, facets || [Adding an author package](./author-packages.md) | Step-by-step: new component, Surface, vocabulary and preview, activation || [Adding a Provider](./providers.md) | Step-by-step: new Endpoint adapter || [Runtime](./runtime.md) | Profile, Workspace, execution and lifecycle boundaries |diff --cc docs/guide/testing.mdindex 36c4d4ea,3e01c4da..545f2cd7--- a/docs/guide/testing.md+++ b/docs/guide/testing.md@@@ -98,6 -100,6 +98,5 @@@ Test fixtures go in `packages/<name>/teordinary `.svml`, `.svs` and `.svrun` files that exercise specific compilation paths.The `examples/` directory also serves as integration-level fixtures:--- `examples/bootstrap/` — smallest source closure check--- `examples/talking-film-graph-check/` — complete graph compilation without Providers--- `examples/talking-head-aroll/` — live example with explicit prior-Build Candidate reuse++- `examples/interview/`, `examples/podcast/` and `examples/ranking-football/` — complete video projects with Sources, Runs and assets.++- `examples/minimal-author-package/` — a complete component package with a Surface preview.diff --cc docs/quickstart.mdindex 043d9219,48b9c870..eabe42cf--- a/docs/quickstart.md+++ b/docs/quickstart.md@@@ -4,8 -4,8 +4,8 @@@ description: Create, review and ship Hy---You do not need to know SVML, SVS, JavaScript or the command line. Describe your video in ordinary--language; the Agent uses the `/hypit` skill to create or reconstruct it and provides a Studio mock--for review before any paid Build.++language; the Agent uses the `/hypit` skill to understand the reference, direct the work and deliver++a video with an editable project.## What you need@@@ -20,7 -20,7 +20,9 @@@ Install the Hypit skillnpx skills add hypit-ai/hypit -g```--Then start a Coding Agent anywhere; the Hypit skill is available globally.++Then start a Coding Agent anywhere; the Hypit skill is available globally. The Skill supplies++production knowledge. The Agent checks whether the Hypit command is installed and sets up the++executable tools when needed.## 2. Describe the video you want@@@ -62,88 -64,100 +66,76 @@@ You can add constraints such as audiencor aspect ratio. The Agent turns the brief into a complete plan and fills in production details fromthe information you provide.-## 3. Configure credentials+## 3. Provide credentials when the Agent asks+ <video controls playsInline preload="metadata" width="100%" src="./quickstart/videos/provide_credentials_when_the_agent_asks.mp4"></video>+-After you describe the video, the Agent checks which models and services the project needs. Hypit-uses HypiHub OAuth by default for hosted models. If that credential is missing, tell the Agent to-sign in to HypiHub; the Agent runs the login command, opens the browser flow and stores the session-in the secure OS credential store. The login itself does not submit a paid generation.+After you describe the video, the Agent checks which models and services the project needs. If a+required credential is missing, it will ask you for it and explain what it is used for. You have two+options:-Only if you explicitly choose an author-owned Provider should you configure its API key instead. The-Agent requests only the credentials declared by the selected Runtime Profile; it does not silently-switch Providers because one credential is unavailable.+1. **Use Hypit's recommended Hypit.ai OAuth login.** Tell the Agent to log in through hypit.ai. This+ single OAuth flow covers all models that Hypit provides through its hosted service, so you do not+ need to collect separate keys for each model.+2. **Use your own provider keys.** You can tell the Agent which models to use and provide API keys+ from the corresponding providers. The Agent will request only the keys needed for this project+ and will not ask for unrelated credentials.Never paste a secret into a public document or commit it to Git. The Agent stores credentials usingthe configured secure credential store.## 4. Let the Agent do the production work- Once you submit the brief, the Agent works through the project automatically without requiring you to- write source code. It does not ask questions during production; wait for the Studio mock. The exact- sequence depends on the video, but it generally includes:-- 1. **Breaking the request into shots.** The Agent identifies the spoken sections, visual beats,- transitions, captions, B-roll opportunities and any persistent elements such as a ranking board.- 2. **Analyzing the reference or brief.** For a clone, it watches the reference and uses timed frames and transcripts to- inspect timing, composition, text, speakers and visual continuity. For an original, it resolves- the same questions from your description and the selected creative direction.- 3. **Resolving details.** The Agent uses the reference, brief and observation results to settle- timing, language, product placement and host treatment automatically.- 4. **Reading existing package declarations.** Before inventing an implementation, it checks the- components already available in the project and in Hypit's official packages. This lets it reuse- a caption, ranking, presenter, B-roll or rendering component when one already fits.- 5. **Writing a new package when needed.** If the requested visual behavior is genuinely missing, the- Agent creates the smallest reusable component required and records how it is used. You do not need- to design the package interface yourself.- 6. **Creating the source and checking it.** The Agent writes the SVML/SVS source, creates the needed- Run configuration, compiles the graph, and fixes type or layout problems it finds.- 7. **Comparing against a mock.** It produces mock media for unbuilt generations, renders the complete- composition in Studio, compares what it sees with the reference or brief, and repairs issues such- as incorrect timing, hierarchy, cropping, captions or visual density.- 8. **Applying your requested changes.** After establishing the base video, it applies the changes in- your brief, such as replacing the person on screen or adapting the video to your product, then- checks the updated result.-- ## 5. Review the mock Studio-- When the first pass is ready, the Agent opens a Studio mock for you. A mock is a review version: it- uses deterministic stand-ins for media that has not been generated yet, while preserving the real- timing, layout, captions, transitions and track relationships. It is intended to answer “does this- video work?” before you pay for the final media and rendering.-- Watch the mock from beginning to end. Check the story, the order of the shots, the readability of- captions, the prominence of the ranking board or product, the rhythm of B-roll, and whether the- overall tone matches your brief. If something is wrong, describe the problem in ordinary language:+ <video controls playsInline preload="metadata" width="100%" src="./quickstart/videos/let_the_agent_do_the_production_work.mp4"></video>+-Once you submit the brief, the Agent works through the project automatically without requiring you to-write source code. It normally proceeds to the Studio mock, but may ask a focused clarification when-the reference or brief does not establish an important editorial detail. The exact sequence depends-on the video, but it generally includes:--1. **Breaking the request into shots.** The Agent identifies the spoken sections, visual beats,- transitions, captions, B-roll opportunities and any persistent elements such as a ranking board.-2. **Analyzing the reference or brief.** For a clone, it uses Gemini and the available media tools to- inspect timing, composition, text, speakers and visual continuity. For an original, it resolves- the same questions from your description and the selected creative direction.-3. **Resolving details.** The Agent uses the reference, brief and observation results to settle- timing, language, product placement and host treatment automatically.-4. **Reading existing package declarations.** Before inventing an implementation, it checks the- components already available in the project and in Hypit's official packages. This lets it reuse- a caption, ranking, presenter, B-roll or rendering component when one already fits.-5. **Writing a new package when needed.** If the requested visual behavior is genuinely missing, the- Agent creates the smallest reusable component required and records how it is used. You do not need- to design the package interface yourself.-6. **Creating the source and checking it.** The Agent writes the SVML/SVS source, creates the needed- Run configuration, compiles the graph, and fixes type or layout problems it finds.- It also selects the project Runtime Profile and starts the local Runtime before any managed- capability is used.-7. **Comparing against a mock.** It produces mock media for unbuilt generations, renders the complete- composition in Studio, compares what it sees with the reference or brief, and repairs issues such- as incorrect timing, hierarchy, cropping, captions or visual density.-8. **Applying your requested changes.** After establishing the base video, it applies the changes in- your brief, such as replacing the person on screen or adapting the video to your product, then- checks the updated result.--## 5. Review the mock Studio++The Agent understands the reference in terms of your goal. Timed frames and words help it explain++the story, pacing, and the purpose and timing of captions, B-roll and graphics. A replacement person++or product shapes the script and creative direction from the beginning.++++It records those decisions in project files, selects or writes suitable components, generates media,++and composes the video around its semantic timeline. Studio and selected-range renders help check++layout, timing and readability. The Agent reuses existing media and keeps you informed about material++decisions, progress and problems.++++## 5. Review the composition in Studio++ <video controls playsInline preload="metadata" width="100%" src="./quickstart/videos/review_the_mock_studio.mp4"></video>+-When the first pass is ready, the Agent opens a Studio mock for you. A mock is a review version: it-uses deterministic stand-ins for media that has not been generated yet, while preserving the real-timing, layout, captions, transitions and track relationships. It is intended to answer “does this-video work?” before you pay for the final media and rendering.++Studio displays the media, captions and graphics selected by the current Run. The Agent can inspect++composition with existing material and continue refining it as generated media becomes available.+-Watch the mock from beginning to end. Check the story, the order of the shots, the readability of-captions, the prominence of the ranking board or product, the rhythm of B-roll, and whether the-overall tone matches your brief. If something is wrong, describe the problem in ordinary language:++Check whether the story is clear, captions are readable, the product or ranking board has enough++prominence, and B-roll appears where it helps. Describe the change you want:```text--The board appears too late, the captions are too small, and the B-roll covers the host--while she is speaking. Please fix those issues and show me the mock again.++The board appears too late and the captions are too small. Bring the board in with the words++introducing the ranking, and make the captions larger.```--The Agent edits the source, reruns the relevant checks and returns an updated mock.++The Agent changes the relevant parts and shows the updated composition.## 6. Approve and submit the paid Build- Only after you explicitly approve the mock should you ask for the paid Build:+ <video controls playsInline preload="metadata" width="100%" src="./quickstart/videos/approve_and_submit_the_paid_build.mp4"></video>+-Only after you explicitly approve the mock should you ask for the paid Build:++Before new paid work, the Agent explains the selected models, expected external work and available++pricing information. Authorize a concrete production scope:```text--The mock is approved. Submit the paid Build and create the final video.++Generate the media and finish the video with this direction, within the budget we agreed.```- The Agent summarizes the selected models, expected external work and Provider pricing information before it starts.- It then submits the Build, follows its progress and reports any provider or runtime issue in plain- language. A paid Build is the step that performs the real generation, media processing and final- rendering; the earlier mock does not silently trigger those billable operations.-The Agent summarizes every selected Provider, credential source, expected external work and estimated-cost before it starts, then waits for your approval. It submits the Build only after approval, follows-its progress and reports any Provider or Runtime issue in plain language. A paid Build is the step that-performs the real generation, media processing and final rendering; the earlier mock does not silently-trigger those billable operations.++The Agent submits a Build and follows its outcome. Completed media and outputs remain in the++project's Result. If an attempt fails, the Agent explains the failure and reuses available outputs++through a new Run and Build.--## 7. Review the paid result++## 7. Review the finished video- When the Build finishes, the Agent opens the resulting video and provides the saved output. Watch- the final result, not only the Studio mock. Real generated shots can differ from their mock- stand-ins, so check the generated host, B-roll, audio, captions, transitions, framing and export- quality. If the result needs a correction, tell the Agent what to change. It will revise the source- and guide you through another review rather than asking you to edit the rendered MP4 by hand.+ <video controls playsInline preload="metadata" width="100%" src="./quickstart/videos/review_the_paid_result.mp4"></video>+-When the Build finishes, the Agent opens the resulting video and provides the saved output. Watch-the final result, not only the Studio mock. Real generated shots can differ from their mock-stand-ins, so check the generated host, B-roll, audio, captions, transitions, framing and export-quality. If the result needs a correction, tell the Agent what to change. It will revise the source-and guide you through another review rather than asking you to edit the rendered MP4 by hand.++When the Build finishes, the Agent provides the final video and its saved location. Review the++content, captions, transitions, framing and sound against your goal. Describe any changes you want;++the project retains editable Sources and generated media.## 8. Request natural-language changes@@@ -157,7 -173,7 +151,7 @@@ look like a paper sports magazine```The Agent traces each request to the relevant source and component, preserves what you asked it to--keep, and shows a new mock before another paid Build.++keep, and reuses existing outputs. New paid generation follows your authorized scope.## 9. Create multiple variants in parallel@@@ -169,8 -187,8 +165,7 @@@ the intended directions with you, for e- one version with a product-focused opening;- one version with faster cuts and denser B-roll.--The Agent confirms the shared parts and the allowed differences before starting. Once you approve the--directions, it creates a separate project scope for each variant and dispatches child Agents to work--in parallel. Each child keeps the agreed boundaries, checks its own layout and source, and reports--back to the main Agent. You receive a clear list of completed variants and any decision that still--needs your input; you do not have to coordinate the child Agents yourself.++The Agent records the shared parts and each version's changes, then gives every variant explicit++production choices. Independent work can execute concurrently within the Runtime's configured++capacity; shared media can be reused. You receive each finished video, its project files and a clear++account of completion.diff --cc docs/quickstart/composition.mdindex 1be50db1,66582628..6140428e--- a/docs/quickstart/composition.md+++ b/docs/quickstart/composition.md@@@ -105,8 -105,8 +105,8 @@@ such as media trimming, audio/frame ext## Full pipeline walkthrough--The complete data flow from Script to rendered video. This example is based on--`examples/talking-film-graph-check/` — the smallest complete graph.++The complete data flow from Script to rendered video. The Sources below are an abridged++illustration. The complete runnable project is `examples/podcast/`; the commands below use it.### Author Source (`main.svml`)@@@ -264,9 -264,9 +264,9 @@@ width and is rejected### Compile and verify```bash--hypit check examples/talking-film-graph-check/main.svml++hypit check examples/podcast/reference.svml--hypit plan examples/talking-film-graph-check/build.svrun++hypit plan examples/podcast/reference.svrun````check` compiles the Author Graph — validates all imports, types, and graph edges without callingdiff --cc docs/quickstart/preview.mdindex 8247ff37,cad4b949..ed75c34b--- a/docs/quickstart/preview.md+++ b/docs/quickstart/preview.md@@@ -7,10 -7,10 +7,11 @@@ description: Open a satisfied Run, inspHypit Studio opens one `.svrun`, traces its Film or Render target back to explainable Semantic and Track projections, and presents four regions: Source at the upper left, Preview in the center, Inspector at the upper right, and Timeline below.-Studio never invokes a Provider or creates a Build. Generated material must already be selected by the Run as a real Candidate, either from a project file or from a Record accepted by an earlier Build and referenced through `<build-record>`. The display closure may contain no unresolved Need. Missing facts fail explicitly; Studio does not guess material or create placeholders.+Studio never submits generation or creates a Build. Generated material must be selected explicitly by the Run: from a project file, an earlier Build through `<build-record>`, or an ordinary stand-in Fragment selected with `satisfy`. Studio may ask the selected Runtime Profile to execute exact media Needs whose Provider marks them safe for transient authoring, such as inspection and normalization. It does not infer that permission from pricing, choose another Candidate or invent a placeholder. Other Needs fail with their capability named.```bash--hypit-studio --run examples/all-components-preview/studio.svrun --workspace .++hypit-studio --run examples/ranking-football/swap-effect-banana/studio.svrun \++ --workspace examples/ranking-football/swap-effect-banana# ➜ http://localhost:5179/```diff --cc docs/quickstart/run.mdindex 6451f0ef,b67ab9a7..cfefb5e1--- a/docs/quickstart/run.md+++ b/docs/quickstart/run.md@@@ -308,7 -262,7 +308,7 @@@ repository. Temporary Resources remain### 1. Select a Runtime```bash--cd examples/talking-head-aroll++cd examples/podcasthypit runtime use hypit.runtime.json```@@@ -334,11 -286,11 +334,11 @@@ JSON for inspection### 3. Check source and inspect the plan```bash--hypit check main.svml++hypit check reference.svml``````bash--hypit plan build.svrun++hypit plan reference.svrun```Review the frozen BuildPlan before spending money. The plan shows every Operation and Needs the@@@ -361,7 -309,7 +361,7 @@@ processes declared by Endpoints### 4. Submit the Build```bash- hypit build build.svrun --title first-cut --follow-hypit build build.svrun --follow++hypit build reference.svrun --title first-cut --follow```Without `--follow`, `build` returns after durable submission. The detached Worker continues. With@@@ -401,21 -348,16 +401,21 @@@ completed public Outputs. Use `--outpu```bashhypit get <build-id> \- --name final.video \- --to examples/talking-head-aroll/output/final.mp4+ --output final.video \- --to examples/talking-head-aroll/output/final.mp4++ --to output/final.mp4```-Every accepted intermediate Record and Artifact is archived before the Build completes. `get` makes-a copy of an already durable Record. Blob Artifacts are streamed from the selected Store, checked-against their declared size and SHA-256 digest, and only then atomically replace the destination;-exporting a large MP4 does not buffer the complete file in CLI memory.+`get` exports one exact `build + output` address to the required `--to` destination. A Scalar becomes+a JSON file. A Resource becomes one file containing its original bytes. A Composite becomes a+self-contained directory: `value.json` holds its Composite value document and the Resource files it+references keep their Result-relative paths inside that directory. The destination must not already+exist.++A forwarded historical Output is resolved transparently to its declared earlier Result. This does+not create a Build, alter a Result or copy anything back into Result storage, and the Runtime Profile+is not involved. Use `inspect` to view an Output; `get` is only explicit local export.-The terminal Build result prints the exact `get --name …` command for every targeted source alias;+The finished Build result prints the exact `get --output …` command for every file Target;there is no need to inspect opaque Record ids just to export `final.video`.### 6. Reuse in a new Builddiff --cc docs/zh/guide/develop.mdindex 940757f4,037217c7..e4364817--- a/docs/zh/guide/develop.md+++ b/docs/zh/guide/develop.md@@@ -53,7 -54,7 +53,7 @@@ hypit| 指南 | 主题 ||---|---|| [Hypit Skill 架构](./skill.md) | 四条路径的入口、工具、路由和持久化 JSON 状态 |--| [包架构](./packages.md) | 五个层次、依赖规则、包的构成、facets |++| [包架构](./packages.md) | 分层、依赖规则、包的构成、facets || [添加 Author 包](./author-packages.md) | 分步说明:新增组件、Surface、词表与预览图、activation || [添加 Provider](./providers.md) | 分步说明:新增 Endpoint 适配器 || [Runtime](./runtime.md) | Profile、Workspace、执行与生命周期边界 |diff --cc docs/zh/guide/testing.mdindex b36fa34f,9dff4416..6ac524ea--- a/docs/zh/guide/testing.md+++ b/docs/zh/guide/testing.md@@@ -77,6 -88,6 +77,5 @@@ OpenCV 的集成测试可以显式 opt-测试夹具放在 `packages/<name>/test/fixtures/`。它们是普通的 `.svml`、`.svs` 和 `.svrun` 文件,用于覆盖特定的编译路径。`examples/` 目录同时充当集成级别的夹具:--- `examples/bootstrap/` — 最小源闭包检查--- `examples/talking-film-graph-check/` — 不含 Provider 的完整图编译--- `examples/talking-head-aroll/` — 显式复用历史 Candidate 的 live example++- `examples/interview/`、`examples/podcast/`、`examples/ranking-football/` — 包含 Source、Run 和素材的完整视频项目。++- `examples/minimal-author-package/` — 带有 Surface 预览的完整组件包。diff --cc docs/zh/quickstart.mdindex 7f866b9e,a709ee30..8d680511--- a/docs/zh/quickstart.md+++ b/docs/zh/quickstart.md@@@ -3,7 -3,7 +3,7 @@@ title: 面向 Agent 使用者的快速�description: 无需手写 SVML 或 SVS,通过 Coding Agent 创建、审阅并交付 Hypit 视频。-----你不需要了解 SVML、SVS、JavaScript 或命令行。用日常语言向 Coding Agent 描述视频,Agent 会通过 `/hypit` skill 完成创作或复刻,并在付费 Build 前提供 Studio mock 供你审阅。++你不需要了解 SVML、SVS、JavaScript 或命令行。用日常语言向 Coding Agent 描述视频,Agent 会通过 `/hypit` skill 理解参考、设计内容、制作视频,并交付可继续修改的项目。## 你需要准备什么@@@ -18,7 -18,7 +18,7 @@@npx skills add hypit-ai/hypit -g```--然后在任意处启动 Coding Agent,Hypit skill 将全局可用。++然后在任意处启动 Coding Agent,Hypit skill 将全局可用。Skill 提供制作知识;Agent 会检查 Hypit 命令是否可用,并在需要时安装可执行工具。### **👉 [免费获得 100 个拥有独特音色的 AI 人物形象](https://drive.google.com/drive/u/2/folders/18J9Fz7mkU3OQNJ-2Res3eIyFQ2cemIK5)**@@@ -53,53 -55,62 +55,56 @@@你还可以补充目标受众、时长、语言、语气、品牌色、主持人、发布平台或画幅比例等要求。Agent 会把 brief 转换成完整计划,并自行补全制作所需的细节。-## 3. 配置凭据+## 3. 按 Agent 提示提供凭据+ <video controls playsInline preload="metadata" width="100%" src="../quickstart/videos/provide_credentials_when_the_agent_asks.mp4"></video>+-在你描述视频之后,Agent 会检查项目需要哪些模型和服务。对于 Hypit 托管模型,Hypit 默认使用 HypiHub OAuth。如果缺少该凭据,请告诉 Agent 登录 HypiHub;Agent 会自己运行登录命令、打开浏览器流程,并把会话保存到系统安全凭据存储中。登录本身不会提交付费生成任务。+在你描述视频之后,Agent 会检查项目需要哪些模型和服务。如果缺少必要凭据,Agent 会向你询问,并说明该凭据的用途。你可以选择两种方式:-只有在你明确选择自有 Provider 时,才配置它的 API key。Agent 只会请求所选 Runtime Profile 声明的凭据;某个凭据不可用时,不会悄悄切换到其他 Provider。+1. **使用 Hypit 推荐的 hypit.ai OAuth 登录。** 告诉 Agent 通过 hypit.ai 登录。一次 OAuth 登录即可覆盖 Hypit 托管服务提供的所有模型,不需要为每个模型分别收集 key。+2. **使用你自己的 Provider key。** 你可以直接和 Agent 约定要使用哪些模型,并提供相应 Provider 的 API key。Agent 只会索取当前项目需要的 key,不会询问无关凭据。不要把密钥粘贴到公开文档中,也不要提交到 Git。Agent 会使用已配置的安全凭据存储来保存这些凭据。## 4. 让 Agent 完成制作- 收到 brief 后,Agent 会在不要求你编写源码的情况下自动推进项目。制作过程中不会询问任何问题,你只需等待 Studio mock。具体顺序会因视频而不同,但通常包括:+ <video controls playsInline preload="metadata" width="100%" src="../quickstart/videos/let_the_agent_do_the_production_work.mp4"></video>+-收到 brief 后,Agent 会在不要求你编写源码的情况下自动推进项目。通常会直接推进到 Studio mock;但如果参考视频或 brief 没有明确重要的剪辑细节,Agent 可能会提出一个聚焦的澄清问题。具体顺序会因视频而不同,但通常包括:++Agent 会从你的目的出发理解参考视频,结合带时间的帧图和台词,弄清故事、节奏,以及字幕、B-roll、图形的作用与出现时机。换人或换产品的要求会从一开始影响剧本和设计。+-1. **拆分镜头。** Agent 识别口播段落、视觉节拍、转场、字幕、B-roll 机会,以及 ranking 板等需要持续保持的元素。-2. **分析参考视频或 brief。** 复刻路线会使用 Gemini 和可用的媒体工具检查节奏、构图、文字、说话人和视觉连续性;原创路线则根据你的描述和确定的创作方向回答同样的问题。-3. **自行确定细节。** Agent 会根据参考视频、brief 和观察结果自动确定时机、语言、产品位置和主持人处理方式。-4. **读取现有 package 声明。** 在自行发明实现之前,Agent 会检查项目和 Hypit 官方 package 中已有的组件。如果已有合适的字幕、ranking、主持人、B-roll 或渲染组件,就直接复用。-5. **必要时编写新 package。** 如果确实缺少所需的视觉行为,Agent 会创建一个足够小、可复用的新组件,并记录它的使用方式。你不需要自行设计 package 接口。-6. **编写并检查源码。** Agent 会写出 SVML/SVS 源码,创建所需的 Run 配置,编译视频图,并修复发现的类型或布局问题。使用任何 Managed capability 之前,Agent 还会选择项目 Runtime Profile 并启动本地 Runtime。-7. **与 mock 对比。** 对尚未真正生成的素材使用 mock,随后在 Studio 中渲染完整构图;Agent 会把看到的结果与参考视频或 brief 对比,修复时机、层级、裁切、字幕和画面密度等问题。-8. **按照要求完成修改。** 基础视频确定后,Agent 会根据你的要求完成定制,例如更换画面中的人物,或替换成你的产品,然后检查修改后的结果。++它把这些决定写入项目文件,选择或编写合适的组件,用图片与视频模型制作素材,再按语义时间线编排。Studio 和局部渲染帮助检查版面、时机与可读性。已有素材会被复用;重要的决定、进展和问题会及时告诉你。- 1. **拆分镜头。** Agent 识别口播段落、视觉节拍、转场、字幕、B-roll 机会,以及 ranking 板等需要持续保持的元素。- 2. **分析参考视频或 brief。** 复刻路线会观看参考视频,并用带时间的帧图与转录检查节奏、构图、文字、说话人和视觉连续性;原创路线则根据你的描述和确定的创作方向回答同样的问题。- 3. **自行确定细节。** Agent 会根据参考视频、brief 和观察结果自动确定时机、语言、产品位置和主持人处理方式。- 4. **读取现有 package 声明。** 在自行发明实现之前,Agent 会检查项目和 Hypit 官方 package 中已有的组件。如果已有合适的字幕、ranking、主持人、B-roll 或渲染组件,就直接复用。- 5. **必要时编写新 package。** 如果确实缺少所需的视觉行为,Agent 会创建一个足够小、可复用的新组件,并记录它的使用方式。你不需要自行设计 package 接口。- 6. **编写并检查源码。** Agent 会写出 SVML/SVS 源码,创建所需的 Run 配置,编译视频图,并修复发现的类型或布局问题。- 7. **与 mock 对比。** 对尚未真正生成的素材使用 mock,随后在 Studio 中渲染完整构图;Agent 会把看到的结果与参考视频或 brief 对比,修复时机、层级、裁切、字幕和画面密度等问题。- 8. **按照要求完成修改。** 基础视频确定后,Agent 会根据你的要求完成定制,例如更换画面中的人物,或替换成你的产品,然后检查修改后的结果。-## 5. 查看 mock Studio++## 5. 在 Studio 查看编排- ## 5. 查看 mock Studio+ <video controls playsInline preload="metadata" width="100%" src="../quickstart/videos/review_the_mock_studio.mp4"></video>--第一版完成后,Agent 会为你打开 Studio mock。Mock 是审阅版本:尚未生成的媒体会使用确定性的临时素材代替,但真实的时序、布局、字幕、转场和 Track 关系都会保留。它要回答的是“这支视频是否成立”,而不是在你确认之前悄悄执行付费生成或最终渲染。++Studio 展示当前 Run 选定的素材、字幕和图形。Agent 可以用已有素材检查构图,也可以在生成素材后继续调整编排。--请从头到尾观看 mock,检查故事是否清楚、镜头顺序是否正确、字幕在手机上是否易读、ranking 板或产品是否突出、B-roll 节奏是否合适,以及整体语气是否符合 brief。如果发现问题,直接用日常语言告诉 Agent:++查看故事是否清楚、字幕是否易读、产品或 ranking 板是否突出、B-roll 是否放在合适的位置。直接描述你想要的改变:```text--ranking 板出现得太晚,字幕太小,而且主持人说话时被 B-roll 盖住了。请修复这些问题,再给我看一次 mock。++ranking 板出现得太晚,字幕太小。让板子跟着介绍排名的台词出现,并把字幕放大一些。```--Agent 会修改源码、重新检查并返回更新后的 mock。++Agent 会修改对应部分,再展示更新后的画面。## 6. 确认后提交付费 Build- 只有在你明确确认 mock 后,才要求 Agent 提交付费 Build:+ <video controls playsInline preload="metadata" width="100%" src="../quickstart/videos/approve_and_submit_the_paid_build.mp4"></video>+-只有在你明确确认 mock 后,才要求 Agent 提交付费 Build:++开始新的付费工作前,Agent 会说明所选模型、将要执行的外部工作和可查到的价格信息。你可以授权明确的制作范围:```text--mock 没有问题。请提交付费 Build 并生成最终视频。++按这个方案生成素材并完成视频,预算在我们刚确认的范围内。```- 开始之前,Agent 会向你总结将使用的模型、预计执行的外部工作和预估费用。随后它会提交 Build、跟踪进度,并用书面化的语言报告 Provider 或 Runtime 问题。付费 Build 才会执行真实的素材生成、媒体处理和最终渲染;之前的 mock 不会自动触发这些计费操作。-开始之前,Agent 会向你总结所有选定的 Provider、凭据来源、预计执行的外部工作和预估费用,并等待你的确认。确认后它才会提交 Build、跟踪进度,并用书面化的语言报告 Provider 或 Runtime 问题。付费 Build 才会执行真实的素材生成、媒体处理和最终渲染;之前的 mock 不会自动触发这些计费操作。++Agent 提交 Build 并跟进结果。已完成的素材和输出会保存在项目的 Result 中;出现失败时,它会说明原因,并在新的 Run 和 Build 中复用可用产物。+-## 7. 查看付费 Build 的结果++## 7. 查看成片- ## 7. 查看付费 Build 的结果+ <video controls playsInline preload="metadata" width="100%" src="../quickstart/videos/review_the_paid_result.mp4"></video>--Build 完成后,Agent 会打开最终视频并提供保存后的输出文件。请查看最终结果,而不只是 Studio mock。真实生成的主持人、B-roll 和音频可能与 mock 的临时素材不同,因此要检查画面、字幕、转场、构图、声音和导出质量。如果需要修改,直接告诉 Agent 要改什么。Agent 会修改源码并带你重新审阅,而不是让你手动编辑已经渲染出的 MP4。++Build 完成后,Agent 会提供最终视频及保存位置。查看内容、字幕、转场、构图和声音是否符合你的目标。需要修改时,直接告诉 Agent;项目保留可编辑的源码和已生成素材。## 8. 继续用自然语言提出修改@@@ -109,7 -122,7 +116,7 @@@ Build 成功后,你仍然可以用对保留台词和排名顺序,但把主持人换成沉稳的男主持,并把 ranking 板做成纸质体育杂志风格。```--Agent 会把每项要求追踪到对应的源码和组件,保留你要求不变的部分,并在再次付费 Build 前先给你看新的 mock。++Agent 会把每项要求落实到对应的源码和组件,保留你要求不变的部分,并复用已有产物。新的付费生成遵循你授权的范围。## 9. 并行制作多个变体@@@ -120,4 -135,4 +129,4 @@@- 把产品卖点放到开头的版本;- 加快剪辑、增加 B-roll 密度的版本。--Agent 会先确认所有版本共用的内容,以及每个版本允许改变的范围。你确认方向后,它会为每个变体创建独立的项目范围,并下发子 Agent 并行制作。每个子 Agent 都会遵守已确认的边界,检查自己的布局和源码,再向主 Agent 汇报。最终你会得到清晰的变体完成列表,以及仍需要你决定的事项;不需要你亲自协调这些子 Agent。++Agent 会整理各版本共用的内容和各自的变化,为每个版本写出明确的制作选择。独立工作可以并发执行,具体并发量由运行配置控制;共用素材可显式复用。最终你会得到每个版本的成片、项目文件和完成情况。diff --cc docs/zh/quickstart/composition.mdindex 06b428b6,06b428b6..a4191a0d--- a/docs/zh/quickstart/composition.md+++ b/docs/zh/quickstart/composition.md@@@ -101,8 -101,8 +101,8 @@@ Build Target,也可以直接接到媒## 完整的管线流程--从 Script 到渲染视频的完整数据流。本示例基于--`examples/talking-film-graph-check/`——最小的完整图。++从 Script 到渲染视频的完整数据流。下面的 Source 是删节示意;可运行的完整项目见++`examples/podcast/`,本节末尾的命令针对该项目。### Author Source (`main.svml`)@@@ -258,9 -258,9 +258,9 @@@### 编译与验证```bash--hypit check examples/talking-film-graph-check/main.svml++hypit check examples/podcast/reference.svml--hypit plan examples/talking-film-graph-check/build.svrun++hypit plan examples/podcast/reference.svrun````check` 编译 Author Graph——验证所有导入、类型和图的边,而不调用任何外部服务。`plan`diff --cc docs/zh/quickstart/preview.mdindex cfb0b8f5,f0c50ad3..99e6af68--- a/docs/zh/quickstart/preview.md+++ b/docs/zh/quickstart/preview.md@@@ -7,10 -7,10 +7,11 @@@ description: 打开一份素材已经�Hypit Studio 打开一份 `.svrun`,把它的 Film 或 Render target 回溯到可解释的 Semantic 与 Track 投影,并用四个区域呈现:左上 Source、中上 Preview、右上 Inspector、下方 Timeline。-Studio 不调用 Provider,也不创建 Build。需要生成的素材必须已经由 Run 选择为真实 Candidate:可以是项目文件,也可以是早先 Build 接受并由 `<build-record>` 引用的 Record。显示闭包里不允许残留 Need;缺失关系会明确失败,不猜测素材、不制造占位。+Studio 不提交生成,也不创建 Build。需要生成的素材必须由 Run 明确选择:可以是项目文件、由 `<build-record>` 引用的历史 Build Output,也可以是用 `satisfy` 选择的普通替身 Fragment。Studio 可以请求所选 Runtime Profile 执行 Provider 明确允许临时创作执行的媒体 Need,例如检查和归一化;它不根据价格猜权限、不替换 Candidate,也不暗中制造占位。其余 Need 会带着准确 capability 失败。```bash--hypit-studio --run examples/all-components-preview/studio.svrun --workspace .++hypit-studio --run examples/ranking-football/swap-effect-banana/studio.svrun \++ --workspace examples/ranking-football/swap-effect-banana# ➜ http://localhost:5179/```diff --cc docs/zh/quickstart/run.mdindex dbfc3290,0c668ab2..065ea9d3--- a/docs/zh/quickstart/run.md+++ b/docs/zh/quickstart/run.md@@@ -306,7 -271,7 +306,7 @@@ Runtime Profile 只选择 Credential St### 1. 选择 Runtime```bash--cd examples/talking-head-aroll++cd examples/podcasthypit runtime use hypit.runtime.json```@@@ -329,11 -293,11 +329,11 @@@ Runtime 角色、Endpoint 配置、凭�### 3. 检查 Source 与计划```bash--hypit check main.svml++hypit check reference.svml``````bash--hypit plan build.svrun++hypit plan reference.svrun```在花费资金之前审查冻结的 BuildPlan。该计划展示调度器将发出的每个 Operation 和 Needs;选择@@@ -351,7 -313,7 +351,7 @@@ Runtime 后只预检这次计划真正�### 4. 提交 Build```bash- hypit build build.svrun --title first-cut --follow-hypit build build.svrun --follow++hypit build reference.svrun --title first-cut --follow```不带 `--follow` 时,Build 在耐久提交后退出,后台 Worker 继续。带 `--follow` 时终端也只是观察者,并会报告 phase / Operation 数量变化;Ctrl-C 不会取消任务。@@@ -388,17 -348,14 +388,17 @@@ hypit inspect <build-id```bashhypit get <build-id> \- --name final.video \- --to examples/talking-head-aroll/output/final.mp4+ --output final.video \- --to examples/talking-head-aroll/output/final.mp4++ --to output/final.mp4```-每个被接受的中间 Record 和 Artifact 在 Build 完成前都会被归档。`get` 会复制一份已持久化的-Record。Blob Artifact 会从所选 Store 流式读取,逐步校验长度与 SHA-256,完整通过后才原子替换目标路径;导出大 MP4 不会把整段视频塞进 CLI 内存。-Build 的最终输出会为每个目标别名打印精确的 `get --name …` 命令,不必为了导出-`final.video` 去查不透明的 Record id。+`get` 把一个精确的 `build + output` 地址导出到必填的 `--to` 目的地。Scalar 写成 JSON 文件;+Resource 原样写成一个文件;Composite 写成一个自足目录,其中 `value.json` 保存它的 Composite 值+文档,被引用的 Resource 则按 Result 内的相对路径一起写入。目的地必须尚不存在。++历史转发会透明地沿显式关系找到更早的 Result。这个过程不会创建 Build、修改 Result,或把+副本写回 Result 仓库,也不需要 Runtime Profile。查看 Output 用 `inspect`;`get` 只负责显式+本地导出。Build 的最终输出会为每个文件 Target 打印精确的 `get --output …` 命令。### 6. 在新 Build 中复用diff --cc packages/provider-hyperframes-local/src/capture-process.tsindex 7b6c7134,00000000..b771454amode 100644,000000..100644--- a/packages/provider-hyperframes-local/src/capture-process.ts+++ b/packages/provider-hyperframes-local/src/capture-process.ts@@@ -1,96 -1,0 +1,110 @@@+import { execFile, spawn } from "node:child_process";+import { promisify } from "node:util";+import { fileURLToPath } from "node:url";++import { setTimeout as delay } from "node:timers/promises";+import type { CaptureInput } from "./capture.js";+import type { HyperframesRenderProgress } from "./render.js";++const exec = promisify(execFile);+const cleanupMs = 5_000;++/** Chrome starts its own process group, so stopping only the Node child is insufficient. */+async function killRenderTree(pid: number): Promise<void> {+ if (process.platform === "win32") {+ await exec("taskkill", ["/PID", String(pid), "/T", "/F"], { windowsHide: true, timeout: cleanupMs });+ return;+ }+ const { stdout } = await exec("ps", ["-A", "-o", "pid=,ppid="], { timeout: cleanupMs });+ const rows = stdout.trim().split("\n").map((line) => line.trim().split(/\s+/u).map(Number));+ const descendants = [pid];+ for (let i = 0; i < descendants.length; i++) {+ for (const [child, parent] of rows) if (parent === descendants[i] && child !== undefined) descendants.push(child);+ }+ for (const child of descendants.reverse()) {+ for (const target of [-child, child]) {+ try { process.kill(target, "SIGKILL"); }+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; }+ }++ // Signal delivery is asynchronous. Wait for execution to stop while the++ // parent is still alive to reap its child; zombies no longer hold resources.++ const deadline = Date.now() + cleanupMs;++ while (true) {++ const state = await exec("ps", ["-p", String(child), "-o", "stat="], { timeout: cleanupMs })++ .then(({ stdout }) => stdout.trim(), (error) => {++ if (error.code === 1 && !error.stdout?.trim()) return "";++ throw error;++ });++ if (state === "" || state.startsWith("Z")) break;++ if (Date.now() >= deadline) throw new Error(`Render process ${child} did not stop after SIGKILL`);++ await delay(20);++ }+ }+}++/** One disposable execution, with no persisted state or resubmission behavior. */+export async function runCaptureProcess(+ input: CaptureInput,+ signal: AbortSignal,+ onProgress: (event: HyperframesRenderProgress) => void,+ entry = new URL("./capture-worker.ts", import.meta.url),+): Promise<void> {+ signal.throwIfAborted();+ await new Promise<void>((resolve, reject) => {+ const child = spawn(process.execPath, ["--import", import.meta.resolve("tsx"), fileURLToPath(entry)], {+ detached: process.platform !== "win32", windowsHide: true,+ stdio: ["ignore", "pipe", "pipe", "ipc"],+ });+ let failure: Error | undefined;+ let completed = false;+ let outputBytes = 0;+ let stderr = "";+ let grace: ReturnType<typeof setTimeout> | undefined;+ let killing: Promise<void> | undefined;+ const kill = () => {+ if (grace !== undefined) clearTimeout(grace);+ killing ??= (child.pid === undefined ? Promise.resolve() : killRenderTree(child.pid)).catch((error) => {+ failure = new Error(`${failure?.message ?? "Render cleanup failed"}; ${String(error)}`);+ child.kill("SIGKILL");+ });+ return killing;+ };+ const stop = (error: Error) => {+ failure ??= error;+ if (child.connected) child.send({ type: "abort", error: failure.message }, () => {});+ grace ??= setTimeout(() => { void kill(); }, cleanupMs);+ };+ const abort = () => stop(signal.reason instanceof Error ? signal.reason : new Error(String(signal.reason)));+ signal.addEventListener("abort", abort, { once: true });+ const log = (chunk: Buffer, error: boolean) => {+ outputBytes += chunk.byteLength;+ if (error) stderr = `${stderr}${chunk.toString()}`.slice(-32_000);+ if (outputBytes > input.config.maxProcessOutputBytes) stop(new Error("HyperFrames process output exceeded the configured limit"));+ };+ child.stdout?.on("data", (chunk: Buffer) => log(chunk, false));+ child.stderr?.on("data", (chunk: Buffer) => log(chunk, true));+ child.on("message", (value: { type: string; event?: HyperframesRenderProgress; error?: string }) => {+ if (value.type === "progress" && value.event !== undefined) {+ try { onProgress(value.event); } catch (error) { stop(error instanceof Error ? error : new Error(String(error))); }+ } else if (value.type === "stopping") {+ stop(new Error(value.error));+ } else if (value.type === "completed" || value.type === "failed") {+ completed = value.type === "completed";+ if (!completed) failure ??= new Error(value.error);+ // The worker has finished cleanup. Terminate any leftover descendants before releasing capacity.+ void kill();+ }+ });+ child.on("error", (error) => { failure ??= error; void kill(); });+ child.on("close", () => {+ if (grace !== undefined) clearTimeout(grace);+ signal.removeEventListener("abort", abort);+ void (killing ?? Promise.resolve()).then(() => {+ if (failure !== undefined) reject(failure);+ else if (!completed) reject(new Error(`HyperFrames process exited before completion: ${stderr}`));+ else resolve();+ });+ });+ child.send({ type: "start", input }, (error) => { if (error) { failure ??= error; void kill(); } });+ if (signal.aborted) abort();+ });+}diff --cc packages/provider-hyperframes-local/test/capture-process.test.tsindex 78399c59,00000000..a6fd7904mode 100644,000000..100644--- a/packages/provider-hyperframes-local/test/capture-process.test.ts+++ b/packages/provider-hyperframes-local/test/capture-process.test.ts@@@ -1,35 -1,0 +1,42 @@@+import assert from "node:assert/strict";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { pathToFileURL } from "node:url";+import test from "node:test";++import { execFileSync } from "node:child_process";+import { runCaptureProcess } from "../src/capture-process.js";+import { resolveExecutionOptions } from "../src/render.js";+import type { CaptureInput } from "../src/capture.js";++test("a stuck renderer and its detached child both stop before the call rejects", async () => {+ const root = await mkdtemp(join(tmpdir(), "hypit-stuck-render-"));+ const controller = new AbortController();+ let descendant: number | undefined;+ try {+ const entry = join(root, "stuck.mjs");+ await writeFile(entry, `import { spawn } from 'node:child_process';+process.once('message', () => {+ const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { detached: true, stdio: 'ignore' });+ process.send({ type: 'progress', event: { phase: 'worker-start', browserPid: child.pid } });+});+setInterval(() => {}, 1000);+`);+ await assert.rejects(runCaptureProcess({ config: resolveExecutionOptions({}) } as CaptureInput,+ controller.signal, (event) => {+ if ("browserPid" in event) descendant = event.browserPid;+ controller.abort(new Error("render deadline"));+ }, pathToFileURL(entry)), /render deadline/u);+ assert.ok(descendant !== undefined);- assert.throws(() => process.kill(descendant!, 0), { code: "ESRCH" });++ try {++ process.kill(descendant, 0);++ assert.notEqual(process.platform, "win32");++ assert.match(execFileSync("ps", ["-p", String(descendant), "-o", "stat="], { encoding: "utf8" }).trim(), /^Z/u);++ } catch (error) {++ if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error;++ }+ } finally {+ if (descendant !== undefined) { try { process.kill(descendant, "SIGKILL"); } catch {} }+ await rm(root, { recursive: true, force: true });+ }+});diff --cc packages/provider-hypihub/README.mdindex a8e1ca3a,7d724ec6..f3f56c98--- a/packages/provider-hypihub/README.md+++ b/packages/provider-hypihub/README.md@@@ -53,78 -31,37 +53,91 @@@ Runtime Profile example}```-Gemini VLM is also exposed as the provider-neutral `@hypit/gemini` Runtime capability, so an Author-Source can select the exact model while the Runtime chooses HypiHub or Vertex. Existing embedded-callers can still use the exported `createHypiHubGeminiGenerator`. Run `hypit auth login hypihub.default --runtime hypit.runtime.json` to sign in with HypiHub OAuth (and optionally set `HYPIHUB_BASE_URL`; either the origin or-an existing `/v1`/`/v1beta` base is accepted) only when choosing HypiHub. The Runtime Provider also-accepts the origin or either versioned base and normalizes it to `/v1`; missing or insufficient user+Remote transcription exposes the same `@hypit/whisperx` alignment capability implemented by the local+WhisperX Provider. The Runtime Profile selects which Endpoint serves it. Run+`hypit auth login hypihub.default --runtime hypit.runtime.json` to sign in with HypiHub OAuth when+choosing HypiHub. A Profile may set `baseUrl`+to the selected deployment's origin or an existing `/v1`/`/v1beta` base. The Runtime Provider+normalizes it to `/v1`; missing or insufficient usercredentials should be resolved at [hypit.ai](https://hypit.ai). Referenced image, audio and video-Artifacts are uploaded automatically. The Provider first sends the file size and SHA-256 to-`POST /v1/files/uploads`; the production policy returns private regional-S3 multipart instructions-for every valid non-empty media file, including files compressed by the tool before upload. Parts-are uploaded concurrently through short-lived signed URLs, so media bytes do not make an extra trip-through the HypiHub application server. A failed part alone is retried with a fresh signed URL.--Whole-file uploads default to **8 concurrent files** per origin/credential in a Node process,-shared across Provider and Gemini uploader instances. Set `uploadConcurrency` (integer 1..64)-in the Provider runtime configuration, `createHypiHubProvider`, or-`createHypiHubGeminiGenerator` to change it. Extra files wait locally. If outstanding calls-sharing a credential specify different limits, the lowest limit controls new starts until-those calls finish; running uploads are allowed to drain. Separate processes still share-the server's account session limit, which defaults to 64. These are configurable protection-limits, not a claim about sustained network throughput.--The server owns the part size, per-file part concurrency, and URL lifetime. Clients do not need to duplicate that-policy. `uploadPartTimeoutMs` (default five minutes) and `uploadPartAttempts` (default three) only-control client retry behavior. Signed S3 URLs are never included in Provider error messages. Uploads remain deduplicated by Artifact digest within one-Runtime operation. Embedded callers may override the entire transport with `publicAssetUrl`.--The provider also serves `@hypit/whisperx#whisperx-alignment` through HypiHub's synchronous-`/v1/audio/transcriptions` endpoint using `victor-upmeet/whisperx`. It always requests-`verbose_json` with both segment- and word-level timestamps, then converts HypiHub's OpenAI-shaped-seconds into Hypit's 16 kHz sample-domain `AlignedTranscriptEvidence`. Override the model with-`whisperxModel` only when the HypiHub catalog exposes a compatible replacement.--HypiHub exposes MiMo VoiceDesign by default. Set `audio: false` only when the user explicitly selects-another VoiceDesign Provider. Hypit does not expose MiMo preset-voice or voice-cloning models.+Resources are uploaded through a session from `POST /v1/files/uploads`, followed by the private+regional multipart instructions returned by HypiHub. The Provider follows the server-selected part- size and concurrency, retries only a failed part with a fresh signed URL, completes or cancels that++size and part concurrency, retries a failed part with a fresh signed URL, completes or cancels that+one upload, and then passes the returned HTTPS URL to generation or transcription. One+Resource identity is uploaded once within one Runtime operation. Hypit keeps no upload catalog or+cross-Build cache. Embedded callers may replace this transport with `publicAssetUrl`.++OAuth login stores the access token, refresh token and expiry as one opaque credential value. The+browser callback only confirms that authorization returned to the CLI; the CLI reports success after+the bounded token exchange and Credential Store write complete. `oauthRequestTimeoutMs` controls that+exchange and defaults to 30 seconds, independently of the longer inference request timeout. The+Provider refreshes that value shortly before expiry or after an unauthorised response when the+selected Store is writable. Its Endpoint receives only the credential slot it declared and a narrow+operation for replacing that same slot; it cannot enumerate the Store, choose another key or read+another Endpoint's credentials. A raw credential remains an ordinary static API key.++The service currently requires whole-file and per-part SHA-256 values as fields of its signed upload+protocol. They exist only while transferring bytes; Hypit never uses them as Resource identity,+Result metadata, lookup keys or reuse evidence. Signed URLs and their query credentials are removed+from surfaced upload errors.++The default remote alignment model is `victor-upmeet/whisperx`; `transcriptionModel` may select another+HypiHub model that exposes the `transcriptions` route. `hypit doctor` reads the authenticated model+catalog to verify configured capabilities; ordinary preflight never makes that request. The package+declares HypiHub's public pricing page, `https://hypit.ai/commercial/pricing/`, as its price source.+For each selected Need, `readPricing` resolves the corresponding HypiHub model and returns the service's+authenticated `GET /v1/pricing?model=<model>` response unchanged together with that URL. It covers- generation, visual observation, alignment, Voice Design, and Voice Clone through the same mechanism;++generation, alignment, Voice Design, and Voice Clone through the same mechanism;+the Provider does not maintain a second list of billing formulas or calculate a request total.++HypiHub declares MiMo Voice Design and Voice Clone together with every other capability it serves; it+never hides one. Voice Design produces an accepted voice-reference Resource, and Voice Clone uses+that reference to produce independent speech. Hypit does not expose MiMo preset voices. When another+selected Endpoint offers the same capability (a local WhisperX or the official MiMo+Provider), the Runtime Profile's `bindings` say which Endpoint serves it.++Execution policy remains local to this Provider:++| Profile field | Default | What it controls |+| --- | ---: | --- |+| `requestTimeoutMs` | 300 seconds | ordinary Provider HTTP requests |+| `oauthRequestTimeoutMs` | 30 seconds | OAuth token exchange and refresh |+| `pricingRequestTimeoutMs` | 30 seconds | authenticated pricing requests |+| `operationTimeoutMs` | 20 minutes | one remote asynchronous operation |++| `uploadConcurrency` | 8 | whole file sessions per origin/credential within this process |+| `uploadPartTimeoutMs` | 5 minutes | one upload part |+| `uploadPartAttempts` | 3 | attempts for one upload part |+| `downloadAttempts` | 3 | attempts to collect one result |++`defaultConcurrency` controls the total shared capacity of this Profile's HypiHub pool. Optional `capabilityConcurrency`+sets narrower group limits, for example `{ "seedance-2-mini": 2, "transcription": 1 }`.+Image/video/speech groups use the exact capability name; WhisperX uses `transcription`. These limits+coordinate this Runtime's requests; HypiHub remains+responsible for service-wide account limits. Immediate speech/transcription slots cover the+active HTTP invocation, while asynchronous image/video slots cover remote work until completion or local execution failure.++For asynchronous image/video jobs, `actionLimits` configures the common `submit`, `poll` and `collect`+admission budgets. Each accepts `concurrency` and `rate: { limit, periodMs }`, shared by the pool.+These limits count lifecycle actions; Provider-specific upload parts and HTTP requests remain inside+those actions. Synchronous speech and transcription retain their ordinary request capacity.++A submission, polling or collection error ends the local attempt. Known job IDs and credential+references remain available in Result receipts; a timeout with no ID is recorded as such. A job can+be inspected at `/jobs/<id>` and its generated assets at `/jobs/<id>/assets` on the selected API base.+The next production attempt uses a new Run and Build. Runtime bindings never switch from a user's+own Provider to HypiHub after a key, quota or transport failure.+- Multipart concurrency is different: HypiHub- selects it for one upload session, and it does not create a Build queue or a second Runtime pool.++`uploadConcurrency` bounds whole files inside the Provider transport. Uploader instances in the same++process share the limit for the same service origin and current credential; the smallest outstanding++limit applies. Token refresh can change that grouping. Separate processes are not coordinated by this++local limit. It is a positive safe integer; HypiHub still enforces its own account quota. Part++concurrency is separately negotiated by HypiHub for each file. These are transport limits inside a++Runtime action, not additional Build admission limits.++++Signing, completing and cancelling a known upload session may retry temporary transport failures++within at most four attempts and the smaller of `requestTimeoutMs` or 120 seconds. A new upload++session is retried only after an explicit temporary 429 rejection; an unknown creation result ends++the attempt. Daily and storage quota errors fail immediately. Active part workers finish before the++session is cancelled. An unconfirmed cancellation logs its upload ID without exposing signed URLs.++OAuth refresh retries the rejected control request on the same session. None of this resumes a++failed Build or changes the selected Provider.diff --cc packages/provider-hypihub/src/activation.tsindex f0550ea0,19eba08e..6715543f--- a/packages/provider-hypihub/src/activation.ts+++ b/packages/provider-hypihub/src/activation.ts@@@ -15,22 -15,7 +15,23 @@@ const adapter = createRuntimeEndpointAdactivate(context) {if (context.pool === undefined) throw new Error("HypiHub Provider Pool is required");const config = runtimeConfigObject(context.config, "HypiHub");- runtimeConfigExact(config, ["baseUrl", "apiKey", "defaultConcurrency", "pollIntervalMs", "requestTimeoutMs", "uploadConcurrency", "audio", "whisperxModel"], "HypiHub");+ runtimeConfigExact(config, [+ "baseUrl",+ "apiKey",+ "defaultConcurrency",+ "actionLimits",+ "capabilityConcurrency",+ "pollIntervalMs",+ "requestTimeoutMs",+ "oauthRequestTimeoutMs",+ "pricingRequestTimeoutMs",+ "operationTimeoutMs",++ "uploadConcurrency",+ "uploadPartTimeoutMs",+ "uploadPartAttempts",+ "downloadAttempts",+ "transcriptionModel",+ ], "HypiHub");const baseUrl = runtimeConfigString(config.baseUrl, "HypiHub baseUrl");if (baseUrl !== undefined) {const url = new URL(baseUrl);@@@ -40,42 -25,25 +41,44 @@@}const apiKey = runtimeConfigCredentialRef(config.apiKey, "HypiHub apiKey");if (apiKey === undefined) throw new Error("HypiHub apiKey CredentialRef is required");+ const actionLimits = runtimeConfigActionLimits(config.actionLimits);const defaultConcurrency = runtimeConfigPositiveInteger(config.defaultConcurrency, "HypiHub defaultConcurrency");const pollIntervalMs = runtimeConfigPositiveInteger(config.pollIntervalMs, "HypiHub pollIntervalMs");- const uploadConcurrency = runtimeConfigPositiveInteger(config.uploadConcurrency, "HypiHub uploadConcurrency");const requestTimeoutMs = runtimeConfigPositiveInteger(config.requestTimeoutMs, "HypiHub requestTimeoutMs");- const audio = runtimeConfigBoolean(config.audio, "HypiHub audio");- const whisperxModel = runtimeConfigString(config.whisperxModel, "HypiHub whisperxModel");- return {- endpoint: createHypiHubProvider({+ const oauthRequestTimeoutMs = runtimeConfigPositiveInteger(config.oauthRequestTimeoutMs, "HypiHub oauthRequestTimeoutMs");+ const pricingRequestTimeoutMs = runtimeConfigPositiveInteger(config.pricingRequestTimeoutMs, "HypiHub pricingRequestTimeoutMs");+ const operationTimeoutMs = runtimeConfigPositiveInteger(config.operationTimeoutMs, "HypiHub operationTimeoutMs");++ const uploadConcurrency = runtimeConfigPositiveInteger(config.uploadConcurrency, "HypiHub uploadConcurrency");+ const uploadPartTimeoutMs = runtimeConfigPositiveInteger(config.uploadPartTimeoutMs, "HypiHub uploadPartTimeoutMs");+ const uploadPartAttempts = runtimeConfigPositiveInteger(config.uploadPartAttempts, "HypiHub uploadPartAttempts");+ const downloadAttempts = runtimeConfigPositiveInteger(config.downloadAttempts, "HypiHub downloadAttempts");+ const transcriptionModel = runtimeConfigString(config.transcriptionModel, "HypiHub transcriptionModel");+ const capabilityConcurrency = config.capabilityConcurrency === undefined ? undefined : Object.fromEntries(+ Object.entries(runtimeConfigObject(config.capabilityConcurrency, "HypiHub capabilityConcurrency"))+ .map(([name, value]) => [name, runtimeConfigPositiveInteger(value, `HypiHub ${name} capacity`)!]),+ );+ const options = {instance: context.instance,pool: context.pool,...(baseUrl === undefined ? {} : { baseUrl }),apiKey,...(defaultConcurrency === undefined ? {} : { defaultConcurrency }),+ ...(actionLimits === undefined ? {} : { actionLimits }),+ ...(capabilityConcurrency === undefined ? {} : { capabilityConcurrency }),...(pollIntervalMs === undefined ? {} : { pollIntervalMs }),...(requestTimeoutMs === undefined ? {} : { requestTimeoutMs }),+ ...(oauthRequestTimeoutMs === undefined ? {} : { oauthRequestTimeoutMs }),+ ...(pricingRequestTimeoutMs === undefined ? {} : { pricingRequestTimeoutMs }),+ ...(operationTimeoutMs === undefined ? {} : { operationTimeoutMs }),+ ...(uploadConcurrency === undefined ? {} : { uploadConcurrency }),- ...(audio === undefined ? {} : { audio }),- ...(whisperxModel === undefined ? {} : { whisperxModel }),- }),+ ...(uploadPartTimeoutMs === undefined ? {} : { uploadPartTimeoutMs }),+ ...(uploadPartAttempts === undefined ? {} : { uploadPartAttempts }),+ ...(downloadAttempts === undefined ? {} : { downloadAttempts }),+ ...(transcriptionModel === undefined ? {} : { transcriptionModel }),+ };+ return {+ endpoint: createHypiHubProvider(options),+ diagnose: async (doctor) => await diagnoseHypiHubProvider(options, doctor),};},});diff --cc packages/provider-hypihub/src/provider.tsindex d3a55ef0,f99c00b3..f11cd58d--- a/packages/provider-hypihub/src/provider.ts+++ b/packages/provider-hypihub/src/provider.ts@@@ -29,21 -26,21 +29,23 @@@ export type CreateHypiHubProviderOptionreadonly baseUrl?: string;readonly apiKey?: CredentialRef;readonly defaultConcurrency?: number;+ readonly actionLimits?: import("@hypit/endpoint-kit").EndpointActionLimits;+ readonly capabilityConcurrency?: Readonly<Record<string, number>>;readonly pollIntervalMs?: number;readonly requestTimeoutMs?: number;- /** Whole file upload concurrency per origin/credential. Defaults to 8; range 1..64. */+ readonly oauthRequestTimeoutMs?: number;+ readonly pricingRequestTimeoutMs?: number;+ readonly operationTimeoutMs?: number;++ /** Whole files uploaded concurrently per service and credential in this process. */+ readonly uploadConcurrency?: number;- /** Timeout for one S3 multipart PUT. Defaults to five minutes. */readonly uploadPartTimeoutMs?: number;- /** Attempts per S3 part; only a failed part is retried. Defaults to three. */readonly uploadPartAttempts?: number;- /** Expose HypiHub VoiceDesign. Defaults to enabled; set false only for an explicit alternate Provider. */- readonly audio?: boolean;- /** HypiHub transcription model used for the WhisperX alignment capability. */- readonly whisperxModel?: string;+ readonly downloadAttempts?: number;+ /** HypiHub model used for the Provider-neutral WhisperX alignment capability. */+ readonly transcriptionModel?: string;readonly fetch?: typeof globalThis.fetch;- /** Overrides the default POST /v1/files upload for referenced artifacts. */- readonly publicAssetUrl?: (artifact: BlobRef, artifacts: ArtifactStore) => Promise<string>;+ /** Overrides HypiHub's negotiated upload transport for referenced Resources. */+ readonly publicAssetUrl?: (artifact: BlobRef, artifacts: ResourceStore) => Promise<string>;};type Handle = { readonly contract: "hypit.hypihub-operation@1"; readonly jobId: string; readonly route: string; readonly startedAt: number };@@@ -98,26 -104,17 +100,28 @@@ class HypiHubHttpError extends Errorclass HypiHubClient {readonly baseUrl: string;readonly timeout: number;+ readonly downloadAttempts: number;readonly fetcher: typeof globalThis.fetch;readonly uploader: HypiHubUploader;- constructor(options: { readonly baseUrl: string; readonly timeout: number; readonly uploadPartTimeout: number; readonly uploadPartAttempts: number; readonly uploadConcurrency: number; readonly fetcher: typeof globalThis.fetch }) {- this.baseUrl = options.baseUrl.replace(/\/$/u, ""); this.timeout = options.timeout;+ constructor(options: {+ readonly baseUrl: string;+ readonly timeout: number;++ readonly uploadConcurrency: number;+ readonly uploadPartTimeout: number;+ readonly uploadPartAttempts: number;+ readonly downloadAttempts: number;+ readonly fetcher: typeof globalThis.fetch;+ }) {+ this.baseUrl = options.baseUrl.replace(/\/$/u, "");+ this.timeout = options.timeout;+ this.downloadAttempts = options.downloadAttempts;this.fetcher = options.fetcher;this.uploader = new HypiHubUploader({baseUrl: this.baseUrl,requestTimeoutMs: this.timeout,++ uploadConcurrency: options.uploadConcurrency,uploadPartTimeoutMs: options.uploadPartTimeout,uploadPartAttempts: options.uploadPartAttempts,- uploadConcurrency: options.uploadConcurrency,fetch: this.fetcher,});}@@@ -151,22 -146,19 +155,15 @@@}throw lastError instanceof Error ? lastError : new Error(String(lastError));}- async upload(artifact: BlobRef, resources: ResourceStore, auth: HypiHubAuth, refreshOnUnauthorized = true): Promise<string> {- async upload(artifact: BlobRef, artifacts: ArtifactStore, auth: HypiHubAuth): Promise<string> {- const bytes = await artifacts.get(artifact.digest);- assert(bytes !== undefined, `HypiHub reference artifact ${artifact.digest} is unavailable`);- assert(bytes.byteLength === artifact.size, `HypiHub reference artifact ${artifact.digest} size differs`);- return this.uploader.upload({- bytes,- mediaType: artifact.mediaType,- purpose: "reference",- sha256: artifact.digest,- }, auth);++ async upload(artifact: BlobRef, resources: ResourceStore, auth: HypiHubAuth): Promise<string> {+ const bytes = await resources.get(artifact.resource);+ assert(bytes !== undefined, `HypiHub reference artifact ${artifact.resource} is unavailable`);+ assert(bytes.byteLength === artifact.size, `HypiHub reference artifact ${artifact.resource} size differs`);- try {- return await this.uploader.upload({ bytes, mediaType: artifact.mediaType }, await auth.token());- } catch (error) {- if (refreshOnUnauthorized && auth.canRefresh() && /HTTP 401\b/u.test(error instanceof Error ? error.message : String(error))) {- await auth.refresh();- return await this.upload(artifact, resources, auth, false);- }- throw error;- }++ return await this.uploader.upload({ bytes, mediaType: artifact.mediaType }, auth);}++async transcribe(body: Record<string, unknown>, auth: HypiHubAuth): Promise<Record<string, unknown>> {- return this.json("/audio/transcriptions", auth, {+ return await this.json("/audio/transcriptions", auth, {method: "POST",headers: { "content-type": "application/json" },body: JSON.stringify(body),@@@ -240,131 -183,9 +237,132 @@@ function pricingAuth(credentials: Reado});}-async function complete(client: HypiHubClient, auth: HypiHubAuth, route: (typeof hypiHubRoutes)[number], id: string, artifacts: ArtifactStore): Promise<EndpointOutcome> {+function pricingModel(request: import("@hypit/endpoint-kit").EndpointRequest, transcriptionModel: string): string | undefined {+ if (capabilityKey(request.capability) === capabilityKey(whisperXCapabilities.alignment)) {+ return transcriptionModel;+ }+ const route = hypiHubRouteForCapability(request.capability);+ if (route === undefined) return undefined;+ const generation = request.constraints as unknown as GenerationRequest;+ return selectWireModelForRequest(+ route,+ generation,+ request.pendingInputs?.map((input) => input.input),+ );+}++/** Read HypiHub's own current model-pricing document without calculating a request total. */+function hypiHubPricingReader(client: HypiHubClient, transcriptionModel: string): EndpointPricingReader {+ const documents = new Map<string, Promise<Record<string, unknown>>>();+ return async ({ request, credentials }) => {+ const model = pricingModel(request, transcriptionModel);+ if (model === undefined) return [];+ const path = `/pricing?model=${encodeURIComponent(model)}`;+ let pending = documents.get(model);+ if (pending === undefined) {+ pending = credentials().then(async (resolved) => await client.json(path, pricingAuth(resolved, client)));+ documents.set(model, pending);+ }+ const response = await pending;+ return [{+ source: `${client.baseUrl}${path}`,+ data: canonicalize(response),+ }];+ };+}++function cardEndpoints(card: Record<string, unknown> | undefined): readonly string[] {+ return Array.isArray(card?.endpoints)+ ? card.endpoints.filter((item): item is string => typeof item === "string")+ : [];+}++/** The catalogue's own names for a card: its id and its canonical name. */+function cardIdentifiers(card: Record<string, unknown>): readonly string[] {+ return [card.id, card.canonical_name].filter((name): name is string => typeof name === "string");+}++/** The additional model names a card answers to. HypiHub publishes the per-operation+ * routing names used by the Provider mapping table as aliases of one canonical card. */+function cardAliases(card: Record<string, unknown>): readonly string[] {+ return Array.isArray(card.aliases)+ ? card.aliases.filter((name): name is string => typeof name === "string")+ : [];+}++/** Active, read-only HypiHub check used only by doctor. */+export async function diagnoseHypiHubProvider(+ options: CreateHypiHubProviderOptions,+ context: {+ readonly credentials: Readonly<Record<string, { readonly secret: string }>>;+ readonly capabilities?: readonly CapabilityRef[];+ },+): Promise<readonly RuntimeDoctorDiagnostic[]> {+ const apiKey = context.credentials.apiKey?.secret;+ assert(typeof apiKey === "string" && apiKey.length > 0, "HypiHub login is unavailable");+ const client = new HypiHubClient({+ baseUrl: apiBaseUrl(options.baseUrl ?? "https://hypit.ai/v1"),+ timeout: options.requestTimeoutMs ?? 30_000,++ uploadConcurrency: options.uploadConcurrency ?? 8,+ uploadPartTimeout: options.uploadPartTimeoutMs ?? 5 * 60_000,+ uploadPartAttempts: options.uploadPartAttempts ?? 3,+ downloadAttempts: options.downloadAttempts ?? 3,+ fetcher: options.fetch ?? globalThis.fetch,+ });+ const auth = createHypiHubAuth({+ credential: { secret: apiKey },+ baseUrl: client.baseUrl,+ requestTimeoutMs: client.timeout,+ fetch: client.fetcher,+ });+ const response = await client.json("/models", auth);+ assert(Array.isArray(response.data), "HypiHub model catalogue has no data array");+ const catalogue: Record<string, unknown>[] = [];+ for (const value of response.data) {+ if (value === null || typeof value !== "object" || Array.isArray(value)) continue;+ catalogue.push(value as Record<string, unknown>);+ }+ const cards = new Map<string, Record<string, unknown>>();+ for (const card of catalogue) for (const name of cardIdentifiers(card)) cards.set(name, card);+ for (const card of catalogue) for (const alias of cardAliases(card)) {+ if (!cards.has(alias)) cards.set(alias, card);+ }+ const transcriptionModel = options.transcriptionModel?.trim() || "victor-upmeet/whisperx";+ const diagnostics: RuntimeDoctorDiagnostic[] = [];+ for (const capability of context.capabilities ?? []) {+ let available = false;+ if (capabilityKey(capability) === capabilityKey(whisperXCapabilities.alignment)) {+ available = cardEndpoints(cards.get(transcriptionModel)).includes("transcriptions");+ } else {+ const route = hypiHubRouteForCapability(capability);+ if (route !== undefined) {+ const acceptable = route.media === "image" ? ["images", "image_edits"]+ : route.media === "video" ? ["videos"] : ["audio_speech"];+ available = route.routes.some(({ model }) => cardEndpoints(cards.get(model))+ .some((endpoint) => acceptable.includes(endpoint)));+ }+ }+ if (!available) diagnostics.push({+ severity: "error",+ code: "HYPIHUB_CAPABILITY_UNAVAILABLE",+ message: `HypiHub login cannot currently route ${capabilityKey(capability)}`,+ subject: capabilityKey(capability),+ });+ }+ return diagnostics;+}++function generationOperation(route: (typeof hypiHubRoutes)[number], input: Record<string, unknown>): HypiHubModelOperation {+ if (route.media === "audio") return "audio_speech";+ if (route.media === "video") return "videos";+ const hasReferences = Object.entries(input).some(([key, value]) => {+ if (!["images", "reference_images", "reference_image_urls", "reference_videos", "reference_audios", "first_frame", "last_frame"].includes(key)) return false;+ return Array.isArray(value) ? value.length > 0 : typeof value === "string" && value.length > 0;+ });+ return hasReferences ? "image_edits" : "images";+}++async function complete(client: HypiHubClient, auth: HypiHubAuth, route: (typeof hypiHubRoutes)[number], id: string, artifacts: ResourceStore): Promise<EndpointOutcome> {const response = await client.json(`/jobs/${encodeURIComponent(id)}/assets`, auth); const items = response.items;assert(Array.isArray(items) && items.length > 0, "HypiHub job has no assets"); const blobs: BlobRef[] = [];for (const item of items) { const asset = object(item, "HypiHub asset"); assert(typeof asset.url === "string", "HypiHub asset has no URL"); const downloaded = await client.download(asset.url); blobs.push(await artifacts.put(downloaded.bytes, downloaded.mediaType)); }@@@ -452,51 -260,22 +450,53 @@@ function endpoint(client: HypiHubClient}export function createHypiHubProvider(options: CreateHypiHubProviderOptions = {}) {+ const capacityNames = new Set([...hypiHubRoutes.map((route) => route.capability.name), "transcription"]);+ const capabilityConcurrency = options.capabilityConcurrency ?? {};+ for (const [name, limit] of Object.entries(capabilityConcurrency)) {+ assert(capacityNames.has(name), `unknown HypiHub capacity ${name}`);+ assert(Number.isSafeInteger(limit) && limit > 0, `HypiHub ${name} capacity must be a positive integer`);+ }+ const requestTimeoutMs = options.requestTimeoutMs ?? 300_000;+ const oauthRequestTimeoutMs = options.oauthRequestTimeoutMs ?? 30_000;+ const pricingRequestTimeoutMs = options.pricingRequestTimeoutMs ?? 30_000;+ const operationTimeoutMs = options.operationTimeoutMs ?? 20 * 60_000;+ const uploadPartTimeoutMs = options.uploadPartTimeoutMs ?? 5 * 60_000;const uploadPartAttempts = options.uploadPartAttempts ?? 3;- assert(Number.isInteger(uploadPartAttempts) && uploadPartAttempts >= 1 && uploadPartAttempts <= 8,- "HypiHub uploadPartAttempts must be within 1..8");- const uploadPartTimeout = options.uploadPartTimeoutMs ?? 5 * 60_000;- assert(Number.isSafeInteger(uploadPartTimeout) && uploadPartTimeout > 0,- "HypiHub uploadPartTimeoutMs must be a positive integer");+ const downloadAttempts = options.downloadAttempts ?? 3;+ for (const [name, value] of Object.entries({+ requestTimeoutMs,+ oauthRequestTimeoutMs,+ pricingRequestTimeoutMs,+ operationTimeoutMs,+ uploadPartTimeoutMs,+ uploadPartAttempts,+ downloadAttempts,+ })) {+ assert(Number.isSafeInteger(value) && value > 0, `HypiHub ${name} must be a positive integer`);+ }+ assert(uploadPartAttempts <= 8, "HypiHub uploadPartAttempts must be within 1..8");const client = new HypiHubClient({- baseUrl: apiBaseUrl(options.baseUrl ?? "https://hypit.ai/v1"), timeout: options.requestTimeoutMs ?? 300_000,- uploadPartTimeout, uploadPartAttempts, uploadConcurrency: options.uploadConcurrency ?? 8,+ baseUrl: apiBaseUrl(options.baseUrl ?? "https://hypit.ai/v1"),+ timeout: requestTimeoutMs,++ uploadConcurrency: options.uploadConcurrency ?? 8,+ uploadPartTimeout: uploadPartTimeoutMs,+ uploadPartAttempts,+ downloadAttempts,+ fetcher: options.fetch ?? globalThis.fetch,+ });+ const pricingClient = new HypiHubClient({+ baseUrl: apiBaseUrl(options.baseUrl ?? "https://hypit.ai/v1"),+ timeout: pricingRequestTimeoutMs,++ uploadConcurrency: options.uploadConcurrency ?? 8,+ uploadPartTimeout: uploadPartTimeoutMs,+ uploadPartAttempts,+ downloadAttempts,fetcher: options.fetch ?? globalThis.fetch,});- const apiKey = options.apiKey ?? credentialRef("os", "hypihub.oauth");- const asyncEndpoint = endpoint(client, apiKey, options.pollIntervalMs ?? 10_000, 20 * 60_000, options.publicAssetUrl);+ const asyncEndpoint = endpoint(client, options.pollIntervalMs ?? 10_000, operationTimeoutMs, options.publicAssetUrl);const audioEndpoint: ImmediateEndpointHandler = async (context) => {try {- return await synthesizeAudio(client, context, apiKey, options.publicAssetUrl);+ return await synthesizeAudio(client, context, options.publicAssetUrl);} catch (error) {throw new Error(guidedMessage(error), { cause: error });}diff --cc packages/provider-hypihub/src/upload.tsindex ba6b046d,e7556ac1..826c0a42--- a/packages/provider-hypihub/src/upload.ts+++ b/packages/provider-hypihub/src/upload.ts@@@ -1,6 -1,17 +1,18 @@@+import { requestDeadline } from "@hypit/runtime-kit";import { createHash } from "node:crypto";+ import type { HypiHubAuth } from "./oauth.js";++ type UploadAuth = HypiHubAuth | string;++ async function uploadToken(auth: UploadAuth): Promise<string> {+ return typeof auth === "string" ? auth : await auth.token();+ }++ function uploadCanRefresh(auth: UploadAuth): boolean {+ return typeof auth !== "string" && auth.canRefresh();+ }+function assert(condition: unknown, message: string): asserts condition {if (!condition) throw new Error(message);}@@@ -50,9 -55,13 +56,13 @@@ class HypiHubHTTPError extends Errorexport type HypiHubUploaderOptions = {readonly baseUrl: string;readonly requestTimeoutMs: number;- readonly uploadPartTimeoutMs: number;- readonly uploadPartAttempts: number;- /** Whole files per origin/credential in this process. Defaults to 8; range 1..64. */++ /** Whole files per origin/credential in this process. Defaults to 8; any positive safe integer. */+ readonly uploadConcurrency?: number;+ readonly uploadPartTimeoutMs?: number;+ readonly uploadPartAttempts?: number;readonly fetch: typeof globalThis.fetch;+ /** Optional diagnostic sink. Defaults to stderr; messages never include credentials or signed URLs. */+ readonly logger?: (message: string) => void;};export type HypiHubUploadInput = {@@@ -75,41 -84,133 +84,131 @@@ type CompletedPart =readonly checksum_sha256: string;};- /** Provider-private transport for HypiHub's negotiated regional multipart upload. */+ function assertHTTPS(value: string, subject: string): void {+ let protocol = "";+ try { protocol = new URL(value).protocol; }+ catch { throw new Error(`${subject} is invalid`); }+ assert(protocol === "https:", `${subject} must use HTTPS`);+ }++ // A provider can upload references from several operations/uploader instances.+ // Bound whole file sessions, independently of each file's S3 part concurrency.+ type UploadGate = { active: number; limits: Map<number, number>; waiting: (() => void)[] };+ const uploadGates = new Map<string, UploadGate>();+ function drainUploadGate(gate: UploadGate): void {+ const limit = Math.min(...gate.limits.keys());+ while (gate.active < limit && gate.waiting.length > 0) {+ gate.active += 1;+ gate.waiting.shift()!();+ }+ }+ async function acquireUploadSlot(origin: string, auth: UploadAuth, limit: number): Promise<() => void> {+ const key = `${origin}:${createHash("sha256").update(await uploadToken(auth)).digest("hex")}`;+ let gate = uploadGates.get(key);+ if (gate === undefined) { gate = { active: 0, limits: new Map(), waiting: [] }; uploadGates.set(key, gate); }+ // Instances sharing a credential share capacity. The strictest outstanding+ // caller wins; a lower limit drains existing work without cancelling it.+ gate.limits.set(limit, (gate.limits.get(limit) ?? 0) + 1);+ await new Promise<void>((resolve) => { gate.waiting.push(resolve); drainUploadGate(gate); });+ return () => {+ gate.active -= 1;+ const remaining = (gate.limits.get(limit) ?? 1) - 1;+ if (remaining === 0) gate.limits.delete(limit); else gate.limits.set(limit, remaining);+ drainUploadGate(gate);+ if (gate.active === 0 && gate.waiting.length === 0) uploadGates.delete(key);+ };+ }++ /** Uploads media through HypiHub's session-negotiated private regional S3 multipart flow. */export class HypiHubUploader {- readonly #baseUrl: string;- readonly #requestTimeoutMs: number;- readonly #uploadPartTimeoutMs: number;- readonly #uploadPartAttempts: number;- readonly #fetch: typeof globalThis.fetch;+ readonly baseUrl: string;+ readonly requestTimeout: number;+ readonly uploadConcurrency: number;+ readonly uploadPartTimeout: number;+ readonly uploadPartAttempts: number;+ readonly fetcher: typeof globalThis.fetch;+ readonly logger: (message: string) => void;constructor(options: HypiHubUploaderOptions) {- this.#baseUrl = apiBaseUrl(options.baseUrl);- this.#requestTimeoutMs = requiredInteger(options.requestTimeoutMs, "HypiHub request timeout");- this.#uploadPartTimeoutMs = requiredInteger(options.uploadPartTimeoutMs, "HypiHub upload part timeout");- this.#uploadPartAttempts = requiredInteger(options.uploadPartAttempts, "HypiHub upload part attempts");- assert(this.#uploadPartAttempts <= 8, "HypiHub upload part attempts must be within 1..8");- this.#fetch = options.fetch;+ this.baseUrl = apiBaseUrl(options.baseUrl);+ this.requestTimeout = requiredInteger(options.requestTimeoutMs, "HypiHub upload request timeout");+ this.uploadConcurrency = requiredInteger(options.uploadConcurrency ?? 8, "HypiHub uploadConcurrency");- assert(this.uploadConcurrency <= 64, "HypiHub uploadConcurrency must be within 1..64");+ this.uploadPartTimeout = requiredInteger(options.uploadPartTimeoutMs ?? 5 * 60_000,+ "HypiHub upload part timeout");+ this.uploadPartAttempts = requiredInteger(options.uploadPartAttempts ?? 3,+ "HypiHub upload part attempts");+ assert(this.uploadPartAttempts <= 8, "HypiHub upload part attempts must be within 1..8");+ this.fetcher = options.fetch;+ this.logger = options.logger ?? ((message) => console.error(`[hypihub-upload] ${message}`));+ }++ private log(message: string): void { this.logger(message); }++ private elapsed(startedAt: number): string { return `${Date.now() - startedAt}ms`; }++ private safeReason(error: unknown): string {+ const message = error instanceof Error ? error.message : String(error);+ return message.replace(/https?:\/\/\S+/giu, "[redacted-url]").slice(0, 300);+ }++ private async json(path: string, auth: UploadAuth, init: RequestInit = {}): Promise<Record<string, unknown>> {+ const existingSession = /^\/files\/uploads\/[^/]+(?:\/(?:parts|complete))?$/u.test(path);+ const deadline = Date.now() + (existingSession ? Math.min(this.requestTimeout, 120_000) : this.requestTimeout);+ for (let attempt = 0; ; attempt += 1) {+ try {+ return await this.jsonOnce(path, auth, init, Math.max(1, deadline - Date.now()));+ } catch (error) {+ const http = error instanceof HypiHubHTTPError ? error : undefined;+ // Existing-session operations are idempotent. A new session may only+ // be retried after an explicit 429 rejection, never an unknown result.+ const retryable = http !== undefined+ ? ([408, 429, 500, 502, 503, 504].includes(http.status)+ || (http.status === 409 && http.code === "upload_incomplete"))+ : existingSession;+ const rejectedCreate = path === "/files/uploads" && http?.status === 429;+ if (attempt >= 3 || !retryable || (!existingSession && !rejectedCreate)+ || http?.code === "upload_daily_limit" || http?.code === "upload_storage_limit") throw error;+ const delay = http?.retryAfterMs ?? 500 * 2 ** attempt;+ // Respect a server's retry time; do not shorten it to fit our budget.+ if (Date.now() + delay >= deadline) throw error;+ this.log(`upload control retry method=${init.method ?? "GET"} path=${path} attempt=${attempt + 2} delay_ms=${delay}`);+ await new Promise((resolve) => setTimeout(resolve, delay));+ }+ }}- async #json(path: string, apiKey: string, init: RequestInit = {}): Promise<Record<string, unknown>> {- const deadline = requestDeadline(this.#requestTimeoutMs);+ private async jsonOnce(path: string, auth: UploadAuth, init: RequestInit, timeoutMs: number, retryAuth = true): Promise<Record<string, unknown>> {- const controller = new AbortController();- const timer = setTimeout(() => controller.abort(), timeoutMs);++ const request = requestDeadline(timeoutMs);+ const deadline = Date.now() + timeoutMs;try {- const response = await deadline.wait(this.#fetch(`${this.#baseUrl}${path}`, {- const response = await this.fetcher(`${this.baseUrl}${path}`, {++ const response = await request.wait(this.fetcher(`${this.baseUrl}${path}`, {...init,- signal: deadline.signal,- headers: { authorization: `Bearer ${apiKey}`, ...(init.headers ?? {}) },- signal: controller.signal,++ signal: request.signal,+ headers: { authorization: `Bearer ${await uploadToken(auth)}`, ...(init.headers ?? {}) },- });- const text = await response.text();+ }));- const text = await deadline.wait(response.text());++ const text = await request.wait(response.text());+ if (response.status === 401 && retryAuth && uploadCanRefresh(auth)) {+ await (auth as HypiHubAuth).refresh();+ return await this.jsonOnce(path, auth, init, Math.max(1, deadline - Date.now()), false);+ }let body: unknown = {};try { body = text.length === 0 ? {} : JSON.parse(text); }- catch { throw new Error(`HypiHub returned invalid JSON (${response.status})`); }+ catch {+ if (response.ok) throw new Error(`HypiHub returned invalid JSON (${response.status})`);+ }if (!response.ok) {- throw new Error(`HypiHub returned HTTP ${response.status}: ${safeMessage(text)}`);+ const errorBody = body !== null && typeof body === "object" && "error" in body ? body.error : undefined;+ const code = errorBody !== null && typeof errorBody === "object" && "code" in errorBody+ && typeof errorBody.code === "string" ? errorBody.code : undefined;+ const retryAfter = response.headers.get("retry-after");+ const parsedRetry = retryAfter === null ? NaN : /^\d+$/u.test(retryAfter.trim())+ ? Number(retryAfter) * 1000 : Date.parse(retryAfter) - Date.now();- throw new HypiHubHTTPError(response.status, `HypiHub returned HTTP ${response.status}: ${text.slice(0, 300)}`,++ throw new HypiHubHTTPError(response.status, `HypiHub returned HTTP ${response.status}: ${this.safeReason(text)}`,+ Number.isFinite(parsedRetry) ? Math.max(0, parsedRetry) : undefined, code);}return object(body, "HypiHub response");} finally {- deadline.finish();- clearTimeout(timer);++ request.finish();}}@@@ -136,96 -236,93 +234,92 @@@return signed;}- #signedHeaders(value: unknown, declaration: PartDeclaration): Record<string, string> {+ private signedHeaders(value: unknown, declaration: PartDeclaration): Record<string, string> {const raw = object(value, "HypiHub signed upload headers");- const headers: Record<string, string> = {};+ const headers = new Map<string, string>();for (const [name, headerValue] of Object.entries(raw)) {assert(typeof headerValue === "string", `HypiHub signed upload header ${name} is invalid`);- headers[name.toLowerCase()] = headerValue;+ headers.set(name.toLowerCase(), headerValue);}- assert(headers["content-length"] === String(declaration.bytes),- "HypiHub signed a different part size");- assert(headers["x-amz-checksum-sha256"] === declaration.checksum_sha256,- "HypiHub signed a different part checksum");- return headers;+ const contentLength = requiredString(headers.get("content-length"), "HypiHub signed Content-Length");+ const checksum = requiredString(headers.get("x-amz-checksum-sha256"), "HypiHub signed checksum");+ assert(contentLength === String(declaration.bytes), "HypiHub signed a different part size");+ assert(checksum === declaration.checksum_sha256, "HypiHub signed a different part checksum");+ return { "content-length": contentLength, "x-amz-checksum-sha256": checksum };}- async #putPart(- uploadId: string,- declaration: PartDeclaration,- initial: Record<string, unknown>,- bytes: Uint8Array,- apiKey: string,- ): Promise<CompletedPart> {- let signed = initial;- for (let attempt = 1; attempt <= this.#uploadPartAttempts; attempt += 1) {- if (attempt > 1) {- signed = (await this.#signParts(uploadId, [declaration], apiKey)).get(declaration.part_number) ?? {};+ private async putPart(uploadId: string, declaration: PartDeclaration, initial: Record<string, unknown>, body: Uint8Array, auth: UploadAuth): Promise<CompletedPart> {+ let capability = initial;+ for (let attempt = 0; attempt < this.uploadPartAttempts; attempt += 1) {+ if (attempt > 0) {+ const refreshed = await this.signParts(uploadId, [declaration], auth);+ capability = refreshed.get(declaration.part_number) ?? {};}- const deadline = requestDeadline(this.#uploadPartTimeoutMs);- const controller = new AbortController();- const timer = setTimeout(() => controller.abort(), this.uploadPartTimeout);++ const request = requestDeadline(this.uploadPartTimeout);+ const startedAt = Date.now();+ this.log(`part upload started upload=${uploadId} part=${declaration.part_number} bytes=${declaration.bytes} attempt=${attempt + 1}`);try {- const url = requiredString(signed.url, "HypiHub signed upload URL");+ const url = requiredString(capability.url, "HypiHub signed upload URL");assertHTTPS(url, "HypiHub signed upload URL");- const body = new ArrayBuffer(bytes.byteLength);- new Uint8Array(body).set(bytes);- const response = await deadline.wait(this.#fetch(url, {+ const payload = new ArrayBuffer(body.byteLength);+ new Uint8Array(payload).set(body);- const response = await this.fetcher(url, {++ const response = await request.wait(this.fetcher(url, {method: "PUT",- headers: this.#signedHeaders(signed.headers, declaration),- body,- signal: deadline.signal,+ headers: this.signedHeaders(capability.headers, declaration),+ body: payload,- signal: controller.signal,- });++ signal: request.signal,+ }));- if (!response.ok) throw new Error(`S3 rejected upload part with HTTP ${response.status}`);+ if (!response.ok) throw new Error(`S3 rejected upload part ${declaration.part_number} with HTTP ${response.status}`);const etag = response.headers.get("etag");- assert(etag !== null && etag.length > 0,- `HypiHub upload part ${declaration.part_number} returned no ETag`);- const returnedChecksum = response.headers.get("x-amz-checksum-sha256");- assert(returnedChecksum === null || returnedChecksum === declaration.checksum_sha256,- `HypiHub upload part ${declaration.part_number} returned a different checksum`);+ assert(etag !== null && etag.length > 0, `S3 upload part ${declaration.part_number} returned no ETag`);+ const verified = response.headers.get("x-amz-checksum-sha256");+ assert(verified === null || verified === declaration.checksum_sha256,+ `S3 upload part ${declaration.part_number} returned a different checksum`);+ this.log(`part upload completed upload=${uploadId} part=${declaration.part_number} bytes=${declaration.bytes} attempt=${attempt + 1} elapsed=${this.elapsed(startedAt)}`);return {part_number: declaration.part_number,etag,checksum_sha256: declaration.checksum_sha256,};- } catch {- if (attempt === this.#uploadPartAttempts) {- throw new Error(`HypiHub upload part ${declaration.part_number} failed after ${attempt} attempts`);+ } catch (error) {+ this.log(`part upload failed upload=${uploadId} part=${declaration.part_number} attempt=${attempt + 1} elapsed=${this.elapsed(startedAt)} reason=${this.safeReason(error)}`);+ if (attempt + 1 < this.uploadPartAttempts) {+ this.log(`part upload retry scheduled upload=${uploadId} part=${declaration.part_number} next_attempt=${attempt + 2}`);+ await new Promise((resolve) => setTimeout(resolve, 500 * (attempt + 1)));}} finally {- deadline.finish();- clearTimeout(timer);++ request.finish();}}- throw new Error(`HypiHub upload part ${declaration.part_number} failed`);+ // A presigned URL is a temporary credential, so never include the fetcher's URL-bearing error.+ throw new Error(`S3 upload part ${declaration.part_number} failed after ${this.uploadPartAttempts} attempts`);}- async #uploadParts(- bytes: Uint8Array,- apiKey: string,- policy: Record<string, unknown>,- ): Promise<string> {+ private async uploadDirect(bytes: Uint8Array, auth: UploadAuth, policy: Record<string, unknown>): Promise<string> {const uploadId = requiredString(policy.upload_id, "HypiHub upload id");- const partSize = requiredInteger(policy.part_size, "HypiHub upload part size");- const partCount = requiredInteger(policy.part_count, "HypiHub upload part count");- const concurrency = requiredInteger(policy.concurrency, "HypiHub upload concurrency");- assert(concurrency <= 8, "HypiHub upload concurrency exceeds 8");- assert(partCount <= 10_000, "HypiHub upload part count exceeds 10000");- assert(partCount === Math.ceil(bytes.byteLength / partSize),- "HypiHub upload part count differs from the file size");-- const declarations = Array.from({ length: partCount }, (_, index): PartDeclaration => {- const part = bytes.subarray(index * partSize, Math.min((index + 1) * partSize, bytes.byteLength));- return {- part_number: index + 1,- bytes: part.byteLength,- checksum_sha256: createHash("sha256").update(part).digest("base64"),- };- });-try {- const signed = await this.#signParts(uploadId, declarations, apiKey);+ const partSize = requiredInteger(policy.part_size, "HypiHub upload part size");+ const partCount = requiredInteger(policy.part_count, "HypiHub upload part count");+ const requestedConcurrency = requiredInteger(policy.concurrency, "HypiHub upload concurrency");+ assert(requestedConcurrency <= 8, "HypiHub upload concurrency exceeds 8");+ assert(partCount <= 10_000, "HypiHub upload part count exceeds 10000");+ assert(partCount === Math.ceil(bytes.byteLength / partSize), "HypiHub upload part count differs from the file size");+ const declarations = Array.from({ length: partCount }, (_, index) => {+ const start = index * partSize;+ const part = bytes.subarray(start, Math.min(start + partSize, bytes.byteLength));+ return {+ part_number: index + 1,+ bytes: part.byteLength,+ checksum_sha256: createHash("sha256").update(part).digest("base64"),+ };+ });+ this.log(`multipart upload negotiated upload=${uploadId} bytes=${bytes.byteLength} part_size=${partSize} parts=${partCount} concurrency=${requestedConcurrency}`);+ const signed = await this.signParts(uploadId, declarations, auth);const completed = new Array<CompletedPart>(partCount);let cursor = 0;+ let workerFailed = false;const worker = async (): Promise<void> => {- while (cursor < partCount) {+ while (!workerFailed && cursor < partCount) {const index = cursor;cursor += 1;const declaration = declarations[index];@@@ -242,39 -347,62 +344,59 @@@headers: { "content-type": "application/json" },body: JSON.stringify({ parts: completed }),});- const url = requiredString(response.url, "HypiHub upload URL");- assertHTTPS(url, "HypiHub upload URL");+ const url = requiredString(response.url, "HypiHub direct upload URL");+ assert(/^https:\/\//iu.test(url), "HypiHub direct upload returned no HTTPS URL");+ this.log(`multipart complete finished upload=${uploadId} parts=${partCount} elapsed=${this.elapsed(completeStartedAt)}`);return url;} catch (error) {- try {- await this.#json(`/files/uploads/${encodeURIComponent(uploadId)}`, apiKey, { method: "DELETE" });- } catch {- // The upload already failed; cancellation is best-effort cleanup, not recovery.+ this.log(`multipart upload failed upload=${uploadId} reason=${this.safeReason(error)}`);+ try { await this.json(`/files/uploads/${encodeURIComponent(uploadId)}`, auth, { method: "DELETE" }); }+ catch (cancelError) {+ if (!(cancelError instanceof HypiHubHTTPError && (cancelError.status === 404+ || (cancelError.status === 409 && cancelError.code === "upload_completed")))) {+ this.log(`upload cancellation still pending upload=${uploadId} reason=${this.safeReason(cancelError)}`);+ }}- // A signed transport URL may be present in a lower-level failure. Do not- // retain that failure as a public cause after the upload has been cancelled.- throw new Error(safeMessage(error));- throw error;++ throw new Error(this.safeReason(error));}}- async upload(input: HypiHubUploadInput, apiKey: string): Promise<string> {+ async upload(input: HypiHubUploadInput, auth: UploadAuth): Promise<string> {+ const release = await acquireUploadSlot(this.baseUrl, auth, this.uploadConcurrency);+ try { return await this.uploadWithSlot(input, auth); }+ finally { release(); }+ }++ private async uploadWithSlot(input: HypiHubUploadInput, auth: UploadAuth): Promise<string> {- assert(input.bytes.byteLength > 0, "HypiHub reference artifact is empty");+ assert(input.bytes.byteLength > 0, "HypiHub reference Resource is empty");- // The current HypiHub upload protocol asks for a whole-file transport checksum.- // It is not persisted by Hypit and never participates in Resource identity or reuse.- const transportChecksum = createHash("sha256").update(input.bytes).digest("hex");- const policy = await this.#json("/files/uploads", apiKey, {- method: "POST",- headers: { "content-type": "application/json" },- body: JSON.stringify({- filename: input.filename ?? `reference.${extension(input.mediaType)}`,- bytes: input.bytes.byteLength,- mime_type: input.mediaType,- purpose: input.purpose ?? "reference",- sha256: transportChecksum,- head_base64: Buffer.from(input.bytes.subarray(0, 512)).toString("base64"),- }),- });+ const startedAt = Date.now();++ // Required wire checksum, not a Resource identity or a reuse key.+ const digest = createHash("sha256").update(input.bytes).digest("hex");- this.log(`upload started bytes=${input.bytes.byteLength} mime=${input.mediaType} digest=${digest.slice(0, 12)}`);- if (input.sha256 !== undefined) {- assert(input.sha256.toLowerCase().replace(/^sha256:/u, "") === digest,- "HypiHub reference artifact failed its SHA-256 check");- }++ this.log(`upload started bytes=${input.bytes.byteLength} mime=${input.mediaType}`);+ let policy: Record<string, unknown>;+ const policyStartedAt = Date.now();+ this.log(`upload session request started bytes=${input.bytes.byteLength} mime=${input.mediaType}`);+ try {+ policy = await this.json("/files/uploads", auth, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({- filename: input.filename ?? `${digest}.${extension(input.mediaType)}`,++ filename: input.filename ?? `reference.${extension(input.mediaType)}`,+ bytes: input.bytes.byteLength,+ mime_type: input.mediaType,+ purpose: input.purpose ?? "reference",+ sha256: digest,+ head_base64: Buffer.from(input.bytes.subarray(0, 512)).toString("base64"),+ }),+ });+ this.log(`upload session request finished elapsed=${this.elapsed(policyStartedAt)}`);+ } catch (error) {+ this.log(`upload session request failed elapsed=${this.elapsed(policyStartedAt)} reason=${this.safeReason(error)}`);+ throw error;+ }assert(policy.upload_mode === "s3_multipart", "HypiHub returned an unknown upload mode");- return await this.#uploadParts(input.bytes, apiKey, policy);+ const result = await this.uploadDirect(input.bytes, auth, policy);+ this.log(`upload finished bytes=${input.bytes.byteLength} mime=${input.mediaType} elapsed=${this.elapsed(startedAt)}`);+ return result;}}diff --cc packages/provider-hypihub/test/upload.test.tsindex 00000000,c6f22bfa..e3b21a5cmode 000000,100644..100644--- a/packages/provider-hypihub/test/upload.test.ts+++ b/packages/provider-hypihub/test/upload.test.ts@@@ -1,0 -1,212 +1,232 @@@+ import assert from "node:assert/strict";+ import { test } from "node:test";+ import { HypiHubUploader } from "../src/upload.js";++ const input = { bytes: new Uint8Array([1, 2, 3, 4]), mediaType: "video/mp4" };+ const retry = (status: number, code = "rate_limited") => Response.json({ error: { code } }, { status, headers: { "retry-after": "0" } });+ function fixture(hook: (url: string, init: RequestInit, calls: string[]) => Response | undefined | Promise<Response | undefined> = () => undefined) {+ const calls: string[] = [];+ const logs: string[] = [];+ const fetcher: typeof fetch = async (resource, init = {}) => {+ const url = String(resource);+ calls.push(`${init.method} ${url}`);+ const override = await hook(url, init, calls);+ if (override !== undefined) return override;+ if (url.endsWith("/files/uploads")) return Response.json({ upload_mode: "s3_multipart", upload_id: "up_test", part_size: 16, part_count: 1, concurrency: 4 });+ if (url.endsWith("/parts")) {+ const body = JSON.parse(String(init.body)) as { parts: { part_number: number; bytes: number; checksum_sha256: string }[] };+ return Response.json({ parts: body.parts.map((p) => ({ part_number: p.part_number, url: `https://s3.test/${p.part_number}`, headers: { "content-length": String(p.bytes), "x-amz-checksum-sha256": p.checksum_sha256 } })) });+ }+ if (url.startsWith("https://s3.test/")) return new Response(null, { headers: { etag: "etag" } });+ if (url.endsWith("/complete")) return Response.json({ url: "https://hub.test/files/result" });+ if (init.method === "DELETE") return new Response(null, { status: 204 });+ throw new Error(`unexpected request ${url}`);+ };+ const uploader = (uploadConcurrency?: number) => new HypiHubUploader({ ...(uploadConcurrency === undefined ? {} : { uploadConcurrency }), baseUrl: "https://hub.test", requestTimeoutMs: 5000, uploadPartAttempts: 1, fetch: fetcher, logger: (message) => logs.push(message) });+ return { uploader, calls, logs };+ }++ test("completion retries HTML 502 and 429 on the same session without creating another upload", async () => {+ let completes = 0;+ const f = fixture((url) => {+ if (!url.endsWith("/complete")) return;+ completes += 1;+ if (completes === 1) return new Response("<html>gateway</html>", { status: 502, headers: { "retry-after": "0" } });+ if (completes === 2) return retry(429);+ });+ assert.equal(await f.uploader().upload(input, "test-key"), "https://hub.test/files/result");+ assert.equal(completes, 3);+ assert.equal(f.calls.filter((c) => c.endsWith("/files/uploads")).length, 1);+ assert.equal(f.calls.filter((c) => c.startsWith("DELETE")).length, 0);+ });++ test("part signing retries and cancellation survives a transient gateway failure", async () => {+ let signs = 0;+ let cancels = 0;+ const f = fixture((url, init) => {+ if (url.endsWith("/parts") && ++signs === 1) return retry(429);+ if (url.startsWith("https://s3.test")) return new Response(null, { status: 400 });+ if (init.method === "DELETE" && ++cancels === 1) return retry(502);+ });+ await assert.rejects(f.uploader().upload(input, "test-key"), /S3 upload part 1 failed/u);+ assert.equal(signs, 2);+ assert.equal(cancels, 2);+ assert.equal(f.calls.filter((c) => c.endsWith("/files/uploads")).length, 1);+ });++ test("new sessions retry explicit temporary rejection, but never an unknown creation result", async () => {+ for (const mode of ["network", "500", "daily", "storage", "429"] as const) {+ let creates = 0;+ const f = fixture((url) => {+ if (!url.endsWith("/files/uploads")) return;+ creates += 1;+ if (mode === "network") throw new TypeError("fetch failed");+ if (mode === "500") return retry(500);+ if (mode === "daily") return retry(429, "upload_daily_limit");+ if (mode === "storage") return retry(429, "upload_storage_limit");+ if (creates === 1) return retry(429, "upload_concurrency_limit");+ });+ if (mode === "429") { await f.uploader().upload(input, "test-key"); assert.equal(creates, 2); }+ else { await assert.rejects(f.uploader().upload(input, "test-key")); assert.equal(creates, 1); }+ }+ });++ test("lifecycle retries are bounded and an unconfirmed cancellation retains its diagnostic id", async () => {+ const f = fixture((url, init) => {+ if (url.endsWith("/complete") || init.method === "DELETE") return retry(503);+ });+ await assert.rejects(f.uploader().upload(input, "test-key"), /503/u);+ assert.equal(f.calls.filter((c) => c.endsWith("/complete")).length, 4);+ assert.equal(f.calls.filter((c) => c.startsWith("DELETE")).length, 4);+ assert(f.logs.some((line) => line.includes("cancellation still pending upload=up_test")));+ assert(!f.logs.some((line) => line.includes("test-key")));+ });++ test("a Retry-After beyond the retry budget is not shortened or retried early", async () => {+ const f = fixture((url) => url.endsWith("/complete")+ ? new Response(null, { status: 429, headers: { "retry-after": "60" } }) : undefined);+ await assert.rejects(f.uploader().upload(input, "test-key"), /429/u);+ assert.equal(f.calls.filter((c) => c.endsWith("/complete")).length, 1);+ });++ test("file concurrency is shared across uploader instances for the same origin and credential", async () => {+ let active = 0;+ let maximum = 0;+ let nextId = 0;+ let release!: () => void;+ const barrier = new Promise<void>((resolve) => { release = resolve; });+ const f = fixture(async (url) => {+ if (url.endsWith("/files/uploads")) {+ active += 1; maximum = Math.max(maximum, active); nextId += 1;+ return Response.json({ upload_mode: "s3_multipart", upload_id: `up_${nextId}`, part_size: 16, part_count: 1, concurrency: 4 });+ }+ if (url.endsWith("/complete")) {+ await barrier; active -= 1;+ return Response.json({ url: "https://hub.test/files/result" });+ }+ });+ const uploads = Array.from({ length: 50 }, () => f.uploader().upload(input, "test-key"));+ await new Promise<void>((resolve) => setImmediate(resolve));+ assert.equal(nextId, 8);+ release();+ await Promise.all(uploads);+ assert.equal(nextId, 50); assert.equal(maximum, 8); assert.equal(active, 0);+ });++ test("cancellation waits for other in-flight part workers to settle", async () => {+ let release!: () => void;+ const barrier = new Promise<void>((resolve) => { release = resolve; });+ const f = fixture(async (url) => {+ if (url.endsWith("/files/uploads")) return Response.json({ upload_mode: "s3_multipart", upload_id: "up_test", part_size: 2, part_count: 2, concurrency: 2 });+ if (url === "https://s3.test/1") return new Response(null, { status: 400 });+ if (url === "https://s3.test/2") { await barrier; return new Response(null, { headers: { etag: "etag" } }); }+ });+ const result = assert.rejects(f.uploader().upload(input, "test-key"), /S3 upload part 1 failed/u);+ await new Promise<void>((resolve) => setImmediate(resolve));+ assert.equal(f.calls.filter((c) => c.startsWith("DELETE")).length, 0);+ release(); await result;+ assert.equal(f.calls.filter((c) => c.startsWith("DELETE")).length, 1);+ });++ test("invalid negotiated policy still cancels its known upload session", async () => {+ const f = fixture((url) => url.endsWith("/files/uploads")+ ? Response.json({ upload_mode: "s3_multipart", upload_id: "up_test", part_size: 0 }) : undefined);+ await assert.rejects(f.uploader().upload(input, "test-key"), /part size/u);+ assert.equal(f.calls.filter((c) => c.startsWith("DELETE")).length, 1);+ });++ test("configured file concurrency controls batches and releases capacity after failures", async () => {+ for (const limit of [1, 4, 16]) {+ let active = 0; let maximum = 0; let created = 0;+ let release!: () => void;+ const barrier = new Promise<void>((resolve) => { release = resolve; });+ const f = fixture(async (url, init) => {+ if (url.endsWith("/files/uploads")) {+ active += 1; maximum = Math.max(maximum, active); created += 1;+ return Response.json({ upload_mode: "s3_multipart", upload_id: `up_${created}`, part_size: 16, part_count: 1, concurrency: 4 });+ }+ if (url.endsWith("/complete")) { await barrier; throw new Error("completion unavailable"); }+ if (init.method === "DELETE") { active -= 1; return new Response(null, { status: 204 }); }+ });+ // A terminal response avoids retry sleeps; all files must still drain.+ const original = f.uploader(limit).fetcher;+ const uploader = new HypiHubUploader({ baseUrl: "https://hub.test", requestTimeoutMs: 5000, uploadConcurrency: limit, logger: () => {}, fetch: async (resource, init) => {+ try { return await original(resource, init); }+ catch { return Response.json({ error: { code: "invalid_completion" } }, { status: 400 }); }+ } });+ const pending = Array.from({ length: 50 }, () => uploader.upload(input, `configured-${limit}`));+ const settled = Promise.allSettled(pending);+ await new Promise<void>((resolve) => setImmediate(resolve));+ assert.equal(created, limit);+ release();+ assert((await settled).every((r) => r.status === "rejected"));+ assert.equal(created, 50); assert.equal(maximum, limit); assert.equal(active, 0);+ }+ });++ test("the strictest outstanding instance limit is shared and disappears when it drains", async () => {+ let active = 0; let created = 0; let phaseMaximum = 0;+ let release!: () => void;+ const barrier = new Promise<void>((resolve) => { release = resolve; });+ const f = fixture(async (url) => {+ if (url.endsWith("/files/uploads")) {+ active += 1; phaseMaximum = Math.max(phaseMaximum, active); created += 1;+ return Response.json({ upload_mode: "s3_multipart", upload_id: `up_${created}`, part_size: 16, part_count: 1, concurrency: 4 });+ }+ if (url.endsWith("/complete")) { await barrier; active -= 1; return Response.json({ url: "https://hub.test/files/result" }); }+ });+ const low = f.uploader(2); const high = f.uploader(8);+ const pending = [low.upload(input, "mixed-limit"), low.upload(input, "mixed-limit"), ...Array.from({ length: 12 }, () => high.upload(input, "mixed-limit"))];+ await new Promise<void>((resolve) => setImmediate(resolve));+ assert.equal(created, 2);+ release(); await Promise.all(pending);+ assert.equal(active, 0); assert.equal(phaseMaximum, 8);+ });++ test("file and part concurrency remain separate for a multipart batch", async () => {+ let puts = 0; let peakPuts = 0; let creates = 0;+ let release!: () => void;+ const barrier = new Promise<void>((resolve) => { release = resolve; });+ const f = fixture(async (url) => {+ if (url.endsWith("/files/uploads")) {+ creates += 1;+ return Response.json({ upload_mode: "s3_multipart", upload_id: `up_${creates}`, part_size: 1, part_count: 4, concurrency: 4 });+ }+ if (url.startsWith("https://s3.test/")) {+ puts += 1; peakPuts = Math.max(peakPuts, puts);+ await barrier; puts -= 1;+ return new Response(null, { headers: { etag: "etag" } });+ }+ });+ const pending = Array.from({ length: 12 }, () => f.uploader().upload(input, "multipart-batch"));+ await new Promise<void>((resolve) => setImmediate(resolve));+ assert.equal(creates, 8); assert.equal(puts, 32);+ release(); await Promise.all(pending);+ assert.equal(creates, 12); assert.equal(puts, 0); assert.equal(peakPuts, 32);+ });++ test("invalid uploadConcurrency is rejected before network activity", () => {+ const f = fixture();- for (const value of [0, -1, 1.5, 65, NaN]) assert.throws(() => f.uploader(value), /uploadConcurrency/u);++ for (const value of [0, -1, 1.5, Number.MAX_SAFE_INTEGER + 1, NaN]) assert.throws(() => f.uploader(value), /uploadConcurrency/u);+ assert.equal(f.calls.length, 0);+ });++++test("OAuth refresh keeps the existing upload session and retries only its rejected request", async () => {++ let token = "expired";++ let refreshes = 0;++ const f = fixture((url, init) => {++ if (url.endsWith("/parts") && new Headers(init.headers).get("authorization") === "Bearer expired") {++ return Response.json({ error: { code: "unauthorized" } }, { status: 401 });++ }++ });++ const auth = {++ token: async () => token,++ canRefresh: () => true,++ refresh: async () => { refreshes += 1; token = "renewed"; return token; },++ };++ assert.equal(await f.uploader().upload(input, auth), "https://hub.test/files/result");++ assert.equal(refreshes, 1);++ assert.equal(f.calls.filter((call) => call.endsWith("/files/uploads")).length, 1);++ assert.equal(f.calls.filter((call) => call.endsWith("/parts")).length, 2);++ assert.equal(f.calls.filter((call) => call.startsWith("DELETE")).length, 0);++});