scripting-cli 1.5.0 → 2.0.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.
@@ -0,0 +1,387 @@
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 dev_terms_1 = require("./dev_terms");
9
+ const skill_sync_1 = require("./skill_sync");
10
+ const fs_1 = __importDefault(require("fs"));
11
+ const path_1 = __importDefault(require("path"));
12
+ const os_1 = __importDefault(require("os"));
13
+ const agent_protocol_1 = require("./agent_protocol");
14
+ const mutations = ['run', 'widget', 'widget.batch', 'scripts.create', 'scripts.attach', 'skills.run'];
15
+ const scriptChanges = ['scripts.create', 'scripts.attach'];
16
+ const terminal = (s) => ['completed', 'failed', 'cancelled'].includes(s);
17
+ class AgentBroker {
18
+ workspace;
19
+ eventLogs = new Map();
20
+ peers = new Map();
21
+ jobs = new Map();
22
+ activeMutations = new Set();
23
+ artifactDirectory;
24
+ constructor(workspace) {
25
+ this.workspace = workspace;
26
+ }
27
+ register(socket, hooks) {
28
+ if (this.peers.size >= 64)
29
+ return;
30
+ const peer = { socket, hooks, pending: new Map() };
31
+ this.peers.set(socket.id, peer);
32
+ socket.on('agentHello', (meta) => {
33
+ 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))
34
+ return;
35
+ // Duplicate installation IDs remain ambiguous. A second socket must not
36
+ // take over a connected device merely by claiming its identifier.
37
+ if (meta.capabilities.length > 32 || !meta.capabilities.every((value) => typeof value === 'string' && value.length < 64))
38
+ return;
39
+ if (peer.metadata && peer.metadata.sessionId !== meta.sessionId)
40
+ this.invalidate(peer);
41
+ peer.metadata = { protocolVersion: 1, deviceId: meta.deviceId, sessionId: meta.sessionId,
42
+ name: typeof meta.name === 'string' ? meta.name.slice(0, 128) : 'Scripting device',
43
+ appVersion: typeof meta.appVersion === 'string' ? meta.appVersion.slice(0, 64) : '',
44
+ capabilities: (0, dev_terms_1.scriptCapabilities)(meta.capabilities), ...this.statusFields(meta) };
45
+ });
46
+ socket.on('agentResult', (reply) => {
47
+ const pending = peer.pending.get(reply?.requestId);
48
+ if (!pending)
49
+ return;
50
+ const request = pending.request;
51
+ if (reply.protocolVersion !== 1 || reply.sessionId !== request.sessionId || reply.runId !== request.runId || peer.metadata?.sessionId !== request.sessionId) {
52
+ pending.reject(new agent_protocol_1.AgentError('invalid_response', 'Device returned mismatched result identity.'));
53
+ }
54
+ else
55
+ pending.resolve(reply);
56
+ });
57
+ socket.on('agentTypes', async (data, ack) => {
58
+ try {
59
+ const pending = peer.pending.get(data?.requestId);
60
+ if (!pending || !scriptChanges.includes((0, dev_terms_1.scriptMethod)(pending.request.method)) || pending.request.runId !== data.runId || pending.request.sessionId !== data.sessionId || peer.metadata?.sessionId !== data.sessionId || !hooks.types)
61
+ throw new agent_protocol_1.AgentError('invalid_request', 'No matching script admission.');
62
+ const files = data.files;
63
+ 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)
64
+ throw new agent_protocol_1.AgentError('invalid_request', 'Invalid declaration bundle.');
65
+ await hooks.types(files);
66
+ if (typeof ack === 'function')
67
+ ack({ success: true });
68
+ }
69
+ catch (e) {
70
+ if (typeof ack === 'function')
71
+ ack({ error: (0, agent_protocol_1.failure)(e) });
72
+ }
73
+ });
74
+ socket.on('agentEvent', (event) => {
75
+ const job = this.jobs.get(event?.runId), pending = peer.pending.get(event?.requestId);
76
+ if (!job || !pending || terminal(job.status) || job.requestId !== event.requestId || job.sessionId !== event.sessionId || job.sessionId !== peer.metadata?.sessionId || pending.request.runId !== job.runId)
77
+ return;
78
+ if (event.type === 'stage' && ['syncing', 'compiling', 'running', 'waiting_ready', 'capturing', 'rendering', 'selecting_project', 'selecting_script'].includes(event.stage)) {
79
+ if (!job.cancellationRequested)
80
+ job.status = event.stage === 'selecting_project' ? 'selecting_script' : event.stage;
81
+ this.event(job, 'stage', { stage: event.stage === 'selecting_project' ? 'selecting_script' : event.stage, caseId: typeof event.caseId === 'string' ? event.caseId.slice(0, 64) : undefined });
82
+ }
83
+ else if (event.type === 'log' && typeof event.message === 'string') {
84
+ 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 });
85
+ }
86
+ else if (event.type === 'diagnostic' && event.diagnostic && typeof event.diagnostic === 'object' && Buffer.byteLength(JSON.stringify(event.diagnostic)) <= 8192) {
87
+ this.event(job, 'diagnostic', { diagnostic: event.diagnostic });
88
+ }
89
+ });
90
+ // Protocol-v1 Apps still publish the original stage event.
91
+ socket.on('agentJobState', (event) => {
92
+ const job = this.jobs.get(event?.runId);
93
+ 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))
94
+ job.status = event.status;
95
+ });
96
+ socket.on('disconnect', () => { this.invalidate(peer); this.peers.delete(socket.id); });
97
+ }
98
+ invalidate(peer) {
99
+ for (const pending of peer.pending.values())
100
+ pending.reject(new agent_protocol_1.AgentError('disconnected', 'Device session ended.'));
101
+ for (const job of this.jobs.values())
102
+ if (!terminal(job.status) && job.sessionId === peer.metadata?.sessionId) {
103
+ job.status = 'failed';
104
+ job.error = { code: 'disconnected', message: 'Device disconnected. The command was not replayed.' };
105
+ job.cancel?.();
106
+ }
107
+ }
108
+ selectedScript(peer) { return peer.hooks.script ? peer.hooks.script() : peer.hooks.project?.() ?? null; }
109
+ select(device) {
110
+ const peers = [...this.peers.values()].filter(p => p.socket.connected && p.metadata);
111
+ const found = device ? peers.filter(p => p.metadata.deviceId === device) : peers;
112
+ if (!found.length)
113
+ throw new agent_protocol_1.AgentError('device_unavailable', 'No compatible device is connected.');
114
+ if (found.length !== 1)
115
+ throw new agent_protocol_1.AgentError('device_ambiguous', 'Select a device using --device.');
116
+ return found[0];
117
+ }
118
+ call(peer, request, deadline) {
119
+ return new Promise((resolve, reject) => {
120
+ const finish = (value, error) => {
121
+ clearTimeout(timer);
122
+ peer.pending.delete(request.requestId);
123
+ error ? reject(error) : resolve(value);
124
+ };
125
+ 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()));
126
+ peer.pending.set(request.requestId, { request, resolve: value => finish(value), reject: error => finish(undefined, error) });
127
+ peer.socket.emit('agentRequest', request);
128
+ });
129
+ }
130
+ async devices() {
131
+ return Promise.all([...this.peers.values()].filter(p => p.socket.connected && p.metadata).map(async (p) => {
132
+ try {
133
+ const id = crypto_1.default.randomUUID();
134
+ const reply = await this.call(p, { protocolVersion: 1, method: 'status', requestId: id, runId: id, sessionId: p.metadata.sessionId }, Date.now() + 3000);
135
+ return { ...p.metadata, ...this.statusFields(reply.result), responsive: reply.status === 'completed' };
136
+ }
137
+ catch {
138
+ return { ...p.metadata, responsive: false };
139
+ }
140
+ }));
141
+ }
142
+ submit(raw) {
143
+ this.prune();
144
+ const command = (0, agent_protocol_1.validateCommand)(raw);
145
+ const peer = this.select(command.device);
146
+ const mutation = mutations.includes(command.method);
147
+ const skillRun = command.method === 'skills.run';
148
+ const skill = peer.hooks.skill?.();
149
+ const scriptChange = scriptChanges.includes(command.method);
150
+ const requestId = command.requestId || crypto_1.default.randomUUID();
151
+ if (!peer.metadata.capabilities.includes(command.method))
152
+ throw new agent_protocol_1.AgentError('unsupported_capability', 'This App does not support the command.');
153
+ if (skillRun && (!skill || skill.name !== command.skill || peer.metadata.skill !== skill.name || peer.metadata.skillBindingId !== skill.bindingId))
154
+ throw new agent_protocol_1.AgentError('skill_mismatch', 'Select this skill in the App development page first.');
155
+ if (command.options?.readyLog && !peer.metadata.capabilities.includes('ready-log') || command.options?.events && !peer.metadata.capabilities.includes('events-v1'))
156
+ throw new agent_protocol_1.AgentError('unsupported_capability', 'This App does not support ready-log or live events.');
157
+ if (mutation && !scriptChange && !skillRun && (!this.selectedScript(peer) || peer.metadata.script !== this.selectedScript(peer)))
158
+ throw new agent_protocol_1.AgentError('debug_session_required', 'Open the current script in the App debug page first.');
159
+ const script = command.script ?? this.selectedScript(peer) ?? undefined;
160
+ if (mutation && !scriptChange && !skillRun && script !== this.selectedScript(peer))
161
+ throw new agent_protocol_1.AgentError('script_mismatch', 'Commands can only run the currently selected debug script.');
162
+ const fingerprint = (0, agent_protocol_1.hash)(JSON.stringify({ ...command, script, device: peer.metadata.deviceId, ...(skillRun ? { bindingId: skill?.bindingId } : {}) }));
163
+ const old = [...this.jobs.values()].find(j => j.requestId === requestId && j.sessionId === peer.metadata.sessionId);
164
+ if (old) {
165
+ if (old.fingerprint !== fingerprint)
166
+ throw new agent_protocol_1.AgentError('request_id_reused', 'A request ID cannot be reused for a different command.');
167
+ return this.publicJob(old);
168
+ }
169
+ if (mutation && this.activeMutations.has(peer.metadata.deviceId))
170
+ throw new agent_protocol_1.AgentError('busy', 'Another device run is active.');
171
+ if (this.jobs.size >= 64) {
172
+ const done = [...this.jobs.values()].find(j => terminal(j.status));
173
+ if (done) {
174
+ this.removeArtifact(done);
175
+ this.jobs.delete(done.runId);
176
+ this.eventLogs.delete(done.runId);
177
+ }
178
+ else
179
+ throw new agent_protocol_1.AgentError('busy', 'Too many outstanding requests.');
180
+ }
181
+ const job = { runId: crypto_1.default.randomUUID(), requestId, deviceId: peer.metadata.deviceId, sessionId: peer.metadata.sessionId, script: mutation && !skillRun ? script : undefined, skill: skillRun ? command.skill : undefined, entry: skillRun ? command.entry : undefined, status: 'accepted', createdAt: Date.now(), fingerprint };
182
+ this.jobs.set(job.runId, job);
183
+ this.event(job, 'stage', { stage: 'accepted' });
184
+ job.cancel = () => peer.socket.emit('agentCancel', { runId: job.runId, sessionId: job.sessionId });
185
+ void this.execute(job, peer, command, mutation);
186
+ return this.publicJob(job);
187
+ }
188
+ async execute(job, peer, command, mutation) {
189
+ const deadline = Date.now() + (command.options?.timeout ?? 30) * 1000;
190
+ let acknowledgedSnapshot;
191
+ const skillRun = command.method === 'skills.run';
192
+ let skillBinding = null;
193
+ if (mutation) {
194
+ this.activeMutations.add(job.deviceId);
195
+ peer.hooks.pause();
196
+ }
197
+ try {
198
+ if (skillRun) {
199
+ await peer.hooks.skillReady?.();
200
+ skillBinding = peer.hooks.skill?.() ?? null;
201
+ if (!skillBinding || skillBinding.name !== command.skill)
202
+ throw new agent_protocol_1.AgentError('skill_mismatch', 'The skill binding changed.');
203
+ }
204
+ if (command.method === 'scripts.create')
205
+ this.scaffold(job.script);
206
+ const snapshot = skillRun ? await (0, skill_sync_1.snapshotSkill)(this.workspace, command.skill, peer.hooks.ignore()) : mutation && !command.options?.noSync ? await (0, agent_protocol_1.snapshotScript)(this.workspace, job.script, peer.hooks.ignore()) : undefined;
207
+ if (terminal(job.status))
208
+ return;
209
+ // Cancellation during local snapshot capture precedes native admission.
210
+ // Do not send a later request after its cancellation event was ignored.
211
+ if (job.cancellationRequested) {
212
+ job.status = 'cancelled';
213
+ job.error = { code: 'cancelled', message: 'Cancelled before device admission.' };
214
+ return;
215
+ }
216
+ if (Date.now() >= deadline)
217
+ throw new agent_protocol_1.AgentError('execution_timeout', 'The command deadline expired while preparing source.');
218
+ if (peer.metadata?.sessionId !== job.sessionId || !peer.socket.connected)
219
+ throw new agent_protocol_1.AgentError('disconnected', 'The session changed before execution.');
220
+ if (mutation && !skillRun && !scriptChanges.includes(command.method) && this.selectedScript(peer) !== job.script)
221
+ throw new agent_protocol_1.AgentError('script_mismatch', 'The debug script changed.');
222
+ const request = { ...command, protocolVersion: 1, requestId: job.requestId, runId: job.runId, sessionId: job.sessionId, method: (0, dev_terms_1.wireMethod)(command.method), project: command.script ?? job.script, ignore: peer.hooks.ignore(), deadline, budgetMs: Math.max(1, deadline - Date.now()), snapshot, ...(skillRun ? { bindingId: skillBinding.bindingId, baseRevision: skillBinding.revision } : {}) };
223
+ job.requestedRevision = snapshot?.revision;
224
+ job.status = mutation ? 'syncing' : 'running';
225
+ const reply = await this.call(peer, request, deadline + 3000);
226
+ if (snapshot && reply.revision === snapshot.revision)
227
+ acknowledgedSnapshot = snapshot;
228
+ if (terminal(job.status))
229
+ return;
230
+ if (!terminal(reply.status))
231
+ throw new agent_protocol_1.AgentError('invalid_response', 'Device did not return a terminal result.');
232
+ if (mutation && reply.status === 'completed' && (!reply.revision || (snapshot && reply.revision !== snapshot.revision)))
233
+ throw new agent_protocol_1.AgentError('invalid_response', 'Source revision did not match the applied snapshot.');
234
+ if (reply.status === 'completed' && scriptChanges.includes(command.method)) {
235
+ const selectScript = peer.hooks.switchScript ?? peer.hooks.switchProject;
236
+ if (!selectScript)
237
+ throw new agent_protocol_1.AgentError('unsupported_capability', 'Server cannot change scripts.');
238
+ await selectScript.call(peer.hooks, job.script);
239
+ }
240
+ job.result = (0, dev_terms_1.scriptResult)(this.storeArtifact(reply.result, job.runId));
241
+ job.status = reply.status;
242
+ job.revision = reply.revision ?? job.revision;
243
+ job.error = (0, dev_terms_1.scriptError)(reply.error);
244
+ }
245
+ catch (e) {
246
+ if (!terminal(job.status)) {
247
+ job.status = 'failed';
248
+ job.error = (0, agent_protocol_1.failure)(e);
249
+ job.cancel?.();
250
+ }
251
+ }
252
+ finally {
253
+ if (mutation) {
254
+ peer.hooks.resume(acknowledgedSnapshot, skillRun ? skillBinding?.bindingId : undefined);
255
+ this.activeMutations.delete(job.deviceId);
256
+ }
257
+ job.cancel = undefined;
258
+ this.event(job, 'stage', { stage: job.status });
259
+ }
260
+ }
261
+ get(id) { this.prune(); const job = this.jobs.get(id); if (!job)
262
+ throw new agent_protocol_1.AgentError('job_not_found', 'Unknown or expired run ID.'); return this.publicJob(job); }
263
+ cancel(id) { const job = this.jobs.get(id); if (!job)
264
+ throw new agent_protocol_1.AgentError('job_not_found', 'Unknown run ID.'); if (!terminal(job.status)) {
265
+ job.cancellationRequested = true;
266
+ job.status = 'cancelling';
267
+ this.event(job, 'stage', { stage: 'cancelling' });
268
+ job.cancel?.();
269
+ } return this.publicJob(job); }
270
+ publicJob(job) { const { cancel, fingerprint, ...copy } = job; return copy; }
271
+ removeArtifact(job) {
272
+ for (const artifact of job.result?.artifacts ?? []) {
273
+ if (this.artifactDirectory && path_1.default.dirname(artifact.path) === this.artifactDirectory) {
274
+ try {
275
+ fs_1.default.unlinkSync(artifact.path);
276
+ }
277
+ catch { }
278
+ }
279
+ }
280
+ if (job.result?.artifacts) {
281
+ job.result.artifacts = [];
282
+ job.result.artifactsExpired = true;
283
+ }
284
+ }
285
+ statusFields(value) {
286
+ if (!value || typeof value !== 'object')
287
+ return {};
288
+ return {
289
+ skill: typeof value.skill === 'string' ? value.skill.slice(0, 255) : null,
290
+ skillBindingId: typeof value.skillBindingId === 'string' ? value.skillBindingId.slice(0, 128) : null,
291
+ skillRevision: typeof value.skillRevision === 'string' ? value.skillRevision : null,
292
+ script: typeof (value.script ?? value.project) === 'string' ? (value.script ?? value.project).slice(0, 255) : null,
293
+ appState: ['foreground', 'background', 'inactive'].includes(value.appState) ? value.appState : 'unknown',
294
+ busy: value.busy === true, revision: typeof value.revision === 'string' && /^[a-f0-9]{64}$/.test(value.revision) ? value.revision : null,
295
+ activeRunId: typeof value.activeRunId === 'string' ? value.activeRunId.slice(0, 128) : null,
296
+ 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 }
297
+ };
298
+ }
299
+ storeArtifact(result, runId) {
300
+ if (result?.artifacts !== undefined || result?.artifactsExpired !== undefined)
301
+ throw new agent_protocol_1.AgentError('invalid_artifact', 'Device cannot supply host filesystem artifact paths.');
302
+ const { image: _boundedImage, images: _boundedImages, ...textResult } = result ?? {};
303
+ if (Buffer.byteLength(JSON.stringify(textResult)) > 1024 * 1024)
304
+ throw new agent_protocol_1.AgentError('invalid_response', 'Text result exceeds 1 MiB.');
305
+ const images = result?.images ?? (result?.image ? [{ ...result.image, id: 'screenshot' }] : []);
306
+ if (!Array.isArray(images) || images.length > 8)
307
+ throw new agent_protocol_1.AgentError('invalid_artifact', 'Invalid image batch.');
308
+ const ids = new Set();
309
+ let totalBytes = 0;
310
+ const decoded = images.map((image) => {
311
+ if (!image || typeof image.id !== 'string' || !/^[a-zA-Z0-9_-]{1,64}$/.test(image.id) || ids.has(image.id))
312
+ throw new agent_protocol_1.AgentError('invalid_artifact', 'Invalid image case identity.');
313
+ ids.add(image.id);
314
+ if (typeof image.data !== 'string' || image.data.length > Math.ceil(agent_protocol_1.MAX_IMAGE_BYTES / 3) * 4 + 4)
315
+ throw new agent_protocol_1.AgentError('invalid_artifact', 'Screenshot payload is too large.');
316
+ const bytes = Buffer.from(image.data, 'base64');
317
+ totalBytes += bytes.length;
318
+ 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)
319
+ throw new agent_protocol_1.AgentError('invalid_artifact', 'Screenshot is not a bounded valid PNG.');
320
+ return { image, bytes };
321
+ });
322
+ if (!decoded.length)
323
+ return textResult;
324
+ const retained = [...this.jobs.values()].filter(j => j.result?.artifacts?.length);
325
+ while (retained.length >= 8)
326
+ this.removeArtifact(retained.shift());
327
+ this.artifactDirectory ??= fs_1.default.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), 'scripting-cli-artifacts-'));
328
+ const artifacts = decoded.map(({ image, bytes }) => {
329
+ const file = path_1.default.join(this.artifactDirectory, runId + '-' + image.id + '.png');
330
+ fs_1.default.writeFileSync(file, bytes, { mode: 0o600, flag: 'wx' });
331
+ return { id: image.id, path: file, mimeType: 'image/png', sha256: image.sha256, width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) };
332
+ });
333
+ const { image: _image, images: _images, ...rest } = result;
334
+ return { ...rest, artifacts };
335
+ }
336
+ event(job, type, data) {
337
+ let log = this.eventLogs.get(job.runId);
338
+ if (!log) {
339
+ log = { sequence: 0, events: [], logBytes: 0, droppedLogs: false };
340
+ this.eventLogs.set(job.runId, log);
341
+ }
342
+ if (type === 'log') {
343
+ const count = Buffer.byteLength(String(data.message));
344
+ if (log.logBytes + count > 65536) {
345
+ log.droppedLogs = true;
346
+ return;
347
+ }
348
+ log.logBytes += count;
349
+ }
350
+ log.events.push({ seq: ++log.sequence, type, runId: job.runId, requestId: job.requestId, deviceId: job.deviceId, sessionId: job.sessionId, ...data });
351
+ if (log.events.length > 256)
352
+ log.events.shift();
353
+ }
354
+ events(id, after) {
355
+ const job = this.get(id), log = this.eventLogs.get(id);
356
+ if (!Number.isSafeInteger(after) || after < 0)
357
+ throw new agent_protocol_1.AgentError('invalid_cursor', 'Invalid event cursor.');
358
+ const events = log?.events.filter(e => e.seq > after) ?? [];
359
+ return { events, nextCursor: log?.sequence ?? 0, truncated: !!log?.events.length && after < log.events[0].seq - 1, terminal: terminal(job.status), logsTruncated: log?.droppedLogs === true };
360
+ }
361
+ scaffold(script) {
362
+ const root = path_1.default.join(this.workspace, 'scripts', script);
363
+ if (fs_1.default.existsSync(root))
364
+ return;
365
+ fs_1.default.mkdirSync(root, { recursive: false });
366
+ fs_1.default.writeFileSync(path_1.default.join(root, 'script.json'), JSON.stringify({ name: script, version: '1.0.0', icon: 'curlybraces', color: 'systemBlue' }, null, 2), { flag: 'wx' });
367
+ fs_1.default.writeFileSync(path_1.default.join(root, 'index.tsx'), 'import { Script } from "scripting"\nScript.exit({ message: "Hello Scripting" })\n', { flag: 'wx' });
368
+ }
369
+ prune(now = Date.now()) {
370
+ for (const job of this.jobs.values())
371
+ if (terminal(job.status) && now - job.createdAt > 15 * 60 * 1000) {
372
+ this.removeArtifact(job);
373
+ this.jobs.delete(job.runId);
374
+ this.eventLogs.delete(job.runId);
375
+ }
376
+ }
377
+ close() {
378
+ for (const peer of this.peers.values())
379
+ this.invalidate(peer);
380
+ if (this.artifactDirectory) {
381
+ fs_1.default.rmSync(this.artifactDirectory, { recursive: true, force: true });
382
+ this.artifactDirectory = undefined;
383
+ }
384
+ }
385
+ }
386
+ exports.AgentBroker = AgentBroker;
387
+ 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;
@@ -0,0 +1,122 @@
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.invokeAgentCommand = invokeAgentCommand;
7
+ exports.installAgentCommands = installAgentCommands;
8
+ const path_1 = __importDefault(require("path"));
9
+ const fs_1 = __importDefault(require("fs"));
10
+ const agent_protocol_1 = require("./agent_protocol");
11
+ const agent_control_1 = require("./agent_control");
12
+ async function invokeAgentCommand(command, output, json, stream = false) {
13
+ const state = (0, agent_control_1.loadControl)(process.cwd());
14
+ const info = await (0, agent_control_1.controlRequest)(state, '/v1/info');
15
+ if (info.result.workspace !== state.workspace)
16
+ throw new agent_protocol_1.AgentError('workspace_mismatch', 'The running server belongs to another workspace.');
17
+ let job = (await (0, agent_control_1.controlRequest)(state, '/v1/requests', command)).result;
18
+ const cancel = () => { void (0, agent_control_1.controlRequest)(state, `/v1/jobs/${job.runId}/cancel`, {}).catch(() => { }); };
19
+ process.once('SIGINT', cancel);
20
+ let cursor = 0, reportedLogLimit = false;
21
+ const emitEvents = async () => {
22
+ if (!stream)
23
+ return;
24
+ const page = (await (0, agent_control_1.controlRequest)(state, `/v1/jobs/${job.runId}/events?after=${cursor}`)).result;
25
+ if (page.logsTruncated && !reportedLogLimit) {
26
+ console.log(JSON.stringify({ type: 'gap', runId: job.runId, reason: 'stream_log_budget' }));
27
+ reportedLogLimit = true;
28
+ }
29
+ if (page.truncated)
30
+ console.log(JSON.stringify({ type: 'gap', runId: job.runId, after: cursor, reason: 'event_retention_limit' }));
31
+ for (const event of page.events)
32
+ console.log(JSON.stringify(event));
33
+ cursor = page.nextCursor;
34
+ };
35
+ try {
36
+ while (!['completed', 'failed', 'cancelled'].includes(job.status)) {
37
+ await emitEvents();
38
+ await new Promise(r => setTimeout(r, 200));
39
+ job = (await (0, agent_control_1.controlRequest)(state, `/v1/jobs/${job.runId}`)).result;
40
+ }
41
+ await emitEvents();
42
+ if (job.result?.artifacts?.length)
43
+ job.result = (0, agent_control_1.materializeArtifacts)(job.result, job.runId, output);
44
+ if (stream)
45
+ console.log(JSON.stringify({ type: 'result', seq: cursor + 1, runId: job.runId, job }));
46
+ else if (json)
47
+ console.log(JSON.stringify(job));
48
+ else
49
+ console.log(JSON.stringify(job, null, 2));
50
+ process.exitCode = job.status === 'completed' ? 0 : job.status === 'cancelled' ? 130 : ['execution_timeout', 'device_timeout'].includes(job.error?.code) ? 124 : 1;
51
+ }
52
+ finally {
53
+ process.removeListener('SIGINT', cancel);
54
+ }
55
+ }
56
+ function common(y, screenshots = true) {
57
+ const options = y.option('device', { type: 'string', describe: 'Target device ID; required when several devices are connected' })
58
+ .option('json', { type: 'boolean', default: false, describe: 'Print one JSON result' });
59
+ return screenshots ? options.option('output', { type: 'string', default: 'artifacts', describe: 'Screenshot output directory' }) : options;
60
+ }
61
+ function streaming(y, screenshots = true) { return common(y, screenshots).option('stream', { type: 'boolean', default: false, describe: 'Print progress/log/diagnostic JSONL events and one final result' }); }
62
+ function runOptions(y, script = true) {
63
+ const options = streaming(y).positional('script', { type: 'string', describe: 'Currently selected App debug script' })
64
+ .option('screenshot', { type: 'boolean', default: false })
65
+ .option('timeout', { type: 'number', default: 30, describe: 'Overall run deadline in seconds, 1...120' })
66
+ .option('no-sync', { type: 'boolean', default: false, describe: 'Use the last acknowledged App revision' });
67
+ return script ? options.option('capture-after', { type: 'number', default: 2, describe: 'Seconds after a script view is available before capture' }).option('ready-log', { type: 'string', describe: 'Wait for this exact console.log line from the current script before capture' }).option('query-parameters', { type: 'string', describe: 'JSON object passed to the script' }) : options;
68
+ }
69
+ const handler = (build) => async (a) => {
70
+ try {
71
+ const command = build(a);
72
+ command.options = { ...command.options, events: a.stream ?? false };
73
+ await invokeAgentCommand(command, path_1.default.resolve(a.output ?? 'artifacts'), a.json ?? false, a.stream ?? false);
74
+ }
75
+ catch (e) {
76
+ const result = { status: 'failed', error: (0, agent_protocol_1.failure)(e) };
77
+ console.log(JSON.stringify(a.stream ? { type: 'result', job: result } : result, a.json || a.stream ? undefined : null, a.json || a.stream ? undefined : 2));
78
+ process.exitCode = 1;
79
+ }
80
+ };
81
+ function scriptOptions(y) { return streaming(y).usage('$0 scripts <action> [name]').positional('action', { choices: ['list', 'inspect', 'create', 'attach'] }).positional('name', { type: 'string' }).option('replace', { type: 'boolean', default: false }).option('expected-revision', { type: 'string' }).option('timeout', { type: 'number', default: 30 }); }
82
+ const scriptHandler = handler(a => ({ method: `scripts.${a.action}`, device: a.device, script: a.name, options: { replace: a.replace, expectedRevision: a.expectedRevision, timeout: a.timeout } }));
83
+ function installAgentCommands(y) {
84
+ return y.command('skill', 'Print the portable Scripting development SKILL.md', () => { }, () => console.log(fs_1.default.readFileSync(path_1.default.join(__dirname, '../skills/scripting-development/SKILL.md'), 'utf8'))).command('devices', 'List connected devices and their current responsiveness', common, async (a) => {
85
+ try {
86
+ const value = await (0, agent_control_1.controlRequest)((0, agent_control_1.loadControl)(process.cwd()), '/v1/devices');
87
+ console.log(JSON.stringify(value.result, null, a.json ? undefined : 2));
88
+ }
89
+ catch (e) {
90
+ console.log(JSON.stringify({ status: 'failed', error: (0, agent_protocol_1.failure)(e) }));
91
+ process.exitCode = 1;
92
+ }
93
+ }).command('status', 'Query the selected App debug session', y => streaming(y), handler(a => ({ method: 'status', device: a.device })))
94
+ .command('docs <action> [value]', 'Search docs or read a returned document ID', y => streaming(y).positional('action', { choices: ['search', 'get'] }).positional('value', { type: 'string' }).option('lang', { choices: ['en', 'zh'], default: 'en' }).option('limit', { type: 'number', default: 20 }), handler(a => ({ method: a.action === 'search' ? 'docs.search' : 'docs.get', device: a.device, query: a.action === 'search' ? a.value : undefined, docId: a.action === 'get' ? a.value : undefined, lang: a.lang, limit: a.limit })))
95
+ .command('api <action> <symbol>', 'Read an exact Scripting API declaration', y => streaming(y).positional('action', { choices: ['get'] }).positional('symbol', { type: 'string' }), handler(a => ({ method: 'api.get', device: a.device, symbol: a.symbol })))
96
+ .command('run [script]', 'Sync and execute the current debug script', y => runOptions(y), handler(a => ({ method: 'run', device: a.device, script: a.script, options: { screenshot: a.screenshot, captureAfter: a.captureAfter, readyLog: a.readyLog, timeout: a.timeout, noSync: a['no-sync'], queryParameters: a['query-parameters'] ? JSON.parse(a['query-parameters']) : undefined } })))
97
+ .command('widget [script]', 'Render the current script widget and close its preview', y => runOptions(y, false).option('family', { type: 'string', default: 'systemSmall' }).option('parameter', { type: 'string' }), handler(a => ({ method: 'widget', device: a.device, script: a.script, options: { screenshot: a.screenshot, timeout: a.timeout, noSync: a['no-sync'], family: a.family, parameter: a.parameter } })))
98
+ .command('widget-batch [script]', 'Render 1...8 widget cases from a JSON file', y => streaming(y).positional('script', { type: 'string' }).option('timeout', { type: 'number', default: 30 }).option('no-sync', { type: 'boolean', default: false }).option('cases', { type: 'string', demandOption: true }), handler(a => {
99
+ const stat = fs_1.default.statSync(a.cases);
100
+ if (stat.size > 128 * 1024)
101
+ throw new agent_protocol_1.AgentError('invalid_request', 'Case manifest exceeds 128 KiB.');
102
+ const cases = JSON.parse(fs_1.default.readFileSync(a.cases, 'utf8'));
103
+ return { method: 'widget.batch', device: a.device, script: a.script, options: { timeout: a.timeout, noSync: a['no-sync'], cases } };
104
+ }))
105
+ .command('scripts <action> [name]', 'List, inspect, create or attach an App script', scriptOptions, scriptHandler)
106
+ .command('projects <action> [name]', false, scriptOptions, scriptHandler)
107
+ .command('skills run <name> <entry>', 'Sync and test a .ts/.tsx entry in the selected App skill', y => streaming(y, false).positional('name', { type: 'string', demandOption: true }).positional('entry', { type: 'string', demandOption: true }).option('check', { type: 'boolean', default: false, describe: 'Check TypeScript without executing the entry' }).option('timeout', { type: 'number', default: 30 }).option('query-parameters', { type: 'string', describe: 'JSON object passed to the skill script' }), handler(a => ({ method: 'skills.run', device: a.device, skill: a.name, entry: a.entry, options: { check: a.check, timeout: a.timeout, queryParameters: a['query-parameters'] ? JSON.parse(a['query-parameters']) : undefined } })))
108
+ .command('jobs <action> <id>', 'Read a recent result or cancel an owned run', y => common(y).positional('action', { choices: ['show', 'cancel', 'events'] }).positional('id', { type: 'string' }).option('after', { type: 'number', default: 0 }), async (a) => {
109
+ try {
110
+ const state = (0, agent_control_1.loadControl)(process.cwd());
111
+ const route = `/v1/jobs/${encodeURIComponent(a.id)}${a.action === 'cancel' ? '/cancel' : a.action === 'events' ? `/events?after=${a.after}` : ''}`;
112
+ let job = (await (0, agent_control_1.controlRequest)(state, route, a.action === 'cancel' ? {} : undefined)).result;
113
+ if (job.result?.artifacts?.length)
114
+ job.result = (0, agent_control_1.materializeArtifacts)(job.result, job.runId, path_1.default.resolve(a.output));
115
+ console.log(JSON.stringify(job, null, a.json ? undefined : 2));
116
+ }
117
+ catch (e) {
118
+ console.log(JSON.stringify({ status: 'failed', error: (0, agent_protocol_1.failure)(e) }));
119
+ process.exitCode = 1;
120
+ }
121
+ });
122
+ }
@@ -0,0 +1,16 @@
1
+ import { AgentBroker } from './agent_broker';
2
+ export interface ControlState {
3
+ protocolVersion: 1;
4
+ port: number;
5
+ token: string;
6
+ instanceId: string;
7
+ workspace: string;
8
+ }
9
+ export declare function statePath(workspace: string): string;
10
+ export declare function loadControl(workspace: string): ControlState;
11
+ export declare function controlRequest(state: ControlState, route: string, body?: unknown): Promise<any>;
12
+ export declare function startAgentControl(broker: AgentBroker): Promise<{
13
+ state: ControlState;
14
+ close: () => Promise<void>;
15
+ }>;
16
+ export declare function materializeArtifacts(result: any, runId: string, output: string): any;