scripting-cli 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -205,4 +205,187 @@ If you encounter issues:
205
205
 
206
206
  ---
207
207
 
208
- Enjoy using `scripting-cli` in your Scripting app development workflow. Happy coding!
208
+ Enjoy using `scripting-cli` in your Scripting app development workflow. Happy coding!
209
+
210
+ ## Desktop agent commands
211
+
212
+ Codex, Claude Code, and other desktop agents can query the connected App's docs,
213
+ sync the current debug project, run it, and inspect results without a separate
214
+ agent-specific plugin. These commands require a compatible Scripting App with
215
+ Desktop Agent protocol v1 support. Older App versions can continue normal file
216
+ syncing but do not support the new commands.
217
+
218
+ 1. Run `scripting-cli start` in your workspace.
219
+ 2. Connect Scripting to that server. Select a script and enter its debug page.
220
+ 3. The existing sync workflow creates `scripts/<project>/` in the workspace.
221
+ 4. Run the commands below from that same workspace. The first release only
222
+ runs the App's selected debug project. Use the explicit projects commands below
223
+ to create or change that selection; execution never switches it implicitly.
224
+
225
+ ```sh
226
+ scripting-cli devices --json
227
+ scripting-cli status --json
228
+ scripting-cli docs search "Navigation" --json
229
+ scripting-cli docs get navigation --lang zh --json # use an ID returned by search
230
+ scripting-cli api get Navigation.present --json
231
+ scripting-cli run "MyScript" --json
232
+ scripting-cli run "MyScript" --query-parameters '{"sample":true}' --json
233
+ scripting-cli run "MyScript" --screenshot --capture-after 2 --output ./artifacts --json
234
+ scripting-cli widget "MyScript" --family systemMedium --json
235
+ scripting-cli widget "MyScript" --family systemMedium --parameter demo --screenshot --output ./artifacts --json
236
+ scripting-cli jobs show <run-id> --json
237
+ scripting-cli jobs cancel <run-id> --json
238
+ ```
239
+
240
+ - With several connected devices, pass `--device <device-id>` from `devices`.
241
+ `devices` makes a fresh request and reports `responsive`; a connected socket
242
+ alone is not proof the App can execute a command. `status` includes foreground
243
+ state, the selected project, current revision, `activeRunId` and background-keeper state.
244
+ - Docs and API declarations come from the connected App, with its version in
245
+ the response. Search returns IDs and summaries; `docs get` reads one document.
246
+ There is no silent offline fallback to older docs.
247
+ - `run` and `widget` first capture a bounded source snapshot, sync all included
248
+ files, and wait for the App to acknowledge its SHA256 revision. Files changed
249
+ after the snapshot belong to a later update. Delayed notifications for the
250
+ already-applied snapshot do not cause an extra automatic run.
251
+ - Ordinary `run` waits for `Script.exit(result)` or failure. The default overall
252
+ deadline is 30 seconds (`--timeout`, 1–120). Forgetting to call `Script.exit`
253
+ can therefore produce a timeout. Request parameters retain the project's
254
+ normal App permission checks.
255
+ - `run --screenshot` requires Scripting in the foreground. It waits for this
256
+ run's view, waits `--capture-after` seconds (0–10, default 2), captures the
257
+ view, and ends this run. Its result says `completionReason: preview_capture`;
258
+ this is a finite preview, not proof the script exited itself or that all
259
+ remote content finished loading. No rendered view means an explicit error,
260
+ not a successful blank image.
261
+ - Both widget modes render the current project's `widget.tsx` in the App's
262
+ foreground preview and close automatically. Without `--screenshot`, no image
263
+ is generated. These commands do not install a home-screen widget or confirm
264
+ a WidgetKit timeline refresh. The supplied family/parameter do not overwrite
265
+ the user's normal preview preferences.
266
+ - `--no-sync` explicitly uses the last acknowledged App revision; it fails if
267
+ the revision is unknown or later file updates invalidated it. Active manual
268
+ runs or previews return `busy`, and commands do not stop them automatically.
269
+ - Ctrl-C requests cancellation of this command only. Cancellation, disconnect,
270
+ source failure, execution failure and screenshot failure remain distinct
271
+ results. A cancellation request stays `cancelling` until the App confirms a
272
+ terminal result; a missing confirmation is a failure, not proof execution stopped. Disconnected runs are not automatically replayed.
273
+
274
+ With `--json`, stdout contains one JSON value (a device array for `devices`, or a
275
+ job record for other commands). Jobs contain `runId`, `requestId`, `deviceId`,
276
+ `sessionId`, `project`, `requestedRevision`, `revision`, `status`, and `result` or `error`. The requested revision and the App-applied revision are separate; failed
277
+ preconditions do not claim that source was applied. Script
278
+ values are in `result.value`, logs in `result.stdout` / `result.stderr`, and
279
+ screenshots in `result.artifacts`. PNG files are copied to
280
+ `<output>/<run-id>/screenshot.png`; base64 image data is never printed to stdout.
281
+ Keep user-requested output files as long as needed. The private server retains
282
+ at most 64 job records / 8 image results, expires results after 15 minutes, and
283
+ removes its temporary results on shutdown.
284
+
285
+ Exit codes: `0` success, `1` command failure, `2` invalid CLI usage, `124` execution
286
+ or device timeout, `130` caller cancellation. Stable error codes include
287
+ `device_ambiguous`, `project_mismatch`, `debug_session_required`, `busy`,
288
+ `needs_foreground`, `sync_failed`, `missing_entry`, `screenshot_unavailable`, and
289
+ `unsupported_capability`. Inspect the result instead of treating a successful
290
+ connection or preview presentation as completed execution.
291
+
292
+ Source snapshots include at most 8 MiB and 2000 regular files, using the existing
293
+ ignore rules. Source symlinks and unsafe paths are rejected. Screenshots are
294
+ bounded to 8 MiB and 16 megapixels. The App preserves excluded files and the
295
+ script's permission identity. A separate authenticated loopback control server
296
+ connects desktop commands to the running service; its credentials live in a
297
+ private per-user OS temporary directory, not the project or command output.
298
+ The existing App-facing LAN / Tailscale server remains available for file sync.
299
+
300
+ ### Tests
301
+
302
+ `npm test` builds the existing TypeScript sources and runs the checked-in Node
303
+ tests. It covers file/byte revisions, traversal and symlink refusals, device and
304
+ session selection, duplicate IDs, cancellation, disconnects, local HTTP control
305
+ boundaries, artifact delivery, retention, and actual CLI child processes. It
306
+ uses only owned temporary fixtures and removes them afterward. Real App
307
+ execution and screenshots also require App-side integration evidence; mocked
308
+ peers do not substitute for device rendering.
309
+
310
+
311
+ ## Live feedback, ready screenshots, batches, and project management
312
+
313
+ The next capabilities are negotiated separately. An older protocol-v1 App can
314
+ still use first-release commands, but unsupported ready-log, streaming or project
315
+ commands fail explicitly.
316
+
317
+ ```sh
318
+ scripting-cli run "MyScript" --stream
319
+ scripting-cli jobs events <run-id> --after 0 --json
320
+ scripting-cli projects list --json
321
+ scripting-cli projects inspect "MyScript" --json
322
+ scripting-cli projects create "NewScript" --json
323
+ scripting-cli projects attach "MyScript" --json
324
+ # Only after reviewing an App/desktop source conflict and choosing desktop source:
325
+ scripting-cli projects attach "MyScript" --replace --expected-revision <App-revision-from-inspect> --json
326
+ ```
327
+
328
+ `--stream` emits JSONL stage/log/diagnostic records with monotonic `seq` and run,
329
+ request, device, session identity, then one `type: result` record with `job`.
330
+ It replaces the single JSON result format even with `--json`. Sync, compilation,
331
+ execution, ready waiting, rendering and capture are distinct stages. Events keep
332
+ 256 recent records and 64 KiB of streamed log text per job; `gap` reports a slow
333
+ reader falling behind retention. Final logs also report truncation. Diagnostics
334
+ are collected on failures within the original deadline, with project-relative
335
+ `file`, one-based `line`/`column`, TypeScript `code` and message when available;
336
+ runtime failures do not necessarily have a TypeScript diagnostic.
337
+
338
+ For data-driven UI, emit an explicit exact log when the intended state is ready:
339
+
340
+ ```ts
341
+ console.log("SCREENSHOT_READY")
342
+ ```
343
+
344
+ Then run `scripting-cli run "MyScript" --screenshot --ready-log SCREENSHOT_READY --capture-after 1 --json`.
345
+ Only a non-error log from this run matches. Capture waits for both the signal and
346
+ a valid view before its settling delay; missing signals/views and foreground
347
+ loss never yield a successful screenshot. A script that exits without its signal
348
+ returns `ready_signal_missing`. Existing timeout rules remain unchanged.
349
+
350
+ `widget-batch "MyScript" --cases ./cases.json --timeout 60 --stream` runs one
351
+ source revision across 1...8 serial widget cases. A manifest is a JSON array:
352
+
353
+ ```json
354
+ [
355
+ {"id":"small","family":"systemSmall","parameter":"default","screenshot":true},
356
+ {"id":"medium","family":"systemMedium","parameter":"empty","screenshot":true},
357
+ {"id":"render-only","family":"systemSmall","screenshot":false}
358
+ ]
359
+ ```
360
+
361
+ IDs use letters, digits, `_` and `-`, and must be unique. Results name each case
362
+ and any skipped cases; PNGs are `<output>/<run-id>/<case-id>.png`. Image bytes total
363
+ at most 8 MiB for the batch. A failed/cancelled batch can retain completed earlier
364
+ cases; remaining cases do not execute. Every preview uses foreground rendering
365
+ and closes automatically, without changing normal preview preferences.
366
+
367
+ Project commands need the App connected; create/attach also need foreground and
368
+ refuse an active manual run/preview. `create` uses an existing desktop directory
369
+ or creates a minimal local `script.json` / `index.tsx` scaffold when absent. App
370
+ name collisions return `project_exists`, without overwriting that App project.
371
+ A scaffold can remain locally if App creation is refused. `attach` publishes a
372
+ desktop snapshot and enters that project's debug page. Different App source
373
+ returns `project_conflict` with its current revision; only explicit `--replace`
374
+ plus the inspected `--expected-revision` permits replacement. A changed App
375
+ revision is rejected again at publication. Ignored files are preserved. The
376
+ server changes its watcher only after native success; delayed old-project events
377
+ cannot write into the newly selected project. Type declarations are refreshed
378
+ from the same App for desktop editing.
379
+
380
+ ### Portable agent skill
381
+
382
+ The package includes [skills/scripting-development/SKILL.md](skills/scripting-development/SKILL.md).
383
+ `scripting-cli skill` prints the complete portable skill. It explains the
384
+ connected documentation → edit → execute → inspect screenshot → refine loop,
385
+ project conflicts, readiness, batches and cancellation for Codex/Claude Code.
386
+ Copy its directory into your agent's configured skill location if desired;
387
+ this command does not install it or change global agent configuration. Inspect
388
+ App/desktop conflicts and obtain authorization for the particular overwrite
389
+ before running the replacement command.
390
+
391
+ If the local service itself stops, commands report `control_unavailable`; they do not replay execution. Reconnect, inspect App status, and explicitly attach the intended project before a new run.
@@ -0,0 +1,83 @@
1
+ import { SourceSnapshot } from './agent_protocol';
2
+ type SocketPeer = {
3
+ id: string;
4
+ connected: boolean;
5
+ on: (event: string, cb: (...args: any[]) => void) => unknown;
6
+ emit: (event: string, ...args: any[]) => unknown;
7
+ };
8
+ interface Peer {
9
+ socket: SocketPeer;
10
+ metadata?: any;
11
+ pending: Map<string, {
12
+ request: any;
13
+ resolve: (reply: any) => void;
14
+ reject: (error: Error) => void;
15
+ }>;
16
+ hooks: {
17
+ project: () => string | null;
18
+ ignore: () => string[];
19
+ pause: () => void;
20
+ resume: (snapshot?: SourceSnapshot) => void;
21
+ switchProject?: (project: string) => Promise<void>;
22
+ types?: (files: Record<string, string>) => Promise<void>;
23
+ };
24
+ }
25
+ interface Job {
26
+ runId: string;
27
+ requestId: string;
28
+ deviceId: string;
29
+ sessionId: string;
30
+ project?: string;
31
+ requestedRevision?: string;
32
+ revision?: string;
33
+ status: string;
34
+ result?: any;
35
+ error?: {
36
+ code: string;
37
+ message: string;
38
+ };
39
+ createdAt: number;
40
+ cancellationRequested?: boolean;
41
+ fingerprint: string;
42
+ cancel?: () => void;
43
+ }
44
+ interface JobEvent {
45
+ seq: number;
46
+ type: string;
47
+ [key: string]: unknown;
48
+ }
49
+ export declare class AgentBroker {
50
+ readonly workspace: string;
51
+ private eventLogs;
52
+ private peers;
53
+ private jobs;
54
+ private activeMutations;
55
+ private artifactDirectory?;
56
+ constructor(workspace: string);
57
+ register(socket: SocketPeer, hooks: Peer['hooks']): void;
58
+ private invalidate;
59
+ private select;
60
+ private call;
61
+ devices(): Promise<any[]>;
62
+ submit(raw: unknown): Job;
63
+ private execute;
64
+ get(id: string): any;
65
+ cancel(id: string): any;
66
+ private publicJob;
67
+ private removeArtifact;
68
+ private statusFields;
69
+ private storeArtifact;
70
+ private event;
71
+ events(id: string, after: number): {
72
+ events: JobEvent[];
73
+ nextCursor: number;
74
+ truncated: boolean;
75
+ terminal: boolean;
76
+ logsTruncated: boolean;
77
+ };
78
+ private scaffold;
79
+ prune(now?: number): void;
80
+ close(): void;
81
+ }
82
+ export declare const agentBroker: AgentBroker;
83
+ export {};
@@ -0,0 +1,368 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.agentBroker = exports.AgentBroker = void 0;
7
+ const crypto_1 = __importDefault(require("crypto"));
8
+ const fs_1 = __importDefault(require("fs"));
9
+ const path_1 = __importDefault(require("path"));
10
+ const os_1 = __importDefault(require("os"));
11
+ const agent_protocol_1 = require("./agent_protocol");
12
+ const mutations = ['run', 'widget', 'widget.batch', 'projects.create', 'projects.attach'];
13
+ const projectChanges = ['projects.create', 'projects.attach'];
14
+ const terminal = (s) => ['completed', 'failed', 'cancelled'].includes(s);
15
+ class AgentBroker {
16
+ workspace;
17
+ eventLogs = new Map();
18
+ peers = new Map();
19
+ jobs = new Map();
20
+ activeMutations = new Set();
21
+ artifactDirectory;
22
+ constructor(workspace) {
23
+ this.workspace = workspace;
24
+ }
25
+ register(socket, hooks) {
26
+ if (this.peers.size >= 64)
27
+ return;
28
+ const peer = { socket, hooks, pending: new Map() };
29
+ this.peers.set(socket.id, peer);
30
+ socket.on('agentHello', (meta) => {
31
+ if (!meta || meta.protocolVersion !== 1 || typeof meta.deviceId !== 'string' || meta.deviceId.length > 128 || typeof meta.sessionId !== 'string' || meta.sessionId.length > 128 || !Array.isArray(meta.capabilities))
32
+ return;
33
+ // Duplicate installation IDs remain ambiguous. A second socket must not
34
+ // take over a connected device merely by claiming its identifier.
35
+ if (meta.capabilities.length > 16 || !meta.capabilities.every((value) => typeof value === 'string' && value.length < 64))
36
+ return;
37
+ if (peer.metadata && peer.metadata.sessionId !== meta.sessionId)
38
+ this.invalidate(peer);
39
+ peer.metadata = { protocolVersion: 1, deviceId: meta.deviceId, sessionId: meta.sessionId,
40
+ name: typeof meta.name === 'string' ? meta.name.slice(0, 128) : 'Scripting device',
41
+ appVersion: typeof meta.appVersion === 'string' ? meta.appVersion.slice(0, 64) : '',
42
+ capabilities: [...meta.capabilities], ...this.statusFields(meta) };
43
+ });
44
+ socket.on('agentResult', (reply) => {
45
+ const pending = peer.pending.get(reply?.requestId);
46
+ if (!pending)
47
+ return;
48
+ const request = pending.request;
49
+ if (reply.protocolVersion !== 1 || reply.sessionId !== request.sessionId || reply.runId !== request.runId || peer.metadata?.sessionId !== request.sessionId) {
50
+ pending.reject(new agent_protocol_1.AgentError('invalid_response', 'Device returned mismatched result identity.'));
51
+ }
52
+ else
53
+ pending.resolve(reply);
54
+ });
55
+ socket.on('agentTypes', async (data, ack) => {
56
+ try {
57
+ const pending = peer.pending.get(data?.requestId);
58
+ if (!pending || !projectChanges.includes(pending.request.method) || pending.request.runId !== data.runId || pending.request.sessionId !== data.sessionId || peer.metadata?.sessionId !== data.sessionId || !hooks.types)
59
+ throw new agent_protocol_1.AgentError('invalid_request', 'No matching project admission.');
60
+ const files = data.files;
61
+ if (!files || typeof files !== 'object' || Array.isArray(files) || Object.keys(files).length > 16 || !files['scripting.d.ts'] || !files['global.d.ts'] || Object.entries(files).some(([name, content]) => !(/^[a-zA-Z0-9_-]+\.d\.ts$/.test(name)) || typeof content !== 'string') || Buffer.byteLength(JSON.stringify(files)) > 8 * 1024 * 1024)
62
+ throw new agent_protocol_1.AgentError('invalid_request', 'Invalid declaration bundle.');
63
+ await hooks.types(files);
64
+ if (typeof ack === 'function')
65
+ ack({ success: true });
66
+ }
67
+ catch (e) {
68
+ if (typeof ack === 'function')
69
+ ack({ error: (0, agent_protocol_1.failure)(e) });
70
+ }
71
+ });
72
+ socket.on('agentEvent', (event) => {
73
+ const job = this.jobs.get(event?.runId), pending = peer.pending.get(event?.requestId);
74
+ if (!job || !pending || terminal(job.status) || job.requestId !== event.requestId || job.sessionId !== event.sessionId || job.sessionId !== peer.metadata?.sessionId || pending.request.runId !== job.runId)
75
+ return;
76
+ if (event.type === 'stage' && ['syncing', 'compiling', 'running', 'waiting_ready', 'capturing', 'rendering', 'selecting_project'].includes(event.stage)) {
77
+ if (!job.cancellationRequested)
78
+ job.status = event.stage;
79
+ this.event(job, 'stage', { stage: event.stage, caseId: typeof event.caseId === 'string' ? event.caseId.slice(0, 64) : undefined });
80
+ }
81
+ else if (event.type === 'log' && typeof event.message === 'string') {
82
+ this.event(job, 'log', { message: event.message.slice(0, 8192), isError: event.isError === true, caseId: typeof event.caseId === 'string' ? event.caseId.slice(0, 64) : undefined });
83
+ }
84
+ else if (event.type === 'diagnostic' && event.diagnostic && typeof event.diagnostic === 'object' && Buffer.byteLength(JSON.stringify(event.diagnostic)) <= 8192) {
85
+ this.event(job, 'diagnostic', { diagnostic: event.diagnostic });
86
+ }
87
+ });
88
+ // Protocol-v1 Apps still publish the original stage event.
89
+ socket.on('agentJobState', (event) => {
90
+ const job = this.jobs.get(event?.runId);
91
+ if (job && peer.pending.has(job.requestId) && job.sessionId === event.sessionId && job.sessionId === peer.metadata?.sessionId && !terminal(job.status) && !job.cancellationRequested && ['syncing', 'running', 'capturing'].includes(event.status))
92
+ job.status = event.status;
93
+ });
94
+ socket.on('disconnect', () => { this.invalidate(peer); this.peers.delete(socket.id); });
95
+ }
96
+ invalidate(peer) {
97
+ for (const pending of peer.pending.values())
98
+ pending.reject(new agent_protocol_1.AgentError('disconnected', 'Device session ended.'));
99
+ for (const job of this.jobs.values())
100
+ if (!terminal(job.status) && job.sessionId === peer.metadata?.sessionId) {
101
+ job.status = 'failed';
102
+ job.error = { code: 'disconnected', message: 'Device disconnected. The command was not replayed.' };
103
+ job.cancel?.();
104
+ }
105
+ }
106
+ select(device) {
107
+ const peers = [...this.peers.values()].filter(p => p.socket.connected && p.metadata);
108
+ const found = device ? peers.filter(p => p.metadata.deviceId === device) : peers;
109
+ if (!found.length)
110
+ throw new agent_protocol_1.AgentError('device_unavailable', 'No compatible device is connected.');
111
+ if (found.length !== 1)
112
+ throw new agent_protocol_1.AgentError('device_ambiguous', 'Select a device using --device.');
113
+ return found[0];
114
+ }
115
+ call(peer, request, deadline) {
116
+ return new Promise((resolve, reject) => {
117
+ const finish = (value, error) => {
118
+ clearTimeout(timer);
119
+ peer.pending.delete(request.requestId);
120
+ error ? reject(error) : resolve(value);
121
+ };
122
+ const timer = setTimeout(() => finish(undefined, new agent_protocol_1.AgentError('device_timeout', 'Device did not return a result before the deadline.')), Math.max(1, deadline - Date.now()));
123
+ peer.pending.set(request.requestId, { request, resolve: value => finish(value), reject: error => finish(undefined, error) });
124
+ peer.socket.emit('agentRequest', request);
125
+ });
126
+ }
127
+ async devices() {
128
+ return Promise.all([...this.peers.values()].filter(p => p.socket.connected && p.metadata).map(async (p) => {
129
+ try {
130
+ const id = crypto_1.default.randomUUID();
131
+ const reply = await this.call(p, { protocolVersion: 1, method: 'status', requestId: id, runId: id, sessionId: p.metadata.sessionId }, Date.now() + 3000);
132
+ return { ...p.metadata, ...this.statusFields(reply.result), responsive: reply.status === 'completed' };
133
+ }
134
+ catch {
135
+ return { ...p.metadata, responsive: false };
136
+ }
137
+ }));
138
+ }
139
+ submit(raw) {
140
+ this.prune();
141
+ const command = (0, agent_protocol_1.validateCommand)(raw);
142
+ const peer = this.select(command.device);
143
+ const mutation = mutations.includes(command.method);
144
+ const projectChange = projectChanges.includes(command.method);
145
+ const requestId = command.requestId || crypto_1.default.randomUUID();
146
+ if (!peer.metadata.capabilities.includes(command.method))
147
+ throw new agent_protocol_1.AgentError('unsupported_capability', 'This App does not support the command.');
148
+ if (command.options?.readyLog && !peer.metadata.capabilities.includes('ready-log') || command.options?.events && !peer.metadata.capabilities.includes('events-v1'))
149
+ throw new agent_protocol_1.AgentError('unsupported_capability', 'This App does not support ready-log or live events.');
150
+ if (mutation && !projectChange && (!peer.hooks.project() || peer.metadata.project !== peer.hooks.project()))
151
+ throw new agent_protocol_1.AgentError('debug_session_required', 'Open the current project in the App debug page first.');
152
+ const project = command.project ?? peer.hooks.project() ?? undefined;
153
+ if (mutation && !projectChange && project !== peer.hooks.project())
154
+ throw new agent_protocol_1.AgentError('project_mismatch', 'Commands can only run the currently selected debug project.');
155
+ const fingerprint = (0, agent_protocol_1.hash)(JSON.stringify({ ...command, project, device: peer.metadata.deviceId }));
156
+ const old = [...this.jobs.values()].find(j => j.requestId === requestId && j.sessionId === peer.metadata.sessionId);
157
+ if (old) {
158
+ if (old.fingerprint !== fingerprint)
159
+ throw new agent_protocol_1.AgentError('request_id_reused', 'A request ID cannot be reused for a different command.');
160
+ return this.publicJob(old);
161
+ }
162
+ if (mutation && this.activeMutations.has(peer.metadata.deviceId))
163
+ throw new agent_protocol_1.AgentError('busy', 'Another device run is active.');
164
+ if (this.jobs.size >= 64) {
165
+ const done = [...this.jobs.values()].find(j => terminal(j.status));
166
+ if (done) {
167
+ this.removeArtifact(done);
168
+ this.jobs.delete(done.runId);
169
+ this.eventLogs.delete(done.runId);
170
+ }
171
+ else
172
+ throw new agent_protocol_1.AgentError('busy', 'Too many outstanding requests.');
173
+ }
174
+ const job = { runId: crypto_1.default.randomUUID(), requestId, deviceId: peer.metadata.deviceId, sessionId: peer.metadata.sessionId, project: mutation ? project : undefined, status: 'accepted', createdAt: Date.now(), fingerprint };
175
+ this.jobs.set(job.runId, job);
176
+ this.event(job, 'stage', { stage: 'accepted' });
177
+ job.cancel = () => peer.socket.emit('agentCancel', { runId: job.runId, sessionId: job.sessionId });
178
+ void this.execute(job, peer, command, mutation);
179
+ return this.publicJob(job);
180
+ }
181
+ async execute(job, peer, command, mutation) {
182
+ const deadline = Date.now() + (command.options?.timeout ?? 30) * 1000;
183
+ let acknowledgedSnapshot;
184
+ if (mutation) {
185
+ this.activeMutations.add(job.deviceId);
186
+ peer.hooks.pause();
187
+ }
188
+ try {
189
+ if (command.method === 'projects.create')
190
+ this.scaffold(job.project);
191
+ const snapshot = mutation && !command.options?.noSync ? await (0, agent_protocol_1.snapshotProject)(this.workspace, job.project, peer.hooks.ignore()) : undefined;
192
+ if (terminal(job.status))
193
+ return;
194
+ // Cancellation during local snapshot capture precedes native admission.
195
+ // Do not send a later request after its cancellation event was ignored.
196
+ if (job.cancellationRequested) {
197
+ job.status = 'cancelled';
198
+ job.error = { code: 'cancelled', message: 'Cancelled before device admission.' };
199
+ return;
200
+ }
201
+ if (Date.now() >= deadline)
202
+ throw new agent_protocol_1.AgentError('execution_timeout', 'The command deadline expired while preparing source.');
203
+ if (peer.metadata?.sessionId !== job.sessionId || !peer.socket.connected)
204
+ throw new agent_protocol_1.AgentError('disconnected', 'The session changed before execution.');
205
+ if (mutation && !projectChanges.includes(command.method) && peer.hooks.project() !== job.project)
206
+ throw new agent_protocol_1.AgentError('project_mismatch', 'The debug project changed.');
207
+ const request = { ...command, protocolVersion: 1, requestId: job.requestId, runId: job.runId, sessionId: job.sessionId, project: command.project ?? job.project, ignore: peer.hooks.ignore(), deadline, budgetMs: Math.max(1, deadline - Date.now()), snapshot };
208
+ job.requestedRevision = snapshot?.revision;
209
+ job.status = mutation ? 'syncing' : 'running';
210
+ const reply = await this.call(peer, request, deadline + 3000);
211
+ if (snapshot && reply.revision === snapshot.revision)
212
+ acknowledgedSnapshot = snapshot;
213
+ if (terminal(job.status))
214
+ return;
215
+ if (!terminal(reply.status))
216
+ throw new agent_protocol_1.AgentError('invalid_response', 'Device did not return a terminal result.');
217
+ if (mutation && reply.status === 'completed' && (!reply.revision || (snapshot && reply.revision !== snapshot.revision)))
218
+ throw new agent_protocol_1.AgentError('invalid_response', 'Source revision did not match the applied snapshot.');
219
+ if (reply.status === 'completed' && projectChanges.includes(command.method)) {
220
+ if (!peer.hooks.switchProject)
221
+ throw new agent_protocol_1.AgentError('unsupported_capability', 'Server cannot change projects.');
222
+ await peer.hooks.switchProject(job.project);
223
+ }
224
+ job.result = this.storeArtifact(reply.result, job.runId);
225
+ job.status = reply.status;
226
+ job.revision = reply.revision ?? job.revision;
227
+ job.error = reply.error;
228
+ }
229
+ catch (e) {
230
+ if (!terminal(job.status)) {
231
+ job.status = 'failed';
232
+ job.error = (0, agent_protocol_1.failure)(e);
233
+ job.cancel?.();
234
+ }
235
+ }
236
+ finally {
237
+ if (mutation) {
238
+ peer.hooks.resume(acknowledgedSnapshot);
239
+ this.activeMutations.delete(job.deviceId);
240
+ }
241
+ job.cancel = undefined;
242
+ this.event(job, 'stage', { stage: job.status });
243
+ }
244
+ }
245
+ get(id) { this.prune(); const job = this.jobs.get(id); if (!job)
246
+ throw new agent_protocol_1.AgentError('job_not_found', 'Unknown or expired run ID.'); return this.publicJob(job); }
247
+ cancel(id) { const job = this.jobs.get(id); if (!job)
248
+ throw new agent_protocol_1.AgentError('job_not_found', 'Unknown run ID.'); if (!terminal(job.status)) {
249
+ job.cancellationRequested = true;
250
+ job.status = 'cancelling';
251
+ this.event(job, 'stage', { stage: 'cancelling' });
252
+ job.cancel?.();
253
+ } return this.publicJob(job); }
254
+ publicJob(job) { const { cancel, fingerprint, ...copy } = job; return copy; }
255
+ removeArtifact(job) {
256
+ for (const artifact of job.result?.artifacts ?? []) {
257
+ if (this.artifactDirectory && path_1.default.dirname(artifact.path) === this.artifactDirectory) {
258
+ try {
259
+ fs_1.default.unlinkSync(artifact.path);
260
+ }
261
+ catch { }
262
+ }
263
+ }
264
+ if (job.result?.artifacts) {
265
+ job.result.artifacts = [];
266
+ job.result.artifactsExpired = true;
267
+ }
268
+ }
269
+ statusFields(value) {
270
+ if (!value || typeof value !== 'object')
271
+ return {};
272
+ return {
273
+ project: typeof value.project === 'string' ? value.project.slice(0, 255) : null,
274
+ appState: ['foreground', 'background', 'inactive'].includes(value.appState) ? value.appState : 'unknown',
275
+ busy: value.busy === true, revision: typeof value.revision === 'string' && /^[a-f0-9]{64}$/.test(value.revision) ? value.revision : null,
276
+ activeRunId: typeof value.activeRunId === 'string' ? value.activeRunId.slice(0, 128) : null,
277
+ backgroundKeeper: { status: typeof value.backgroundKeeper?.status === 'string' ? value.backgroundKeeper.status.slice(0, 32) : 'unknown', requested: value.backgroundKeeper?.requested === true, isActive: value.backgroundKeeper?.isActive === true, lastFailure: typeof value.backgroundKeeper?.lastFailure === 'string' ? value.backgroundKeeper.lastFailure.slice(0, 128) : null }
278
+ };
279
+ }
280
+ storeArtifact(result, runId) {
281
+ if (result?.artifacts !== undefined || result?.artifactsExpired !== undefined)
282
+ throw new agent_protocol_1.AgentError('invalid_artifact', 'Device cannot supply host filesystem artifact paths.');
283
+ const { image: _boundedImage, images: _boundedImages, ...textResult } = result ?? {};
284
+ if (Buffer.byteLength(JSON.stringify(textResult)) > 1024 * 1024)
285
+ throw new agent_protocol_1.AgentError('invalid_response', 'Text result exceeds 1 MiB.');
286
+ const images = result?.images ?? (result?.image ? [{ ...result.image, id: 'screenshot' }] : []);
287
+ if (!Array.isArray(images) || images.length > 8)
288
+ throw new agent_protocol_1.AgentError('invalid_artifact', 'Invalid image batch.');
289
+ const ids = new Set();
290
+ let totalBytes = 0;
291
+ const decoded = images.map((image) => {
292
+ if (!image || typeof image.id !== 'string' || !/^[a-zA-Z0-9_-]{1,64}$/.test(image.id) || ids.has(image.id))
293
+ throw new agent_protocol_1.AgentError('invalid_artifact', 'Invalid image case identity.');
294
+ ids.add(image.id);
295
+ if (typeof image.data !== 'string' || image.data.length > Math.ceil(agent_protocol_1.MAX_IMAGE_BYTES / 3) * 4 + 4)
296
+ throw new agent_protocol_1.AgentError('invalid_artifact', 'Screenshot payload is too large.');
297
+ const bytes = Buffer.from(image.data, 'base64');
298
+ totalBytes += bytes.length;
299
+ if (bytes.length < 24 || totalBytes > agent_protocol_1.MAX_IMAGE_BYTES || bytes.subarray(0, 8).toString('hex') !== '89504e470d0a1a0a' || (0, agent_protocol_1.hash)(bytes) !== image.sha256 || bytes.readUInt32BE(16) < 1 || bytes.readUInt32BE(20) < 1 || bytes.readUInt32BE(16) > 8192 || bytes.readUInt32BE(20) > 8192 || bytes.readUInt32BE(16) * bytes.readUInt32BE(20) > 16777216)
300
+ throw new agent_protocol_1.AgentError('invalid_artifact', 'Screenshot is not a bounded valid PNG.');
301
+ return { image, bytes };
302
+ });
303
+ if (!decoded.length)
304
+ return textResult;
305
+ const retained = [...this.jobs.values()].filter(j => j.result?.artifacts?.length);
306
+ while (retained.length >= 8)
307
+ this.removeArtifact(retained.shift());
308
+ this.artifactDirectory ??= fs_1.default.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), 'scripting-cli-artifacts-'));
309
+ const artifacts = decoded.map(({ image, bytes }) => {
310
+ const file = path_1.default.join(this.artifactDirectory, runId + '-' + image.id + '.png');
311
+ fs_1.default.writeFileSync(file, bytes, { mode: 0o600, flag: 'wx' });
312
+ return { id: image.id, path: file, mimeType: 'image/png', sha256: image.sha256, width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) };
313
+ });
314
+ const { image: _image, images: _images, ...rest } = result;
315
+ return { ...rest, artifacts };
316
+ }
317
+ event(job, type, data) {
318
+ let log = this.eventLogs.get(job.runId);
319
+ if (!log) {
320
+ log = { sequence: 0, events: [], logBytes: 0, droppedLogs: false };
321
+ this.eventLogs.set(job.runId, log);
322
+ }
323
+ if (type === 'log') {
324
+ const count = Buffer.byteLength(String(data.message));
325
+ if (log.logBytes + count > 65536) {
326
+ log.droppedLogs = true;
327
+ return;
328
+ }
329
+ log.logBytes += count;
330
+ }
331
+ log.events.push({ seq: ++log.sequence, type, runId: job.runId, requestId: job.requestId, deviceId: job.deviceId, sessionId: job.sessionId, ...data });
332
+ if (log.events.length > 256)
333
+ log.events.shift();
334
+ }
335
+ events(id, after) {
336
+ const job = this.get(id), log = this.eventLogs.get(id);
337
+ if (!Number.isSafeInteger(after) || after < 0)
338
+ throw new agent_protocol_1.AgentError('invalid_cursor', 'Invalid event cursor.');
339
+ const events = log?.events.filter(e => e.seq > after) ?? [];
340
+ return { events, nextCursor: log?.sequence ?? 0, truncated: !!log?.events.length && after < log.events[0].seq - 1, terminal: terminal(job.status), logsTruncated: log?.droppedLogs === true };
341
+ }
342
+ scaffold(project) {
343
+ const root = path_1.default.join(this.workspace, 'scripts', project);
344
+ if (fs_1.default.existsSync(root))
345
+ return;
346
+ fs_1.default.mkdirSync(root, { recursive: false });
347
+ fs_1.default.writeFileSync(path_1.default.join(root, 'script.json'), JSON.stringify({ name: project, version: '1.0.0', icon: 'curlybraces', color: 'systemBlue' }, null, 2), { flag: 'wx' });
348
+ fs_1.default.writeFileSync(path_1.default.join(root, 'index.tsx'), 'import { Script } from "scripting"\nScript.exit({ message: "Hello Scripting" })\n', { flag: 'wx' });
349
+ }
350
+ prune(now = Date.now()) {
351
+ for (const job of this.jobs.values())
352
+ if (terminal(job.status) && now - job.createdAt > 15 * 60 * 1000) {
353
+ this.removeArtifact(job);
354
+ this.jobs.delete(job.runId);
355
+ this.eventLogs.delete(job.runId);
356
+ }
357
+ }
358
+ close() {
359
+ for (const peer of this.peers.values())
360
+ this.invalidate(peer);
361
+ if (this.artifactDirectory) {
362
+ fs_1.default.rmSync(this.artifactDirectory, { recursive: true, force: true });
363
+ this.artifactDirectory = undefined;
364
+ }
365
+ }
366
+ }
367
+ exports.AgentBroker = AgentBroker;
368
+ exports.agentBroker = new AgentBroker(process.cwd());
@@ -0,0 +1,4 @@
1
+ import { Argv } from 'yargs';
2
+ import { AgentCommand } from './agent_protocol';
3
+ export declare function invokeAgentCommand(command: AgentCommand, output: string, json: boolean, stream?: boolean): Promise<void>;
4
+ export declare function installAgentCommands(y: Argv): Argv;