@playcraft/cli 0.1.23 → 0.1.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/cli-root-help.js +1 -0
  2. package/dist/commands/playable.js +53 -0
  3. package/dist/commands/tools-3d.js +11 -0
  4. package/dist/commands/tools-batch.js +42 -14
  5. package/dist/commands/tools-generation.js +6 -0
  6. package/dist/commands/video.js +111 -0
  7. package/dist/index.js +29 -3
  8. package/dist/project-skills/builtin-import.js +225 -0
  9. package/dist/project-skills/commands.js +6 -1
  10. package/dist/project-skills/local-store.js +73 -1
  11. package/dist/project-skills/messages.js +8 -0
  12. package/dist/recording/messages.js +40 -0
  13. package/dist/recording/project-digest.js +85 -0
  14. package/dist/recording/recorder.js +293 -0
  15. package/dist/recording/scenario.js +50 -0
  16. package/dist/utils/agent-api-client.js +39 -3
  17. package/dist/utils/video-evidence-git.js +81 -0
  18. package/dist/video-replication/client.js +222 -0
  19. package/dist/video-replication/comparison-evidence.js +149 -0
  20. package/dist/video-replication/comparison-files.js +57 -0
  21. package/dist/video-replication/comparison-log.js +72 -0
  22. package/dist/video-replication/comparison-messages.js +104 -0
  23. package/dist/video-replication/comparison-output.js +63 -0
  24. package/dist/video-replication/comparison-preflight.js +66 -0
  25. package/dist/video-replication/comparison.js +216 -0
  26. package/dist/video-replication/evidence.js +165 -0
  27. package/dist/video-replication/media.js +111 -0
  28. package/dist/video-replication/messages.js +89 -0
  29. package/dist/workspace-runtime/codex/app-server.js +65 -12
  30. package/dist/workspace-runtime/codex/config-toml.js +3 -2
  31. package/dist/workspace-runtime/persistence/native-subagents.js +162 -0
  32. package/dist/workspace-runtime/persistence/sqlite-client.js +17 -1
  33. package/dist/workspace-runtime/persistence/sqlite-worker.js +116 -74
  34. package/dist/workspace-runtime/production/native.js +21 -1
  35. package/dist/workspace-runtime/production/save-command.js +5 -1
  36. package/dist/workspace-runtime/production/source-copy.js +91 -0
  37. package/dist/workspace-runtime/production/stages.js +48 -21
  38. package/dist/workspace-runtime/serve.js +3 -0
  39. package/dist/workspace-runtime/server/dispatch.js +34 -6
  40. package/dist/workspace-runtime/server/http.js +60 -3
  41. package/dist/workspace-runtime/server/terminal-host.js +2 -2
  42. package/dist/workspace-runtime/workspaces/artifact-events.js +55 -0
  43. package/dist/workspace-runtime/workspaces/artifact-files.js +195 -0
  44. package/dist/workspace-runtime/workspaces/artifact-receipts.js +89 -0
  45. package/dist/workspace-runtime/workspaces/artifacts.js +260 -0
  46. package/dist/workspace-runtime/workspaces/attachments.js +70 -4
  47. package/dist/workspace-runtime/workspaces/batch-commit.js +1 -1
  48. package/dist/workspace-runtime/workspaces/cli-context.js +23 -0
  49. package/dist/workspace-runtime/workspaces/directories.js +10 -3
  50. package/dist/workspace-runtime/workspaces/directory-access.js +9 -0
  51. package/dist/workspace-runtime/workspaces/disk-snapshot.js +31 -0
  52. package/dist/workspace-runtime/workspaces/empty-template.js +12 -4
  53. package/dist/workspace-runtime/workspaces/files.js +8 -1
  54. package/dist/workspace-runtime/workspaces/prepare.js +2 -1
  55. package/dist/workspace-runtime/workspaces/registry.js +13 -5
  56. package/dist/workspace-runtime/workspaces/skill-artifact-loader.js +45 -0
  57. package/dist/workspace-runtime/workspaces/skills.js +28 -18
  58. package/dist/workspace-runtime/workspaces/video-attachments.js +49 -0
  59. package/package.json +7 -4
  60. package/project-template/.claude/skills/playcraft-replica-validation/SKILL.md +25 -0
  61. package/project-template/.claude/skills/playcraft-replica-validation/references/contracts.md +79 -0
  62. package/project-template/.claude/skills/playcraft-video-understanding/SKILL.md +29 -0
  63. package/project-template/.claude/skills/playcraft-video-understanding/references/contracts.md +37 -0
  64. package/project-templates/empty/AGENTS.md +2 -0
  65. package/project-templates/empty/gitignore +2 -0
@@ -5,6 +5,7 @@ export function getCliTopicsHelpText() {
5
5
  '',
6
6
  ' 本地开发 create, init, start, stop, status, logs, config, sync, fix-ids',
7
7
  ' 素材 tools generate-* | image <子命令> | audio <子命令> | prefab <子命令>',
8
+ ' 视频理解 video models | video understand | video jobs get/cancel',
8
9
  ' 平台 build, build-base, build-playable, build-all, analyze, inspect, upgrade',
9
10
  ' tools 除 generate-* 外(Git / 沙箱构建 / 发布 / 列表 / Prefab 等,需后端 API)',
10
11
  ' 沙箱常驻 workspace-runtime serve(Cloud Workspace,由 Runtime 引导配置启动)',
@@ -0,0 +1,53 @@
1
+ import { recordPlayable } from '../recording/recorder.js';
2
+ import { RecordingError, recordingMessage as t } from '../recording/messages.js';
3
+ import { dirname, join } from 'node:path';
4
+ import { captureGeneratedArtifact } from '../workspace-runtime/workspaces/artifact-receipts.js';
5
+ export async function runPlayableRecord(options) {
6
+ const interrupted = new AbortController();
7
+ const deadline = new AbortController();
8
+ const onInterrupt = () => interrupted.abort(new DOMException('Interrupted', 'AbortError'));
9
+ process.once('SIGINT', onInterrupt);
10
+ let timer;
11
+ try {
12
+ const seconds = options.timeout === undefined ? 1200 : Number(options.timeout);
13
+ if (!Number.isFinite(seconds) || seconds <= 0 || seconds > 1800)
14
+ throw new RecordingError('invalidArguments', 64);
15
+ timer = setTimeout(() => deadline.abort(new DOMException('Timed out', 'TimeoutError')), seconds * 1000);
16
+ const result = await recordPlayable(options, AbortSignal.any([interrupted.signal, deadline.signal]));
17
+ const metadata = result.envelope.result;
18
+ const output = result.envelope.artifacts;
19
+ if (result.envelope.ok && metadata && output?.candidate) {
20
+ const artifacts = [metadata.candidate, ...metadata.controls];
21
+ const paths = [output.candidate, ...(output.controls ?? [])];
22
+ for (let index = 0; index < artifacts.length; index++) {
23
+ const artifact = artifacts[index], path = paths[index];
24
+ if (!path)
25
+ continue;
26
+ const thumbnail = artifact.screenshots?.[0]?.path;
27
+ await captureGeneratedArtifact(path, 'playable record', {
28
+ width: artifact.video.source.width, height: artifact.video.source.height,
29
+ duration: artifact.video.source.durationMs / 1000,
30
+ ...(thumbnail ? { thumbnailPath: join(dirname(output.metadata), thumbnail) } : {}),
31
+ });
32
+ }
33
+ }
34
+ process.stdout.write(`${JSON.stringify(result.envelope)}\n`);
35
+ process.exitCode = result.exitCode;
36
+ }
37
+ catch (error) {
38
+ const code = error instanceof RecordingError ? error.code : 'recordingFailed';
39
+ process.stdout.write(`${JSON.stringify({ schemaVersion: 'playcraft.video-cli.v1', command: 'playable record', state: 'failed', ok: false, error: { code, message: t(code) } })}\n`);
40
+ process.exitCode = error instanceof RecordingError ? error.exitCode : 4;
41
+ }
42
+ finally {
43
+ if (timer)
44
+ clearTimeout(timer);
45
+ process.removeListener('SIGINT', onInterrupt);
46
+ }
47
+ }
48
+ export function registerPlayableCommands(program) {
49
+ program.command('playable').description(t('topic')).command('record').description(t('record'))
50
+ .option('--url <url>', t('url')).option('--scenario <file>', t('scenario')).option('--out <directory>', t('out'))
51
+ .option('--browser-path <path>', t('browser')).option('--timeout <seconds>', t('timeout'))
52
+ .action(runPlayableRecord);
53
+ }
@@ -2,6 +2,7 @@ import { writeFileSync, mkdirSync, readFileSync } from 'fs';
2
2
  import { dirname } from 'path';
3
3
  import { AgentApiClient } from '../utils/agent-api-client.js';
4
4
  import { mimeTypeForImagePath, handleError } from './tools-utils.js';
5
+ import { captureGeneratedArtifact } from '../workspace-runtime/workspaces/artifact-receipts.js';
5
6
  const AVATAR_TEMPLATES = [
6
7
  'basketball', 'badminton', 'pingpong', 'gymnastics', 'pilidance',
7
8
  'tennis', 'athletics', 'footballboykicking1', 'footballboykicking2',
@@ -148,6 +149,9 @@ export function register3DCommands(tools) {
148
149
  writeFileSync(opts.savePreview, previewBuf);
149
150
  console.log(` Preview saved: ${opts.savePreview}`);
150
151
  }
152
+ await captureGeneratedArtifact(opts.output, 'generate-3d', {
153
+ ...(opts.savePreview && result.previewImageBase64 ? { thumbnailPath: opts.savePreview } : {}),
154
+ });
151
155
  console.log(`\nNext steps:`);
152
156
  console.log(` Inspect: playcraft 3d info ${opts.output}`);
153
157
  console.log(` Apply texture: playcraft tools generate-texture --model-url <url> --reference-image <img> --output out.glb`);
@@ -209,6 +213,7 @@ export function register3DCommands(tools) {
209
213
  const outDir = dirname(opts.output);
210
214
  mkdirSync(outDir, { recursive: true });
211
215
  writeFileSync(opts.output, buf);
216
+ await captureGeneratedArtifact(opts.output, 'generate-texture');
212
217
  const sizeMB = (buf.length / 1024 / 1024).toFixed(2);
213
218
  console.log(`\nTextured model saved: ${opts.output} (${sizeMB}MB, ${elapsed}s)`);
214
219
  if (result.resultUrl)
@@ -253,6 +258,7 @@ export function register3DCommands(tools) {
253
258
  const outDir = dirname(opts.output);
254
259
  mkdirSync(outDir, { recursive: true });
255
260
  writeFileSync(opts.output, buf);
261
+ await captureGeneratedArtifact(opts.output, 'retopology');
256
262
  const sizeMB = (buf.length / 1024 / 1024).toFixed(2);
257
263
  console.log(`\nRetopologized model saved: ${opts.output} (${sizeMB}MB, ${elapsed}s)`);
258
264
  }
@@ -289,6 +295,7 @@ export function register3DCommands(tools) {
289
295
  const outDir = dirname(opts.output);
290
296
  mkdirSync(outDir, { recursive: true });
291
297
  writeFileSync(opts.output, buf);
298
+ await captureGeneratedArtifact(opts.output, 'uv-unwrap');
292
299
  const sizeMB = (buf.length / 1024 / 1024).toFixed(2);
293
300
  console.log(`\nUV-unwrapped model saved: ${opts.output} (${sizeMB}MB, ${elapsed}s)`);
294
301
  }
@@ -324,6 +331,7 @@ export function register3DCommands(tools) {
324
331
  const outDir = dirname(opts.output);
325
332
  mkdirSync(outDir, { recursive: true });
326
333
  writeFileSync(opts.output, buf);
334
+ await captureGeneratedArtifact(opts.output, 'convert-3d');
327
335
  const sizeMB = (buf.length / 1024 / 1024).toFixed(2);
328
336
  console.log(`\nConverted model saved: ${opts.output} (${sizeMB}MB, ${elapsed}s)`);
329
337
  console.log(` Format: ${result.format.toUpperCase()}`);
@@ -359,6 +367,7 @@ export function register3DCommands(tools) {
359
367
  const outDir = dirname(opts.output);
360
368
  mkdirSync(outDir, { recursive: true });
361
369
  writeFileSync(opts.output, buf);
370
+ await captureGeneratedArtifact(opts.output, 'generate-3d-parts');
362
371
  const sizeMB = (buf.length / 1024 / 1024).toFixed(2);
363
372
  console.log(`\n3D parts model saved: ${opts.output} (${sizeMB}MB, ${elapsed}s)`);
364
373
  }
@@ -402,6 +411,7 @@ export function register3DCommands(tools) {
402
411
  const outDir = dirname(opts.output);
403
412
  mkdirSync(outDir, { recursive: true });
404
413
  writeFileSync(opts.output, buf);
414
+ await captureGeneratedArtifact(opts.output, 'generate-motion');
405
415
  const sizeMB = (buf.length / 1024 / 1024).toFixed(2);
406
416
  console.log(`\nMotion FBX saved: ${opts.output} (${sizeMB}MB, ${elapsed}s)`);
407
417
  }
@@ -463,6 +473,7 @@ export function register3DCommands(tools) {
463
473
  const outDir = dirname(opts.output);
464
474
  mkdirSync(outDir, { recursive: true });
465
475
  writeFileSync(opts.output, buf);
476
+ await captureGeneratedArtifact(opts.output, 'generate-avatar');
466
477
  const sizeMB = (buf.length / 1024 / 1024).toFixed(2);
467
478
  console.log(`\n3D avatar saved: ${opts.output} (${sizeMB}MB, ${elapsed}s)`);
468
479
  }
@@ -1,25 +1,35 @@
1
1
  import { readFile } from 'node:fs/promises';
2
- import { batchCreateSchema } from '@playcraft/common/cloud-workspace/runtime';
2
+ import { batchCreateSchema, batchPromptCreateSchema } from '@playcraft/common/cloud-workspace/runtime';
3
3
  import { AgentApiClient } from '../utils/agent-api-client.js';
4
4
  import { handleError } from './tools-utils.js';
5
5
  const messages = {
6
6
  en: {
7
- create: 'Create a batch draft; confirm the whole batch in the browser',
7
+ create: 'Create and automatically run independent Remix variants from one prompt',
8
8
  input: 'Path to the batch draft JSON (JavaScript Object Notation, 数据交换格式) file',
9
- status: 'Read a batch draft and its generation status',
9
+ status: 'Read a batch and its generation status',
10
10
  id: 'Batch identifier',
11
- created: 'Batch draft created',
12
- help: '\nDraft shape: { clientRequestId, title, commonGoal, sourceWorkspaceId, engine, variants: [{ variantId, name, changes, preserves }] }\nUse the current workspace identifier as sourceWorkspaceId and a stable clientRequestId for retries. Maximum 10 variants. Confirm the batch in the browser.\n',
13
- confirmation: 'Review the baseline and differences, then approve the whole batch in the browser.',
11
+ created: 'Batch created',
12
+ prompt: 'The complete batch generation request', workspace: 'Source workspace identifier',
13
+ directory: 'Source engineering directory; defaults to basic', request: 'Stable batch creation identity for retries',
14
+ team: 'Team identifier for a standalone workspace', invalidMode: 'Provide either --prompt with --workspace-id or --input, exclusively.',
15
+ requestRequired: 'Prompt creation requires a stable --client-request-id; reuse it when retrying the same request.',
16
+ help: '\nUse --prompt with --workspace-id and a stable --client-request-id. The platform plans and generates independent Remix directories while preserving the source. An omitted count defaults to 3; maximum 10. --input also accepts existing structured drafts.\n',
17
+ confirmation: 'Generation is queued. Read the batch status to track its results.',
18
+ review: 'This existing draft requires baseline approval in the browser.',
14
19
  },
15
20
  zh: {
16
- create: '创建批次草案;整批确认须在浏览器完成',
21
+ create: '用一个 prompt 创建并自动生成独立 Remix 变体',
17
22
  input: '批次草案 JSON (JavaScript Object Notation, 数据交换格式) 文件路径',
18
- status: '查询批次草案及生成状态',
23
+ status: '查询批次及生成状态',
19
24
  id: '批次标识',
20
- created: '批次草案已创建',
21
- help: '\n草案格式:{ clientRequestId, title, commonGoal, sourceWorkspaceId, engine, variants: [{ variantId, name, changes, preserves }] }\nsourceWorkspaceId 填当前 workspace 标识,重试使用稳定的 clientRequestId。最多 10 个变体,整批在浏览器确认。\n',
22
- confirmation: '请在浏览器查看基准和差异清单,然后确认整批。',
25
+ created: '批次已创建',
26
+ prompt: '完整的批量生成需求', workspace: '来源 workspace 标识',
27
+ directory: '来源工程目录,默认 basic', request: '用于重试的稳定批次创建标识',
28
+ team: '独立工作区所属团队标识', invalidMode: '请选择 --prompt 配合 --workspace-id,或 --input,两种方式不能同时使用。',
29
+ requestRequired: '使用 prompt 创建时必须提供稳定的 --client-request-id,重试同一请求时复用该标识。',
30
+ help: '\n使用 --prompt、--workspace-id 和稳定的 --client-request-id。平台自动规划,在副本中生成独立 Remix,保持来源不变。未指定数量默认 3 个,最多 10 个。--input 也兼容现有结构化草案。\n',
31
+ confirmation: '生成已排队,可查询批次状态追踪各项成果。',
32
+ review: '此历史草案需要在浏览器确认基准。',
23
33
  },
24
34
  };
25
35
  const language = () => /^zh/i.test(process.env.PLAYCRAFT_LANG ?? process.env.LANG ?? '') ? messages.zh : messages.en;
@@ -27,17 +37,35 @@ export async function createBatchDraft(path, client = new AgentApiClient()) {
27
37
  const draft = batchCreateSchema.parse(JSON.parse(await readFile(path, 'utf8')));
28
38
  return client.post('/create-batch', draft);
29
39
  }
40
+ export async function createPromptBatch(input, client = new AgentApiClient()) {
41
+ return client.post('/create-batch', batchPromptCreateSchema.parse(input));
42
+ }
30
43
  export function registerBatchCommands(tools) {
31
44
  const t = language();
32
45
  tools.command('create-batch')
33
46
  .description(t.create)
34
- .requiredOption('--input <path>', t.input)
47
+ .option('--input <path>', t.input)
48
+ .option('--prompt <text>', t.prompt)
49
+ .option('--workspace-id <id>', t.workspace)
50
+ .option('--source-directory <name>', t.directory, 'basic')
51
+ .option('--client-request-id <id>', t.request)
52
+ .option('--team-id <id>', t.team)
35
53
  .option('--json', 'JSON (JavaScript Object Notation, 数据交换格式)')
36
54
  .addHelpText('after', t.help)
37
55
  .action(async (opts) => {
38
56
  try {
39
- const result = await createBatchDraft(opts.input);
40
- console.log(opts.json ? JSON.stringify(result, null, 2) : `${t.created}: ${result.batchId}\n${t.confirmation}`);
57
+ if (Boolean(opts.input) === Boolean(opts.prompt))
58
+ throw new Error(t.invalidMode);
59
+ if (opts.prompt && !opts.workspaceId)
60
+ throw new Error(t.invalidMode);
61
+ if (opts.prompt && !opts.clientRequestId)
62
+ throw new Error(t.requestRequired);
63
+ const result = opts.input ? await createBatchDraft(opts.input) : await createPromptBatch({
64
+ clientRequestId: opts.clientRequestId, prompt: opts.prompt,
65
+ sourceWorkspaceId: opts.workspaceId, sourceDirectoryName: opts.sourceDirectory,
66
+ ...(opts.teamId ? { teamId: opts.teamId } : {}),
67
+ });
68
+ console.log(opts.json ? JSON.stringify(result, null, 2) : `${t.created}: ${result.batchId}\n${result.manifest.autoStart ? t.confirmation : t.review}`);
41
69
  }
42
70
  catch (error) {
43
71
  handleError(error);
@@ -1,6 +1,7 @@
1
1
  import { writeFileSync, mkdirSync } from 'fs';
2
2
  import { dirname, parse, join } from 'path';
3
3
  import sharp from 'sharp';
4
+ import { captureGeneratedArtifact } from '../workspace-runtime/workspaces/artifact-receipts.js';
4
5
  import { AgentApiClient } from '../utils/agent-api-client.js';
5
6
  import { MAX_REFERENCE_IMAGES, collectReferenceImagePaths, collectReferenceImagePayloads, sniffImageExtension, extensionForImageMime, resolveImageOutputPath, handleError, raceWithTimeout, } from './tools-utils.js';
6
7
  function isMasterCompositeStripRequest(opts) {
@@ -330,6 +331,9 @@ export function registerGenerationCommands(tools) {
330
331
  };
331
332
  const sidecarPath = resolvedPath.replace(/\.[^.]+$/, '.json');
332
333
  writeFileSync(sidecarPath, JSON.stringify(sidecar, null, 2));
334
+ await captureGeneratedArtifact(resolvedPath, 'generate-image', {
335
+ ...(actualWidth ? { width: actualWidth } : {}), ...(actualHeight ? { height: actualHeight } : {}),
336
+ });
333
337
  console.log(` └─ Generation metadata: ${sidecarPath}`);
334
338
  }
335
339
  if (!isBatch && opts.output !== savedPaths[0] && savedPaths[0]) {
@@ -377,6 +381,7 @@ export function registerGenerationCommands(tools) {
377
381
  output: opts.output, generatedAt: new Date().toISOString(),
378
382
  };
379
383
  writeFileSync(opts.output.replace(/\.[^.]+$/, '.json'), JSON.stringify(sfxSidecar, null, 2));
384
+ await captureGeneratedArtifact(opts.output, 'generate-sfx', { duration: result.duration });
380
385
  console.log(` └─ Generation metadata: ${opts.output.replace(/\.[^.]+$/, '.json')}`);
381
386
  }
382
387
  catch (e) {
@@ -409,6 +414,7 @@ export function registerGenerationCommands(tools) {
409
414
  output: opts.output, generatedAt: new Date().toISOString(),
410
415
  };
411
416
  writeFileSync(opts.output.replace(/\.[^.]+$/, '.json'), JSON.stringify(bgmSidecar, null, 2));
417
+ await captureGeneratedArtifact(opts.output, 'generate-bgm', { duration: result.duration });
412
418
  console.log(` └─ Generation metadata: ${opts.output.replace(/\.[^.]+$/, '.json')}`);
413
419
  }
414
420
  catch (e) {
@@ -0,0 +1,111 @@
1
+ import { videoAnalysisRunSchema, videoModelCatalogSchema } from '@playcraft/common/agent-tools';
2
+ import { AgentApiClient } from '../utils/agent-api-client.js';
3
+ import { executeVideoUnderstanding, readVideoRun, requireVideoId, resolveVideoWorkspace, videoTimeout, } from '../video-replication/client.js';
4
+ import { materializeVideoEvidence } from '../video-replication/evidence.js';
5
+ import { probeVideo } from '../video-replication/media.js';
6
+ import { VideoCliError, videoMessage as t } from '../video-replication/messages.js';
7
+ import { comparisonMessage as c } from '../video-replication/comparison-messages.js';
8
+ import { executeVideoComparison, readComparisonRun, comparisonRunResult } from '../video-replication/comparison.js';
9
+ import { materializeComparisonEvidence } from '../video-replication/comparison-evidence.js';
10
+ /** One final structured stdout record; progress and diagnostics stay on stderr. */
11
+ export async function runVideoCliAction(command, options, action) {
12
+ const interrupt = new AbortController();
13
+ const onInterrupt = () => interrupt.abort(new DOMException('Interrupted', 'AbortError'));
14
+ process.once('SIGINT', onInterrupt);
15
+ let timer;
16
+ const deadline = new AbortController();
17
+ try {
18
+ timer = setTimeout(() => deadline.abort(new DOMException('Timed out', 'TimeoutError')), videoTimeout(options));
19
+ const result = await action(AbortSignal.any([interrupt.signal, deadline.signal]));
20
+ process.stdout.write(`${JSON.stringify(result.envelope)}\n`);
21
+ process.exitCode = result.exitCode;
22
+ }
23
+ catch (error) {
24
+ const key = error instanceof VideoCliError ? error.code : interrupt.signal.aborted ? 'interrupted' : deadline.signal.aborted ? 'timeoutReached' : 'failed';
25
+ const envelope = {
26
+ schemaVersion: 'playcraft.video-cli.v1', command, state: interrupt.signal.aborted || deadline.signal.aborted ? 'uncertain' : 'failed', ok: false,
27
+ error: { code: key, message: t(key) },
28
+ };
29
+ process.stdout.write(`${JSON.stringify(envelope)}\n`);
30
+ process.exitCode = error instanceof VideoCliError ? error.exitCode : interrupt.signal.aborted ? 130 : deadline.signal.aborted ? 75 : 4;
31
+ }
32
+ finally {
33
+ if (timer)
34
+ clearTimeout(timer);
35
+ process.removeListener('SIGINT', onInterrupt);
36
+ }
37
+ }
38
+ function shared(command) {
39
+ return command.option('--workspace <id>', t('workspace')).option('--timeout <seconds>', t('timeout'));
40
+ }
41
+ export function registerVideoCommands(program) {
42
+ const video = program.command('video').description(t('topic'));
43
+ shared(video.command('models').description(t('models')))
44
+ .option('--json', t('json'))
45
+ .action((options) => runVideoCliAction('video models', options, async (signal) => {
46
+ const workspaceId = await resolveVideoWorkspace(options.workspace);
47
+ const catalog = videoModelCatalogSchema.parse(await new AgentApiClient().get('/video-models', { workspaceId }, { signal }));
48
+ return { exitCode: 0, envelope: { schemaVersion: 'playcraft.video-cli.v1', command: 'video models', state: 'completed', ok: true, result: catalog } };
49
+ }));
50
+ shared(video.command('understand').description(t('understand')))
51
+ .option('--video <path>', t('video')).option('--question <text>', t('question'))
52
+ .option('--context <path>', t('context')).option('--processing <mode>', t('processing'))
53
+ .option('--fps <number>', t('fps')).option('--clip <start:end>', t('clip'))
54
+ .option('--model-config <id>', t('model')).option('--out <directory>', t('out'))
55
+ .option('--resume <runId>', t('resume'))
56
+ .action((options) => runVideoCliAction('video understand', options, signal => executeVideoUnderstanding(options, signal, {
57
+ client: new AgentApiClient(), probe: probeVideo, materialize: materializeVideoEvidence,
58
+ progress: key => process.stderr.write(`[video] ${t(key)}\n`),
59
+ })));
60
+ shared(video.command('compare').description(c('compare')))
61
+ .option('--reference <path>', c('reference')).option('--analysis <path>', c('analysis'))
62
+ .option('--candidate <path>', c('candidate')).option('--recording <path>', c('recording'))
63
+ .option('--policy <path>', c('policy')).option('--processing <mode>', c('processing'))
64
+ .option('--fps <number>', t('fps')).option('--model-config <id>', t('model'))
65
+ .option('--out <directory>', t('out')).option('--resume <runId>', t('resume'))
66
+ .action((options) => runVideoCliAction('video compare', options, signal => executeVideoComparison(options, signal, {
67
+ client: new AgentApiClient(), probe: probeVideo, materialize: materializeComparisonEvidence,
68
+ progress: key => process.stderr.write(`[video] ${t(key)}\n`),
69
+ })));
70
+ const jobs = video.command('jobs').description(t('jobs'));
71
+ shared(jobs.command('get <runId>').description(t('get')))
72
+ .option('--kind <kind>', c('kind'))
73
+ .action((runId, options) => runVideoCliAction('video jobs get', options, async (signal) => {
74
+ const workspaceId = await resolveVideoWorkspace(options.workspace);
75
+ if (options.kind !== undefined && !['understanding', 'comparison'].includes(options.kind))
76
+ throw new VideoCliError('invalidArguments', 64);
77
+ if (options.kind === 'comparison') {
78
+ const run = await readComparisonRun(new AgentApiClient(), requireVideoId(runId), workspaceId, signal);
79
+ return comparisonRunResult('video jobs get', run);
80
+ }
81
+ const run = await readVideoRun(new AgentApiClient(), requireVideoId(runId), workspaceId, signal);
82
+ return { exitCode: run.state === 'uncertain' ? 75 : run.state === 'failed' || run.state === 'cancelled' ? 4 : 0, envelope: {
83
+ schemaVersion: 'playcraft.video-cli.v1', command: 'video jobs get', runId: run.runId, state: run.state,
84
+ ok: !['failed', 'uncertain', 'cancelled'].includes(run.state), result: run,
85
+ } };
86
+ }));
87
+ shared(jobs.command('cancel <runId>').description(t('cancel')))
88
+ .option('--kind <kind>', c('kind'))
89
+ .action((identifier, options) => runVideoCliAction('video jobs cancel', options, async (signal) => {
90
+ const workspaceId = await resolveVideoWorkspace(options.workspace);
91
+ const runId = requireVideoId(identifier);
92
+ if (options.kind !== undefined && !['understanding', 'comparison'].includes(options.kind))
93
+ throw new VideoCliError('invalidArguments', 64);
94
+ if (options.kind === 'comparison') {
95
+ const run = await readComparisonRun(new AgentApiClient(), runId, workspaceId, signal, true);
96
+ const confirmed = run.state === 'cancelled';
97
+ return { exitCode: confirmed ? 0 : 75, envelope: {
98
+ schemaVersion: 'playcraft.video-cli.v1', command: 'video jobs cancel', runId, state: run.state,
99
+ ok: confirmed, result: { ...run, cancellationConfirmed: confirmed },
100
+ } };
101
+ }
102
+ const run = videoAnalysisRunSchema.parse(await new AgentApiClient().post(`/video-analysis/${runId}/cancel`, { workspaceId, runId }, { signal }));
103
+ if (run.runId !== runId || run.workspaceId !== workspaceId)
104
+ throw new VideoCliError('invalidResult');
105
+ const confirmed = run.state === 'cancelled';
106
+ return { exitCode: confirmed ? 0 : 75, envelope: {
107
+ schemaVersion: 'playcraft.video-cli.v1', command: 'video jobs cancel', runId, state: run.state,
108
+ ok: confirmed, result: { ...run, cancellationConfirmed: confirmed },
109
+ } };
110
+ }));
111
+ }
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { Command } from 'commander';
2
+ import { Command, CommanderError } from 'commander';
3
3
  import { accountActivationMessage } from './auth/messages.js';
4
4
  import { readFileSync } from 'fs';
5
5
  import { fileURLToPath } from 'url';
@@ -29,16 +29,22 @@ import { registerPatternsCommands } from './commands/patterns.js';
29
29
  import { registerPradCommands } from './commands/prad.js';
30
30
  import { register3DCommands } from './commands/3d.js';
31
31
  import { registerWorkspaceRuntimeCommands } from './commands/workspace-runtime.js';
32
+ import { registerVideoCommands } from './commands/video.js';
33
+ import { registerPlayableCommands } from './commands/playable.js';
34
+ import { videoMessage } from './video-replication/messages.js';
32
35
  import { CLI_ROOT_DESCRIPTION, getCliTopicsHelpText, registerRootProgramHelp, } from './cli-root-help.js';
33
36
  const __filename = fileURLToPath(import.meta.url);
34
37
  const __dirname = dirname(__filename);
35
38
  const packageJson = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf-8'));
36
39
  const program = new Command();
40
+ const structuredVideoTopic = ['video', 'playable'].includes(process.argv[2] ?? '');
41
+ if (structuredVideoTopic)
42
+ program.exitOverride();
37
43
  program.name('playcraft').description(CLI_ROOT_DESCRIPTION).version(packageJson.version);
38
44
  registerRootProgramHelp(program);
39
45
  // 版本检查(非阻塞,后台执行)
40
46
  // 只在非 upgrade 命令时检查,避免重复提示
41
- if (!process.argv.includes('upgrade') && !process.argv.includes('workspace-runtime')) {
47
+ if (!structuredVideoTopic && !process.argv.includes('upgrade') && !process.argv.includes('workspace-runtime')) {
42
48
  checkForUpdates(packageJson);
43
49
  }
44
50
  // create 命令
@@ -373,4 +379,24 @@ registerPradCommands(program);
373
379
  // 3D model utilities (playcraft 3d <command>)
374
380
  register3DCommands(program);
375
381
  registerWorkspaceRuntimeCommands(program);
376
- program.parse(process.argv);
382
+ registerVideoCommands(program);
383
+ registerPlayableCommands(program);
384
+ if (structuredVideoTopic) {
385
+ try {
386
+ await program.parseAsync(process.argv);
387
+ }
388
+ catch (error) {
389
+ if (!(error instanceof CommanderError))
390
+ throw error;
391
+ if (error.exitCode === 0)
392
+ process.exitCode = 0;
393
+ else {
394
+ const command = [process.argv[2], process.argv[3]?.startsWith('-') ? undefined : process.argv[3]].filter(Boolean).join(' ');
395
+ process.stdout.write(`${JSON.stringify({ schemaVersion: 'playcraft.video-cli.v1', command, state: 'failed', ok: false,
396
+ error: { code: 'invalidArguments', message: videoMessage('invalidArguments') } })}\n`);
397
+ process.exitCode = 64;
398
+ }
399
+ }
400
+ }
401
+ else
402
+ program.parse(process.argv);