scripting-cli 1.5.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,6 +11,9 @@ 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 skill_sync_1 = require("./skill_sync");
16
+ const agent_protocol_1 = require("./agent_protocol");
14
17
  class Controller {
15
18
  static instances = new Map();
16
19
  static create(socket, config) {
@@ -21,6 +24,18 @@ class Controller {
21
24
  static get(socketId) {
22
25
  return Controller.instances.get(socketId);
23
26
  }
27
+ agentPauses = 0;
28
+ pendingAgentChanges = new Map();
29
+ sendChange(event, data) {
30
+ if (data.scriptName !== this.scriptName)
31
+ return;
32
+ if (this.agentPauses) {
33
+ this.pendingAgentChanges.set(data.filePath, { event, data });
34
+ return;
35
+ }
36
+ this.socket?.emit(event, data);
37
+ }
38
+ skillSync;
24
39
  watcher = null;
25
40
  scriptName = null;
26
41
  socket = null;
@@ -28,6 +43,54 @@ class Controller {
28
43
  constructor(socket, config) {
29
44
  this.config = config;
30
45
  this.socket = socket;
46
+ this.skillSync = new skill_sync_1.SkillSyncController(socket, process.cwd(), config.ignore, async () => {
47
+ if (this.agentPauses)
48
+ throw new Error('A desktop run is active.');
49
+ await this.watcher?.close();
50
+ this.watcher = null;
51
+ this.scriptName = null;
52
+ this.pendingAgentChanges.clear();
53
+ });
54
+ agent_broker_1.agentBroker.register(socket, {
55
+ script: () => this.scriptName,
56
+ skill: () => this.skillSync.selected(),
57
+ skillReady: () => this.skillSync.drain(),
58
+ types: async (files) => {
59
+ const directory = path_1.default.join(process.cwd(), 'dts');
60
+ if (fs_1.default.existsSync(directory) && fs_1.default.lstatSync(directory).isSymbolicLink())
61
+ throw new Error('Type directory cannot be a symlink.');
62
+ for (const name of Object.keys(files)) {
63
+ const file = path_1.default.join(directory, name);
64
+ if (fs_1.default.existsSync(file) && fs_1.default.lstatSync(file).isSymbolicLink())
65
+ throw new Error('Type file cannot be a symlink.');
66
+ }
67
+ await (0, util_1.writeDtsFiles)(files);
68
+ for (const [name, value] of Object.entries(files))
69
+ if (fs_1.default.readFileSync(path_1.default.join(directory, name), 'utf8') !== value)
70
+ throw new Error('Type declarations were not written.');
71
+ },
72
+ switchScript: async (script) => {
73
+ await this.watcher?.close();
74
+ this.watcher = null;
75
+ this.pendingAgentChanges.clear();
76
+ this.scriptName = script;
77
+ this.createWatcher(script, true);
78
+ },
79
+ ignore: () => this.config.ignore,
80
+ pause: () => { this.agentPauses++; this.skillSync.pause(); },
81
+ resume: (snapshot, bindingId) => {
82
+ this.skillSync.resume(bindingId === this.skillSync.selected()?.bindingId ? snapshot : undefined);
83
+ this.agentPauses = Math.max(0, this.agentPauses - 1);
84
+ if (!this.agentPauses) {
85
+ for (const { event, data } of this.pendingAgentChanges.values()) {
86
+ if (snapshot && this.scriptName && (0, agent_protocol_1.isAcknowledgedChange)(process.cwd(), this.scriptName, data.filePath, snapshot))
87
+ continue;
88
+ this.socket?.emit(event, data);
89
+ }
90
+ this.pendingAgentChanges.clear();
91
+ }
92
+ },
93
+ });
31
94
  socket.emit("socketId", socket.id);
32
95
  // socket.on('syncScriptFromClient', this.handleSyncScriptFromClient);
33
96
  // socket.on("syncScriptFromServer", this.handleSyncScriptFromClient);
@@ -38,6 +101,7 @@ class Controller {
38
101
  socket.on('disconnect', (reason) => {
39
102
  console.log(chalk_1.default.gray(`Client [${socket.id}] disconnected: ${reason}`));
40
103
  this.watcher?.close();
104
+ void this.skillSync.close();
41
105
  this.watcher = null;
42
106
  this.scriptName = null;
43
107
  Controller.instances.delete(socket.id);
@@ -50,11 +114,12 @@ class Controller {
50
114
  socket.emit("serverScripts", serverScriptNames);
51
115
  });
52
116
  }
53
- createWatcher(scriptName) {
117
+ createWatcher(scriptName, ignoreInitial = false) {
54
118
  const scriptDir = (0, util_1.getScriptPath)(scriptName);
55
119
  this.watcher = chokidar_1.default.watch(scriptDir, {
56
120
  ignored: (filePath) => (0, util_1.isIgnoredPath)((0, util_1.getRelativePath)(scriptDir, filePath), this.config.ignore),
57
121
  persistent: true,
122
+ ignoreInitial,
58
123
  });
59
124
  const updateHandler = (filePath) => {
60
125
  if (!(0, util_1.isBinaryFile)(filePath)) {
@@ -68,7 +133,7 @@ class Controller {
68
133
  const hash = (0, util_1.md5)(content);
69
134
  const relativePath = (0, util_1.getRelativePath)(scriptDir, filePath);
70
135
  console.log(`[${chalk_1.default.bold.blue(scriptName)}] File changed: [${hash}]${relativePath}`);
71
- this.socket?.emit('fileChange', {
136
+ this.sendChange('fileChange', {
72
137
  scriptName,
73
138
  filePath: relativePath,
74
139
  hash,
@@ -79,7 +144,7 @@ class Controller {
79
144
  // Other file types, just notify the client to reload the file
80
145
  const relativePath = (0, util_1.getRelativePath)(scriptDir, filePath);
81
146
  console.log(`[${chalk_1.default.bold.blue(scriptName)}] File changed: ${relativePath}`);
82
- this.socket?.emit('otherFileChange', {
147
+ this.sendChange('otherFileChange', {
83
148
  scriptName,
84
149
  filePath: relativePath,
85
150
  });
@@ -87,7 +152,7 @@ class Controller {
87
152
  };
88
153
  const deleteHandler = (filePath) => {
89
154
  const relativePath = (0, util_1.getRelativePath)(scriptDir, filePath);
90
- this.socket?.emit('deleteFile', {
155
+ this.sendChange('deleteFile', {
91
156
  scriptName,
92
157
  filePath: relativePath,
93
158
  });
@@ -102,6 +167,11 @@ class Controller {
102
167
  }
103
168
  handleSyncScriptFromClient = async (data, ack) => {
104
169
  try {
170
+ if (this.agentPauses) {
171
+ ack({ error: 'A desktop run is active.' });
172
+ return;
173
+ }
174
+ await this.skillSync.stop();
105
175
  if (data.scriptName === this.scriptName) {
106
176
  ack({
107
177
  error: `Script [${data.scriptName}] is already initialized`,
@@ -153,6 +223,11 @@ class Controller {
153
223
  };
154
224
  handleSyncScriptFromServer = async (data, ack) => {
155
225
  try {
226
+ if (this.agentPauses) {
227
+ ack({ error: 'A desktop run is active.' });
228
+ return;
229
+ }
230
+ await this.skillSync.stop();
156
231
  if (this.scriptName === data.scriptName) {
157
232
  ack({
158
233
  error: `Script ${data.scriptName} is already initialized`,
@@ -0,0 +1,9 @@
1
+ /** Protocol v1 used older names. Keep that transport detail out of the public
2
+ * script/skill vocabulary while remaining usable with already released Apps. */
3
+ export declare function scriptMethod(method: string): string;
4
+ export declare function wireMethod(method: string): string;
5
+ export declare function scriptCapabilities(values: string[]): string[];
6
+ export declare function scriptError(value: any): any;
7
+ /** Only protocol-owned result headers are renamed; never rewrite Script.exit
8
+ * values, user logs, diagnostics, filenames or other script-owned data. */
9
+ export declare function scriptResult(value: any): any;
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.scriptMethod = scriptMethod;
4
+ exports.wireMethod = wireMethod;
5
+ exports.scriptCapabilities = scriptCapabilities;
6
+ exports.scriptError = scriptError;
7
+ exports.scriptResult = scriptResult;
8
+ /** Protocol v1 used older names. Keep that transport detail out of the public
9
+ * script/skill vocabulary while remaining usable with already released Apps. */
10
+ function scriptMethod(method) { return method.startsWith('projects.') ? 'scripts.' + method.slice(9) : method; }
11
+ function wireMethod(method) { return method.startsWith('scripts.') ? 'projects.' + method.slice(8) : method; }
12
+ function scriptCapabilities(values) { return [...new Set(values.map(scriptMethod))]; }
13
+ function scriptError(value) {
14
+ if (!value || typeof value !== 'object')
15
+ return value;
16
+ const codes = { invalid_project: 'invalid_script', project_mismatch: 'script_mismatch', project_exists: 'script_exists', project_not_found: 'script_not_found', project_conflict: 'script_conflict' };
17
+ return codes[value.code] ? { ...value, code: codes[value.code], message: typeof value.message === 'string' ? value.message.replace(/\bprojects\b/gi, 'scripts').replace(/\bproject\b/gi, 'script') : value.message } : value;
18
+ }
19
+ /** Only protocol-owned result headers are renamed; never rewrite Script.exit
20
+ * values, user logs, diagnostics, filenames or other script-owned data. */
21
+ function scriptResult(value) {
22
+ if (!value || typeof value !== 'object' || Array.isArray(value))
23
+ return value;
24
+ const { project, projects, currentProject, ...result } = value;
25
+ if (result.script === undefined && project !== undefined)
26
+ result.script = project;
27
+ if (result.scripts === undefined && projects !== undefined)
28
+ result.scripts = projects;
29
+ if (result.currentScript === undefined && currentProject !== undefined)
30
+ result.currentScript = currentProject;
31
+ if (result.completionReason === 'project_attached')
32
+ result.completionReason = 'script_attached';
33
+ if (Array.isArray(result.capabilities))
34
+ result.capabilities = scriptCapabilities(result.capabilities);
35
+ return result;
36
+ }
@@ -0,0 +1,39 @@
1
+ import { Socket } from 'socket.io';
2
+ import { SourceSnapshot } from './agent_protocol';
3
+ export declare function skillIgnores(ignore: string[]): string[];
4
+ export declare function validateSkillSnapshot(raw: any): SourceSnapshot;
5
+ export declare function snapshotSkill(workspace: string, name: string, ignore: string[]): Promise<SourceSnapshot>;
6
+ export declare function inspectSkill(workspace: string, name: string, ignore: string[]): Promise<SourceSnapshot | undefined>;
7
+ export declare function applySkillSnapshot(workspace: string, name: string, raw: unknown, expected: string | null): Promise<SourceSnapshot>;
8
+ export declare class SkillSyncController {
9
+ private socket;
10
+ private workspace;
11
+ private ignore;
12
+ private beforeBind;
13
+ private binding?;
14
+ private watcher?;
15
+ private catalog?;
16
+ private timer?;
17
+ private catalogTimer?;
18
+ private tail;
19
+ private pauses;
20
+ private closed;
21
+ constructor(socket: Socket, workspace: string, ignore: string[], beforeBind: () => Promise<void>);
22
+ private serial;
23
+ selected(): {
24
+ name: string;
25
+ bindingId: string;
26
+ revision: string;
27
+ } | null;
28
+ drain(): Promise<void>;
29
+ pause(): void;
30
+ resume(snapshot?: SourceSnapshot): void;
31
+ stop(): Promise<void>;
32
+ close(): Promise<void>;
33
+ private names;
34
+ private watchCatalog;
35
+ private request;
36
+ private schedule;
37
+ private block;
38
+ private pump;
39
+ }
@@ -0,0 +1,311 @@
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.SkillSyncController = void 0;
7
+ exports.skillIgnores = skillIgnores;
8
+ exports.validateSkillSnapshot = validateSkillSnapshot;
9
+ exports.snapshotSkill = snapshotSkill;
10
+ exports.inspectSkill = inspectSkill;
11
+ exports.applySkillSnapshot = applySkillSnapshot;
12
+ const fs_1 = __importDefault(require("fs"));
13
+ const path_1 = __importDefault(require("path"));
14
+ const crypto_1 = __importDefault(require("crypto"));
15
+ const chokidar_1 = __importDefault(require("chokidar"));
16
+ const agent_protocol_1 = require("./agent_protocol");
17
+ const util_1 = require("./util");
18
+ // Package metadata belongs to the App. It must survive development publication.
19
+ function skillIgnores(ignore) { return [...new Set(['/skill.json', ...ignore])]; }
20
+ function validateSkillSnapshot(raw) {
21
+ if (!raw || !Array.isArray(raw.files) || raw.files.length > agent_protocol_1.MAX_FILES || !Array.isArray(raw.ignore) || raw.ignore.length > 100 || raw.ignore.some((p) => typeof p !== 'string' || Buffer.byteLength(p) > 1024) || !raw.ignore.includes('/skill.json'))
22
+ throw new agent_protocol_1.AgentError('invalid_snapshot', 'Invalid skill manifest.');
23
+ let bytes = 0;
24
+ const seen = new Set(), portableNames = new Set();
25
+ for (const file of raw.files) {
26
+ if (!file || typeof file.path !== 'string' || !(0, agent_protocol_1.safeRelativePath)(file.path) || seen.has(file.path) || (0, util_1.isIgnoredPath)(file.path, raw.ignore) || typeof file.data !== 'string' || file.data.length > Math.ceil(agent_protocol_1.MAX_SOURCE_BYTES / 3) * 4)
27
+ throw new agent_protocol_1.AgentError('invalid_snapshot', 'Unsafe skill source.');
28
+ const portable = file.path.normalize('NFC').toLowerCase();
29
+ if (portableNames.has(portable))
30
+ throw new agent_protocol_1.AgentError('invalid_path', 'Source names differ only in case or normalization.');
31
+ portableNames.add(portable);
32
+ seen.add(file.path);
33
+ const data = Buffer.from(file.data, 'base64');
34
+ bytes += data.length;
35
+ if (bytes > agent_protocol_1.MAX_SOURCE_BYTES || data.toString('base64') !== file.data || (0, agent_protocol_1.hash)(data) !== file.sha256)
36
+ throw new agent_protocol_1.AgentError('invalid_snapshot', 'Skill content exceeds the limit or has a bad digest.');
37
+ }
38
+ if ((0, agent_protocol_1.revisionForFiles)(raw.files) !== raw.revision)
39
+ throw new agent_protocol_1.AgentError('revision_mismatch', 'Skill manifest digest does not match.');
40
+ const skill = raw.files.find((f) => f.path === 'SKILL.md');
41
+ const markdown = skill ? Buffer.from(skill.data, 'base64').toString('utf8') : '';
42
+ const front = markdown.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)?.[1];
43
+ if (!front || !['name', 'description'].every(key => front.split(/\r?\n/).some(line => line.startsWith(key + ':') && line.slice(key.length + 1).trim().replace(/^["']|["']$/g, '').trim())))
44
+ throw new agent_protocol_1.AgentError('invalid_skill', 'SKILL.md needs name and description in its frontmatter.');
45
+ return raw;
46
+ }
47
+ async function snapshotSkill(workspace, name, ignore) {
48
+ ensureRoot(workspace);
49
+ return validateSkillSnapshot(await (0, agent_protocol_1.snapshotSource)(workspace, name, skillIgnores(ignore), 'skills'));
50
+ }
51
+ function ensureRoot(workspace) {
52
+ const root = path_1.default.join(workspace, 'skills');
53
+ if (fs_1.default.existsSync(root)) {
54
+ if (fs_1.default.lstatSync(root).isSymbolicLink() || !fs_1.default.statSync(root).isDirectory())
55
+ throw new agent_protocol_1.AgentError('invalid_path', 'skills must be a regular directory.');
56
+ }
57
+ else
58
+ fs_1.default.mkdirSync(root);
59
+ return root;
60
+ }
61
+ async function inspectSkill(workspace, name, ignore) {
62
+ if (!(0, agent_protocol_1.validPackageName)(name))
63
+ throw new agent_protocol_1.AgentError('invalid_skill', 'Invalid skill directory name.');
64
+ const root = path_1.default.join(ensureRoot(workspace), name);
65
+ try {
66
+ await fs_1.default.promises.lstat(root);
67
+ }
68
+ catch (e) {
69
+ if (e.code === 'ENOENT')
70
+ return;
71
+ throw e;
72
+ }
73
+ return snapshotSkill(workspace, name, ignore);
74
+ }
75
+ async function applySkillSnapshot(workspace, name, raw, expected) {
76
+ if (!(0, agent_protocol_1.validPackageName)(name))
77
+ throw new agent_protocol_1.AgentError('invalid_skill', 'Invalid skill directory name.');
78
+ const snapshot = validateSkillSnapshot(raw), parent = ensureRoot(workspace), root = path_1.default.join(parent, name);
79
+ const stage = await fs_1.default.promises.mkdtemp(path_1.default.join(parent, '.skill-stage-'));
80
+ const backup = path_1.default.join(parent, '.skill-backup-' + crypto_1.default.randomUUID());
81
+ let moved = false, published = false, retainRecovery = false;
82
+ try {
83
+ for (const file of snapshot.files) {
84
+ const target = path_1.default.join(stage, file.path);
85
+ await fs_1.default.promises.mkdir(path_1.default.dirname(target), { recursive: true });
86
+ await fs_1.default.promises.writeFile(target, Buffer.from(file.data, 'base64'));
87
+ }
88
+ for (const file of snapshot.files) {
89
+ const target = path_1.default.join(stage, file.path);
90
+ if (path_1.default.relative(fs_1.default.realpathSync(stage), fs_1.default.realpathSync(target)).split(path_1.default.sep).join('/') !== file.path || (0, agent_protocol_1.hash)(fs_1.default.readFileSync(target)) !== file.sha256)
91
+ throw new agent_protocol_1.AgentError('invalid_path', 'Source names collide on this filesystem.');
92
+ }
93
+ // No await between the final version check and the directory swap. Changes
94
+ // from this server cannot interleave publication; external edits conflict.
95
+ const current = await inspectSkill(workspace, name, snapshot.ignore);
96
+ if ((current?.revision ?? null) !== expected)
97
+ throw new agent_protocol_1.AgentError('skill_conflict', 'Desktop skill changed. Select the source again.');
98
+ const preserved = [];
99
+ const movedPaths = [];
100
+ if (current) {
101
+ const collect = (dir, relative = '') => {
102
+ for (const item of fs_1.default.readdirSync(dir, { withFileTypes: true })) {
103
+ const rel = relative ? relative + '/' + item.name : item.name;
104
+ if ((0, util_1.isIgnoredPath)(rel, snapshot.ignore))
105
+ preserved.push(rel);
106
+ else if (item.isDirectory())
107
+ collect(path_1.default.join(root, rel), rel);
108
+ }
109
+ };
110
+ collect(root);
111
+ fs_1.default.renameSync(root, backup);
112
+ moved = true;
113
+ }
114
+ try {
115
+ for (const rel of preserved) {
116
+ const target = path_1.default.join(stage, rel);
117
+ fs_1.default.mkdirSync(path_1.default.dirname(target), { recursive: true });
118
+ fs_1.default.renameSync(path_1.default.join(backup, rel), target);
119
+ movedPaths.push(rel);
120
+ }
121
+ fs_1.default.renameSync(stage, root);
122
+ published = true;
123
+ }
124
+ catch (e) {
125
+ if (moved) {
126
+ try {
127
+ for (const rel of movedPaths.reverse()) {
128
+ const target = path_1.default.join(backup, rel);
129
+ fs_1.default.mkdirSync(path_1.default.dirname(target), { recursive: true });
130
+ fs_1.default.renameSync(path_1.default.join(stage, rel), target);
131
+ }
132
+ fs_1.default.renameSync(backup, root);
133
+ }
134
+ catch {
135
+ retainRecovery = true;
136
+ throw new agent_protocol_1.AgentError('recovery_required', `Preserve ${backup} and ${stage} for recovery.`);
137
+ }
138
+ }
139
+ throw e;
140
+ }
141
+ return snapshot;
142
+ }
143
+ finally {
144
+ if (!retainRecovery) {
145
+ await fs_1.default.promises.rm(stage, { recursive: true, force: true }).catch(() => { });
146
+ if (published && moved)
147
+ await fs_1.default.promises.rm(backup, { recursive: true, force: true }).catch(() => { });
148
+ }
149
+ }
150
+ }
151
+ class SkillSyncController {
152
+ socket;
153
+ workspace;
154
+ ignore;
155
+ beforeBind;
156
+ binding;
157
+ watcher;
158
+ catalog;
159
+ timer;
160
+ catalogTimer;
161
+ tail = Promise.resolve();
162
+ pauses = 0;
163
+ closed = false;
164
+ constructor(socket, workspace, ignore, beforeBind) {
165
+ this.socket = socket;
166
+ this.workspace = workspace;
167
+ this.ignore = ignore;
168
+ this.beforeBind = beforeBind;
169
+ socket.on('skillSyncRequest', (request, ack) => {
170
+ void this.serial(async () => {
171
+ try {
172
+ if (typeof ack !== 'function')
173
+ return;
174
+ ack({ success: true, ...await this.request(request) });
175
+ }
176
+ catch (e) {
177
+ if (typeof ack === 'function')
178
+ ack({ error: (0, agent_protocol_1.failure)(e) });
179
+ }
180
+ });
181
+ });
182
+ socket.emit('skillSyncHello', { version: 1 });
183
+ }
184
+ serial(work) { const result = this.tail.then(work); this.tail = result.catch(() => { }); return result; }
185
+ selected() { const b = this.binding; return b?.ready && !b.blocked ? { name: b.name, bindingId: b.id, revision: b.revision } : null; }
186
+ async drain() { await this.tail; }
187
+ pause() { this.pauses++; }
188
+ resume(snapshot) {
189
+ this.pauses = Math.max(0, this.pauses - 1);
190
+ if (snapshot && this.binding)
191
+ this.binding.revision = snapshot.revision;
192
+ this.schedule();
193
+ }
194
+ async stop() {
195
+ this.binding = undefined;
196
+ if (this.timer)
197
+ clearTimeout(this.timer);
198
+ const watcher = this.watcher;
199
+ this.watcher = undefined;
200
+ await watcher?.close();
201
+ }
202
+ async close() { this.closed = true; await this.stop(); if (this.catalogTimer)
203
+ clearTimeout(this.catalogTimer); await this.catalog?.close(); }
204
+ async names() {
205
+ const root = ensureRoot(this.workspace);
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
+ }
208
+ watchCatalog() {
209
+ if (this.catalog)
210
+ return;
211
+ 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
+ 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', () => { });
215
+ }
216
+ async request(r) {
217
+ if (this.closed || !this.socket.connected)
218
+ throw new agent_protocol_1.AgentError('disconnected', 'Skill connection ended.');
219
+ if (r?.version !== 1)
220
+ throw new agent_protocol_1.AgentError('unsupported_capability', 'Unsupported skill sync version.');
221
+ if (r.method === 'list') {
222
+ this.watchCatalog();
223
+ return { names: await this.names(), ignore: skillIgnores(this.ignore) };
224
+ }
225
+ if (r.method === 'inspect')
226
+ return { snapshot: await inspectSkill(this.workspace, r.name, this.ignore) ?? null };
227
+ if (this.pauses)
228
+ throw new agent_protocol_1.AgentError('busy', 'A desktop run is active.');
229
+ if (r.method === 'stop') {
230
+ if (this.binding && r.bindingId !== this.binding.id)
231
+ throw new agent_protocol_1.AgentError('skill_mismatch', 'The skill binding changed.');
232
+ await this.stop();
233
+ return {};
234
+ }
235
+ if (r.method === 'bind') {
236
+ if (!(0, agent_protocol_1.validPackageName)(r.name) || typeof r.bindingId !== 'string' || !/^[a-f0-9-]{36}$/i.test(r.bindingId))
237
+ throw new agent_protocol_1.AgentError('invalid_request', 'Invalid skill binding.');
238
+ await this.beforeBind();
239
+ await this.stop();
240
+ const files = r.types;
241
+ if (!files || typeof files !== 'object' || Array.isArray(files) || Object.keys(files).length > 16 || !files['global.d.ts'] || !files['scripting.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)
242
+ throw new agent_protocol_1.AgentError('invalid_request', 'Invalid declaration bundle.');
243
+ const dts = path_1.default.join(this.workspace, 'dts');
244
+ if (fs_1.default.existsSync(dts) && fs_1.default.lstatSync(dts).isSymbolicLink())
245
+ throw new agent_protocol_1.AgentError('invalid_path', 'Type directory cannot be a symlink.');
246
+ for (const name of Object.keys(files))
247
+ if (fs_1.default.existsSync(path_1.default.join(dts, name)) && fs_1.default.lstatSync(path_1.default.join(dts, name)).isSymbolicLink())
248
+ throw new agent_protocol_1.AgentError('invalid_path', 'Type file cannot be a symlink.');
249
+ await (0, util_1.writeDtsFiles)(files, this.workspace);
250
+ for (const [name, content] of Object.entries(files))
251
+ if (fs_1.default.readFileSync(path_1.default.join(dts, name), 'utf8') !== content)
252
+ throw new agent_protocol_1.AgentError('sync_failed', 'Type declarations were not written.');
253
+ let snapshot;
254
+ if (r.snapshot) {
255
+ const checked = validateSkillSnapshot(r.snapshot);
256
+ if (JSON.stringify(checked.ignore) !== JSON.stringify(skillIgnores(this.ignore)))
257
+ throw new agent_protocol_1.AgentError('invalid_snapshot', 'Ignore configuration changed.');
258
+ snapshot = await applySkillSnapshot(this.workspace, r.name, checked, r.expectedRevision ?? null);
259
+ }
260
+ else {
261
+ snapshot = await inspectSkill(this.workspace, r.name, this.ignore);
262
+ if (!snapshot || snapshot.revision !== r.expectedRevision)
263
+ throw new agent_protocol_1.AgentError('skill_conflict', 'Desktop skill changed. Select the source again.');
264
+ }
265
+ if (this.closed || !this.socket.connected)
266
+ throw new agent_protocol_1.AgentError('disconnected', 'Connection ended before binding.');
267
+ this.binding = { name: r.name, id: r.bindingId, revision: snapshot.revision, ready: false, blocked: false };
268
+ return { snapshot };
269
+ }
270
+ if (r.method === 'ready') {
271
+ const b = this.binding;
272
+ if (!b || b.id !== r.bindingId || b.name !== r.name || b.revision !== r.revision)
273
+ throw new agent_protocol_1.AgentError('skill_mismatch', 'The skill binding changed.');
274
+ const root = path_1.default.join(this.workspace, 'skills', b.name);
275
+ this.watcher = chokidar_1.default.watch(root, { ignoreInitial: true, ignored: p => (0, util_1.isIgnoredPath)(path_1.default.relative(root, p).split(path_1.default.sep).join('/'), skillIgnores(this.ignore)) });
276
+ this.watcher.on('all', () => this.schedule()).on('ready', () => this.schedule()).on('error', e => this.block(b, e));
277
+ b.ready = true;
278
+ return {};
279
+ }
280
+ throw new agent_protocol_1.AgentError('invalid_request', 'Unknown skill sync method.');
281
+ }
282
+ schedule() { if (this.timer)
283
+ clearTimeout(this.timer); if (this.closed)
284
+ return; this.timer = setTimeout(() => { void this.serial(() => this.pump()); }, 200); }
285
+ block(b, error) { if (this.binding !== b)
286
+ return; b.blocked = true; this.socket.emit('skillSyncFailure', { bindingId: b.id, name: b.name, error: (0, agent_protocol_1.failure)(error) }); }
287
+ async pump() {
288
+ const b = this.binding;
289
+ if (!b || !b.ready || b.blocked || this.pauses || this.closed)
290
+ return;
291
+ try {
292
+ const snapshot = await snapshotSkill(this.workspace, b.name, this.ignore);
293
+ if (this.binding !== b || this.pauses)
294
+ return;
295
+ if (snapshot.revision === b.revision)
296
+ return;
297
+ const reply = await new Promise((resolve, reject) => this.socket.timeout(10000).emit('skillSyncUpdate', { version: 1, name: b.name, bindingId: b.id, baseRevision: b.revision, snapshot }, (error, value) => error ? reject(new agent_protocol_1.AgentError('device_timeout', 'Skill synchronization was not acknowledged.')) : resolve(value)));
298
+ if (this.binding !== b)
299
+ return;
300
+ if (reply?.success !== true || reply.revision !== snapshot.revision)
301
+ throw new agent_protocol_1.AgentError(reply?.error?.code ?? 'sync_failed', reply?.error?.message ?? 'Skill publication failed.');
302
+ b.revision = snapshot.revision;
303
+ // Capture again after acknowledgement so saves during transmission remain.
304
+ this.schedule();
305
+ }
306
+ catch (e) {
307
+ this.block(b, e);
308
+ }
309
+ }
310
+ }
311
+ exports.SkillSyncController = SkillSyncController;
@@ -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.d.ts CHANGED
@@ -5,7 +5,7 @@ export declare function getScriptPath(filename?: string): string;
5
5
  export declare function createTsConfig(): void;
6
6
  export declare function ensureScriptsDirectory(): void;
7
7
  export declare function ensureDirectoryExistence(filePath: string): void;
8
- export declare function writeDtsFiles(files: Record<string, string>): Promise<void>;
8
+ export declare function writeDtsFiles(files: Record<string, string>, workspace?: string): Promise<void>;
9
9
  export declare function getRelativePath(from: string, to: string): string;
10
10
  export declare function isIgnoredPath(relativePath: string, patterns?: string[]): boolean;
11
11
  export declare function migrateOldFiles(): Promise<void>;
package/dist/util.js CHANGED
@@ -124,7 +124,8 @@ function createTsConfig() {
124
124
  },
125
125
  "include": [
126
126
  "./dts/*.d.ts",
127
- "scripts"
127
+ "scripts",
128
+ "skills"
128
129
  ],
129
130
  "exclude": [
130
131
  "./dts/${const_1.scriptingDtsFileName}"
@@ -151,6 +152,8 @@ function createTsConfig() {
151
152
  nextInclude.unshift('./dts/*.d.ts');
152
153
  if (!nextInclude.includes('scripts'))
153
154
  nextInclude.push('scripts');
155
+ if (!nextInclude.includes('skills'))
156
+ nextInclude.push('skills');
154
157
  const nextExclude = exclude.includes(`./dts/${const_1.scriptingDtsFileName}`)
155
158
  ? exclude
156
159
  : [...exclude, `./dts/${const_1.scriptingDtsFileName}`];
@@ -182,7 +185,7 @@ function ensureDirectoryExistence(filePath) {
182
185
  fs_1.default.mkdirSync(dirname, { recursive: true });
183
186
  }
184
187
  }
185
- async function writeDtsFiles(files) {
188
+ async function writeDtsFiles(files, workspace = process.cwd()) {
186
189
  await Promise.all(Object.entries(files).map(async ([filename, content]) => {
187
190
  // These names arrive over the wire; only allow a plain `.d.ts` basename so
188
191
  // a crafted name can't escape the dts/ directory.
@@ -192,7 +195,7 @@ async function writeDtsFiles(files) {
192
195
  console.log(chalk_1.default.red(`Skipped writing dts file with unexpected name: ${filename}`));
193
196
  return;
194
197
  }
195
- const filePath = getPath(`dts/${filename}`);
198
+ const filePath = path_1.default.join(workspace, 'dts', filename);
196
199
  ensureDirectoryExistence(filePath);
197
200
  await fs_1.default
198
201
  .promises
@@ -248,7 +251,7 @@ async function migrateOldFiles() {
248
251
  const list = await fs_1.default.promises.readdir(process.cwd());
249
252
  let hasMigrated = false;
250
253
  for (const file of list) {
251
- if (file === 'dts' || file == "scripts" || file === 'tsconfig.json' || file === 'package.json' || file === 'node_modules' || file.startsWith('.')) {
254
+ if (file === 'dts' || file == "scripts" || file === "skills" || file === 'tsconfig.json' || file === 'package.json' || file === 'node_modules' || file.startsWith('.')) {
252
255
  continue;
253
256
  }
254
257
  const filePath = path_1.default.join(process.cwd(), file);