@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
@@ -0,0 +1,293 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { createReadStream } from 'node:fs';
4
+ import { access, appendFile, mkdir, readFile, rename, stat, writeFile } from 'node:fs/promises';
5
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path';
6
+ import { performance } from 'node:perf_hooks';
7
+ import { setTimeout as delay } from 'node:timers/promises';
8
+ import { promisify } from 'node:util';
9
+ import { createRequire } from 'node:module';
10
+ import { canonicalReplicaJson, replicaRecordingMetadataSchema, } from '@playcraft/common/agent-tools';
11
+ import { prepareArtifactDirectory, writeJsonAtomic } from '../video-replication/evidence.js';
12
+ import { probeVideo } from '../video-replication/media.js';
13
+ import { VideoCliError } from '../video-replication/messages.js';
14
+ import { computeProjectInputDigest } from './project-digest.js';
15
+ import { RecordingError, recordingMessage } from './messages.js';
16
+ import { parseRecordingScenario, recordingControls, recordingPoint, recordingUrl } from './scenario.js';
17
+ const execute = promisify(execFile);
18
+ const require = createRequire(import.meta.url);
19
+ const relativeFile = (root, path) => relative(root, path).split(sep).join('/');
20
+ const sha = (value) => createHash('sha256').update(value).digest('hex');
21
+ const printableUrl = (value) => { try {
22
+ const url = new URL(value);
23
+ return `${url.origin}${url.pathname}`;
24
+ }
25
+ catch {
26
+ return '[unavailable]';
27
+ } };
28
+ export async function hashRecordingFile(path) {
29
+ const hash = createHash('sha256');
30
+ for await (const bytes of createReadStream(path))
31
+ hash.update(bytes);
32
+ return hash.digest('hex');
33
+ }
34
+ async function mediaCommand(tool, args, signal) {
35
+ const executable = process.env[tool === 'ffmpeg' ? 'FFMPEG_PATH' : 'FFPROBE_PATH'] || tool;
36
+ if (executable !== tool && !isAbsolute(executable))
37
+ throw new RecordingError('invalidArguments', 64);
38
+ try {
39
+ return (await execute(executable, args, { timeout: 60_000, maxBuffer: 1024 * 1024, encoding: 'utf8', signal })).stdout;
40
+ }
41
+ catch (error) {
42
+ if (signal?.aborted)
43
+ throw signal.reason;
44
+ throw new RecordingError('recordingFailed');
45
+ }
46
+ }
47
+ export async function waitUntil(origin, atMs, signal) {
48
+ // Timers can wake before a fractional deadline. Never dispatch input or finish a capture early.
49
+ for (;;) {
50
+ signal.throwIfAborted();
51
+ const remaining = origin + atMs - performance.now();
52
+ if (remaining <= 0)
53
+ return;
54
+ await delay(Math.ceil(remaining), undefined, { signal });
55
+ }
56
+ }
57
+ async function dispatchStep(page, session, scenario, step, origin, signal, emit) {
58
+ const point = recordingPoint(scenario, step.type === 'tap' ? step : step.path[0]);
59
+ if (step.type === 'tap') {
60
+ if (scenario.pointer === 'touch')
61
+ await page.touchscreen.tap(point.x, point.y);
62
+ else
63
+ await page.mouse.click(point.x, point.y);
64
+ emit(point, 'tap', step.atMs);
65
+ return;
66
+ }
67
+ if (scenario.pointer === 'touch')
68
+ await session.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ ...point, id: 1 }] });
69
+ else {
70
+ await page.mouse.move(point.x, point.y);
71
+ await page.mouse.down();
72
+ }
73
+ emit(point, 'start', step.atMs);
74
+ let completed = false;
75
+ try {
76
+ for (const next of step.path.slice(1)) {
77
+ await waitUntil(origin, step.atMs + next.offsetMs, signal);
78
+ const actual = recordingPoint(scenario, next);
79
+ if (scenario.pointer === 'touch')
80
+ await session.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ ...actual, id: 1 }] });
81
+ else
82
+ await page.mouse.move(actual.x, actual.y);
83
+ emit(actual, 'move', step.atMs + next.offsetMs);
84
+ }
85
+ completed = true;
86
+ }
87
+ finally {
88
+ const release = scenario.pointer === 'touch' ? session.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }) : page.mouse.up();
89
+ if (completed) {
90
+ await release;
91
+ emit(recordingPoint(scenario, step.path.at(-1)), 'end', step.atMs + step.path.at(-1).offsetMs);
92
+ }
93
+ else
94
+ await release.catch(() => { });
95
+ }
96
+ }
97
+ async function recordOne(browser, root, url, scenario, variant, signal) {
98
+ const directory = variant.kind === 'candidate' ? root : join(root, 'controls', variant.id);
99
+ await mkdir(join(directory, 'screenshots'), { recursive: true });
100
+ const eventPath = join(directory, 'events.jsonl');
101
+ const consolePath = join(directory, 'console.jsonl');
102
+ await writeFile(eventPath, '', { flag: 'wx', mode: 0o600 });
103
+ await writeFile(consolePath, '', { flag: 'wx', mode: 0o600 });
104
+ const context = await browser.newContext({
105
+ viewport: { width: scenario.viewport.width, height: scenario.viewport.height }, deviceScaleFactor: scenario.viewport.deviceScaleFactor,
106
+ hasTouch: scenario.pointer === 'touch', isMobile: scenario.pointer === 'touch', serviceWorkers: 'block',
107
+ acceptDownloads: false, recordVideo: { dir: join(directory, 'capture'), size: { width: scenario.viewport.width, height: scenario.viewport.height } },
108
+ });
109
+ let logs = Promise.resolve();
110
+ let logBytes = 0;
111
+ let failed;
112
+ const runtime = { pageErrors: 0, consoleErrors: 0, failedRequests: 0 };
113
+ let origin = performance.now();
114
+ let inputOriginMs = Date.now();
115
+ const log = (path, value) => {
116
+ const line = `${JSON.stringify(value)}\n`;
117
+ logBytes += Buffer.byteLength(line);
118
+ if (logBytes > 16 * 1024 * 1024) {
119
+ failed = new RecordingError('recordingFailed');
120
+ return;
121
+ }
122
+ logs = logs.then(() => appendFile(path, line));
123
+ };
124
+ const closeOnAbort = () => { void context.close().catch(() => { }); };
125
+ signal.addEventListener('abort', closeOnAbort, { once: true });
126
+ let closed = false;
127
+ try {
128
+ signal.throwIfAborted();
129
+ const page = await context.newPage();
130
+ const video = page.video();
131
+ if (!video)
132
+ throw new RecordingError('browserUnavailable');
133
+ page.on('console', message => {
134
+ if (message.type() === 'error')
135
+ runtime.consoleErrors++;
136
+ log(consolePath, { atMs: performance.now() - origin, kind: 'console', level: message.type(), text: message.text().slice(0, 32768) });
137
+ });
138
+ page.on('pageerror', error => { runtime.pageErrors++; log(consolePath, { atMs: performance.now() - origin, kind: 'pageerror', level: 'error', text: error.message.slice(0, 32768) }); });
139
+ page.on('requestfailed', request => { runtime.failedRequests++; log(consolePath, { atMs: performance.now() - origin, kind: 'requestfailed', level: 'error', url: printableUrl(request.url()), text: request.failure()?.errorText }); });
140
+ context.on('page', popup => { if (popup !== page) {
141
+ runtime.pageErrors++;
142
+ log(consolePath, { atMs: performance.now() - origin, kind: 'popup', level: 'error', text: 'recording.popupUnsupported' });
143
+ void popup.close().catch(() => { });
144
+ } });
145
+ await context.route('**/*', async (route) => {
146
+ if (route.request().isNavigationRequest() && new URL(route.request().url()).origin !== url.origin) {
147
+ failed = new RecordingError('navigationFailed');
148
+ await route.abort();
149
+ }
150
+ else
151
+ await route.continue();
152
+ });
153
+ page.on('dialog', dialog => { runtime.pageErrors++; log(consolePath, { atMs: performance.now() - origin, kind: 'dialog', level: 'error', text: dialog.message().slice(0, 32768) }); void dialog.dismiss(); });
154
+ const response = await page.goto(url.href, { waitUntil: 'load', timeout: 30_000 });
155
+ if (!response?.ok() || new URL(page.url()).origin !== url.origin || page.isClosed())
156
+ throw new RecordingError('navigationFailed');
157
+ const initial = join(directory, 'screenshots', 'initial.png');
158
+ await page.screenshot({ path: initial, timeout: 10_000 });
159
+ origin = performance.now();
160
+ inputOriginMs = Date.now();
161
+ const screenshots = [{ path: relativeFile(root, initial), sha256: await hashRecordingFile(initial), atMs: 0 }];
162
+ const session = await context.newCDPSession(page);
163
+ log(eventPath, { kind: 'recording-start', plannedAtMs: 0, actualAtMs: 0, inputOriginMs, navigationUrl: printableUrl(url.href), finalUrl: printableUrl(page.url()), device: scenario.pointer, reset: scenario.reset, seedApplied: false });
164
+ for (const step of scenario.steps) {
165
+ await waitUntil(origin, step.atMs, signal);
166
+ if (failed)
167
+ throw failed;
168
+ const omitted = variant.omittedStepIds.includes(step.id);
169
+ const points = (step.type === 'tap' ? [{ offsetMs: 0, x: step.x, y: step.y }] : step.path).map(point => ({ ...point, actual: recordingPoint(scenario, point) }));
170
+ if (omitted) {
171
+ log(eventPath, { stepId: step.id, kind: step.type, plannedAtMs: step.atMs, actualAtMs: performance.now() - origin, device: scenario.pointer, points, status: 'omitted' });
172
+ continue;
173
+ }
174
+ const before = join(directory, 'screenshots', `${step.id}-before.png`);
175
+ await page.screenshot({ path: before, timeout: 10_000 });
176
+ screenshots.push({ path: relativeFile(root, before), sha256: await hashRecordingFile(before), atMs: Math.round(performance.now() - origin) });
177
+ const started = performance.now() - origin;
178
+ log(eventPath, { stepId: step.id, kind: step.type, plannedAtMs: step.atMs, actualAtMs: started, device: scenario.pointer, points, status: 'started' });
179
+ try {
180
+ await dispatchStep(page, session, scenario, step, origin, signal, (point, phase, plannedAtMs) => log(eventPath, { stepId: step.id, kind: 'pointer', phase, plannedAtMs, actualAtMs: performance.now() - origin, device: scenario.pointer, actual: point, status: 'dispatched' }));
181
+ log(eventPath, { stepId: step.id, kind: step.type, plannedAtMs: step.atMs, actualAtMs: started, completedAtMs: performance.now() - origin, device: scenario.pointer, points, status: 'dispatched' });
182
+ }
183
+ catch (error) {
184
+ log(eventPath, { stepId: step.id, kind: step.type, plannedAtMs: step.atMs, actualAtMs: started, device: scenario.pointer, points, status: 'failed' });
185
+ throw error;
186
+ }
187
+ const after = join(directory, 'screenshots', `${step.id}-after.png`);
188
+ await page.screenshot({ path: after, timeout: 10_000 });
189
+ screenshots.push({ path: relativeFile(root, after), sha256: await hashRecordingFile(after), atMs: Math.round(performance.now() - origin) });
190
+ }
191
+ await waitUntil(origin, scenario.durationMs, signal);
192
+ if (failed)
193
+ throw failed;
194
+ log(eventPath, { kind: 'recording-end', plannedAtMs: scenario.durationMs, actualAtMs: performance.now() - origin, status: 'completed' });
195
+ const closingAt = Date.now();
196
+ await context.close();
197
+ closed = true;
198
+ const closedAt = Date.now();
199
+ await logs;
200
+ const raw = join(directory, 'raw-capture.webm');
201
+ await rename(await video.path(), raw);
202
+ const rawProbe = JSON.parse(await mediaCommand('ffprobe', ['-v', 'error', '-show_entries', 'format=duration:stream=avg_frame_rate,codec_type', '-of', 'json', raw], signal));
203
+ const rawDuration = Number(rawProbe.format.duration) * 1000;
204
+ const stream = rawProbe.streams.find(value => value.codec_type === 'video');
205
+ const rate = stream?.avg_frame_rate.split('/').map(Number);
206
+ const fps = rate && rate[0] > 0 && rate[1] > 0 ? rate[0] / rate[1] : 0;
207
+ if (!Number.isFinite(rawDuration) || rawDuration <= 0 || !fps)
208
+ throw new RecordingError('recordingFailed');
209
+ // The encoder's final frame falls inside the measured context-close interval.
210
+ const rawOriginMs = closingAt - rawDuration;
211
+ const offsetMs = Math.max(0, inputOriginMs - rawOriginMs);
212
+ const candidate = join(directory, 'candidate.mp4');
213
+ await mediaCommand('ffmpeg', ['-v', 'error', '-nostdin', '-i', raw, '-ss', (offsetMs / 1000).toFixed(6), '-t', (scenario.durationMs / 1000).toFixed(6), '-an', '-c:v', 'libx264', '-preset', 'ultrafast', '-crf', '20', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', candidate], signal);
214
+ const probed = await probeVideo(candidate, signal);
215
+ const uncertaintyMs = closedAt - closingAt + 1000 / fps + Math.max(0, rawOriginMs - inputOriginMs);
216
+ if (probed.source.width !== scenario.viewport.width || probed.source.height !== scenario.viewport.height || probed.source.durationMs < scenario.durationMs - uncertaintyMs - 1000 / fps)
217
+ throw new RecordingError('recordingFailed');
218
+ return {
219
+ ...variant, video: { path: relativeFile(root, candidate), source: probed.source, fps },
220
+ events: { path: relativeFile(root, eventPath), sha256: await hashRecordingFile(eventPath) }, console: { path: relativeFile(root, consolePath), sha256: await hashRecordingFile(consolePath) },
221
+ timing: { inputOriginMs, videoOriginMs: inputOriginMs, uncertaintyMs }, runtime, screenshots,
222
+ };
223
+ }
224
+ finally {
225
+ signal.removeEventListener('abort', closeOnAbort);
226
+ if (!closed)
227
+ await context.close().catch(() => { });
228
+ await logs;
229
+ }
230
+ }
231
+ export async function recordPlayable(options, signal) {
232
+ const runId = randomUUID();
233
+ let out;
234
+ let browser;
235
+ let prepared = false;
236
+ try {
237
+ const url = recordingUrl(options.url);
238
+ if (!options.scenario || options.browserPath && !isAbsolute(options.browserPath))
239
+ throw new RecordingError('invalidArguments', 64);
240
+ const scenarioStat = await stat(options.scenario).catch(() => { throw new RecordingError('invalidArguments', 64); });
241
+ if (!scenarioStat.isFile() || scenarioStat.size > 1024 * 1024)
242
+ throw new RecordingError('invalidArguments', 64);
243
+ let scenario;
244
+ try {
245
+ scenario = parseRecordingScenario(JSON.parse(await readFile(options.scenario, 'utf8')));
246
+ }
247
+ catch {
248
+ throw new RecordingError('invalidArguments', 64);
249
+ }
250
+ const scenarioSha256 = sha(canonicalReplicaJson(scenario));
251
+ const configuredPath = options.browserPath || process.env.PLAYCRAFT_CHROMIUM_PATH || '/usr/bin/chromium';
252
+ if (!isAbsolute(configuredPath))
253
+ throw new RecordingError('invalidArguments', 64);
254
+ await access(configuredPath).catch(() => { throw new RecordingError('browserUnavailable'); });
255
+ out = resolve(options.out || join('.playcraft', 'video-replication', runId, 'recording'));
256
+ const project = await computeProjectInputDigest(process.cwd(), [out]);
257
+ await prepareArtifactDirectory(out, runId, false);
258
+ prepared = true;
259
+ await writeJsonAtomic(join(out, 'metadata.json'), { schemaVersion: 'playcraft.replica-recording.v1', runId, state: 'recording', scenarioSha256 });
260
+ const ffmpeg = (await mediaCommand('ffmpeg', ['-version'], signal)).split('\n')[0];
261
+ if (!process.env.PLAYWRIGHT_BROWSERS_PATH && await access('/opt/playcraft/playwright').then(() => true, () => false))
262
+ process.env.PLAYWRIGHT_BROWSERS_PATH = '/opt/playcraft/playwright';
263
+ const { chromium } = await import('playwright-core');
264
+ browser = await chromium.launch({ executablePath: configuredPath, headless: true, args: ['--mute-audio', '--disable-dev-shm-usage', '--enable-unsafe-swiftshader', '--use-gl=angle', '--use-angle=swiftshader', ...(process.getuid?.() === 0 ? ['--no-sandbox'] : [])] }).catch(() => { throw new RecordingError('browserUnavailable'); });
265
+ process.stderr.write(`[record] ${recordingMessage('recording')}\n`);
266
+ const candidate = await recordOne(browser, out, url, scenario, { id: 'candidate', kind: 'candidate', omittedStepIds: [] }, signal);
267
+ const controls = [];
268
+ for (const control of recordingControls(scenario))
269
+ controls.push(await recordOne(browser, out, url, scenario, control, signal));
270
+ const current = await computeProjectInputDigest(process.cwd(), [out]);
271
+ if (current.sha256 !== project.sha256)
272
+ throw new RecordingError('projectChanged', 64);
273
+ const metadata = replicaRecordingMetadataSchema.parse({
274
+ schemaVersion: 'playcraft.replica-recording.v1', runId, state: 'completed', scenario, scenarioSha256, project,
275
+ toolVersions: { cli: require('../../package.json').version, playwright: require('playwright-core/package.json').version, browser: browser.version(), ffmpeg },
276
+ conditions: { audio: 'muted', seedSupport: scenario.seed ? 'best-effort' : 'not-requested', serverStateReset: 'not-guaranteed' },
277
+ candidate, controls,
278
+ });
279
+ await writeJsonAtomic(join(out, 'metadata.json'), metadata);
280
+ return { exitCode: 0, envelope: { schemaVersion: 'playcraft.video-cli.v1', command: 'playable record', runId, state: 'completed', ok: true,
281
+ artifacts: { metadata: join(out, 'metadata.json'), candidate: join(out, candidate.video.path), controls: controls.map(control => join(out, control.video.path)) }, result: metadata } };
282
+ }
283
+ catch (error) {
284
+ const code = error instanceof RecordingError ? error.code : error instanceof VideoCliError && error.code === 'outputConflict' ? 'outputConflict' : signal.aborted ? signal.reason?.name === 'TimeoutError' ? 'timedOut' : 'interrupted' : 'recordingFailed';
285
+ const exitCode = error instanceof RecordingError || error instanceof VideoCliError ? error.exitCode : signal.aborted ? code === 'timedOut' ? 75 : 130 : 4;
286
+ if (out && prepared)
287
+ await writeJsonAtomic(join(out, 'metadata.json'), { schemaVersion: 'playcraft.replica-recording.v1', runId, state: 'failed', error: { code } }).catch(() => { });
288
+ return { exitCode, envelope: { schemaVersion: 'playcraft.video-cli.v1', command: 'playable record', runId, state: 'failed', ok: false, ...(out && prepared ? { artifacts: { metadata: join(out, 'metadata.json') } } : {}), error: { code, message: recordingMessage(code) } } };
289
+ }
290
+ finally {
291
+ await browser?.close().catch(() => { });
292
+ }
293
+ }
@@ -0,0 +1,50 @@
1
+ import { replicaScenarioSchema } from '@playcraft/common/agent-tools';
2
+ import { RecordingError } from './messages.js';
3
+ export function recordingUrl(value) {
4
+ try {
5
+ if (!value)
6
+ throw new Error();
7
+ const url = new URL(value);
8
+ if (url.protocol !== 'http:' || !['127.0.0.1', '[::1]', 'localhost'].includes(url.hostname) || url.username || url.password || url.hash)
9
+ throw new Error();
10
+ return url;
11
+ }
12
+ catch {
13
+ throw new RecordingError('invalidUrl', 64);
14
+ }
15
+ }
16
+ export function parseRecordingScenario(value) {
17
+ const parsed = replicaScenarioSchema.safeParse(value);
18
+ if (!parsed.success)
19
+ throw new RecordingError('invalidArguments', 64);
20
+ const scenario = parsed.data;
21
+ if (scenario.draft || scenario.viewport.width % 2 || scenario.viewport.height % 2 || scenario.steps.length > 63 || scenario.steps.some(step => step.id.length > 110))
22
+ throw new RecordingError('invalidArguments', 64);
23
+ const ids = new Set();
24
+ let previousEnd = -1;
25
+ for (const step of scenario.steps) {
26
+ if (ids.has(step.id) || step.atMs < previousEnd)
27
+ throw new RecordingError('invalidArguments', 64);
28
+ ids.add(step.id);
29
+ const end = step.atMs + (step.type === 'drag' ? step.path.at(-1).offsetMs : 0);
30
+ if (end >= scenario.durationMs)
31
+ throw new RecordingError('invalidArguments', 64);
32
+ if (step.type === 'drag' && (step.path[0].offsetMs !== 0 || step.path.some((point, index) => index > 0 && point.offsetMs <= step.path[index - 1].offsetMs)))
33
+ throw new RecordingError('invalidArguments', 64);
34
+ previousEnd = end;
35
+ }
36
+ const required = new Set(scenario.requiredEffects.map(effect => effect.stepId));
37
+ if ([...required].some(id => !ids.has(id)) || (scenario.controls.noInput ? 1 : 0) + (scenario.controls.omitRequiredSteps ? required.size : 0) > 4)
38
+ throw new RecordingError('invalidArguments', 64);
39
+ return scenario;
40
+ }
41
+ export function recordingControls(scenario) {
42
+ return [
43
+ ...(scenario.controls.noInput ? [{ id: 'control-no-input', kind: 'no-input', omittedStepIds: scenario.steps.map(step => step.id) }] : []),
44
+ ...(scenario.controls.omitRequiredSteps ? [...new Set(scenario.requiredEffects.map(effect => effect.stepId))].map(id => ({ id: `control-omit-${id}`, kind: 'omit-step', omittedStepIds: [id] })) : []),
45
+ ];
46
+ }
47
+ export function recordingPoint(scenario, point) {
48
+ const rect = scenario.contentRect;
49
+ return { x: (rect.x + point.x * rect.width) * scenario.viewport.width, y: (rect.y + point.y * rect.height) * scenario.viewport.height };
50
+ }
@@ -90,10 +90,19 @@ export class AgentApiClient {
90
90
  `continue this request: it returns the result if the request finished, or finishes it if ` +
91
91
  `the tool can be safely redone; it never starts a second operation. Record: ${operation.file}.`;
92
92
  try {
93
+ try {
94
+ await options?.onPrepared?.({ requestId: operation.requestId, file: operation.file });
95
+ }
96
+ catch {
97
+ operation.reject();
98
+ throw new ToolRequestError('Tool request preparation failed; no operation was sent');
99
+ }
93
100
  const capabilityResponse = await fetch(this.toolsRequestUrl(AGENT_TOOL_OPERATION_CAPABILITIES_PATH), {
94
101
  headers: this.authHeaders(),
95
102
  redirect: 'error',
96
- signal: AbortSignal.timeout(30_000),
103
+ signal: options?.signal
104
+ ? AbortSignal.any([options.signal, AbortSignal.timeout(30_000)])
105
+ : AbortSignal.timeout(30_000),
97
106
  });
98
107
  if (!capabilityResponse.ok) {
99
108
  if (capabilityResponse.status === 403) {
@@ -114,7 +123,9 @@ export class AgentApiClient {
114
123
  const res = await fetch(url, {
115
124
  method: 'POST',
116
125
  redirect: 'error',
117
- signal: AbortSignal.timeout(30 * 60_000),
126
+ signal: options?.signal
127
+ ? AbortSignal.any([options.signal, AbortSignal.timeout(30 * 60_000)])
128
+ : AbortSignal.timeout(30 * 60_000),
118
129
  headers: {
119
130
  'Content-Type': 'application/json',
120
131
  ...this.authHeaders(),
@@ -180,7 +191,7 @@ export class AgentApiClient {
180
191
  operation.release();
181
192
  }
182
193
  }
183
- async get(path, params) {
194
+ async get(path, params, options) {
184
195
  const url = this.toolsRequestUrl(path);
185
196
  if (params) {
186
197
  for (const [k, v] of Object.entries(params)) {
@@ -190,6 +201,8 @@ export class AgentApiClient {
190
201
  }
191
202
  const res = await fetch(url, {
192
203
  headers: this.authHeaders(),
204
+ redirect: 'error',
205
+ signal: options?.signal ?? AbortSignal.timeout(30_000),
193
206
  });
194
207
  if (!res.ok) {
195
208
  const text = await res.text().catch(() => res.statusText);
@@ -200,6 +213,29 @@ export class AgentApiClient {
200
213
  }
201
214
  return res.json();
202
215
  }
216
+ /** Stream only to the authenticated, same-service video upload endpoint. */
217
+ async putVideoMedia(path, body, headers, signal) {
218
+ if (!/^\/video-media\/[a-f0-9-]{36}\/content\?/.test(path))
219
+ throw new Error('invalid_video_upload_target');
220
+ const url = this.toolsRequestUrl(path);
221
+ const keys = [...url.searchParams.keys()].sort();
222
+ if (keys.join(',') !== 'expires,signature,workspaceId')
223
+ throw new Error('invalid_video_upload_target');
224
+ const allowed = new Set(['content-type', 'content-md5', 'content-length']);
225
+ if (Object.keys(headers).some(key => !allowed.has(key.toLowerCase())))
226
+ throw new Error('invalid_video_upload_headers');
227
+ const response = await fetch(url, {
228
+ method: 'PUT', redirect: 'error', signal,
229
+ headers: { ...headers, ...this.authHeaders() },
230
+ body: body,
231
+ duplex: 'half',
232
+ });
233
+ if (!response.ok) {
234
+ await response.body?.cancel();
235
+ throw new Error(`video_upload_failed:${response.status}`);
236
+ }
237
+ await response.body?.cancel();
238
+ }
203
239
  /**
204
240
  * 按顺序搜索本地 .playcraft.json 文件(沙箱内或项目目录)。
205
241
  * 与全局 login 配置(~/.playcraft/config.json)不同,前者专用于沙箱 token。
@@ -0,0 +1,81 @@
1
+ import { constants } from 'node:fs';
2
+ import { lstat, mkdir, open, realpath } from 'node:fs/promises';
3
+ import { dirname, join } from 'node:path';
4
+ const ENTRY = '/.playcraft/video-replication/';
5
+ /** Keep local analysis evidence out of a repository without changing its tracked ignore rules. */
6
+ export async function ensureVideoEvidenceGitExcluded(directory) {
7
+ let root = await realpath(directory);
8
+ while (true) {
9
+ const marker = await lstat(join(root, '.git')).catch((error) => {
10
+ if (error.code === 'ENOENT')
11
+ return undefined;
12
+ throw error;
13
+ });
14
+ if (marker) {
15
+ // Cloud workspaces own a real .git directory; never follow a redirected Git metadata tree.
16
+ if (!marker.isDirectory() || marker.isSymbolicLink())
17
+ return false;
18
+ try {
19
+ await appendExclude(root);
20
+ return true;
21
+ }
22
+ catch (error) {
23
+ if (['EACCES', 'EPERM', 'EROFS'].includes(error.code ?? ''))
24
+ return false;
25
+ throw error;
26
+ }
27
+ }
28
+ const parent = dirname(root);
29
+ if (parent === root)
30
+ return true;
31
+ root = parent;
32
+ }
33
+ }
34
+ async function appendExclude(root) {
35
+ const flags = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW;
36
+ const handles = [];
37
+ let file;
38
+ try {
39
+ const directory = await open(root, flags);
40
+ handles.push(directory);
41
+ const pinned = (handle, fallback) => process.platform === 'linux' ? `/proc/self/fd/${handle.fd}` : fallback;
42
+ const git = await open(join(pinned(directory, root), '.git'), flags);
43
+ handles.push(git);
44
+ const gitPath = pinned(git, join(root, '.git'));
45
+ await mkdir(join(gitPath, 'info')).catch((error) => {
46
+ if (error.code !== 'EEXIST')
47
+ throw error;
48
+ });
49
+ const info = await open(join(gitPath, 'info'), flags);
50
+ handles.push(info);
51
+ const exclude = join(pinned(info, join(root, '.git/info')), 'exclude');
52
+ const readable = await open(exclude, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
53
+ .catch((error) => { if (error.code === 'ENOENT')
54
+ return undefined; throw error; });
55
+ if (readable) {
56
+ try {
57
+ const stat = await readable.stat();
58
+ if (!stat.isFile() || stat.nlink !== 1 || stat.size > 1024 * 1024)
59
+ throw new Error('invalid_git_exclude');
60
+ if ((await readable.readFile('utf8')).split('\n').some(line => line.trim() === ENTRY))
61
+ return;
62
+ }
63
+ finally {
64
+ await readable.close();
65
+ }
66
+ }
67
+ file = await open(exclude, constants.O_RDWR | constants.O_CREAT | constants.O_APPEND | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o666);
68
+ const stat = await file.stat();
69
+ if (!stat.isFile() || stat.nlink !== 1 || stat.size > 1024 * 1024)
70
+ throw new Error('invalid_git_exclude');
71
+ const current = await file.readFile('utf8');
72
+ if (!current.split('\n').some(line => line.trim() === ENTRY)) {
73
+ await file.writeFile(`${current && !current.endsWith('\n') ? '\n' : ''}${ENTRY}\n`);
74
+ }
75
+ }
76
+ finally {
77
+ await file?.close();
78
+ for (const handle of handles.reverse())
79
+ await handle.close();
80
+ }
81
+ }