scripting-cli 1.4.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,6 +11,8 @@ const chalk_1 = __importDefault(require("chalk"));
11
11
  const path_1 = __importDefault(require("path"));
12
12
  const const_1 = require("./const");
13
13
  const editors_1 = require("./editors");
14
+ const agent_broker_1 = require("./agent_broker");
15
+ const agent_protocol_1 = require("./agent_protocol");
14
16
  class Controller {
15
17
  static instances = new Map();
16
18
  static create(socket, config) {
@@ -21,6 +23,17 @@ class Controller {
21
23
  static get(socketId) {
22
24
  return Controller.instances.get(socketId);
23
25
  }
26
+ agentPauses = 0;
27
+ pendingAgentChanges = new Map();
28
+ sendChange(event, data) {
29
+ if (data.scriptName !== this.scriptName)
30
+ return;
31
+ if (this.agentPauses) {
32
+ this.pendingAgentChanges.set(data.filePath, { event, data });
33
+ return;
34
+ }
35
+ this.socket?.emit(event, data);
36
+ }
24
37
  watcher = null;
25
38
  scriptName = null;
26
39
  socket = null;
@@ -28,6 +41,43 @@ class Controller {
28
41
  constructor(socket, config) {
29
42
  this.config = config;
30
43
  this.socket = socket;
44
+ agent_broker_1.agentBroker.register(socket, {
45
+ project: () => this.scriptName,
46
+ types: async (files) => {
47
+ const directory = path_1.default.join(process.cwd(), 'dts');
48
+ if (fs_1.default.existsSync(directory) && fs_1.default.lstatSync(directory).isSymbolicLink())
49
+ throw new Error('Type directory cannot be a symlink.');
50
+ for (const name of Object.keys(files)) {
51
+ const file = path_1.default.join(directory, name);
52
+ if (fs_1.default.existsSync(file) && fs_1.default.lstatSync(file).isSymbolicLink())
53
+ throw new Error('Type file cannot be a symlink.');
54
+ }
55
+ await (0, util_1.writeDtsFiles)(files);
56
+ for (const [name, value] of Object.entries(files))
57
+ if (fs_1.default.readFileSync(path_1.default.join(directory, name), 'utf8') !== value)
58
+ throw new Error('Type declarations were not written.');
59
+ },
60
+ switchProject: async (project) => {
61
+ await this.watcher?.close();
62
+ this.watcher = null;
63
+ this.pendingAgentChanges.clear();
64
+ this.scriptName = project;
65
+ this.createWatcher(project, true);
66
+ },
67
+ ignore: () => this.config.ignore,
68
+ pause: () => { this.agentPauses++; },
69
+ resume: snapshot => {
70
+ this.agentPauses = Math.max(0, this.agentPauses - 1);
71
+ if (!this.agentPauses) {
72
+ for (const { event, data } of this.pendingAgentChanges.values()) {
73
+ if (snapshot && this.scriptName && (0, agent_protocol_1.isAcknowledgedChange)(process.cwd(), this.scriptName, data.filePath, snapshot))
74
+ continue;
75
+ this.socket?.emit(event, data);
76
+ }
77
+ this.pendingAgentChanges.clear();
78
+ }
79
+ },
80
+ });
31
81
  socket.emit("socketId", socket.id);
32
82
  // socket.on('syncScriptFromClient', this.handleSyncScriptFromClient);
33
83
  // socket.on("syncScriptFromServer", this.handleSyncScriptFromClient);
@@ -50,11 +100,12 @@ class Controller {
50
100
  socket.emit("serverScripts", serverScriptNames);
51
101
  });
52
102
  }
53
- createWatcher(scriptName) {
103
+ createWatcher(scriptName, ignoreInitial = false) {
54
104
  const scriptDir = (0, util_1.getScriptPath)(scriptName);
55
105
  this.watcher = chokidar_1.default.watch(scriptDir, {
56
106
  ignored: (filePath) => (0, util_1.isIgnoredPath)((0, util_1.getRelativePath)(scriptDir, filePath), this.config.ignore),
57
107
  persistent: true,
108
+ ignoreInitial,
58
109
  });
59
110
  const updateHandler = (filePath) => {
60
111
  if (!(0, util_1.isBinaryFile)(filePath)) {
@@ -68,7 +119,7 @@ class Controller {
68
119
  const hash = (0, util_1.md5)(content);
69
120
  const relativePath = (0, util_1.getRelativePath)(scriptDir, filePath);
70
121
  console.log(`[${chalk_1.default.bold.blue(scriptName)}] File changed: [${hash}]${relativePath}`);
71
- this.socket?.emit('fileChange', {
122
+ this.sendChange('fileChange', {
72
123
  scriptName,
73
124
  filePath: relativePath,
74
125
  hash,
@@ -79,7 +130,7 @@ class Controller {
79
130
  // Other file types, just notify the client to reload the file
80
131
  const relativePath = (0, util_1.getRelativePath)(scriptDir, filePath);
81
132
  console.log(`[${chalk_1.default.bold.blue(scriptName)}] File changed: ${relativePath}`);
82
- this.socket?.emit('otherFileChange', {
133
+ this.sendChange('otherFileChange', {
83
134
  scriptName,
84
135
  filePath: relativePath,
85
136
  });
@@ -87,7 +138,7 @@ class Controller {
87
138
  };
88
139
  const deleteHandler = (filePath) => {
89
140
  const relativePath = (0, util_1.getRelativePath)(scriptDir, filePath);
90
- this.socket?.emit('deleteFile', {
141
+ this.sendChange('deleteFile', {
91
142
  scriptName,
92
143
  filePath: relativePath,
93
144
  });
@@ -102,6 +153,10 @@ class Controller {
102
153
  }
103
154
  handleSyncScriptFromClient = async (data, ack) => {
104
155
  try {
156
+ if (this.agentPauses) {
157
+ ack({ error: 'A desktop run is active.' });
158
+ return;
159
+ }
105
160
  if (data.scriptName === this.scriptName) {
106
161
  ack({
107
162
  error: `Script [${data.scriptName}] is already initialized`,
@@ -116,6 +171,7 @@ class Controller {
116
171
  await (0, util_1.writeDtsFiles)({
117
172
  [const_1.globalDtsFileName]: data[const_1.globalDtsFileName],
118
173
  [const_1.scriptingDtsFileName]: data[const_1.scriptingDtsFileName],
174
+ ...(data.extraDtsFiles ?? {}),
119
175
  });
120
176
  this.scriptName = data.scriptName;
121
177
  const scriptDir = (0, util_1.getScriptPath)(data.scriptName);
@@ -152,6 +208,10 @@ class Controller {
152
208
  };
153
209
  handleSyncScriptFromServer = async (data, ack) => {
154
210
  try {
211
+ if (this.agentPauses) {
212
+ ack({ error: 'A desktop run is active.' });
213
+ return;
214
+ }
155
215
  if (this.scriptName === data.scriptName) {
156
216
  ack({
157
217
  error: `Script ${data.scriptName} is already initialized`,
@@ -166,6 +226,7 @@ class Controller {
166
226
  await (0, util_1.writeDtsFiles)({
167
227
  [const_1.globalDtsFileName]: data[const_1.globalDtsFileName],
168
228
  [const_1.scriptingDtsFileName]: data[const_1.scriptingDtsFileName],
229
+ ...(data.extraDtsFiles ?? {}),
169
230
  });
170
231
  const scriptDir = (0, util_1.getScriptPath)(data.scriptName);
171
232
  if (!fs_1.default.existsSync(scriptDir)) {
@@ -14,13 +14,14 @@ const chalk_1 = __importDefault(require("chalk"));
14
14
  const qrcode_terminal_1 = __importDefault(require("qrcode-terminal"));
15
15
  const util_1 = require("./util");
16
16
  const controller_1 = require("./controller");
17
+ const agent_broker_1 = require("./agent_broker");
18
+ const agent_control_1 = require("./agent_control");
17
19
  const http_router_1 = require("./http_router");
18
20
  const config_1 = require("./config");
19
21
  const editors_1 = require("./editors");
20
22
  const app = (0, express_1.default)();
21
23
  const server = http_1.default.createServer(app);
22
- const io = new socket_io_1.Server(server);
23
- const bonjour = (0, bonjour_1.default)();
24
+ const io = new socket_io_1.Server(server, { maxHttpBufferSize: 16 * 1024 * 1024 });
24
25
  // Keywords to identify VPN/virtual network adapters that should be excluded
25
26
  const VIRTUAL_ADAPTER_KEYWORDS = [
26
27
  'virtual',
@@ -101,6 +102,8 @@ async function startServer({ port, noAutoOpen, startBonjourService, editorOverri
101
102
  reconfigure,
102
103
  });
103
104
  const PORT = config.port;
105
+ const bonjour = startBonjourService ? (0, bonjour_1.default)() : undefined;
106
+ await (0, agent_control_1.startAgentControl)(agent_broker_1.agentBroker);
104
107
  const editor = (0, editors_1.getEditor)(config.editor);
105
108
  console.log(chalk_1.default.gray(`Editor: ${editor?.displayName ?? config.editor}`));
106
109
  (0, http_router_1.initHttpRouter)(app);
@@ -125,21 +128,22 @@ async function startServer({ port, noAutoOpen, startBonjourService, editorOverri
125
128
  console.log(`Server listening on ${chalk_1.default.bold.blue(address)}\nYou can ${chalk_1.default.green.bold("use the Scripting app to scan")} the QR code and connect: `);
126
129
  }
127
130
  qrcode_terminal_1.default.generate(address, { small: true });
128
- if (startBonjourService) {
131
+ if (startBonjourService && bonjour) {
132
+ const publishedBonjour = bonjour;
129
133
  function gracefulShutdown() {
130
134
  console.log('Shutting down Bonjour...');
131
135
  service.stop(() => {
132
- bonjour.unpublishAll(() => {
136
+ publishedBonjour.unpublishAll(() => {
133
137
  // wait for 500ms,let goodbye message be sent completely
134
138
  setTimeout(() => {
135
- bonjour.destroy();
139
+ publishedBonjour.destroy();
136
140
  console.log('Bonjour services have been shut down properly.');
137
141
  process.exit(0);
138
142
  }, 500);
139
143
  });
140
144
  });
141
145
  }
142
- const service = bonjour.publish({
146
+ const service = publishedBonjour.publish({
143
147
  name: 'Scripting-service',
144
148
  type: 'http',
145
149
  port: PORT,
package/dist/util.js CHANGED
@@ -123,8 +123,11 @@ function createTsConfig() {
123
123
  }
124
124
  },
125
125
  "include": [
126
- "./dts/${const_1.globalDtsFileName}",
126
+ "./dts/*.d.ts",
127
127
  "scripts"
128
+ ],
129
+ "exclude": [
130
+ "./dts/${const_1.scriptingDtsFileName}"
128
131
  ]
129
132
  }`;
130
133
  const filePath = getPath('tsconfig.json');
@@ -132,20 +135,35 @@ function createTsConfig() {
132
135
  if (!fs_1.default.existsSync(filePath)) {
133
136
  fs_1.default.writeFileSync(filePath, tsconfigContent);
134
137
  console.log(chalk_1.default.green('tsconfig.json created.'));
138
+ return;
139
+ }
140
+ // Migrate an existing tsconfig to the current include/exclude shape:
141
+ // - all ambient dts are picked up via the "./dts/*.d.ts" glob (so newly synced
142
+ // node.d.ts / web-fetch.d.ts / safari-ext.d.ts are covered automatically),
143
+ // - scripting.d.ts is excluded from the root program (it stays importable via
144
+ // the "scripting" paths mapping). Existing custom entries are preserved.
145
+ const tsconfig = JSON.parse(fs_1.default.readFileSync(filePath, 'utf-8'));
146
+ const include = Array.isArray(tsconfig.include) ? [...tsconfig.include] : [];
147
+ const exclude = Array.isArray(tsconfig.exclude) ? [...tsconfig.exclude] : [];
148
+ // Drop the stale explicit global entry now covered by the glob.
149
+ let nextInclude = include.filter((x) => x !== `./dts/${const_1.globalDtsFileName}`);
150
+ if (!nextInclude.includes('./dts/*.d.ts'))
151
+ nextInclude.unshift('./dts/*.d.ts');
152
+ if (!nextInclude.includes('scripts'))
153
+ nextInclude.push('scripts');
154
+ const nextExclude = exclude.includes(`./dts/${const_1.scriptingDtsFileName}`)
155
+ ? exclude
156
+ : [...exclude, `./dts/${const_1.scriptingDtsFileName}`];
157
+ const includeChanged = JSON.stringify(nextInclude) !== JSON.stringify(include);
158
+ const excludeChanged = JSON.stringify(nextExclude) !== JSON.stringify(exclude);
159
+ if (includeChanged || excludeChanged) {
160
+ tsconfig.include = nextInclude;
161
+ tsconfig.exclude = nextExclude;
162
+ fs_1.default.writeFileSync(filePath, JSON.stringify(tsconfig, null, 2));
163
+ console.log(chalk_1.default.yellow('tsconfig.json updated to sync all ambient type declarations.'));
135
164
  }
136
165
  else {
137
- const tsconfig = JSON.parse(fs_1.default.readFileSync(filePath, 'utf-8'));
138
- if (tsconfig.include && !tsconfig.include.includes('scripts')) {
139
- tsconfig.include = [
140
- `./dts/${const_1.globalDtsFileName}`,
141
- "scripts"
142
- ];
143
- fs_1.default.writeFileSync(filePath, JSON.stringify(tsconfig, null, 2));
144
- console.log(chalk_1.default.yellow('tsconfig.json updated to include scripts directory.'));
145
- }
146
- else {
147
- console.log(chalk_1.default.gray('tsconfig.json already exists.'));
148
- }
166
+ console.log(chalk_1.default.gray('tsconfig.json already exists.'));
149
167
  }
150
168
  }
151
169
  function ensureScriptsDirectory() {
@@ -166,6 +184,14 @@ function ensureDirectoryExistence(filePath) {
166
184
  }
167
185
  async function writeDtsFiles(files) {
168
186
  await Promise.all(Object.entries(files).map(async ([filename, content]) => {
187
+ // These names arrive over the wire; only allow a plain `.d.ts` basename so
188
+ // a crafted name can't escape the dts/ directory.
189
+ if (typeof content !== 'string' ||
190
+ filename !== path_1.default.basename(filename) ||
191
+ !filename.endsWith('.d.ts')) {
192
+ console.log(chalk_1.default.red(`Skipped writing dts file with unexpected name: ${filename}`));
193
+ return;
194
+ }
169
195
  const filePath = getPath(`dts/${filename}`);
170
196
  ensureDirectoryExistence(filePath);
171
197
  await fs_1.default
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "scripting-cli",
3
- "version": "1.4.0",
3
+ "version": "1.6.0",
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",
@@ -14,14 +14,15 @@
14
14
  }
15
15
  },
16
16
  "files": [
17
- "dist"
17
+ "dist",
18
+ "skills"
18
19
  ],
19
20
  "scripts": {
20
21
  "build": "npx tsc && chmod +x dist/cli.js",
21
22
  "start": "node dist/cli.js",
22
23
  "dev": "ts-node src/cli.ts",
23
24
  "help": "node dist/cli.js --help",
24
- "test": "echo \"Error: no test specified\" && exit 1"
25
+ "test": "npm run build && node --test test/*.test.js"
25
26
  },
26
27
  "keywords": [
27
28
  "Scripting app",
@@ -0,0 +1,54 @@
1
+ ---
2
+ name: scripting-development
3
+ description: Develop and debug Scripting App scripts or widgets from a desktop workspace using scripting-cli, connected App documentation, execution results, live logs and rendered screenshots. Use for Scripting scripts and widgets, not unrelated iOS app development.
4
+ ---
5
+
6
+ # Scripting development
7
+
8
+ Use the connected App as the source of API documentation and runtime/rendering evidence. Run commands from the workspace where `scripting-cli start` is already running; its projects live under `scripts/<project>/`. A local CLI checkout can be invoked with `node /absolute/path/to/scripting-cli/dist/cli.js` instead of a published binary.
9
+
10
+ ## Establish context
11
+
12
+ - Read the workspace's instructions and the intended project's existing files before changing code.
13
+ - Run `scripting-cli devices --json`, select `--device <id>` when several devices exist, then query `status --json`. Inspect `responsive`, capabilities, current project, foreground state and `activeRunId`; connection alone does not prove execution.
14
+ - Search with `docs search "<topic>" --json`, read the exact returned ID with `docs get <id> --lang en|zh --json`, and use `api get <symbol> --json` for declarations. Do not invent APIs from a screenshot or substitute stale offline docs for the connected App version.
15
+
16
+ ## Bind a project deliberately
17
+
18
+ - `projects list --json` lists App projects. `projects inspect "Project" --json` returns source file hashes and the current App revision without modifying it.
19
+ - `projects create "Project" --json` creates from an existing desktop project, or scaffolds a minimal desktop script if absent; App name collisions are rejected. It does not overwrite a colliding App project.
20
+ - `projects attach "Project" --json` syncs the desktop snapshot and selects that App debug project. Matching source needs no replacement flag. If source differs, `project_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 `projects attach "Project" --replace --expected-revision <inspected-App-revision> --json`. A changed revision is a fresh conflict, not a reason to retry blindly.
21
+ - Project changes need App foreground and refuse an existing manual run or preview. Do not stop unrelated work, overwrite projects, install the skill globally, or publish packages merely to make a command succeed.
22
+
23
+ ## Iterate using evidence
24
+
25
+ - Edit only the requested project. `run "Project" --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
+ - 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 project-relative, lines/columns are one-based. Runtime errors and TypeScript diagnostics are distinct evidence.
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 "Project" --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`.
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
+ - 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
+
32
+ ## Widgets and batches
33
+
34
+ `widget "Project" --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.
35
+
36
+ For multiple sizes or parameters, create a JSON array such as:
37
+
38
+ ```json
39
+ [
40
+ {"id":"small-default","family":"systemSmall","parameter":"default","screenshot":true},
41
+ {"id":"medium-empty","family":"systemMedium","parameter":"empty","screenshot":true},
42
+ {"id":"render-only","family":"systemSmall","screenshot":false}
43
+ ]
44
+ ```
45
+
46
+ Invoke `widget-batch "Project" --cases ./cases.json --timeout 60 --output ./artifacts --stream`. At most eight unique safe case IDs run serially from one source snapshot. Inspect each case's status, skipped count, and corresponding `<output>/<run-id>/<case-id>.png`. A failed/cancelled batch may contain earlier completed cases; never claim all cases passed from partial results.
47
+
48
+ ## Failure and cancellation
49
+
50
+ The overall deadline is finite (`--timeout` 1–120 seconds, default 30). Do not increase timeouts to hide missing completion, failed readiness or a broken fixture. Fix the cause or choose a justified budget before rerunning.
51
+
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
+
54
+ Preserve App permission checks. Handle `needs_foreground`, `busy`, `unsupported_capability`, `project_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.