scripting-cli 1.6.0 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +59 -36
- package/dist/agent_broker.d.ts +14 -3
- package/dist/agent_broker.js +53 -34
- package/dist/agent_cli.js +15 -11
- package/dist/agent_protocol.d.ts +12 -7
- package/dist/agent_protocol.js +32 -19
- package/dist/controller.d.ts +2 -0
- package/dist/controller.js +22 -6
- package/dist/dev_terms.d.ts +9 -0
- package/dist/dev_terms.js +36 -0
- package/dist/skill_sync.d.ts +39 -0
- package/dist/skill_sync.js +311 -0
- package/dist/util.d.ts +1 -1
- package/dist/util.js +7 -4
- package/package.json +1 -1
- package/skills/scripting-development/SKILL.md +20 -14
package/README.md
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
# Scripting App Command-Line Tool
|
|
2
2
|
|
|
3
|
+
Latest release: [2.0.1](docs/releases/2.0.1.md). Migration from 1.x: [2.0.0](docs/releases/2.0.0.md).
|
|
4
|
+
|
|
3
5
|
Welcome to the `scripting-cli`, the command-line tool designed for integrating with the Scripting app. This tool allows you to synchronize and preview your scripts in real-time as you develop them using your favorite desktop editor (VSCode, Cursor, Windsurf, Zed, WebStorm, Vim, and more).
|
|
4
6
|
|
|
5
7
|
[中文](./README_zh.md) | [日本語](./README_ja.md) | [Deutsch](./README_de.md) | [Français](./README_fr.md) | [Italiano](./README_it.md)
|
|
@@ -31,8 +33,8 @@ npx scripting-cli <command>
|
|
|
31
33
|
Start by creating a directory where your Scripting app scripts will reside. For example:
|
|
32
34
|
|
|
33
35
|
```bash
|
|
34
|
-
mkdir my-scripting-
|
|
35
|
-
cd my-scripting-
|
|
36
|
+
mkdir my-scripting-workspace
|
|
37
|
+
cd my-scripting-workspace
|
|
36
38
|
```
|
|
37
39
|
|
|
38
40
|
### 2. Start the Local Service
|
|
@@ -61,7 +63,7 @@ Once the service is running, open the **Scripting app** and connect to the local
|
|
|
61
63
|
|
|
62
64
|
### 4. Debug and Synchronize Your Code
|
|
63
65
|
|
|
64
|
-
After connecting, select the script
|
|
66
|
+
After connecting, select the script you want to debug. The Scripting app will automatically sync the script’s code with your working directory.
|
|
65
67
|
|
|
66
68
|
### 5. Real-Time Code Synchronization
|
|
67
69
|
|
|
@@ -69,7 +71,7 @@ As you write and save scripts using your desktop editor (e.g., VSCode), the chan
|
|
|
69
71
|
|
|
70
72
|
## Editor Selection and Config File
|
|
71
73
|
|
|
72
|
-
`scripting-cli` is no longer tied to VSCode. The first time you run `npx scripting-cli start`, you'll be prompted to choose the editor you actually use. Your choice is saved to `scripting.config.json` in your
|
|
74
|
+
`scripting-cli` is no longer tied to VSCode. The first time you run `npx scripting-cli start`, you'll be prompted to choose the editor you actually use. Your choice is saved to `scripting.config.json` in your workspace root so the prompt won't appear again.
|
|
73
75
|
|
|
74
76
|
### Supported editors
|
|
75
77
|
|
|
@@ -210,16 +212,16 @@ Enjoy using `scripting-cli` in your Scripting app development workflow. Happy co
|
|
|
210
212
|
## Desktop agent commands
|
|
211
213
|
|
|
212
214
|
Codex, Claude Code, and other desktop agents can query the connected App's docs,
|
|
213
|
-
sync the current debug
|
|
215
|
+
sync the current debug script, run it, and inspect results without a separate
|
|
214
216
|
agent-specific plugin. These commands require a compatible Scripting App with
|
|
215
217
|
Desktop Agent protocol v1 support. Older App versions can continue normal file
|
|
216
218
|
syncing but do not support the new commands.
|
|
217
219
|
|
|
218
220
|
1. Run `scripting-cli start` in your workspace.
|
|
219
221
|
2. Connect Scripting to that server. Select a script and enter its debug page.
|
|
220
|
-
3. The existing sync workflow creates `scripts/<
|
|
222
|
+
3. The existing sync workflow creates `scripts/<script>/` in the workspace.
|
|
221
223
|
4. Run the commands below from that same workspace. The first release only
|
|
222
|
-
runs the App's selected debug
|
|
224
|
+
runs the App's selected debug script. Use the explicit scripts commands below
|
|
223
225
|
to create or change that selection; execution never switches it implicitly.
|
|
224
226
|
|
|
225
227
|
```sh
|
|
@@ -240,7 +242,7 @@ scripting-cli jobs cancel <run-id> --json
|
|
|
240
242
|
- With several connected devices, pass `--device <device-id>` from `devices`.
|
|
241
243
|
`devices` makes a fresh request and reports `responsive`; a connected socket
|
|
242
244
|
alone is not proof the App can execute a command. `status` includes foreground
|
|
243
|
-
state, the selected
|
|
245
|
+
state, the selected script, current revision, `activeRunId` and background-keeper state.
|
|
244
246
|
- Docs and API declarations come from the connected App, with its version in
|
|
245
247
|
the response. Search returns IDs and summaries; `docs get` reads one document.
|
|
246
248
|
There is no silent offline fallback to older docs.
|
|
@@ -250,16 +252,17 @@ scripting-cli jobs cancel <run-id> --json
|
|
|
250
252
|
already-applied snapshot do not cause an extra automatic run.
|
|
251
253
|
- Ordinary `run` waits for `Script.exit(result)` or failure. The default overall
|
|
252
254
|
deadline is 30 seconds (`--timeout`, 1–120). Forgetting to call `Script.exit`
|
|
253
|
-
can therefore produce a timeout. Request parameters retain the
|
|
255
|
+
can therefore produce a timeout. Request parameters retain the script's
|
|
254
256
|
normal App permission checks.
|
|
255
|
-
- `run --screenshot`
|
|
257
|
+
- `run --screenshot` attempts capture in either foreground or background. It waits for this
|
|
256
258
|
run's view, waits `--capture-after` seconds (0–10, default 2), captures the
|
|
257
259
|
view, and ends this run. Its result says `completionReason: preview_capture`;
|
|
258
260
|
this is a finite preview, not proof the script exited itself or that all
|
|
259
261
|
remote content finished loading. No rendered view means an explicit error,
|
|
260
262
|
not a successful blank image.
|
|
261
|
-
- Both widget modes render the current
|
|
262
|
-
|
|
263
|
+
- Both widget modes render the current script's `widget.tsx` in the App's
|
|
264
|
+
preview and close automatically. Rendering is attempted in either App state;
|
|
265
|
+
unavailable views, render errors or timeouts are reported. Without `--screenshot`, no image
|
|
263
266
|
is generated. These commands do not install a home-screen widget or confirm
|
|
264
267
|
a WidgetKit timeline refresh. The supplied family/parameter do not overwrite
|
|
265
268
|
the user's normal preview preferences.
|
|
@@ -273,7 +276,7 @@ scripting-cli jobs cancel <run-id> --json
|
|
|
273
276
|
|
|
274
277
|
With `--json`, stdout contains one JSON value (a device array for `devices`, or a
|
|
275
278
|
job record for other commands). Jobs contain `runId`, `requestId`, `deviceId`,
|
|
276
|
-
`sessionId`, `
|
|
279
|
+
`sessionId`, `script`, `requestedRevision`, `revision`, `status`, and `result` or `error`. The requested revision and the App-applied revision are separate; failed
|
|
277
280
|
preconditions do not claim that source was applied. Script
|
|
278
281
|
values are in `result.value`, logs in `result.stdout` / `result.stderr`, and
|
|
279
282
|
screenshots in `result.artifacts`. PNG files are copied to
|
|
@@ -284,7 +287,7 @@ removes its temporary results on shutdown.
|
|
|
284
287
|
|
|
285
288
|
Exit codes: `0` success, `1` command failure, `2` invalid CLI usage, `124` execution
|
|
286
289
|
or device timeout, `130` caller cancellation. Stable error codes include
|
|
287
|
-
`device_ambiguous`, `
|
|
290
|
+
`device_ambiguous`, `script_mismatch`, `debug_session_required`, `busy`,
|
|
288
291
|
`needs_foreground`, `sync_failed`, `missing_entry`, `screenshot_unavailable`, and
|
|
289
292
|
`unsupported_capability`. Inspect the result instead of treating a successful
|
|
290
293
|
connection or preview presentation as completed execution.
|
|
@@ -294,7 +297,7 @@ ignore rules. Source symlinks and unsafe paths are rejected. Screenshots are
|
|
|
294
297
|
bounded to 8 MiB and 16 megapixels. The App preserves excluded files and the
|
|
295
298
|
script's permission identity. A separate authenticated loopback control server
|
|
296
299
|
connects desktop commands to the running service; its credentials live in a
|
|
297
|
-
private per-user OS temporary directory, not the
|
|
300
|
+
private per-user OS temporary directory, not the script or command output.
|
|
298
301
|
The existing App-facing LAN / Tailscale server remains available for file sync.
|
|
299
302
|
|
|
300
303
|
### Tests
|
|
@@ -308,21 +311,21 @@ execution and screenshots also require App-side integration evidence; mocked
|
|
|
308
311
|
peers do not substitute for device rendering.
|
|
309
312
|
|
|
310
313
|
|
|
311
|
-
## Live feedback, ready screenshots, batches, and
|
|
314
|
+
## Live feedback, ready screenshots, batches, and script management
|
|
312
315
|
|
|
313
316
|
The next capabilities are negotiated separately. An older protocol-v1 App can
|
|
314
|
-
still use first-release commands, but unsupported ready-log, streaming or
|
|
317
|
+
still use first-release commands, but unsupported ready-log, streaming or script
|
|
315
318
|
commands fail explicitly.
|
|
316
319
|
|
|
317
320
|
```sh
|
|
318
321
|
scripting-cli run "MyScript" --stream
|
|
319
322
|
scripting-cli jobs events <run-id> --after 0 --json
|
|
320
|
-
scripting-cli
|
|
321
|
-
scripting-cli
|
|
322
|
-
scripting-cli
|
|
323
|
-
scripting-cli
|
|
323
|
+
scripting-cli scripts list --json
|
|
324
|
+
scripting-cli scripts inspect "MyScript" --json
|
|
325
|
+
scripting-cli scripts create "NewScript" --json
|
|
326
|
+
scripting-cli scripts attach "MyScript" --json
|
|
324
327
|
# Only after reviewing an App/desktop source conflict and choosing desktop source:
|
|
325
|
-
scripting-cli
|
|
328
|
+
scripting-cli scripts attach "MyScript" --replace --expected-revision <App-revision-from-inspect> --json
|
|
326
329
|
```
|
|
327
330
|
|
|
328
331
|
`--stream` emits JSONL stage/log/diagnostic records with monotonic `seq` and run,
|
|
@@ -331,7 +334,7 @@ It replaces the single JSON result format even with `--json`. Sync, compilation,
|
|
|
331
334
|
execution, ready waiting, rendering and capture are distinct stages. Events keep
|
|
332
335
|
256 recent records and 64 KiB of streamed log text per job; `gap` reports a slow
|
|
333
336
|
reader falling behind retention. Final logs also report truncation. Diagnostics
|
|
334
|
-
are collected on failures within the original deadline, with
|
|
337
|
+
are collected on failures within the original deadline, with script-relative
|
|
335
338
|
`file`, one-based `line`/`column`, TypeScript `code` and message when available;
|
|
336
339
|
runtime failures do not necessarily have a TypeScript diagnostic.
|
|
337
340
|
|
|
@@ -343,8 +346,8 @@ console.log("SCREENSHOT_READY")
|
|
|
343
346
|
|
|
344
347
|
Then run `scripting-cli run "MyScript" --screenshot --ready-log SCREENSHOT_READY --capture-after 1 --json`.
|
|
345
348
|
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
|
|
347
|
-
|
|
349
|
+
a valid view before its settling delay; missing signals/views never yield a
|
|
350
|
+
successful screenshot. Backgrounding alone does not cancel a capture attempt. A script that exits without its signal
|
|
348
351
|
returns `ready_signal_missing`. Existing timeout rules remain unchanged.
|
|
349
352
|
|
|
350
353
|
`widget-batch "MyScript" --cases ./cases.json --timeout 60 --stream` runs one
|
|
@@ -361,20 +364,22 @@ source revision across 1...8 serial widget cases. A manifest is a JSON array:
|
|
|
361
364
|
IDs use letters, digits, `_` and `-`, and must be unique. Results name each case
|
|
362
365
|
and any skipped cases; PNGs are `<output>/<run-id>/<case-id>.png`. Image bytes total
|
|
363
366
|
at most 8 MiB for the batch. A failed/cancelled batch can retain completed earlier
|
|
364
|
-
cases; remaining cases do not execute. Every preview
|
|
365
|
-
and closes automatically, without changing normal preview preferences.
|
|
367
|
+
cases; remaining cases do not execute. Every preview attempts rendering in the
|
|
368
|
+
current App state and closes automatically, without changing normal preview preferences.
|
|
366
369
|
|
|
367
|
-
|
|
368
|
-
refuse an active manual run/preview. `create` uses an existing desktop directory
|
|
370
|
+
Script commands need the App connected; create/attach can bind in the background
|
|
371
|
+
and refuse an active manual run/preview. `create` uses an existing desktop directory
|
|
369
372
|
or creates a minimal local `script.json` / `index.tsx` scaffold when absent. App
|
|
370
|
-
name collisions return `
|
|
373
|
+
name collisions return `script_exists`, without overwriting that App script.
|
|
371
374
|
A scaffold can remain locally if App creation is refused. `attach` publishes a
|
|
372
|
-
desktop snapshot and
|
|
373
|
-
|
|
375
|
+
desktop snapshot and binds the script immediately. If the App is backgrounded,
|
|
376
|
+
its debug page appears when the App returns to the foreground; this does not
|
|
377
|
+
rerun the command. Different App source
|
|
378
|
+
returns `script_conflict` with its current revision; only explicit `--replace`
|
|
374
379
|
plus the inspected `--expected-revision` permits replacement. A changed App
|
|
375
380
|
revision is rejected again at publication. Ignored files are preserved. The
|
|
376
|
-
server changes its watcher only after native success; delayed old-
|
|
377
|
-
cannot write into the newly selected
|
|
381
|
+
server changes its watcher only after native success; delayed old-script events
|
|
382
|
+
cannot write into the newly selected script. Type declarations are refreshed
|
|
378
383
|
from the same App for desktop editing.
|
|
379
384
|
|
|
380
385
|
### Portable agent skill
|
|
@@ -382,10 +387,28 @@ from the same App for desktop editing.
|
|
|
382
387
|
The package includes [skills/scripting-development/SKILL.md](skills/scripting-development/SKILL.md).
|
|
383
388
|
`scripting-cli skill` prints the complete portable skill. It explains the
|
|
384
389
|
connected documentation → edit → execute → inspect screenshot → refine loop,
|
|
385
|
-
|
|
390
|
+
script conflicts, readiness, batches and cancellation for Codex/Claude Code.
|
|
386
391
|
Copy its directory into your agent's configured skill location if desired;
|
|
387
392
|
this command does not install it or change global agent configuration. Inspect
|
|
388
393
|
App/desktop conflicts and obtain authorization for the particular overwrite
|
|
389
394
|
before running the replacement command.
|
|
390
395
|
|
|
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
|
|
396
|
+
If the local service itself stops, commands report `control_unavailable`; they do not replay execution. Reconnect, inspect App status, and explicitly attach the intended script before a new run.
|
|
397
|
+
|
|
398
|
+
## Skill development
|
|
399
|
+
|
|
400
|
+
Select **Skill** in the App’s Development Server page, then choose a package. The server creates `skills/` beside `scripts/`; the selected package lives at `skills/<name>/`. App-only and desktop-only packages can be copied across. When both sides differ, choose the source in the App. Later desktop saves synchronize only that package and do not execute it. Stop and reselect after a source conflict or reconnect.
|
|
401
|
+
|
|
402
|
+
A package needs `SKILL.md` with `name` and `description` frontmatter. Its `.ts`/`.tsx`, references and binary assets synchronize; `.git`, dependencies and configured ignored files stay local. `skill.json` remains App-managed and is preserved. A package is limited to 8 MiB / 2000 synced files; paths differing only in case or Unicode normalization are rejected. Deleting a whole package or its `SKILL.md` on the desktop does not delete the App package.
|
|
403
|
+
|
|
404
|
+
Run an entry relative to the **currently selected** skill:
|
|
405
|
+
|
|
406
|
+
```sh
|
|
407
|
+
scripting-cli skills run my-skill scripts/main.tsx --stream
|
|
408
|
+
scripting-cli skills run my-skill scripts/main.tsx --check --json
|
|
409
|
+
scripting-cli skills run my-skill scripts/main.tsx --query-parameters '{"sample":true}' --timeout 30 --json
|
|
410
|
+
```
|
|
411
|
+
|
|
412
|
+
Each run synchronizes one complete source revision, pauses synchronization while testing, and returns stdout/stderr, the result from `Script.exit(value)`, exit code and errors. Skill identity, permissions, `Script.directory` and Storage/Keychain behavior match the App’s `scripting-ts run`. End successful scripts with `Script.exit(...)`; otherwise the run times out. `--check` checks without executing. `--stream`, `--device`, Ctrl-C and `jobs show/events/cancel` work as for script runs. Entry paths must stay inside the selected package. Skill runs do not support screenshots in this version.
|
|
413
|
+
|
|
414
|
+
Use an updated App and CLI for this capability. The existing singular `scripting-cli skill` still prints the portable development guide.
|
package/dist/agent_broker.d.ts
CHANGED
|
@@ -14,10 +14,18 @@ interface Peer {
|
|
|
14
14
|
reject: (error: Error) => void;
|
|
15
15
|
}>;
|
|
16
16
|
hooks: {
|
|
17
|
-
|
|
17
|
+
script?: () => string | null;
|
|
18
|
+
project?: () => string | null;
|
|
18
19
|
ignore: () => string[];
|
|
19
20
|
pause: () => void;
|
|
20
|
-
resume: (snapshot?: SourceSnapshot) => void;
|
|
21
|
+
resume: (snapshot?: SourceSnapshot, bindingId?: string) => void;
|
|
22
|
+
skill?: () => {
|
|
23
|
+
name: string;
|
|
24
|
+
bindingId: string;
|
|
25
|
+
revision: string;
|
|
26
|
+
} | null;
|
|
27
|
+
skillReady?: () => Promise<void>;
|
|
28
|
+
switchScript?: (script: string) => Promise<void>;
|
|
21
29
|
switchProject?: (project: string) => Promise<void>;
|
|
22
30
|
types?: (files: Record<string, string>) => Promise<void>;
|
|
23
31
|
};
|
|
@@ -27,7 +35,9 @@ interface Job {
|
|
|
27
35
|
requestId: string;
|
|
28
36
|
deviceId: string;
|
|
29
37
|
sessionId: string;
|
|
30
|
-
|
|
38
|
+
script?: string;
|
|
39
|
+
skill?: string;
|
|
40
|
+
entry?: string;
|
|
31
41
|
requestedRevision?: string;
|
|
32
42
|
revision?: string;
|
|
33
43
|
status: string;
|
|
@@ -56,6 +66,7 @@ export declare class AgentBroker {
|
|
|
56
66
|
constructor(workspace: string);
|
|
57
67
|
register(socket: SocketPeer, hooks: Peer['hooks']): void;
|
|
58
68
|
private invalidate;
|
|
69
|
+
private selectedScript;
|
|
59
70
|
private select;
|
|
60
71
|
private call;
|
|
61
72
|
devices(): Promise<any[]>;
|
package/dist/agent_broker.js
CHANGED
|
@@ -5,12 +5,14 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.agentBroker = exports.AgentBroker = void 0;
|
|
7
7
|
const crypto_1 = __importDefault(require("crypto"));
|
|
8
|
+
const dev_terms_1 = require("./dev_terms");
|
|
9
|
+
const skill_sync_1 = require("./skill_sync");
|
|
8
10
|
const fs_1 = __importDefault(require("fs"));
|
|
9
11
|
const path_1 = __importDefault(require("path"));
|
|
10
12
|
const os_1 = __importDefault(require("os"));
|
|
11
13
|
const agent_protocol_1 = require("./agent_protocol");
|
|
12
|
-
const mutations = ['run', 'widget', 'widget.batch', '
|
|
13
|
-
const
|
|
14
|
+
const mutations = ['run', 'widget', 'widget.batch', 'scripts.create', 'scripts.attach', 'skills.run'];
|
|
15
|
+
const scriptChanges = ['scripts.create', 'scripts.attach'];
|
|
14
16
|
const terminal = (s) => ['completed', 'failed', 'cancelled'].includes(s);
|
|
15
17
|
class AgentBroker {
|
|
16
18
|
workspace;
|
|
@@ -32,14 +34,14 @@ class AgentBroker {
|
|
|
32
34
|
return;
|
|
33
35
|
// Duplicate installation IDs remain ambiguous. A second socket must not
|
|
34
36
|
// take over a connected device merely by claiming its identifier.
|
|
35
|
-
if (meta.capabilities.length >
|
|
37
|
+
if (meta.capabilities.length > 32 || !meta.capabilities.every((value) => typeof value === 'string' && value.length < 64))
|
|
36
38
|
return;
|
|
37
39
|
if (peer.metadata && peer.metadata.sessionId !== meta.sessionId)
|
|
38
40
|
this.invalidate(peer);
|
|
39
41
|
peer.metadata = { protocolVersion: 1, deviceId: meta.deviceId, sessionId: meta.sessionId,
|
|
40
42
|
name: typeof meta.name === 'string' ? meta.name.slice(0, 128) : 'Scripting device',
|
|
41
43
|
appVersion: typeof meta.appVersion === 'string' ? meta.appVersion.slice(0, 64) : '',
|
|
42
|
-
capabilities:
|
|
44
|
+
capabilities: (0, dev_terms_1.scriptCapabilities)(meta.capabilities), ...this.statusFields(meta) };
|
|
43
45
|
});
|
|
44
46
|
socket.on('agentResult', (reply) => {
|
|
45
47
|
const pending = peer.pending.get(reply?.requestId);
|
|
@@ -55,8 +57,8 @@ class AgentBroker {
|
|
|
55
57
|
socket.on('agentTypes', async (data, ack) => {
|
|
56
58
|
try {
|
|
57
59
|
const pending = peer.pending.get(data?.requestId);
|
|
58
|
-
if (!pending || !
|
|
59
|
-
throw new agent_protocol_1.AgentError('invalid_request', 'No matching
|
|
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.');
|
|
60
62
|
const files = data.files;
|
|
61
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)
|
|
62
64
|
throw new agent_protocol_1.AgentError('invalid_request', 'Invalid declaration bundle.');
|
|
@@ -73,10 +75,10 @@ class AgentBroker {
|
|
|
73
75
|
const job = this.jobs.get(event?.runId), pending = peer.pending.get(event?.requestId);
|
|
74
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)
|
|
75
77
|
return;
|
|
76
|
-
if (event.type === 'stage' && ['syncing', 'compiling', 'running', 'waiting_ready', 'capturing', 'rendering', 'selecting_project'].includes(event.stage)) {
|
|
78
|
+
if (event.type === 'stage' && ['syncing', 'compiling', 'running', 'waiting_ready', 'capturing', 'rendering', 'selecting_project', 'selecting_script'].includes(event.stage)) {
|
|
77
79
|
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
|
+
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 });
|
|
80
82
|
}
|
|
81
83
|
else if (event.type === 'log' && typeof event.message === 'string') {
|
|
82
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 });
|
|
@@ -103,6 +105,7 @@ class AgentBroker {
|
|
|
103
105
|
job.cancel?.();
|
|
104
106
|
}
|
|
105
107
|
}
|
|
108
|
+
selectedScript(peer) { return peer.hooks.script ? peer.hooks.script() : peer.hooks.project?.() ?? null; }
|
|
106
109
|
select(device) {
|
|
107
110
|
const peers = [...this.peers.values()].filter(p => p.socket.connected && p.metadata);
|
|
108
111
|
const found = device ? peers.filter(p => p.metadata.deviceId === device) : peers;
|
|
@@ -141,18 +144,22 @@ class AgentBroker {
|
|
|
141
144
|
const command = (0, agent_protocol_1.validateCommand)(raw);
|
|
142
145
|
const peer = this.select(command.device);
|
|
143
146
|
const mutation = mutations.includes(command.method);
|
|
144
|
-
const
|
|
147
|
+
const skillRun = command.method === 'skills.run';
|
|
148
|
+
const skill = peer.hooks.skill?.();
|
|
149
|
+
const scriptChange = scriptChanges.includes(command.method);
|
|
145
150
|
const requestId = command.requestId || crypto_1.default.randomUUID();
|
|
146
151
|
if (!peer.metadata.capabilities.includes(command.method))
|
|
147
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.');
|
|
148
155
|
if (command.options?.readyLog && !peer.metadata.capabilities.includes('ready-log') || command.options?.events && !peer.metadata.capabilities.includes('events-v1'))
|
|
149
156
|
throw new agent_protocol_1.AgentError('unsupported_capability', 'This App does not support ready-log or live events.');
|
|
150
|
-
if (mutation && !
|
|
151
|
-
throw new agent_protocol_1.AgentError('debug_session_required', 'Open the current
|
|
152
|
-
const
|
|
153
|
-
if (mutation && !
|
|
154
|
-
throw new agent_protocol_1.AgentError('
|
|
155
|
-
const fingerprint = (0, agent_protocol_1.hash)(JSON.stringify({ ...command,
|
|
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 } : {}) }));
|
|
156
163
|
const old = [...this.jobs.values()].find(j => j.requestId === requestId && j.sessionId === peer.metadata.sessionId);
|
|
157
164
|
if (old) {
|
|
158
165
|
if (old.fingerprint !== fingerprint)
|
|
@@ -171,7 +178,7 @@ class AgentBroker {
|
|
|
171
178
|
else
|
|
172
179
|
throw new agent_protocol_1.AgentError('busy', 'Too many outstanding requests.');
|
|
173
180
|
}
|
|
174
|
-
const job = { runId: crypto_1.default.randomUUID(), requestId, deviceId: peer.metadata.deviceId, sessionId: peer.metadata.sessionId,
|
|
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 };
|
|
175
182
|
this.jobs.set(job.runId, job);
|
|
176
183
|
this.event(job, 'stage', { stage: 'accepted' });
|
|
177
184
|
job.cancel = () => peer.socket.emit('agentCancel', { runId: job.runId, sessionId: job.sessionId });
|
|
@@ -181,14 +188,22 @@ class AgentBroker {
|
|
|
181
188
|
async execute(job, peer, command, mutation) {
|
|
182
189
|
const deadline = Date.now() + (command.options?.timeout ?? 30) * 1000;
|
|
183
190
|
let acknowledgedSnapshot;
|
|
191
|
+
const skillRun = command.method === 'skills.run';
|
|
192
|
+
let skillBinding = null;
|
|
184
193
|
if (mutation) {
|
|
185
194
|
this.activeMutations.add(job.deviceId);
|
|
186
195
|
peer.hooks.pause();
|
|
187
196
|
}
|
|
188
197
|
try {
|
|
189
|
-
if (
|
|
190
|
-
|
|
191
|
-
|
|
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;
|
|
192
207
|
if (terminal(job.status))
|
|
193
208
|
return;
|
|
194
209
|
// Cancellation during local snapshot capture precedes native admission.
|
|
@@ -202,9 +217,9 @@ class AgentBroker {
|
|
|
202
217
|
throw new agent_protocol_1.AgentError('execution_timeout', 'The command deadline expired while preparing source.');
|
|
203
218
|
if (peer.metadata?.sessionId !== job.sessionId || !peer.socket.connected)
|
|
204
219
|
throw new agent_protocol_1.AgentError('disconnected', 'The session changed before execution.');
|
|
205
|
-
if (mutation && !
|
|
206
|
-
throw new agent_protocol_1.AgentError('
|
|
207
|
-
const request = { ...command, protocolVersion: 1, requestId: job.requestId, runId: job.runId, sessionId: job.sessionId,
|
|
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 } : {}) };
|
|
208
223
|
job.requestedRevision = snapshot?.revision;
|
|
209
224
|
job.status = mutation ? 'syncing' : 'running';
|
|
210
225
|
const reply = await this.call(peer, request, deadline + 3000);
|
|
@@ -216,15 +231,16 @@ class AgentBroker {
|
|
|
216
231
|
throw new agent_protocol_1.AgentError('invalid_response', 'Device did not return a terminal result.');
|
|
217
232
|
if (mutation && reply.status === 'completed' && (!reply.revision || (snapshot && reply.revision !== snapshot.revision)))
|
|
218
233
|
throw new agent_protocol_1.AgentError('invalid_response', 'Source revision did not match the applied snapshot.');
|
|
219
|
-
if (reply.status === 'completed' &&
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
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);
|
|
223
239
|
}
|
|
224
|
-
job.result = this.storeArtifact(reply.result, job.runId);
|
|
240
|
+
job.result = (0, dev_terms_1.scriptResult)(this.storeArtifact(reply.result, job.runId));
|
|
225
241
|
job.status = reply.status;
|
|
226
242
|
job.revision = reply.revision ?? job.revision;
|
|
227
|
-
job.error = reply.error;
|
|
243
|
+
job.error = (0, dev_terms_1.scriptError)(reply.error);
|
|
228
244
|
}
|
|
229
245
|
catch (e) {
|
|
230
246
|
if (!terminal(job.status)) {
|
|
@@ -235,7 +251,7 @@ class AgentBroker {
|
|
|
235
251
|
}
|
|
236
252
|
finally {
|
|
237
253
|
if (mutation) {
|
|
238
|
-
peer.hooks.resume(acknowledgedSnapshot);
|
|
254
|
+
peer.hooks.resume(acknowledgedSnapshot, skillRun ? skillBinding?.bindingId : undefined);
|
|
239
255
|
this.activeMutations.delete(job.deviceId);
|
|
240
256
|
}
|
|
241
257
|
job.cancel = undefined;
|
|
@@ -270,7 +286,10 @@ class AgentBroker {
|
|
|
270
286
|
if (!value || typeof value !== 'object')
|
|
271
287
|
return {};
|
|
272
288
|
return {
|
|
273
|
-
|
|
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,
|
|
274
293
|
appState: ['foreground', 'background', 'inactive'].includes(value.appState) ? value.appState : 'unknown',
|
|
275
294
|
busy: value.busy === true, revision: typeof value.revision === 'string' && /^[a-f0-9]{64}$/.test(value.revision) ? value.revision : null,
|
|
276
295
|
activeRunId: typeof value.activeRunId === 'string' ? value.activeRunId.slice(0, 128) : null,
|
|
@@ -339,12 +358,12 @@ class AgentBroker {
|
|
|
339
358
|
const events = log?.events.filter(e => e.seq > after) ?? [];
|
|
340
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 };
|
|
341
360
|
}
|
|
342
|
-
scaffold(
|
|
343
|
-
const root = path_1.default.join(this.workspace, 'scripts',
|
|
361
|
+
scaffold(script) {
|
|
362
|
+
const root = path_1.default.join(this.workspace, 'scripts', script);
|
|
344
363
|
if (fs_1.default.existsSync(root))
|
|
345
364
|
return;
|
|
346
365
|
fs_1.default.mkdirSync(root, { recursive: false });
|
|
347
|
-
fs_1.default.writeFileSync(path_1.default.join(root, 'script.json'), JSON.stringify({ name:
|
|
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' });
|
|
348
367
|
fs_1.default.writeFileSync(path_1.default.join(root, 'index.tsx'), 'import { Script } from "scripting"\nScript.exit({ message: "Hello Scripting" })\n', { flag: 'wx' });
|
|
349
368
|
}
|
|
350
369
|
prune(now = Date.now()) {
|
package/dist/agent_cli.js
CHANGED
|
@@ -53,14 +53,14 @@ async function invokeAgentCommand(command, output, json, stream = false) {
|
|
|
53
53
|
process.removeListener('SIGINT', cancel);
|
|
54
54
|
}
|
|
55
55
|
}
|
|
56
|
-
function common(y) {
|
|
57
|
-
|
|
58
|
-
.option('json', { type: 'boolean', default: false, describe: 'Print one JSON result' })
|
|
59
|
-
|
|
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
60
|
}
|
|
61
|
-
function streaming(y) { return common(y).option('stream', { type: 'boolean', default: false, describe: 'Print progress/log/diagnostic JSONL events and one final result' }); }
|
|
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
62
|
function runOptions(y, script = true) {
|
|
63
|
-
const options = streaming(y).positional('
|
|
63
|
+
const options = streaming(y).positional('script', { type: 'string', describe: 'Currently selected App debug script' })
|
|
64
64
|
.option('screenshot', { type: 'boolean', default: false })
|
|
65
65
|
.option('timeout', { type: 'number', default: 30, describe: 'Overall run deadline in seconds, 1...120' })
|
|
66
66
|
.option('no-sync', { type: 'boolean', default: false, describe: 'Use the last acknowledged App revision' });
|
|
@@ -78,6 +78,8 @@ const handler = (build) => async (a) => {
|
|
|
78
78
|
process.exitCode = 1;
|
|
79
79
|
}
|
|
80
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 } }));
|
|
81
83
|
function installAgentCommands(y) {
|
|
82
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) => {
|
|
83
85
|
try {
|
|
@@ -91,16 +93,18 @@ function installAgentCommands(y) {
|
|
|
91
93
|
}).command('status', 'Query the selected App debug session', y => streaming(y), handler(a => ({ method: 'status', device: a.device })))
|
|
92
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 })))
|
|
93
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 })))
|
|
94
|
-
.command('run [
|
|
95
|
-
.command('widget [
|
|
96
|
-
.command('widget-batch [
|
|
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 => {
|
|
97
99
|
const stat = fs_1.default.statSync(a.cases);
|
|
98
100
|
if (stat.size > 128 * 1024)
|
|
99
101
|
throw new agent_protocol_1.AgentError('invalid_request', 'Case manifest exceeds 128 KiB.');
|
|
100
102
|
const cases = JSON.parse(fs_1.default.readFileSync(a.cases, 'utf8'));
|
|
101
|
-
return { method: 'widget.batch', device: a.device,
|
|
103
|
+
return { method: 'widget.batch', device: a.device, script: a.script, options: { timeout: a.timeout, noSync: a['no-sync'], cases } };
|
|
102
104
|
}))
|
|
103
|
-
.command('
|
|
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 } })))
|
|
104
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) => {
|
|
105
109
|
try {
|
|
106
110
|
const state = (0, agent_control_1.loadControl)(process.cwd());
|
package/dist/agent_protocol.d.ts
CHANGED
|
@@ -26,6 +26,7 @@ export interface WidgetCase {
|
|
|
26
26
|
screenshot: boolean;
|
|
27
27
|
}
|
|
28
28
|
export interface AgentOptions {
|
|
29
|
+
check?: boolean;
|
|
29
30
|
events?: boolean;
|
|
30
31
|
readyLog?: string;
|
|
31
32
|
cases?: WidgetCase[];
|
|
@@ -42,7 +43,10 @@ export interface AgentOptions {
|
|
|
42
43
|
export interface AgentCommand {
|
|
43
44
|
method: string;
|
|
44
45
|
device?: string;
|
|
46
|
+
script?: string; /** @deprecated Compatibility input for protocol-v1 clients. */
|
|
45
47
|
project?: string;
|
|
48
|
+
skill?: string;
|
|
49
|
+
entry?: string;
|
|
46
50
|
options?: AgentOptions;
|
|
47
51
|
query?: string;
|
|
48
52
|
docId?: string;
|
|
@@ -53,14 +57,15 @@ export interface AgentCommand {
|
|
|
53
57
|
}
|
|
54
58
|
export declare const methods: string[];
|
|
55
59
|
export declare function validateCommand(value: any): AgentCommand;
|
|
56
|
-
export declare function
|
|
60
|
+
export declare function validPackageName(value: unknown): value is string;
|
|
57
61
|
export declare function safeRelativePath(value: string): boolean;
|
|
58
62
|
export declare function revisionForFiles(files: Pick<SourceFile, 'path' | 'sha256'>[]): string;
|
|
59
|
-
export declare function
|
|
60
|
-
export declare
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
63
|
+
export declare function snapshotSource(workspace: string, name: string, ignore: string[], kind?: 'scripts' | 'skills'): Promise<SourceSnapshot>;
|
|
64
|
+
export declare const snapshotScript: typeof snapshotSource;
|
|
65
|
+
/** @deprecated Protocol-v1 compatibility exports. */
|
|
66
|
+
export declare const snapshotProject: typeof snapshotSource;
|
|
67
|
+
export declare const validProjectName: typeof validPackageName;
|
|
68
|
+
export declare function failure(error: unknown): any;
|
|
64
69
|
/** A delayed watcher notification for bytes already applied by this job must
|
|
65
70
|
* not trigger a second automatic run. Changes made after the snapshot remain. */
|
|
66
|
-
export declare function isAcknowledgedChange(workspace: string,
|
|
71
|
+
export declare function isAcknowledgedChange(workspace: string, script: string, relative: string, snapshot: SourceSnapshot): boolean;
|