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/dist/agent_protocol.js
CHANGED
|
@@ -3,15 +3,16 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.methods = exports.hash = exports.AgentError = exports.widgetFamilies = exports.MAX_IMAGE_BYTES = exports.MAX_FILES = exports.MAX_SOURCE_BYTES = exports.PROTOCOL_VERSION = void 0;
|
|
6
|
+
exports.validProjectName = exports.snapshotProject = exports.snapshotScript = exports.methods = exports.hash = exports.AgentError = exports.widgetFamilies = exports.MAX_IMAGE_BYTES = exports.MAX_FILES = exports.MAX_SOURCE_BYTES = exports.PROTOCOL_VERSION = void 0;
|
|
7
7
|
exports.validateCommand = validateCommand;
|
|
8
|
-
exports.
|
|
8
|
+
exports.validPackageName = validPackageName;
|
|
9
9
|
exports.safeRelativePath = safeRelativePath;
|
|
10
10
|
exports.revisionForFiles = revisionForFiles;
|
|
11
|
-
exports.
|
|
11
|
+
exports.snapshotSource = snapshotSource;
|
|
12
12
|
exports.failure = failure;
|
|
13
13
|
exports.isAcknowledgedChange = isAcknowledgedChange;
|
|
14
14
|
const fs_1 = __importDefault(require("fs"));
|
|
15
|
+
const dev_terms_1 = require("./dev_terms");
|
|
15
16
|
const path_1 = __importDefault(require("path"));
|
|
16
17
|
const crypto_1 = __importDefault(require("crypto"));
|
|
17
18
|
const util_1 = require("./util");
|
|
@@ -30,11 +31,17 @@ class AgentError extends Error {
|
|
|
30
31
|
exports.AgentError = AgentError;
|
|
31
32
|
const hash = (bytes) => crypto_1.default.createHash('sha256').update(bytes).digest('hex');
|
|
32
33
|
exports.hash = hash;
|
|
33
|
-
exports.methods = ['status', 'docs.search', 'docs.get', 'api.get', 'run', 'widget', 'widget.batch', '
|
|
34
|
+
exports.methods = ['status', 'docs.search', 'docs.get', 'api.get', 'run', 'widget', 'widget.batch', 'scripts.list', 'scripts.inspect', 'scripts.create', 'scripts.attach', 'skills.run'];
|
|
34
35
|
function validateCommand(value) {
|
|
36
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
37
|
+
if (value.script !== undefined && value.project !== undefined && value.script !== value.project)
|
|
38
|
+
throw new AgentError('invalid_request', 'Conflicting script names.');
|
|
39
|
+
const { project, ...canonical } = value;
|
|
40
|
+
value = { ...canonical, method: typeof value.method === 'string' ? (0, dev_terms_1.scriptMethod)(value.method) : value.method, script: value.script ?? project };
|
|
41
|
+
}
|
|
35
42
|
if (!value || typeof value !== 'object' || Array.isArray(value) || !exports.methods.includes(value.method))
|
|
36
43
|
throw new AgentError('invalid_request', 'Unknown command.');
|
|
37
|
-
for (const key of ['device', '
|
|
44
|
+
for (const key of ['device', 'script', 'query', 'docId', 'symbol', 'requestId', 'skill', 'entry']) {
|
|
38
45
|
if (value[key] !== undefined && (typeof value[key] !== 'string' || value[key].length > 1024))
|
|
39
46
|
throw new AgentError('invalid_request', `Invalid ${key}.`);
|
|
40
47
|
}
|
|
@@ -49,7 +56,7 @@ function validateCommand(value) {
|
|
|
49
56
|
const o = value.options ?? {};
|
|
50
57
|
if (!o || typeof o !== 'object' || Array.isArray(o))
|
|
51
58
|
throw new AgentError('invalid_request', 'Invalid options.');
|
|
52
|
-
for (const k of ['screenshot', 'noSync', 'replace', 'events'])
|
|
59
|
+
for (const k of ['screenshot', 'noSync', 'replace', 'events', 'check'])
|
|
53
60
|
if (o[k] !== undefined && typeof o[k] !== 'boolean')
|
|
54
61
|
throw new AgentError('invalid_request', `Invalid ${k}.`);
|
|
55
62
|
if (o.timeout !== undefined && (!Number.isFinite(o.timeout) || o.timeout < 1 || o.timeout > 120))
|
|
@@ -66,8 +73,8 @@ function validateCommand(value) {
|
|
|
66
73
|
throw new AgentError('invalid_request', 'Ready log requires script screenshot mode and one exact line.');
|
|
67
74
|
if (o.expectedRevision !== undefined && (typeof o.expectedRevision !== 'string' || !/^[a-f0-9]{64}$/.test(o.expectedRevision)))
|
|
68
75
|
throw new AgentError('invalid_request', 'Invalid expected revision.');
|
|
69
|
-
if (value.method.startsWith('
|
|
70
|
-
throw new AgentError('
|
|
76
|
+
if (value.method.startsWith('scripts.') && value.method !== 'scripts.list' && !validPackageName(value.script))
|
|
77
|
+
throw new AgentError('invalid_script', 'A safe script name is required.');
|
|
71
78
|
if (value.method === 'widget.batch') {
|
|
72
79
|
if (!Array.isArray(o.cases) || o.cases.length < 1 || o.cases.length > 8)
|
|
73
80
|
throw new AgentError('invalid_request', 'Supply 1...8 widget cases.');
|
|
@@ -78,22 +85,24 @@ function validateCommand(value) {
|
|
|
78
85
|
ids.add(c.id);
|
|
79
86
|
}
|
|
80
87
|
}
|
|
88
|
+
if (value.method === 'skills.run' && (!validPackageName(value.skill) || typeof value.entry !== 'string' || !safeRelativePath(value.entry) || !/\.tsx?$/.test(value.entry) || o.screenshot || o.readyLog || o.noSync))
|
|
89
|
+
throw new AgentError('invalid_request', 'Specify a skill name and a skill-relative .ts/.tsx entry.');
|
|
81
90
|
return { ...value, options: o };
|
|
82
91
|
}
|
|
83
|
-
function
|
|
92
|
+
function validPackageName(value) { return typeof value === 'string' && value.length > 0 && Buffer.byteLength(value) < 256 && value !== '.' && value !== '..' && !value.startsWith('.') && !/[\/\\:\x00-\x1f\x7f]/.test(value); }
|
|
84
93
|
function safeRelativePath(value) {
|
|
85
94
|
return Buffer.byteLength(value) > 0 && Buffer.byteLength(value) < 1024 && !/[\\:\x00-\x1f\x7f]/.test(value) && !path_1.default.posix.isAbsolute(value) && value.split('/').length <= 32 && value.split('/').every(p => !!p && p !== '.' && p !== '..');
|
|
86
95
|
}
|
|
87
96
|
function revisionForFiles(files) {
|
|
88
97
|
return (0, exports.hash)([...files].sort((a, b) => Buffer.compare(Buffer.from(a.path), Buffer.from(b.path))).map(f => `${f.path}\0${f.sha256}\n`).join(''));
|
|
89
98
|
}
|
|
90
|
-
async function
|
|
91
|
-
if (!
|
|
92
|
-
throw new AgentError('
|
|
93
|
-
const root = path_1.default.join(workspace,
|
|
94
|
-
const scripts = await fs_1.default.promises.realpath(path_1.default.join(workspace,
|
|
95
|
-
if ((await fs_1.default.promises.realpath(root)) !== path_1.default.join(scripts,
|
|
96
|
-
throw new AgentError('
|
|
99
|
+
async function snapshotSource(workspace, name, ignore, kind = 'scripts') {
|
|
100
|
+
if (!validPackageName(name))
|
|
101
|
+
throw new AgentError(kind === 'skills' ? 'invalid_skill' : 'invalid_script', 'Invalid source name.');
|
|
102
|
+
const root = path_1.default.join(workspace, kind, name);
|
|
103
|
+
const scripts = await fs_1.default.promises.realpath(path_1.default.join(workspace, kind));
|
|
104
|
+
if ((await fs_1.default.promises.realpath(root)) !== path_1.default.join(scripts, name) || (await fs_1.default.promises.lstat(root)).isSymbolicLink())
|
|
105
|
+
throw new AgentError('invalid_path', 'Source symlinks are unsupported.');
|
|
97
106
|
const files = [];
|
|
98
107
|
let bytes = 0;
|
|
99
108
|
const stamps = [];
|
|
@@ -152,16 +161,20 @@ async function snapshotProject(workspace, project, ignore) {
|
|
|
152
161
|
}
|
|
153
162
|
return { files, revision: revisionForFiles(files), ignore: [...ignore] };
|
|
154
163
|
}
|
|
164
|
+
exports.snapshotScript = snapshotSource;
|
|
165
|
+
/** @deprecated Protocol-v1 compatibility exports. */
|
|
166
|
+
exports.snapshotProject = snapshotSource;
|
|
167
|
+
exports.validProjectName = validPackageName;
|
|
155
168
|
function failure(error) {
|
|
156
|
-
return { code: error instanceof AgentError ? error.code : 'internal_error', message: error instanceof Error ? error.message : String(error) };
|
|
169
|
+
return (0, dev_terms_1.scriptError)({ code: error instanceof AgentError ? error.code : 'internal_error', message: error instanceof Error ? error.message : String(error) });
|
|
157
170
|
}
|
|
158
171
|
/** A delayed watcher notification for bytes already applied by this job must
|
|
159
172
|
* not trigger a second automatic run. Changes made after the snapshot remain. */
|
|
160
|
-
function isAcknowledgedChange(workspace,
|
|
173
|
+
function isAcknowledgedChange(workspace, script, relative, snapshot) {
|
|
161
174
|
if (!safeRelativePath(relative))
|
|
162
175
|
return false;
|
|
163
176
|
const expected = snapshot.files.find(file => file.path === relative);
|
|
164
|
-
const file = path_1.default.join(workspace, 'scripts',
|
|
177
|
+
const file = path_1.default.join(workspace, 'scripts', script, relative);
|
|
165
178
|
if (!fs_1.default.existsSync(file))
|
|
166
179
|
return expected === undefined;
|
|
167
180
|
if (!expected || fs_1.default.lstatSync(file).isSymbolicLink() || !fs_1.default.statSync(file).isFile())
|
package/dist/controller.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { FSWatcher } from 'chokidar';
|
|
|
2
2
|
import { Socket } from 'socket.io';
|
|
3
3
|
import { globalDtsFileName, scriptingDtsFileName } from './const';
|
|
4
4
|
import { ResolvedConfig } from './types';
|
|
5
|
+
import { SkillSyncController } from './skill_sync';
|
|
5
6
|
export declare class Controller {
|
|
6
7
|
private static instances;
|
|
7
8
|
static create(socket: Socket, config: ResolvedConfig): Controller;
|
|
@@ -9,6 +10,7 @@ export declare class Controller {
|
|
|
9
10
|
private agentPauses;
|
|
10
11
|
private pendingAgentChanges;
|
|
11
12
|
private sendChange;
|
|
13
|
+
readonly skillSync: SkillSyncController;
|
|
12
14
|
watcher: FSWatcher | null;
|
|
13
15
|
scriptName: string | null;
|
|
14
16
|
socket: Socket | null;
|
package/dist/controller.js
CHANGED
|
@@ -12,6 +12,7 @@ const path_1 = __importDefault(require("path"));
|
|
|
12
12
|
const const_1 = require("./const");
|
|
13
13
|
const editors_1 = require("./editors");
|
|
14
14
|
const agent_broker_1 = require("./agent_broker");
|
|
15
|
+
const skill_sync_1 = require("./skill_sync");
|
|
15
16
|
const agent_protocol_1 = require("./agent_protocol");
|
|
16
17
|
class Controller {
|
|
17
18
|
static instances = new Map();
|
|
@@ -34,6 +35,7 @@ class Controller {
|
|
|
34
35
|
}
|
|
35
36
|
this.socket?.emit(event, data);
|
|
36
37
|
}
|
|
38
|
+
skillSync;
|
|
37
39
|
watcher = null;
|
|
38
40
|
scriptName = null;
|
|
39
41
|
socket = null;
|
|
@@ -41,8 +43,18 @@ class Controller {
|
|
|
41
43
|
constructor(socket, config) {
|
|
42
44
|
this.config = config;
|
|
43
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
|
+
});
|
|
44
54
|
agent_broker_1.agentBroker.register(socket, {
|
|
45
|
-
|
|
55
|
+
script: () => this.scriptName,
|
|
56
|
+
skill: () => this.skillSync.selected(),
|
|
57
|
+
skillReady: () => this.skillSync.drain(),
|
|
46
58
|
types: async (files) => {
|
|
47
59
|
const directory = path_1.default.join(process.cwd(), 'dts');
|
|
48
60
|
if (fs_1.default.existsSync(directory) && fs_1.default.lstatSync(directory).isSymbolicLink())
|
|
@@ -57,16 +69,17 @@ class Controller {
|
|
|
57
69
|
if (fs_1.default.readFileSync(path_1.default.join(directory, name), 'utf8') !== value)
|
|
58
70
|
throw new Error('Type declarations were not written.');
|
|
59
71
|
},
|
|
60
|
-
|
|
72
|
+
switchScript: async (script) => {
|
|
61
73
|
await this.watcher?.close();
|
|
62
74
|
this.watcher = null;
|
|
63
75
|
this.pendingAgentChanges.clear();
|
|
64
|
-
this.scriptName =
|
|
65
|
-
this.createWatcher(
|
|
76
|
+
this.scriptName = script;
|
|
77
|
+
this.createWatcher(script, true);
|
|
66
78
|
},
|
|
67
79
|
ignore: () => this.config.ignore,
|
|
68
|
-
pause: () => { this.agentPauses++; },
|
|
69
|
-
resume: snapshot => {
|
|
80
|
+
pause: () => { this.agentPauses++; this.skillSync.pause(); },
|
|
81
|
+
resume: (snapshot, bindingId) => {
|
|
82
|
+
this.skillSync.resume(bindingId === this.skillSync.selected()?.bindingId ? snapshot : undefined);
|
|
70
83
|
this.agentPauses = Math.max(0, this.agentPauses - 1);
|
|
71
84
|
if (!this.agentPauses) {
|
|
72
85
|
for (const { event, data } of this.pendingAgentChanges.values()) {
|
|
@@ -88,6 +101,7 @@ class Controller {
|
|
|
88
101
|
socket.on('disconnect', (reason) => {
|
|
89
102
|
console.log(chalk_1.default.gray(`Client [${socket.id}] disconnected: ${reason}`));
|
|
90
103
|
this.watcher?.close();
|
|
104
|
+
void this.skillSync.close();
|
|
91
105
|
this.watcher = null;
|
|
92
106
|
this.scriptName = null;
|
|
93
107
|
Controller.instances.delete(socket.id);
|
|
@@ -157,6 +171,7 @@ class Controller {
|
|
|
157
171
|
ack({ error: 'A desktop run is active.' });
|
|
158
172
|
return;
|
|
159
173
|
}
|
|
174
|
+
await this.skillSync.stop();
|
|
160
175
|
if (data.scriptName === this.scriptName) {
|
|
161
176
|
ack({
|
|
162
177
|
error: `Script [${data.scriptName}] is already initialized`,
|
|
@@ -212,6 +227,7 @@ class Controller {
|
|
|
212
227
|
ack({ error: 'A desktop run is active.' });
|
|
213
228
|
return;
|
|
214
229
|
}
|
|
230
|
+
await this.skillSync.stop();
|
|
215
231
|
if (this.scriptName === data.scriptName) {
|
|
216
232
|
ack({
|
|
217
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;
|
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
|
|
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>;
|