@mindscraft/branch-video-agent-cli 0.4.7 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -254,6 +254,60 @@ AI Gateway Seed Audio 音频生成并等待示例:
254
254
 
255
255
  `tts-create` / `tts-get` 是 Seed Audio 的历史兼容别名;新脚本优先使用 `seed-audio-create` / `seed-audio-get`。
256
256
 
257
+ ## RPG2 生产工作台
258
+
259
+ 工作台 CLI 只提交调用方显式登记的项目、产物和归档清单;它不会扫描 RPG 阶段目录,也不会根据文件名推断版本关系。认证仍使用 `AIHUB_AGENT_TOKEN` 与 `BRANCH_VIDEO_AGENT_BASE_URL`,不要在 JSON、命令行或日志中保存 token。
260
+
261
+ 项目、生产记录和外部 CDN 产物可使用 JSON 文件提交:
262
+
263
+ ```powershell
264
+ branch-video-agent workbench project create --file .\project.json --raw
265
+ branch-video-agent workbench record put --project wb_project_id --file .\record.json --raw
266
+ branch-video-agent workbench submit --file .\artifact-external.json --raw
267
+ branch-video-agent workbench annotation put --project wb_project_id --file .\annotation.json --raw
268
+ ```
269
+
270
+ 同一产物用稳定的 `artifactKey` 和由流程侧持久维护的递增 `sourceRevision`。`idempotencyKey` 由流程侧保存并在重试时复用。已有持久媒体使用 `content.type: "external"`;本地文档、脱敏 session 或其他需要长期保存的文件使用 `content.type: "local"` 与 `sourcePath`。CLI 会先计算原文件 SHA-256、声明 blob,再流式 gzip 压缩上传(包括媒体与 session)。传输使用 `Content-Type: application/gzip` 和 `x-workbench-upload-format: gzip`,不使用 `Content-Encoding`;服务端流式解压后校验原始大小与 SHA-256,原 MIME、版本和幂等键不变,下载返回原文件字节。原文件上限为 64 MiB,压缩传输上限为 65 MiB。损坏、截断或超限上传不会成为 ready,CLI 不会自动回退 raw。CLI 生成单个 gzip member;服务端支持受限 gzip 字节流并统一校验解压后的总字节,无目录或多文件提取。服务端仍兼容未带传输标识的旧 raw 请求(原生 gzip 文件也保持原样);部署时应先更新服务端再发布 CLI。服务端只收到 blob 描述,绝不会收到本地路径。
271
+
272
+ ```json
273
+ {
274
+ "schemaVersion": "workbench.artifact/1",
275
+ "projectId": "wb_project_id",
276
+ "artifactKey": "document:director-program",
277
+ "sourceRevision": 2,
278
+ "idempotencyKey": "persisted-event-uuid",
279
+ "kind": "markdown",
280
+ "stageKey": "04",
281
+ "title": "导演稿",
282
+ "content": {
283
+ "type": "local",
284
+ "sourcePath": "C:/production/canonical/director.md",
285
+ "mime": "text/markdown"
286
+ },
287
+ "source": {
288
+ "productionRecordId": "record_id",
289
+ "archiveGeneration": 0,
290
+ "sourceSchema": "director-program/4"
291
+ }
292
+ }
293
+ ```
294
+
295
+ 上传响应在网络中丢失时,CLI 会先查询同一个已声明 blob;ready 状态不会重传,也不会重新登记业务版本。失败交给流程侧持久待传队列用相同事件重试。
296
+
297
+ `sync` 只读取 `--manifest` 中显式的 `items`。每个 item 为 `type: "artifact"`(默认)或 `type: "annotation"`,可直接携带提交字段或放进 `submission`;不会递归任何工作目录。
298
+
299
+ ```powershell
300
+ branch-video-agent workbench sync --manifest .\.workbench\pending-items.json --raw
301
+ branch-video-agent workbench archive prepare --manifest .\.workbench\archive-wrapper.json --raw
302
+ branch-video-agent workbench archive finalize --project wb_project_id --record record_id --revision 1 --manifest-hash <sha256> --raw
303
+ branch-video-agent workbench archive status --project wb_project_id --record record_id --raw
304
+ branch-video-agent workbench archive download --project wb_project_id --record record_id --revision 1 --file .\entry.json --output .\session.jsonl.zst --raw
305
+ ```
306
+
307
+ `archive prepare` 的文件是调用方维护的 wrapper:`{ manifest, manifestHash, expectedPreviousRevision }`;CLI 原样提交规范化清单和 hash。`archive finalize` 只校验已经提交的清单,不补扫文件。下载的 `entry.json` 至少包含 `{ "entryId": "..." }`;受权限保护的字节写入 `--output`,stdout 仍只输出 JSON 回执。
308
+
309
+ `record put` 的路径参数是稳定的流程 `recordKey`,返回对象的 `id` 才是后续 `end-intent`、`reopen` 和所有 `archive` 命令使用的 `productionRecordId`(也可传给 `--record`)。不要把 `recordKey` 当成归档路由 ID。
310
+
257
311
  ## 在仓库内构建发布包
258
312
 
259
313
  从仓库根目录执行:
@@ -263,6 +317,14 @@ npm run agent:cli:package:build
263
317
  npm run agent:cli:package:smoke
264
318
  ```
265
319
 
320
+ 需要运行会启动 standalone Mongo、真实 CLI HTTP 流、Python adapter 或 Chromium 的 Production Workbench 集成验收时,使用专用命令;常规 `npm test` 会排除这些外部运行时依赖。adapter E2E 需要相邻的 rpg2 adapter checkout,或显式设置 `RPG2_WORKBENCH_ADAPTER_ROOT`;缺失 checkout、`zstd` 或 Chromium 时命令应失败。
321
+
322
+ ```powershell
323
+ npm run test:workbench-cli-integration
324
+ npm run test:workbench-adapter-e2e
325
+ npm run test:workbench-integration
326
+ ```
327
+
266
328
  产物输出到:
267
329
 
268
330
  ```text
@@ -0,0 +1,2 @@
1
+ import type { CommandHandler } from '../lib/types.js';
2
+ export declare const workbenchCommands: Record<string, CommandHandler>;
@@ -0,0 +1,318 @@
1
+ import { createGzip } from 'node:zlib';
2
+ import { pipeline } from 'node:stream/promises';
3
+ import { createHash } from 'node:crypto';
4
+ import { createReadStream } from 'node:fs';
5
+ import { stat, writeFile } from 'node:fs/promises';
6
+ import { Readable } from 'node:stream';
7
+ import { CliCommandError } from '../lib/errors.js';
8
+ import { ensureObject, getRequiredInt, getRequiredString, omitKeys, pickDefined } from '../lib/payload.js';
9
+ const workbenchPath = '/api/production-workbench';
10
+ const MAX_LOCAL_FILE_BYTES = 64 * 1024 * 1024;
11
+ const blobPurposes = new Set(['artifact', 'manifest', 'session', 'evidence']);
12
+ function payloadValue(payload, flagValue, key) {
13
+ return getRequiredString({ [key]: payload[key] || flagValue }, key);
14
+ }
15
+ function projectId(payload, flagValue) {
16
+ return payloadValue(payload, flagValue, 'projectId');
17
+ }
18
+ function productionRecordId(payload, flagValue) {
19
+ return getRequiredString({ productionRecordId: payload.productionRecordId || payload.recordId || flagValue }, 'productionRecordId');
20
+ }
21
+ function getRevision(payload, flagValue) {
22
+ return payload.revision === undefined && flagValue
23
+ ? getRequiredInt({ revision: flagValue }, 'revision')
24
+ : getRequiredInt(payload, 'revision');
25
+ }
26
+ function localContent(payload) {
27
+ const content = ensureObject(payload.content, 'content');
28
+ const sourcePath = typeof content.sourcePath === 'string' && content.sourcePath.trim()
29
+ ? content.sourcePath.trim()
30
+ : typeof payload.sourcePath === 'string' && payload.sourcePath.trim()
31
+ ? payload.sourcePath.trim()
32
+ : '';
33
+ return sourcePath ? { content, sourcePath } : null;
34
+ }
35
+ async function sha256File(sourcePath) {
36
+ const digest = createHash('sha256');
37
+ for await (const chunk of createReadStream(sourcePath))
38
+ digest.update(chunk);
39
+ return digest.digest('hex');
40
+ }
41
+ async function uploadLocalContent(context, sourcePath, content) {
42
+ let fileStat;
43
+ try {
44
+ fileStat = await stat(sourcePath);
45
+ }
46
+ catch (error) {
47
+ throw new CliCommandError(`Cannot read sourcePath: ${error?.message || error}`, 'VALIDATION_ERROR');
48
+ }
49
+ if (!fileStat.isFile())
50
+ throw new CliCommandError('sourcePath must be a regular file', 'VALIDATION_ERROR');
51
+ if (fileStat.size > MAX_LOCAL_FILE_BYTES)
52
+ throw new CliCommandError(`sourcePath exceeds ${MAX_LOCAL_FILE_BYTES} byte upload limit`, 'FILE_TOO_LARGE');
53
+ const sha256 = await sha256File(sourcePath);
54
+ if (typeof content.sha256 === 'string' && content.sha256 && content.sha256 !== sha256) {
55
+ throw new CliCommandError('sourcePath sha256 does not match content.sha256', 'VALIDATION_ERROR');
56
+ }
57
+ const mime = typeof content.mime === 'string' && content.mime ? content.mime : 'application/octet-stream';
58
+ const purpose = typeof content.purpose === 'string' && content.purpose ? content.purpose : 'artifact';
59
+ if (!blobPurposes.has(purpose))
60
+ throw new CliCommandError(`Invalid local content purpose: ${purpose}`, 'VALIDATION_ERROR');
61
+ const declared = await context.client.request(`${workbenchPath}/projects/${encodeURIComponent(projectId(context.payload, context.flags.project))}/blobs`, {
62
+ method: 'POST',
63
+ body: {
64
+ sha256,
65
+ size: fileStat.size,
66
+ mime,
67
+ purpose,
68
+ ...(content.redaction === undefined ? {} : { redaction: content.redaction }),
69
+ },
70
+ timeoutMs: context.flags.timeoutMs,
71
+ });
72
+ const blobId = getRequiredString(declared.data, 'id');
73
+ if (declared.data.state !== 'ready') {
74
+ let uploadError;
75
+ const source = createReadStream(sourcePath), compressed = createGzip();
76
+ const compressing = pipeline(source, compressed);
77
+ // Fetch consumes the compressed readable; prevent an unhandled rejection
78
+ // until its stream error reaches requestStream. Always close both below.
79
+ void compressing.catch(() => undefined);
80
+ try {
81
+ await context.client.requestStream(`${workbenchPath}/projects/${encodeURIComponent(projectId(context.payload, context.flags.project))}/blobs/${encodeURIComponent(blobId)}/content`, {
82
+ method: 'PUT',
83
+ body: Readable.toWeb(compressed),
84
+ contentType: 'application/gzip',
85
+ uploadFormat: 'gzip',
86
+ timeoutMs: context.flags.timeoutMs,
87
+ });
88
+ }
89
+ catch (error) {
90
+ uploadError = error;
91
+ }
92
+ finally {
93
+ source.destroy();
94
+ compressed.destroy();
95
+ await compressing.catch(() => undefined);
96
+ }
97
+ if (uploadError) {
98
+ const status = await context.client.request(`${workbenchPath}/projects/${encodeURIComponent(projectId(context.payload, context.flags.project))}/blobs/${encodeURIComponent(blobId)}`, {
99
+ method: 'GET',
100
+ timeoutMs: context.flags.timeoutMs,
101
+ });
102
+ if (status.data.state !== 'ready')
103
+ throw uploadError;
104
+ }
105
+ }
106
+ return { type: 'blob', blobId, sha256, size: fileStat.size, mime };
107
+ }
108
+ function validateSubmission(payload) {
109
+ if (payload.schemaVersion !== 'workbench.artifact/1') {
110
+ throw new CliCommandError('schemaVersion must be workbench.artifact/1', 'VALIDATION_ERROR');
111
+ }
112
+ getRequiredString(payload, 'artifactKey');
113
+ const sourceRevision = getRequiredInt(payload, 'sourceRevision');
114
+ if (sourceRevision < 1)
115
+ throw new CliCommandError('Invalid sourceRevision', 'VALIDATION_ERROR');
116
+ getRequiredString(payload, 'idempotencyKey');
117
+ getRequiredString(payload, 'title');
118
+ getRequiredString(payload, 'kind');
119
+ getRequiredString(payload, 'stageKey');
120
+ const source = ensureObject(payload.source, 'source');
121
+ getRequiredString(source, 'productionRecordId');
122
+ const archiveGeneration = getRequiredInt(source, 'archiveGeneration');
123
+ if (archiveGeneration < 0)
124
+ throw new CliCommandError('Invalid source.archiveGeneration', 'VALIDATION_ERROR');
125
+ }
126
+ async function submitArtifact(context, payload) {
127
+ const id = projectId(payload, context.flags.project);
128
+ validateSubmission(payload);
129
+ const local = localContent(payload);
130
+ let body = omitKeys(payload, ['projectId', 'sourcePath']);
131
+ if (local) {
132
+ const blob = await uploadLocalContent({ ...context, payload }, local.sourcePath, local.content);
133
+ body = { ...body, content: blob };
134
+ }
135
+ const result = await context.client.request(`${workbenchPath}/projects/${encodeURIComponent(id)}/artifact-versions`, {
136
+ method: 'POST',
137
+ body,
138
+ timeoutMs: context.flags.timeoutMs,
139
+ });
140
+ return { data: result.data, requestId: result.requestId };
141
+ }
142
+ async function readManifest(context) {
143
+ if (!context.flags.manifest)
144
+ throw new CliCommandError('Missing --manifest', 'VALIDATION_ERROR');
145
+ try {
146
+ return ensureObject(JSON.parse(await context.runtime.readTextFile(context.flags.manifest)), '--manifest');
147
+ }
148
+ catch (error) {
149
+ if (error instanceof CliCommandError)
150
+ throw error;
151
+ throw new CliCommandError(`Invalid JSON in --manifest: ${error?.message || error}`, 'VALIDATION_ERROR');
152
+ }
153
+ }
154
+ export const workbenchCommands = {
155
+ 'project.create': async ({ client, payload }) => {
156
+ const result = await client.request(`${workbenchPath}/projects`, {
157
+ method: 'POST',
158
+ body: payload,
159
+ });
160
+ return { data: result.data, requestId: result.requestId };
161
+ },
162
+ 'project.get': async ({ client, payload, flags }) => {
163
+ const id = payloadValue(payload, flags.id, 'id');
164
+ const result = await client.request(`${workbenchPath}/projects/${encodeURIComponent(id)}`, { method: 'GET' });
165
+ return { data: result.data, requestId: result.requestId };
166
+ },
167
+ 'project.list': async ({ client, payload }) => {
168
+ const result = await client.request(`${workbenchPath}/projects`, {
169
+ method: 'GET',
170
+ query: pickDefined(payload, ['cursor', 'limit', 'query']),
171
+ });
172
+ return { data: result.data, requestId: result.requestId };
173
+ },
174
+ 'project.update': async ({ client, payload, flags }) => {
175
+ const id = projectId(payload, flags.id);
176
+ const result = await client.request(`${workbenchPath}/projects/${encodeURIComponent(id)}`, {
177
+ method: 'PATCH',
178
+ body: omitKeys(payload, ['projectId']),
179
+ });
180
+ return { data: result.data, requestId: result.requestId };
181
+ },
182
+ 'record.put': async ({ client, payload, flags }) => {
183
+ const id = projectId(payload, flags.project);
184
+ const recordKey = payloadValue(payload, flags.record, 'recordKey');
185
+ const result = await client.request(`${workbenchPath}/projects/${encodeURIComponent(id)}/records/${encodeURIComponent(recordKey)}`, {
186
+ method: 'PUT',
187
+ body: omitKeys(payload, ['projectId', 'recordKey']),
188
+ });
189
+ return { data: result.data, requestId: result.requestId };
190
+ },
191
+ 'record.end-intent': async ({ client, payload, flags }) => {
192
+ const id = projectId(payload, flags.project);
193
+ const recordId = productionRecordId(payload, flags.record);
194
+ const result = await client.request(`${workbenchPath}/projects/${encodeURIComponent(id)}/records/${encodeURIComponent(recordId)}/end-intent`, {
195
+ method: 'POST',
196
+ body: omitKeys(payload, ['projectId', 'productionRecordId', 'recordId']),
197
+ });
198
+ return { data: result.data, requestId: result.requestId };
199
+ },
200
+ 'record.reopen': async ({ client, payload, flags }) => {
201
+ const id = projectId(payload, flags.project);
202
+ const recordId = productionRecordId(payload, flags.record);
203
+ const result = await client.request(`${workbenchPath}/projects/${encodeURIComponent(id)}/records/${encodeURIComponent(recordId)}/reopen`, {
204
+ method: 'POST',
205
+ body: omitKeys(payload, ['projectId', 'productionRecordId', 'recordId']),
206
+ });
207
+ return { data: result.data, requestId: result.requestId };
208
+ },
209
+ 'annotation.put': async ({ client, payload, flags }) => {
210
+ const id = projectId(payload, flags.project);
211
+ const result = await client.request(`${workbenchPath}/projects/${encodeURIComponent(id)}/annotations`, {
212
+ method: 'POST',
213
+ body: omitKeys(payload, ['projectId']),
214
+ });
215
+ return { data: result.data, requestId: result.requestId };
216
+ },
217
+ 'artifact.list': async ({ client, payload, flags }) => {
218
+ const id = projectId(payload, flags.project);
219
+ const result = await client.request(`${workbenchPath}/projects/${encodeURIComponent(id)}/artifacts`, {
220
+ method: 'GET', query: pickDefined(payload, ['kind', 'stageKey', 'query', 'cursor', 'limit']),
221
+ });
222
+ return { data: result.data, requestId: result.requestId };
223
+ },
224
+ 'artifact.versions': async ({ client, payload, flags }) => {
225
+ const id = projectId(payload, flags.project);
226
+ const result = await client.request(`${workbenchPath}/projects/${encodeURIComponent(id)}/artifact-versions`, {
227
+ method: 'GET', query: pickDefined(payload, ['artifactKey', 'idempotencyKey', 'cursor', 'limit']),
228
+ });
229
+ return { data: result.data, requestId: result.requestId };
230
+ },
231
+ 'blob.put': async (context) => {
232
+ projectId(context.payload, context.flags.project);
233
+ const local = localContent(context.payload);
234
+ if (!local)
235
+ throw new CliCommandError('blob put requires local content.sourcePath', 'VALIDATION_ERROR');
236
+ return { data: await uploadLocalContent(context, local.sourcePath, local.content) };
237
+ },
238
+ submit: async (context) => submitArtifact(context, context.payload),
239
+ sync: async (context) => {
240
+ const manifest = await readManifest(context);
241
+ const items = manifest.items;
242
+ if (!Array.isArray(items))
243
+ throw new CliCommandError('--manifest items must be an array', 'VALIDATION_ERROR');
244
+ const results = [];
245
+ for (const item of items) {
246
+ const entry = ensureObject(item, 'manifest item');
247
+ const type = typeof entry.type === 'string' ? entry.type : 'artifact';
248
+ const itemPayload = entry.submission === undefined
249
+ ? omitKeys(entry, ['type'])
250
+ : ensureObject(entry.submission, 'manifest item submission');
251
+ const merged = { ...itemPayload, projectId: itemPayload.projectId || manifest.projectId || context.flags.project };
252
+ if (type === 'artifact')
253
+ results.push((await submitArtifact(context, merged)).data);
254
+ else if (type === 'annotation') {
255
+ const id = projectId(merged, context.flags.project);
256
+ results.push((await context.client.request(`${workbenchPath}/projects/${encodeURIComponent(id)}/annotations`, {
257
+ method: 'POST', body: omitKeys(merged, ['projectId']), timeoutMs: context.flags.timeoutMs,
258
+ })).data);
259
+ }
260
+ else
261
+ throw new CliCommandError(`Unsupported sync item type: ${type}`, 'VALIDATION_ERROR');
262
+ }
263
+ return { data: { items: results, nextCursor: null } };
264
+ },
265
+ 'archive.prepare': async (context) => {
266
+ const wrapper = await readManifest(context);
267
+ const manifest = ensureObject(wrapper.manifest || wrapper, 'manifest');
268
+ const id = projectId(manifest, context.flags.project);
269
+ const recordKey = payloadValue(manifest, context.flags.record, 'productionRecordId');
270
+ const revision = getRequiredInt(manifest, 'revision');
271
+ const manifestHash = payloadValue(wrapper, context.flags.manifestHash, 'manifestHash');
272
+ const result = await context.client.request(`${workbenchPath}/projects/${encodeURIComponent(id)}/records/${encodeURIComponent(recordKey)}/manifests/${revision}`, {
273
+ method: 'PUT',
274
+ body: {
275
+ manifest,
276
+ manifestHash,
277
+ expectedPreviousRevision: wrapper.expectedPreviousRevision,
278
+ },
279
+ timeoutMs: context.flags.timeoutMs,
280
+ });
281
+ return { data: result.data, requestId: result.requestId };
282
+ },
283
+ 'archive.finalize': async ({ client, payload, flags }) => {
284
+ const id = projectId(payload, flags.project);
285
+ const recordId = productionRecordId(payload, flags.record);
286
+ const revision = getRevision(payload, flags.revision);
287
+ const manifestHash = payloadValue(payload, flags.manifestHash, 'manifestHash');
288
+ const result = await client.request(`${workbenchPath}/projects/${encodeURIComponent(id)}/records/${encodeURIComponent(recordId)}/manifests/${revision}/finalize`, {
289
+ method: 'POST',
290
+ body: { manifestHash, ...pickDefined(payload, ['archiveGeneration']) },
291
+ });
292
+ return { data: result.data, requestId: result.requestId };
293
+ },
294
+ 'archive.status': async ({ client, payload, flags }) => {
295
+ const id = projectId(payload, flags.project);
296
+ const recordId = productionRecordId(payload, flags.record);
297
+ const result = await client.request(`${workbenchPath}/projects/${encodeURIComponent(id)}/records/${encodeURIComponent(recordId)}/archive`, { method: 'GET' });
298
+ return { data: result.data, requestId: result.requestId };
299
+ },
300
+ 'archive.download': async ({ client, payload, flags }) => {
301
+ const id = projectId(payload, flags.project);
302
+ const recordId = productionRecordId(payload, flags.record);
303
+ const revision = getRevision(payload, flags.revision);
304
+ const entryId = getRequiredString(payload, 'entryId');
305
+ if (!flags.output)
306
+ throw new CliCommandError('Missing --output', 'VALIDATION_ERROR');
307
+ const result = await client.requestBinary(`${workbenchPath}/projects/${encodeURIComponent(id)}/records/${encodeURIComponent(recordId)}/manifests/${revision}/files/${encodeURIComponent(entryId)}/content`, {
308
+ method: 'GET', timeoutMs: flags.timeoutMs,
309
+ });
310
+ try {
311
+ await writeFile(flags.output, result.data);
312
+ }
313
+ catch (error) {
314
+ throw new CliCommandError(`Cannot write --output: ${error?.message || error}`, 'VALIDATION_ERROR');
315
+ }
316
+ return { data: { output: flags.output, size: result.data.byteLength, contentType: result.contentType }, requestId: result.requestId };
317
+ },
318
+ };
package/dist/index.js CHANGED
@@ -7,6 +7,7 @@ import { workflowCommands } from './commands/workflow.js';
7
7
  import { characterCommands } from './commands/character.js';
8
8
  import { aiGatewayCommands } from './commands/aiGateway.js';
9
9
  import { playtestCommands } from './commands/playtest.js';
10
+ import { workbenchCommands } from './commands/workbench.js';
10
11
  import { CliCommandError } from './lib/errors.js';
11
12
  import { getCliHelpText, parseCliArgs, resolveCliConfig } from './lib/flags.js';
12
13
  import { CliHttpClient } from './lib/http.js';
@@ -22,6 +23,7 @@ const commandRegistry = {
22
23
  character: characterCommands,
23
24
  'ai-gateway': aiGatewayCommands,
24
25
  playtest: playtestCommands,
26
+ workbench: workbenchCommands,
25
27
  };
26
28
  function normalizeError(error) {
27
29
  if (error instanceof CliCommandError) {
@@ -53,6 +55,16 @@ function writeError(runtime, command, raw, error) {
53
55
  meta: { command },
54
56
  });
55
57
  }
58
+ async function readJsonFile(runtime, filePath, flag) {
59
+ try {
60
+ return ensureObject(JSON.parse(await runtime.readTextFile(filePath)));
61
+ }
62
+ catch (error) {
63
+ if (error instanceof CliCommandError)
64
+ throw error;
65
+ throw new CliCommandError(`Invalid JSON in ${flag}: ${error?.message || error}`, 'VALIDATION_ERROR');
66
+ }
67
+ }
56
68
  export async function main(argv, runtime = createProcessRuntime()) {
57
69
  let commandName = '';
58
70
  let rawOutput = false;
@@ -79,7 +91,9 @@ export async function main(argv, runtime = createProcessRuntime()) {
79
91
  throw new CliCommandError(`Invalid stdin JSON: ${error?.message || error}`, 'VALIDATION_ERROR');
80
92
  }
81
93
  }
82
- const { baseUrl, token, commandPayload } = await resolveCliConfig(stdinPayload, parsed.flags, runtime);
94
+ const filePayload = parsed.flags.file ? await readJsonFile(runtime, parsed.flags.file, '--file') : {};
95
+ const mergedPayload = { ...filePayload, ...stdinPayload };
96
+ const { baseUrl, token, commandPayload } = await resolveCliConfig(mergedPayload, parsed.flags, runtime);
83
97
  const client = new CliHttpClient(baseUrl, token, runtime.fetchImpl);
84
98
  const result = await command({
85
99
  payload: commandPayload,
@@ -10,6 +10,14 @@ export type CliFlags = {
10
10
  baseUrlArg: string;
11
11
  tokenArg: string;
12
12
  tokenFile: string;
13
+ file: string;
14
+ manifest: string;
15
+ id: string;
16
+ project: string;
17
+ record: string;
18
+ revision: string;
19
+ manifestHash: string;
20
+ output: string;
13
21
  };
14
22
  export type ParsedCliArgs = {
15
23
  group: string;
package/dist/lib/flags.js CHANGED
@@ -38,6 +38,14 @@ export function parseCliArgs(argv) {
38
38
  baseUrlArg: '',
39
39
  tokenArg: '',
40
40
  tokenFile: '',
41
+ file: '',
42
+ manifest: '',
43
+ id: '',
44
+ project: '',
45
+ record: '',
46
+ revision: '',
47
+ manifestHash: '',
48
+ output: '',
41
49
  };
42
50
  for (let index = 0; index < argv.length; index += 1) {
43
51
  const arg = argv[index];
@@ -81,6 +89,38 @@ export function parseCliArgs(argv) {
81
89
  flags.tokenFile = readValue(argv, index, arg).trim();
82
90
  index += 1;
83
91
  break;
92
+ case '--file':
93
+ flags.file = readValue(argv, index, arg).trim();
94
+ index += 1;
95
+ break;
96
+ case '--manifest':
97
+ flags.manifest = readValue(argv, index, arg).trim();
98
+ index += 1;
99
+ break;
100
+ case '--id':
101
+ flags.id = readValue(argv, index, arg).trim();
102
+ index += 1;
103
+ break;
104
+ case '--project':
105
+ flags.project = readValue(argv, index, arg).trim();
106
+ index += 1;
107
+ break;
108
+ case '--record':
109
+ flags.record = readValue(argv, index, arg).trim();
110
+ index += 1;
111
+ break;
112
+ case '--revision':
113
+ flags.revision = readValue(argv, index, arg).trim();
114
+ index += 1;
115
+ break;
116
+ case '--manifest-hash':
117
+ flags.manifestHash = readValue(argv, index, arg).trim();
118
+ index += 1;
119
+ break;
120
+ case '--output':
121
+ flags.output = readValue(argv, index, arg).trim();
122
+ index += 1;
123
+ break;
84
124
  default:
85
125
  throw new CliCommandError(`Unknown flag: ${arg}`, 'VALIDATION_ERROR');
86
126
  }
@@ -93,7 +133,7 @@ export function parseCliArgs(argv) {
93
133
  }
94
134
  export function getCliHelpText() {
95
135
  return [
96
- 'Usage: branch-video-agent <group> <action> [--wait] [--raw] [--timeout <ms>] [--poll-interval <ms>] [--base-url <url>] [--token <token>] [--token-file <path>]',
136
+ 'Usage: branch-video-agent <group> <action> [--file <json>] [--manifest <json>] [--raw] [--timeout <ms>] [--base-url <url>] [--token-file <path>]',
97
137
  '',
98
138
  'Groups:',
99
139
  ' preset list | upsert',
@@ -106,6 +146,7 @@ export function getCliHelpText() {
106
146
  ' ai-gateway capabilities | request | media-understand | image-generate | image-edit | image-get | video-create | video-get | seed-audio-create | seed-audio-get | music-submit | music-get | tts-create | tts-get',
107
147
  ' Images: --async (or --wait) requires stdin idempotencyKey; image-get accepts taskId or idempotencyKey. Recovery receipts go to stderr; stdout remains one JSON document.',
108
148
  ' playtest run',
149
+ ' workbench project create|get|list|update | record put|end-intent|reopen | submit | sync | annotation put | archive prepare|finalize|status|download',
109
150
  '',
110
151
  'Config precedence:',
111
152
  ' AIHUB_AGENT_TOKEN / BRANCH_VIDEO_AGENT_BASE_URL > stdin JSON or --token-file > command flags',
@@ -9,6 +9,19 @@ type RequestResult<T> = {
9
9
  status: number;
10
10
  requestId: string | null;
11
11
  };
12
+ type StreamRequestOptions = {
13
+ method: string;
14
+ body: ReadableStream<Uint8Array>;
15
+ contentType: string;
16
+ uploadFormat?: 'gzip';
17
+ timeoutMs?: number;
18
+ };
19
+ type BinaryRequestResult = {
20
+ data: Uint8Array;
21
+ status: number;
22
+ requestId: string | null;
23
+ contentType: string | null;
24
+ };
12
25
  export declare class CliHttpClient {
13
26
  private readonly baseUrl;
14
27
  private readonly token;
@@ -16,5 +29,10 @@ export declare class CliHttpClient {
16
29
  constructor(baseUrl: string, token: string, fetchImpl: typeof fetch);
17
30
  resolveUrl(path: string): string;
18
31
  request<T>(path: string, options: RequestOptions): Promise<RequestResult<T>>;
32
+ requestStream<T>(path: string, options: StreamRequestOptions): Promise<RequestResult<T>>;
33
+ requestBinary(path: string, options: {
34
+ method: string;
35
+ timeoutMs?: number;
36
+ }): Promise<BinaryRequestResult>;
19
37
  }
20
38
  export {};
package/dist/lib/http.js CHANGED
@@ -17,6 +17,21 @@ function extractRequestId(response, parsed) {
17
17
  || response.headers.get('x-ai-gateway-request-id')
18
18
  || (typeof parsed?.requestId === 'string' ? parsed.requestId : null);
19
19
  }
20
+ function parseResponseError(parsed, response) {
21
+ const error = typeof parsed === 'object' && parsed ? parsed?.error : undefined;
22
+ const nested = typeof error === 'object' && error ? error : undefined;
23
+ const message = typeof nested?.message === 'string'
24
+ ? nested.message
25
+ : typeof error === 'string'
26
+ ? error
27
+ : response.statusText || 'Request failed';
28
+ const code = typeof nested?.code === 'string'
29
+ ? nested.code
30
+ : typeof parsed?.code === 'string'
31
+ ? String(parsed.code)
32
+ : `HTTP_${response.status}`;
33
+ return { message, code };
34
+ }
20
35
  export class CliHttpClient {
21
36
  baseUrl;
22
37
  token;
@@ -61,13 +76,8 @@ export class CliHttpClient {
61
76
  : null;
62
77
  const requestId = extractRequestId(response, parsed);
63
78
  if (!response.ok) {
64
- const errorMessage = typeof parsed === 'object' && parsed && typeof parsed.error === 'string'
65
- ? String(parsed.error)
66
- : response.statusText || 'Request failed';
67
- const errorCode = typeof parsed === 'object' && parsed && typeof parsed.code === 'string'
68
- ? String(parsed.code)
69
- : `HTTP_${response.status}`;
70
- throw new CliCommandError(errorMessage, errorCode, parsed, requestId, response.status);
79
+ const error = parseResponseError(parsed, response);
80
+ throw new CliCommandError(error.message, error.code, parsed, requestId, response.status);
71
81
  }
72
82
  return {
73
83
  data: parsed,
@@ -75,4 +85,69 @@ export class CliHttpClient {
75
85
  requestId,
76
86
  };
77
87
  }
88
+ async requestStream(path, options) {
89
+ let response;
90
+ try {
91
+ response = await this.fetchImpl(buildUrl(this.baseUrl, path), {
92
+ method: options.method,
93
+ headers: {
94
+ Authorization: `Bearer ${this.token}`,
95
+ 'content-type': options.contentType,
96
+ ...(options.uploadFormat ? { 'x-workbench-upload-format': options.uploadFormat } : {}),
97
+ },
98
+ body: options.body,
99
+ duplex: 'half',
100
+ // A redirect to another origin must never receive the bearer token.
101
+ redirect: 'error',
102
+ signal: options.timeoutMs ? AbortSignal.timeout(options.timeoutMs) : undefined,
103
+ });
104
+ }
105
+ catch (error) {
106
+ throw new CliCommandError(error?.message || 'Network request failed', 'NETWORK_ERROR');
107
+ }
108
+ const text = await response.text();
109
+ const parsed = text
110
+ ? (() => {
111
+ try {
112
+ return JSON.parse(text);
113
+ }
114
+ catch {
115
+ return text;
116
+ }
117
+ })()
118
+ : null;
119
+ const requestId = extractRequestId(response, parsed);
120
+ if (!response.ok) {
121
+ const error = parseResponseError(parsed, response);
122
+ throw new CliCommandError(error.message, error.code, parsed, requestId, response.status);
123
+ }
124
+ return { data: parsed, status: response.status, requestId };
125
+ }
126
+ async requestBinary(path, options) {
127
+ let response;
128
+ try {
129
+ response = await this.fetchImpl(buildUrl(this.baseUrl, path), {
130
+ method: options.method,
131
+ headers: { Authorization: `Bearer ${this.token}` },
132
+ redirect: 'error',
133
+ signal: options.timeoutMs ? AbortSignal.timeout(options.timeoutMs) : undefined,
134
+ });
135
+ }
136
+ catch (error) {
137
+ throw new CliCommandError(error?.message || 'Network request failed', 'NETWORK_ERROR');
138
+ }
139
+ const bytes = new Uint8Array(await response.arrayBuffer());
140
+ const requestId = response.headers.get('x-request-id') || response.headers.get('x-correlation-id');
141
+ if (!response.ok) {
142
+ const text = new TextDecoder().decode(bytes);
143
+ let parsed = text;
144
+ try {
145
+ parsed = JSON.parse(text);
146
+ }
147
+ catch { /* preserve plain error body */ }
148
+ const error = parseResponseError(parsed, response);
149
+ throw new CliCommandError(error.message, error.code, parsed, requestId, response.status);
150
+ }
151
+ return { data: bytes, status: response.status, requestId, contentType: response.headers.get('content-type') };
152
+ }
78
153
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mindscraft/branch-video-agent-cli",
3
- "version": "0.4.7",
3
+ "version": "0.5.1",
4
4
  "description": "Published CLI for branch-video and AIHub agent APIs.",
5
5
  "type": "module",
6
6
  "bin": {