scripting-cli 2.0.0 → 2.0.2

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
@@ -1,6 +1,6 @@
1
1
  # Scripting App Command-Line Tool
2
2
 
3
- Release notes and migration from 1.x: [scripting-cli 2.0.0](docs/releases/2.0.0.md).
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
4
 
5
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).
6
6
 
@@ -254,14 +254,15 @@ scripting-cli jobs cancel <run-id> --json
254
254
  deadline is 30 seconds (`--timeout`, 1–120). Forgetting to call `Script.exit`
255
255
  can therefore produce a timeout. Request parameters retain the script's
256
256
  normal App permission checks.
257
- - `run --screenshot` requires Scripting in the foreground. It waits for this
257
+ - `run --screenshot` attempts capture in either foreground or background. It waits for this
258
258
  run's view, waits `--capture-after` seconds (0–10, default 2), captures the
259
259
  view, and ends this run. Its result says `completionReason: preview_capture`;
260
260
  this is a finite preview, not proof the script exited itself or that all
261
261
  remote content finished loading. No rendered view means an explicit error,
262
262
  not a successful blank image.
263
263
  - Both widget modes render the current script's `widget.tsx` in the App's
264
- foreground preview and close automatically. Without `--screenshot`, no image
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
265
266
  is generated. These commands do not install a home-screen widget or confirm
266
267
  a WidgetKit timeline refresh. The supplied family/parameter do not overwrite
267
268
  the user's normal preview preferences.
@@ -345,8 +346,8 @@ console.log("SCREENSHOT_READY")
345
346
 
346
347
  Then run `scripting-cli run "MyScript" --screenshot --ready-log SCREENSHOT_READY --capture-after 1 --json`.
347
348
  Only a non-error log from this run matches. Capture waits for both the signal and
348
- a valid view before its settling delay; missing signals/views and foreground
349
- loss never yield a successful screenshot. A script that exits without its signal
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
350
351
  returns `ready_signal_missing`. Existing timeout rules remain unchanged.
351
352
 
352
353
  `widget-batch "MyScript" --cases ./cases.json --timeout 60 --stream` runs one
@@ -363,15 +364,17 @@ source revision across 1...8 serial widget cases. A manifest is a JSON array:
363
364
  IDs use letters, digits, `_` and `-`, and must be unique. Results name each case
364
365
  and any skipped cases; PNGs are `<output>/<run-id>/<case-id>.png`. Image bytes total
365
366
  at most 8 MiB for the batch. A failed/cancelled batch can retain completed earlier
366
- cases; remaining cases do not execute. Every preview uses foreground rendering
367
- 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.
368
369
 
369
- Script commands need the App connected; create/attach also need foreground and
370
- 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
371
372
  or creates a minimal local `script.json` / `index.tsx` scaffold when absent. App
372
373
  name collisions return `script_exists`, without overwriting that App script.
373
374
  A scaffold can remain locally if App creation is refused. `attach` publishes a
374
- desktop snapshot and enters that script's debug page. Different App source
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
375
378
  returns `script_conflict` with its current revision; only explicit `--replace`
376
379
  plus the inspected `--expected-revision` permits replacement. A changed App
377
380
  revision is rejected again at publication. Ignored files are preserved. The
@@ -409,3 +412,9 @@ scripting-cli skills run my-skill scripts/main.tsx --query-parameters '{"sample"
409
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.
410
413
 
411
414
  Use an updated App and CLI for this capability. The existing singular `scripting-cli skill` still prints the portable development guide.
415
+
416
+ ### Offline documentation in your workspace
417
+
418
+ After connecting the App to this server, tap **Sync Documentation** in the Development Server page. The App copies its bundled English and Chinese documentation, examples and assets to `docs/Scripting Documentation/` in the workspace where you started the CLI. This does not select or run a script or skill.
419
+
420
+ That subdirectory is a generated copy: syncing again replaces its contents and removes files absent from the App’s current bundle. Keep personal notes elsewhere in `docs/`. An existing directory that was not created by this feature is left untouched; move it before retrying. Both the App and CLI must support documentation sync. The existing `docs` commands continue to query the connected App.
@@ -36,12 +36,15 @@ class AgentBroker {
36
36
  // take over a connected device merely by claiming its identifier.
37
37
  if (meta.capabilities.length > 32 || !meta.capabilities.every((value) => typeof value === 'string' && value.length < 64))
38
38
  return;
39
+ const capabilities = (0, dev_terms_1.scriptCapabilities)(meta.capabilities);
40
+ if (meta.screenshotFinal === true && !capabilities.includes('screenshot-final'))
41
+ capabilities.push('screenshot-final');
39
42
  if (peer.metadata && peer.metadata.sessionId !== meta.sessionId)
40
43
  this.invalidate(peer);
41
44
  peer.metadata = { protocolVersion: 1, deviceId: meta.deviceId, sessionId: meta.sessionId,
42
45
  name: typeof meta.name === 'string' ? meta.name.slice(0, 128) : 'Scripting device',
43
46
  appVersion: typeof meta.appVersion === 'string' ? meta.appVersion.slice(0, 64) : '',
44
- capabilities: (0, dev_terms_1.scriptCapabilities)(meta.capabilities), ...this.statusFields(meta) };
47
+ capabilities, ...this.statusFields(meta) };
45
48
  });
46
49
  socket.on('agentResult', (reply) => {
47
50
  const pending = peer.pending.get(reply?.requestId);
@@ -152,6 +155,8 @@ class AgentBroker {
152
155
  throw new agent_protocol_1.AgentError('unsupported_capability', 'This App does not support the command.');
153
156
  if (skillRun && (!skill || skill.name !== command.skill || peer.metadata.skill !== skill.name || peer.metadata.skillBindingId !== skill.bindingId))
154
157
  throw new agent_protocol_1.AgentError('skill_mismatch', 'Select this skill in the App development page first.');
158
+ if (command.options?.screenshotFinal && !peer.metadata.capabilities.includes('screenshot-final'))
159
+ throw new agent_protocol_1.AgentError('unsupported_capability', 'This App does not support final screenshots.');
155
160
  if (command.options?.readyLog && !peer.metadata.capabilities.includes('ready-log') || command.options?.events && !peer.metadata.capabilities.includes('events-v1'))
156
161
  throw new agent_protocol_1.AgentError('unsupported_capability', 'This App does not support ready-log or live events.');
157
162
  if (mutation && !scriptChange && !skillRun && (!this.selectedScript(peer) || peer.metadata.script !== this.selectedScript(peer)))
package/dist/agent_cli.js CHANGED
@@ -64,7 +64,7 @@ function runOptions(y, script = true) {
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' });
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;
67
+ return script ? options.option('capture-after', { type: 'number', describe: 'Seconds after a script view is available before preview capture (default 2)' }).option('screenshot-final', { type: 'boolean', describe: 'Capture the latest script view when the script exits' }).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
68
  }
69
69
  const handler = (build) => async (a) => {
70
70
  try {
@@ -93,7 +93,7 @@ function installAgentCommands(y) {
93
93
  }).command('status', 'Query the selected App debug session', y => streaming(y), handler(a => ({ method: 'status', device: a.device })))
94
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
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 } })))
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, screenshotFinal: a.screenshotFinal, captureAfter: a.captureAfter, readyLog: a.readyLog, timeout: a.timeout, noSync: a['no-sync'], queryParameters: a['query-parameters'] ? JSON.parse(a['query-parameters']) : undefined } })))
97
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
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
99
  const stat = fs_1.default.statSync(a.cases);
@@ -34,6 +34,7 @@ export interface AgentOptions {
34
34
  expectedRevision?: string;
35
35
  timeout?: number;
36
36
  screenshot?: boolean;
37
+ screenshotFinal?: boolean;
37
38
  captureAfter?: number;
38
39
  family?: string;
39
40
  parameter?: string;
@@ -56,20 +56,22 @@ function validateCommand(value) {
56
56
  const o = value.options ?? {};
57
57
  if (!o || typeof o !== 'object' || Array.isArray(o))
58
58
  throw new AgentError('invalid_request', 'Invalid options.');
59
- for (const k of ['screenshot', 'noSync', 'replace', 'events', 'check'])
59
+ for (const k of ['screenshot', 'screenshotFinal', 'noSync', 'replace', 'events', 'check'])
60
60
  if (o[k] !== undefined && typeof o[k] !== 'boolean')
61
61
  throw new AgentError('invalid_request', `Invalid ${k}.`);
62
62
  if (o.timeout !== undefined && (!Number.isFinite(o.timeout) || o.timeout < 1 || o.timeout > 120))
63
63
  throw new AgentError('invalid_request', 'Timeout must be 1...120 seconds.');
64
64
  if (o.captureAfter !== undefined && (!Number.isFinite(o.captureAfter) || o.captureAfter < 0 || o.captureAfter > 10))
65
65
  throw new AgentError('invalid_request', 'Capture delay must be 0...10 seconds.');
66
+ if (o.screenshotFinal && (value.method !== 'run' || o.captureAfter !== undefined))
67
+ throw new AgentError('invalid_request', 'Final capture requires a script run without a capture delay.');
66
68
  if (o.family !== undefined && !exports.widgetFamilies.includes(o.family))
67
69
  throw new AgentError('invalid_request', 'Unsupported widget family.');
68
70
  if (o.parameter !== undefined && (typeof o.parameter !== 'string' || o.parameter.length > 16384))
69
71
  throw new AgentError('invalid_request', 'Invalid widget parameter.');
70
72
  if (o.queryParameters !== undefined && (!o.queryParameters || typeof o.queryParameters !== 'object' || Array.isArray(o.queryParameters) || Buffer.byteLength(JSON.stringify(o.queryParameters)) > 65536))
71
73
  throw new AgentError('invalid_request', 'Invalid query parameters.');
72
- if (o.readyLog !== undefined && (value.method !== 'run' || !o.screenshot || typeof o.readyLog !== 'string' || !o.readyLog.length || Buffer.byteLength(o.readyLog) > 1024 || /[\r\n]/.test(o.readyLog)))
74
+ if (o.readyLog !== undefined && (value.method !== 'run' || !(o.screenshot || o.screenshotFinal) || typeof o.readyLog !== 'string' || !o.readyLog.length || Buffer.byteLength(o.readyLog) > 1024 || /[\r\n]/.test(o.readyLog)))
73
75
  throw new AgentError('invalid_request', 'Ready log requires script screenshot mode and one exact line.');
74
76
  if (o.expectedRevision !== undefined && (typeof o.expectedRevision !== 'string' || !/^[a-f0-9]{64}$/.test(o.expectedRevision)))
75
77
  throw new AgentError('invalid_request', 'Invalid expected revision.');
@@ -4,6 +4,7 @@ import { globalDtsFileName, scriptingDtsFileName } from './const';
4
4
  import { ResolvedConfig } from './types';
5
5
  import { SkillSyncController } from './skill_sync';
6
6
  export declare class Controller {
7
+ readonly workspace: string;
7
8
  private static instances;
8
9
  static create(socket: Socket, config: ResolvedConfig): Controller;
9
10
  static get(socketId: string): Controller | undefined;
@@ -15,6 +15,7 @@ const agent_broker_1 = require("./agent_broker");
15
15
  const skill_sync_1 = require("./skill_sync");
16
16
  const agent_protocol_1 = require("./agent_protocol");
17
17
  class Controller {
18
+ workspace = fs_1.default.realpathSync(process.cwd());
18
19
  static instances = new Map();
19
20
  static create(socket, config) {
20
21
  const ctrl = new Controller(socket, config);
@@ -0,0 +1,12 @@
1
+ export declare const documentationPath = "docs/Scripting Documentation";
2
+ export declare function developmentWorkspace(workspace: string): {
3
+ version: number;
4
+ workspaceId: string;
5
+ documentationSync: boolean;
6
+ documentationPath: string;
7
+ };
8
+ export declare function syncDocumentation(workspace: string, raw: any, active: () => boolean): Promise<{
9
+ success: boolean;
10
+ path: string;
11
+ fileCount: number;
12
+ }>;
@@ -0,0 +1,158 @@
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.documentationPath = void 0;
7
+ exports.developmentWorkspace = developmentWorkspace;
8
+ exports.syncDocumentation = syncDocumentation;
9
+ const fs_1 = __importDefault(require("fs"));
10
+ const path_1 = __importDefault(require("path"));
11
+ const os_1 = __importDefault(require("os"));
12
+ const crypto_1 = __importDefault(require("crypto"));
13
+ const agent_protocol_1 = require("./agent_protocol");
14
+ exports.documentationPath = 'docs/Scripting Documentation';
15
+ const marker = '.scripting-documentation.json';
16
+ const owner = 'scripting-cli.documentation.v1';
17
+ const publishing = new Set();
18
+ const maxBytes = 32 * 1024 * 1024;
19
+ function developmentWorkspace(workspace) {
20
+ return { version: 1, workspaceId: crypto_1.default.createHash('sha256').update(os_1.default.hostname() + '\0' + fs_1.default.realpathSync(workspace)).digest('hex'), documentationSync: true, documentationPath: exports.documentationPath };
21
+ }
22
+ function stat(file) {
23
+ try {
24
+ return fs_1.default.lstatSync(file);
25
+ }
26
+ catch (e) {
27
+ if (e.code === 'ENOENT')
28
+ return;
29
+ throw e;
30
+ }
31
+ }
32
+ function directory(file) {
33
+ const value = stat(file);
34
+ if (value && (!value.isDirectory() || value.isSymbolicLink()))
35
+ throw new agent_protocol_1.AgentError('invalid_path', 'Documentation directories cannot be symbolic links or files.');
36
+ return value;
37
+ }
38
+ function checkTarget(parent, target, workspaceId) {
39
+ if (!directory(parent))
40
+ throw new agent_protocol_1.AgentError('invalid_path', 'Documentation parent disappeared.');
41
+ if (!directory(target))
42
+ return;
43
+ const receipt = path_1.default.join(target, marker), info = stat(receipt);
44
+ if (!info?.isFile() || info.isSymbolicLink() || info.size > 1024)
45
+ throw new agent_protocol_1.AgentError('documentation_conflict', 'Move the existing docs/Scripting Documentation directory before syncing.');
46
+ let value;
47
+ try {
48
+ value = JSON.parse(fs_1.default.readFileSync(receipt, 'utf8'));
49
+ }
50
+ catch { /* Report a conflict below. */ }
51
+ if (value?.owner !== owner || value?.workspaceId !== workspaceId)
52
+ throw new agent_protocol_1.AgentError('documentation_conflict', 'The existing documentation directory is not managed by this workspace.');
53
+ }
54
+ // Independent of script/skill selection and watchers. A whole snapshot is
55
+ // published only after all writes complete and the original socket is live.
56
+ async function syncDocumentation(workspace, raw, active) {
57
+ const root = fs_1.default.realpathSync(workspace), { workspaceId } = developmentWorkspace(root);
58
+ if (publishing.has(root))
59
+ throw new agent_protocol_1.AgentError('busy', 'Documentation synchronization is already active.');
60
+ if (raw?.version !== 1 || raw?.workspaceId !== workspaceId || !Array.isArray(raw.files) || !raw.files.length || raw.files.length > 5000)
61
+ throw new agent_protocol_1.AgentError('invalid_snapshot', 'Invalid documentation snapshot or workspace.');
62
+ const files = [], names = new Set(), components = new Map();
63
+ let bytes = 0;
64
+ for (const item of raw.files) {
65
+ if (typeof item?.path !== 'string' || !(0, agent_protocol_1.safeRelativePath)(item.path) || item.path.split('/').some((part) => part.startsWith('.')) || item.path.length > 1024 || typeof item.data !== 'string' || item.data.length > Math.ceil(8 * 1024 * 1024 / 3) * 4)
66
+ throw new agent_protocol_1.AgentError('invalid_path', 'Unsafe documentation path or content.');
67
+ const portable = item.path.normalize('NFC').toLowerCase();
68
+ if (names.has(portable))
69
+ throw new agent_protocol_1.AgentError('invalid_path', 'Documentation paths collide.');
70
+ names.add(portable);
71
+ const parts = item.path.split('/');
72
+ for (let count = 1; count <= parts.length; count++) {
73
+ const original = parts.slice(0, count).join('/'), folded = original.normalize('NFC').toLowerCase();
74
+ if (components.has(folded) && components.get(folded) !== original)
75
+ throw new agent_protocol_1.AgentError('invalid_path', 'Documentation directory names collide.');
76
+ components.set(folded, original);
77
+ }
78
+ const data = Buffer.from(item.data, 'base64');
79
+ bytes += data.length;
80
+ if (data.length > 8 * 1024 * 1024 || data.toString('base64') !== item.data || bytes > maxBytes)
81
+ throw new agent_protocol_1.AgentError('invalid_snapshot', 'Documentation exceeds the limit or contains invalid base64.');
82
+ files.push({ path: item.path, data });
83
+ }
84
+ for (const name of names) {
85
+ const parts = name.split('/');
86
+ parts.pop();
87
+ while (parts.length) {
88
+ if (names.has(parts.join('/')))
89
+ throw new agent_protocol_1.AgentError('invalid_path', 'A documentation file is also a directory.');
90
+ parts.pop();
91
+ }
92
+ }
93
+ if (!names.has('doc.json'))
94
+ throw new agent_protocol_1.AgentError('invalid_snapshot', 'Documentation index is missing.');
95
+ publishing.add(root);
96
+ const parent = path_1.default.join(root, 'docs'), target = path_1.default.join(root, exports.documentationPath);
97
+ let stage, backup, keepRecovery = false;
98
+ try {
99
+ if (!active())
100
+ throw new agent_protocol_1.AgentError('disconnected', 'The development connection ended.');
101
+ if (!directory(parent))
102
+ fs_1.default.mkdirSync(parent);
103
+ checkTarget(parent, target, workspaceId);
104
+ const parentIdentity = fs_1.default.statSync(parent);
105
+ // Keep staged writes outside docs: replacing docs with a symlink while an
106
+ // upload is in progress must never redirect those writes. The final parent
107
+ // identity check below still rejects publication into a replaced directory.
108
+ stage = await fs_1.default.promises.mkdtemp(path_1.default.join(root, '.scripting-docs-stage-'));
109
+ for (const file of files) {
110
+ if (!active())
111
+ throw new agent_protocol_1.AgentError('disconnected', 'The development connection ended.');
112
+ const destination = path_1.default.join(stage, file.path);
113
+ await fs_1.default.promises.mkdir(path_1.default.dirname(destination), { recursive: true });
114
+ await fs_1.default.promises.writeFile(destination, file.data, { flag: 'wx' });
115
+ }
116
+ await fs_1.default.promises.writeFile(path_1.default.join(stage, marker), JSON.stringify({ owner, workspaceId }), { flag: 'wx' });
117
+ // No await between final boundary/session validation and commit/rollback.
118
+ checkTarget(parent, target, workspaceId);
119
+ const currentParent = fs_1.default.statSync(parent);
120
+ if (currentParent.dev !== parentIdentity.dev || currentParent.ino !== parentIdentity.ino || fs_1.default.realpathSync(parent) !== parent || !active())
121
+ throw new agent_protocol_1.AgentError('disconnected', 'The workspace or development connection changed.');
122
+ if (stat(target)) {
123
+ backup = path_1.default.join(parent, '.scripting-docs-backup-' + crypto_1.default.randomUUID());
124
+ fs_1.default.renameSync(target, backup);
125
+ }
126
+ try {
127
+ fs_1.default.renameSync(stage, target);
128
+ stage = undefined;
129
+ }
130
+ catch (e) {
131
+ if (backup) {
132
+ try {
133
+ fs_1.default.renameSync(backup, target);
134
+ backup = undefined;
135
+ }
136
+ catch {
137
+ keepRecovery = true;
138
+ throw new agent_protocol_1.AgentError('recovery_required', 'Preserve the documentation stage and backup directories for recovery.');
139
+ }
140
+ }
141
+ throw e;
142
+ }
143
+ return { success: true, path: exports.documentationPath, fileCount: files.length };
144
+ }
145
+ finally {
146
+ try {
147
+ if (!keepRecovery) {
148
+ if (stage)
149
+ await fs_1.default.promises.rm(stage, { recursive: true, force: true });
150
+ if (backup)
151
+ await fs_1.default.promises.rm(backup, { recursive: true, force: true });
152
+ }
153
+ }
154
+ finally {
155
+ publishing.delete(root);
156
+ }
157
+ }
158
+ }
@@ -7,6 +7,8 @@ exports.initHttpRouter = initHttpRouter;
7
7
  const express_1 = __importDefault(require("express"));
8
8
  const controller_1 = require("./controller");
9
9
  const chalk_1 = __importDefault(require("chalk"));
10
+ const documentation_sync_1 = require("./documentation_sync");
11
+ const agent_protocol_1 = require("./agent_protocol");
10
12
  const getFileContent = (req, res) => {
11
13
  const { socketId, scriptName, relativePath, } = req.query;
12
14
  if (!socketId) {
@@ -157,6 +159,27 @@ const syncScriptFromServer = (req, res) => {
157
159
  function initHttpRouter(app) {
158
160
  app.use(express_1.default.json({ limit: '50mb' }));
159
161
  app.use(express_1.default.urlencoded({ extended: true }));
162
+ app.get('/developmentWorkspace', (req, res) => {
163
+ const ctrl = typeof req.query.socketId === 'string' ? controller_1.Controller.get(req.query.socketId) : undefined;
164
+ if (!ctrl?.socket?.connected) {
165
+ res.status(409).json({ error: { code: 'disconnected', message: 'Connect to a development server first.' } });
166
+ return;
167
+ }
168
+ res.json({ success: true, ...(0, documentation_sync_1.developmentWorkspace)(ctrl.workspace) });
169
+ });
170
+ app.post('/syncDocumentation', async (req, res) => {
171
+ const ctrl = typeof req.body?.socketId === 'string' ? controller_1.Controller.get(req.body.socketId) : undefined;
172
+ if (!ctrl?.socket?.connected) {
173
+ res.status(409).json({ error: { code: 'disconnected', message: 'The development connection ended.' } });
174
+ return;
175
+ }
176
+ try {
177
+ res.json(await (0, documentation_sync_1.syncDocumentation)(ctrl.workspace, req.body, () => ctrl.socket?.connected === true));
178
+ }
179
+ catch (e) {
180
+ res.status(409).json({ error: (0, agent_protocol_1.failure)(e) });
181
+ }
182
+ });
160
183
  app.get("/getFileContent", getFileContent);
161
184
  app.get("/getFileData", getFileData);
162
185
  app.post("/putFileData", express_1.default.raw({ type: 'application/octet-stream', limit: '100mb' }), putFileData);
@@ -31,6 +31,7 @@ export declare class SkillSyncController {
31
31
  stop(): Promise<void>;
32
32
  close(): Promise<void>;
33
33
  private names;
34
+ private catalogSnapshot;
34
35
  private watchCatalog;
35
36
  private request;
36
37
  private schedule;
@@ -205,13 +205,44 @@ class SkillSyncController {
205
205
  const root = ensureRoot(this.workspace);
206
206
  return fs_1.default.readdirSync(root, { withFileTypes: true }).filter(item => item.isDirectory() && !item.isSymbolicLink() && (0, agent_protocol_1.validPackageName)(item.name) && fs_1.default.existsSync(path_1.default.join(root, item.name, 'SKILL.md'))).map(x => x.name).sort().slice(0, 1000);
207
207
  }
208
+ async catalogSnapshot() {
209
+ const names = await this.names();
210
+ const entries = [];
211
+ for (const name of names) {
212
+ let title = name, description;
213
+ try {
214
+ const file = path_1.default.join(this.workspace, 'skills', name, 'SKILL.md');
215
+ const info = await fs_1.default.promises.lstat(file);
216
+ if (info.isFile() && !info.isSymbolicLink() && info.size <= 512 * 1024) {
217
+ const text = await fs_1.default.promises.readFile(file, 'utf8');
218
+ const header = text.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)?.[1];
219
+ const scalar = (value) => {
220
+ const trimmed = value?.trim();
221
+ if (trimmed?.startsWith('"')) {
222
+ try {
223
+ return String(JSON.parse(trimmed));
224
+ }
225
+ catch { /* Use the same quote trimming as App. */ }
226
+ }
227
+ return trimmed?.replace(/^["']|["']$/g, '');
228
+ };
229
+ description = scalar(header?.match(/^description:\s*(.*)$/m)?.[1])?.slice(0, 4096);
230
+ title = scalar(header?.match(/^\s+display_name:\s*(.*)$/m)?.[1])?.slice(0, 256) || name;
231
+ }
232
+ }
233
+ catch { /* A catalog is still useful when a package is unreadable. */ }
234
+ entries.push({ name, title, description });
235
+ }
236
+ return { names, entries };
237
+ }
208
238
  watchCatalog() {
209
239
  if (this.catalog)
210
240
  return;
211
241
  this.catalog = chokidar_1.default.watch(ensureRoot(this.workspace), { depth: 1, ignoreInitial: true, ignored: p => path_1.default.relative(path_1.default.join(this.workspace, 'skills'), p).split(path_1.default.sep).some(x => x.startsWith('.') || x === 'node_modules') });
212
242
  const refresh = () => { if (this.catalogTimer)
213
- clearTimeout(this.catalogTimer); this.catalogTimer = setTimeout(() => { void this.names().then(names => this.socket.emit('skillSyncCatalog', { version: 1, names })).catch(() => { }); }, 200); };
214
- this.catalog.on('add', refresh).on('unlink', refresh).on('addDir', refresh).on('unlinkDir', refresh).on('error', () => { });
243
+ clearTimeout(this.catalogTimer); this.catalogTimer = setTimeout(() => { void this.catalogSnapshot().then(catalog => { if (!this.closed)
244
+ this.socket.emit('skillSyncCatalog', { version: 1, ...catalog }); }).catch(() => { }); }, 200); };
245
+ this.catalog.on('add', refresh).on('change', refresh).on('unlink', refresh).on('addDir', refresh).on('unlinkDir', refresh).on('error', () => { });
215
246
  }
216
247
  async request(r) {
217
248
  if (this.closed || !this.socket.connected)
@@ -220,7 +251,7 @@ class SkillSyncController {
220
251
  throw new agent_protocol_1.AgentError('unsupported_capability', 'Unsupported skill sync version.');
221
252
  if (r.method === 'list') {
222
253
  this.watchCatalog();
223
- return { names: await this.names(), ignore: skillIgnores(this.ignore) };
254
+ return { ...await this.catalogSnapshot(), ignore: skillIgnores(this.ignore) };
224
255
  }
225
256
  if (r.method === 'inspect')
226
257
  return { snapshot: await inspectSkill(this.workspace, r.name, this.ignore) ?? null };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "scripting-cli",
3
- "version": "2.0.0",
3
+ "version": "2.0.2",
4
4
  "description": "This plugin integrates the desktop editor synchronization feature of the Scripting app.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -18,20 +18,20 @@ Use the connected App as the source of API documentation and runtime/rendering e
18
18
  - `scripts list --json` lists App scripts. `scripts inspect "Script" --json` returns source file hashes and the current App revision without modifying it.
19
19
  - `scripts create "Script" --json` creates from an existing desktop script, or scaffolds a minimal desktop script if absent; App name collisions are rejected. It does not overwrite a colliding App script.
20
20
  - `scripts attach "Script" --json` syncs the desktop snapshot and selects that App debug script. Matching source needs no replacement flag. If source differs, `script_conflict` returns the current App revision. Inspect both versions and resolve the user's intended source before replacing anything. Only when the user has authorized that overwrite, use `scripts attach "Script" --replace --expected-revision <inspected-App-revision> --json`. A changed revision is a fresh conflict, not a reason to retry blindly.
21
- - Script changes need App foreground and refuse an existing manual run or preview. Do not stop unrelated work, overwrite scripts, install the skill globally, or publish packages merely to make a command succeed.
21
+ - Script create/attach can bind in the background; the debug page appears upon foregrounding without rerunning the command. They refuse an existing manual run or preview. Do not stop unrelated work, overwrite scripts, install the skill globally, or publish packages merely to make a command succeed.
22
22
 
23
23
  ## Iterate using evidence
24
24
 
25
25
  - Edit only the requested script. `run "Script" --query-parameters '{"sample":true}' --json` takes a bounded snapshot and executes only after the App confirms its revision. Use `requestedRevision` versus `revision` to distinguish attempted from applied source. Changes after snapshot capture belong to another run.
26
26
  - Ordinary scripts should call `Script.exit(result)` to finish. Inspect `status`, `error.code`, `result.value`, stdout/stderr and diagnostics; a nonzero result is not success because a page once appeared. Diagnostic paths are script-relative, lines/columns are one-based. Runtime errors and TypeScript diagnostics are distinct evidence.
27
27
  - Use `--stream` for JSONL stage/log/diagnostic events followed by one `type: result` record. It replaces single-result stdout formatting; never parse the entire stream as one JSON value. A `gap` means retained events were lost; final logs may also report `logsTruncated`.
28
- - Use `run "Script" --screenshot --output ./artifacts --json` for a finite UI preview. The App must be foreground. The screenshot belongs to this run, then the run ends; `preview_capture` does not mean the script called `Script.exit`.
28
+ - Use `run "Script" --screenshot --output ./artifacts --json` for a finite UI preview. Capture is attempted in either App state; backgrounding alone does not cancel the run. Treat unavailable views or timeouts as actual failures. The screenshot belongs to this run, then the run ends; `preview_capture` does not mean the script called `Script.exit`.
29
29
  - For asynchronous UI, emit a distinctive exact `console.log("SCREENSHOT_READY")` after the intended data/state is ready and invoke `--screenshot --ready-log SCREENSHOT_READY --capture-after 1`. Only the current run's matching non-error log counts. The marker is the script author's readiness contract, not automatic proof all remote work is complete. Missing signal/view or background transition must remain a failure.
30
30
  - Open the actual PNG listed in `result.artifacts` using the host's image-viewing tool. Compare the requested layout and content, fix specific discrepancies, and rerun the affected case. A file path alone does not prove rendering correctness. Keep requested final output files; clean only disposable artifacts you created.
31
31
 
32
32
  ## Widgets and batches
33
33
 
34
- `widget "Script" --family systemMedium --parameter demo --screenshot --output ./artifacts --json` renders `widget.tsx` in foreground, captures if requested, then closes. Omit `--screenshot` for render-and-close without an image. This does not install a home-screen widget or verify WidgetKit timeline delivery, and it does not overwrite normal preview preferences.
34
+ `widget "Script" --family systemMedium --parameter demo --screenshot --output ./artifacts --json` attempts rendering `widget.tsx` in either App state, captures if requested, then closes. Require actual render/image evidence; report the real renderer error or timeout when unavailable. Omit `--screenshot` for render-and-close without an image. This does not install a home-screen widget or verify WidgetKit timeline delivery, and it does not overwrite normal preview preferences.
35
35
 
36
36
  For multiple sizes or parameters, create a JSON array such as:
37
37
 
@@ -51,7 +51,7 @@ The overall deadline is finite (`--timeout` 1–120 seconds, default 30). Do not
51
51
 
52
52
  Ctrl-C or `jobs cancel <run-id> --json` requests cancellation of that owned run. `cancelling` is not confirmed termination. Inspect `jobs show <run-id> --json` until a terminal state; a disconnect/timeout is failure with potentially uncertain side effects, so do not replay mutating scripts automatically. `jobs events <run-id> --after <cursor> --json` reads recent events. Results expire; absence is not proof of no execution.
53
53
 
54
- Preserve App permission checks. Handle `needs_foreground`, `busy`, `unsupported_capability`, `script_conflict`, `execution_timeout` and `screenshot_unavailable` according to their actual meaning. Report unavailable device, VoiceOver, long-background, audio interruption or real WidgetKit evidence as pending. Do not claim those from desktop mocks or Simulator success.
54
+ Preserve App permission checks. Older Apps may still return `needs_foreground`; do not proactively block a request solely because status reports background. Handle `busy`, `unsupported_capability`, `script_conflict`, `execution_timeout` and `screenshot_unavailable` according to their actual meaning. Report unavailable device, VoiceOver, long-background, audio interruption or real WidgetKit evidence as pending. Do not claim those from desktop mocks or Simulator success.
55
55
 
56
56
  ## Develop a Skill package
57
57