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.
@@ -0,0 +1,197 @@
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.statePath = statePath;
7
+ exports.loadControl = loadControl;
8
+ exports.controlRequest = controlRequest;
9
+ exports.startAgentControl = startAgentControl;
10
+ exports.materializeArtifacts = materializeArtifacts;
11
+ const fs_1 = __importDefault(require("fs"));
12
+ const path_1 = __importDefault(require("path"));
13
+ const os_1 = __importDefault(require("os"));
14
+ const http_1 = __importDefault(require("http"));
15
+ const crypto_1 = __importDefault(require("crypto"));
16
+ const express_1 = __importDefault(require("express"));
17
+ const agent_protocol_1 = require("./agent_protocol");
18
+ function statePath(workspace) {
19
+ const user = typeof process.getuid === 'function' ? String(process.getuid()) : (0, agent_protocol_1.hash)(os_1.default.userInfo().username).slice(0, 16);
20
+ return path_1.default.join(os_1.default.tmpdir(), `scripting-cli-${user}`, (0, agent_protocol_1.hash)(fs_1.default.realpathSync(workspace)), 'server.json');
21
+ }
22
+ function privateDirectory(directory) {
23
+ if (fs_1.default.existsSync(directory) && fs_1.default.lstatSync(directory).isSymbolicLink())
24
+ throw new agent_protocol_1.AgentError('unsafe_state', 'Private state directory cannot be a symlink.');
25
+ fs_1.default.mkdirSync(directory, { recursive: true, mode: 0o700 });
26
+ const stat = fs_1.default.statSync(directory);
27
+ if (typeof process.getuid === 'function' && stat.uid !== process.getuid())
28
+ throw new agent_protocol_1.AgentError('unsafe_state', 'Private state belongs to another user.');
29
+ fs_1.default.chmodSync(directory, 0o700);
30
+ }
31
+ function loadControl(workspace) {
32
+ const file = statePath(workspace);
33
+ if (!fs_1.default.existsSync(file))
34
+ throw new agent_protocol_1.AgentError('server_unavailable', 'Start scripting-cli start in this workspace first.');
35
+ const stat = fs_1.default.lstatSync(file);
36
+ if (stat.isSymbolicLink() || (typeof process.getuid === 'function' && (stat.uid !== process.getuid() || (stat.mode & 0o077) !== 0)))
37
+ throw new agent_protocol_1.AgentError('unsafe_state', 'Unsafe local control credentials.');
38
+ const state = JSON.parse(fs_1.default.readFileSync(file, 'utf8'));
39
+ if (state.workspace !== fs_1.default.realpathSync(workspace) || state.protocolVersion !== 1 || !Number.isInteger(state.port) || state.port < 1 || state.port > 65535 || typeof state.token !== 'string' || !/^[0-9a-f]{64}$/.test(state.token))
40
+ throw new agent_protocol_1.AgentError('invalid_state', 'Invalid local control state.');
41
+ return state;
42
+ }
43
+ async function controlRequest(state, route, body) {
44
+ const controller = new AbortController();
45
+ const timer = setTimeout(() => controller.abort(), 10000);
46
+ try {
47
+ const response = await fetch(`http://127.0.0.1:${state.port}${route}`, { method: body === undefined ? 'GET' : 'POST', headers: { authorization: `Bearer ${state.token}`, 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body), signal: controller.signal });
48
+ const value = await response.json();
49
+ if (!response.ok)
50
+ throw new agent_protocol_1.AgentError(value.error?.code ?? 'control_error', value.error?.message ?? 'Control request failed.');
51
+ if (value.instanceId !== state.instanceId)
52
+ throw new agent_protocol_1.AgentError('stale_server', 'The local server instance changed.');
53
+ return value;
54
+ }
55
+ catch (error) {
56
+ if (error instanceof agent_protocol_1.AgentError)
57
+ throw error;
58
+ throw new agent_protocol_1.AgentError('control_unavailable', 'The local CLI service stopped responding. Execution was not replayed; inspect the App before retrying.');
59
+ }
60
+ finally {
61
+ clearTimeout(timer);
62
+ }
63
+ }
64
+ async function startAgentControl(broker) {
65
+ const file = statePath(broker.workspace);
66
+ privateDirectory(path_1.default.dirname(path_1.default.dirname(file)));
67
+ privateDirectory(path_1.default.dirname(file));
68
+ if (fs_1.default.existsSync(file)) {
69
+ const old = loadControl(broker.workspace);
70
+ let alive = false;
71
+ try {
72
+ await controlRequest(old, '/v1/info');
73
+ alive = true;
74
+ }
75
+ catch { }
76
+ if (alive)
77
+ throw new agent_protocol_1.AgentError('server_already_running', 'A CLI server is already running for this workspace.');
78
+ fs_1.default.unlinkSync(file);
79
+ }
80
+ const app = (0, express_1.default)();
81
+ const server = http_1.default.createServer(app);
82
+ const state = { protocolVersion: 1, port: 0, token: crypto_1.default.randomBytes(32).toString('hex'), instanceId: crypto_1.default.randomUUID(), workspace: fs_1.default.realpathSync(broker.workspace) };
83
+ app.use((req, res, next) => {
84
+ const expected = Buffer.from(`Bearer ${state.token}`);
85
+ const supplied = Buffer.from(req.headers.authorization ?? '');
86
+ if (req.socket.remoteAddress !== '127.0.0.1' || req.headers.origin || req.headers.host !== `127.0.0.1:${state.port}` || supplied.length !== expected.length || !crypto_1.default.timingSafeEqual(expected, supplied)) {
87
+ res.status(403).json({ error: { code: 'forbidden', message: 'Local authenticated control only.' } });
88
+ return;
89
+ }
90
+ next();
91
+ });
92
+ app.use(express_1.default.json({ limit: '128kb' }));
93
+ const send = (res, result) => res.json({ instanceId: state.instanceId, result });
94
+ app.get('/v1/info', (_req, res) => { send(res, { protocolVersion: 1, workspace: state.workspace }); });
95
+ app.get('/v1/devices', async (_req, res, next) => { try {
96
+ send(res, await broker.devices());
97
+ }
98
+ catch (e) {
99
+ next(e);
100
+ } });
101
+ app.post('/v1/requests', (req, res, next) => { try {
102
+ send(res, broker.submit(req.body));
103
+ }
104
+ catch (e) {
105
+ next(e);
106
+ } });
107
+ app.get('/v1/jobs/:id', (req, res, next) => { try {
108
+ send(res, broker.get(req.params.id));
109
+ }
110
+ catch (e) {
111
+ next(e);
112
+ } });
113
+ app.get('/v1/jobs/:id/events', (req, res, next) => { try {
114
+ send(res, broker.events(req.params.id, Number(req.query.after ?? 0)));
115
+ }
116
+ catch (e) {
117
+ next(e);
118
+ } });
119
+ app.post('/v1/jobs/:id/cancel', (req, res, next) => { try {
120
+ send(res, broker.cancel(req.params.id));
121
+ }
122
+ catch (e) {
123
+ next(e);
124
+ } });
125
+ app.use((_req, res) => { res.status(404).json({ error: { code: 'not_found', message: 'Unknown control route.' } }); });
126
+ app.use((error, _req, res, _next) => { res.status(400).json({ error: (0, agent_protocol_1.failure)(error) }); });
127
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
128
+ state.port = server.address().port;
129
+ try {
130
+ fs_1.default.writeFileSync(file, JSON.stringify(state), { mode: 0o600, flag: 'wx' });
131
+ }
132
+ catch (e) {
133
+ server.close();
134
+ throw e;
135
+ }
136
+ const sweep = setInterval(() => broker.prune(), 60000);
137
+ sweep.unref();
138
+ const cleanup = () => {
139
+ clearInterval(sweep);
140
+ broker.close();
141
+ try {
142
+ if (JSON.parse(fs_1.default.readFileSync(file, 'utf8')).instanceId === state.instanceId) {
143
+ fs_1.default.unlinkSync(file);
144
+ fs_1.default.rmdirSync(path_1.default.dirname(file));
145
+ }
146
+ }
147
+ catch { }
148
+ };
149
+ const signalCleanup = () => {
150
+ cleanup();
151
+ server.close();
152
+ // The existing Bonjour handler may finish sooner; otherwise stop this
153
+ // server process after its private credentials have been removed.
154
+ setTimeout(() => process.exit(0), 1000).unref();
155
+ };
156
+ process.once('exit', cleanup);
157
+ process.once('SIGINT', signalCleanup);
158
+ process.once('SIGTERM', signalCleanup);
159
+ return { state, close: async () => {
160
+ cleanup();
161
+ process.removeListener('exit', cleanup);
162
+ process.removeListener('SIGINT', signalCleanup);
163
+ process.removeListener('SIGTERM', signalCleanup);
164
+ await new Promise(r => server.close(() => r()));
165
+ } };
166
+ }
167
+ function materializeArtifacts(result, runId, output) {
168
+ if (!result?.artifacts?.length)
169
+ return result;
170
+ if (!/^[0-9a-f-]{36}$/i.test(runId))
171
+ throw new agent_protocol_1.AgentError('invalid_artifact', 'Invalid run ID.');
172
+ const artifacts = result.artifacts.map((image) => {
173
+ if (typeof image.path !== 'string' || fs_1.default.lstatSync(image.path).isSymbolicLink())
174
+ throw new agent_protocol_1.AgentError('invalid_artifact', 'Invalid screenshot source.');
175
+ const size = fs_1.default.statSync(image.path).size;
176
+ if (size > agent_protocol_1.MAX_IMAGE_BYTES)
177
+ throw new agent_protocol_1.AgentError('invalid_artifact', 'Screenshot exceeds the image limit.');
178
+ const bytes = fs_1.default.readFileSync(image.path);
179
+ if (bytes.length < 24 || bytes.subarray(0, 8).toString('hex') !== '89504e470d0a1a0a' || (0, agent_protocol_1.hash)(bytes) !== image.sha256)
180
+ throw new agent_protocol_1.AgentError('invalid_artifact', 'Invalid PNG screenshot.');
181
+ const directory = path_1.default.resolve(output, runId);
182
+ fs_1.default.mkdirSync(directory, { recursive: true });
183
+ if (fs_1.default.lstatSync(directory).isSymbolicLink())
184
+ throw new agent_protocol_1.AgentError('invalid_artifact', 'Artifact directory cannot be a symlink.');
185
+ if (image.id !== undefined && (typeof image.id !== 'string' || !/^[a-zA-Z0-9_-]{1,64}$/.test(image.id)))
186
+ throw new agent_protocol_1.AgentError('invalid_artifact', 'Invalid image case ID.');
187
+ const file = path_1.default.join(directory, (image.id ?? 'screenshot') + '.png');
188
+ if (fs_1.default.existsSync(file)) {
189
+ if (fs_1.default.lstatSync(file).isSymbolicLink() || (0, agent_protocol_1.hash)(fs_1.default.readFileSync(file)) !== image.sha256)
190
+ throw new agent_protocol_1.AgentError('artifact_exists', 'Output already exists with different content.');
191
+ }
192
+ else
193
+ fs_1.default.writeFileSync(file, bytes, { flag: 'wx', mode: 0o600 });
194
+ return { ...(image.id ? { id: image.id } : {}), path: file, mimeType: 'image/png', width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20), sha256: image.sha256 };
195
+ });
196
+ return { ...result, artifacts };
197
+ }
@@ -0,0 +1,71 @@
1
+ import crypto from 'crypto';
2
+ export declare const PROTOCOL_VERSION = 1;
3
+ export declare const MAX_SOURCE_BYTES: number;
4
+ export declare const MAX_FILES = 2000;
5
+ export declare const MAX_IMAGE_BYTES: number;
6
+ export declare const widgetFamilies: string[];
7
+ export declare class AgentError extends Error {
8
+ code: string;
9
+ constructor(code: string, message: string);
10
+ }
11
+ export declare const hash: (bytes: crypto.BinaryLike) => string;
12
+ export interface SourceFile {
13
+ path: string;
14
+ sha256: string;
15
+ data: string;
16
+ }
17
+ export interface SourceSnapshot {
18
+ revision: string;
19
+ files: SourceFile[];
20
+ ignore: string[];
21
+ }
22
+ export interface WidgetCase {
23
+ id: string;
24
+ family: string;
25
+ parameter?: string;
26
+ screenshot: boolean;
27
+ }
28
+ export interface AgentOptions {
29
+ check?: boolean;
30
+ events?: boolean;
31
+ readyLog?: string;
32
+ cases?: WidgetCase[];
33
+ replace?: boolean;
34
+ expectedRevision?: string;
35
+ timeout?: number;
36
+ screenshot?: boolean;
37
+ captureAfter?: number;
38
+ family?: string;
39
+ parameter?: string;
40
+ noSync?: boolean;
41
+ queryParameters?: Record<string, unknown>;
42
+ }
43
+ export interface AgentCommand {
44
+ method: string;
45
+ device?: string;
46
+ script?: string; /** @deprecated Compatibility input for protocol-v1 clients. */
47
+ project?: string;
48
+ skill?: string;
49
+ entry?: string;
50
+ options?: AgentOptions;
51
+ query?: string;
52
+ docId?: string;
53
+ symbol?: string;
54
+ lang?: string;
55
+ limit?: number;
56
+ requestId?: string;
57
+ }
58
+ export declare const methods: string[];
59
+ export declare function validateCommand(value: any): AgentCommand;
60
+ export declare function validPackageName(value: unknown): value is string;
61
+ export declare function safeRelativePath(value: string): boolean;
62
+ export declare function revisionForFiles(files: Pick<SourceFile, 'path' | 'sha256'>[]): string;
63
+ export declare function snapshotSource(workspace: string, name: string, ignore: string[], kind?: 'scripts' | 'skills'): Promise<SourceSnapshot>;
64
+ export declare const snapshotScript: typeof snapshotSource;
65
+ /** @deprecated Protocol-v1 compatibility exports. */
66
+ export declare const snapshotProject: typeof snapshotSource;
67
+ export declare const validProjectName: typeof validPackageName;
68
+ export declare function failure(error: unknown): any;
69
+ /** A delayed watcher notification for bytes already applied by this job must
70
+ * not trigger a second automatic run. Changes made after the snapshot remain. */
71
+ export declare function isAcknowledgedChange(workspace: string, script: string, relative: string, snapshot: SourceSnapshot): boolean;
@@ -0,0 +1,188 @@
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.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
+ exports.validateCommand = validateCommand;
8
+ exports.validPackageName = validPackageName;
9
+ exports.safeRelativePath = safeRelativePath;
10
+ exports.revisionForFiles = revisionForFiles;
11
+ exports.snapshotSource = snapshotSource;
12
+ exports.failure = failure;
13
+ exports.isAcknowledgedChange = isAcknowledgedChange;
14
+ const fs_1 = __importDefault(require("fs"));
15
+ const dev_terms_1 = require("./dev_terms");
16
+ const path_1 = __importDefault(require("path"));
17
+ const crypto_1 = __importDefault(require("crypto"));
18
+ const util_1 = require("./util");
19
+ exports.PROTOCOL_VERSION = 1;
20
+ exports.MAX_SOURCE_BYTES = 8 * 1024 * 1024;
21
+ exports.MAX_FILES = 2000;
22
+ exports.MAX_IMAGE_BYTES = 8 * 1024 * 1024;
23
+ exports.widgetFamilies = ['systemSmall', 'systemMedium', 'systemLarge', 'systemExtraLarge', 'accessoryCircular', 'accessoryRectangular', 'accessoryInline'];
24
+ class AgentError extends Error {
25
+ code;
26
+ constructor(code, message) {
27
+ super(message);
28
+ this.code = code;
29
+ }
30
+ }
31
+ exports.AgentError = AgentError;
32
+ const hash = (bytes) => crypto_1.default.createHash('sha256').update(bytes).digest('hex');
33
+ exports.hash = hash;
34
+ exports.methods = ['status', 'docs.search', 'docs.get', 'api.get', 'run', 'widget', 'widget.batch', 'scripts.list', 'scripts.inspect', 'scripts.create', 'scripts.attach', 'skills.run'];
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
+ }
42
+ if (!value || typeof value !== 'object' || Array.isArray(value) || !exports.methods.includes(value.method))
43
+ throw new AgentError('invalid_request', 'Unknown command.');
44
+ for (const key of ['device', 'script', 'query', 'docId', 'symbol', 'requestId', 'skill', 'entry']) {
45
+ if (value[key] !== undefined && (typeof value[key] !== 'string' || value[key].length > 1024))
46
+ throw new AgentError('invalid_request', `Invalid ${key}.`);
47
+ }
48
+ if (value.lang !== undefined && !['en', 'zh'].includes(value.lang))
49
+ throw new AgentError('invalid_request', 'Language must be en or zh.');
50
+ if (value.limit !== undefined && (!Number.isInteger(value.limit) || value.limit < 1 || value.limit > 50))
51
+ throw new AgentError('invalid_request', 'Limit must be 1...50.');
52
+ if (value.method === 'docs.get' && !value.docId)
53
+ throw new AgentError('invalid_request', 'A document ID is required.');
54
+ if (value.method === 'api.get' && !value.symbol)
55
+ throw new AgentError('invalid_request', 'An API symbol is required.');
56
+ const o = value.options ?? {};
57
+ if (!o || typeof o !== 'object' || Array.isArray(o))
58
+ throw new AgentError('invalid_request', 'Invalid options.');
59
+ for (const k of ['screenshot', 'noSync', 'replace', 'events', 'check'])
60
+ if (o[k] !== undefined && typeof o[k] !== 'boolean')
61
+ throw new AgentError('invalid_request', `Invalid ${k}.`);
62
+ if (o.timeout !== undefined && (!Number.isFinite(o.timeout) || o.timeout < 1 || o.timeout > 120))
63
+ throw new AgentError('invalid_request', 'Timeout must be 1...120 seconds.');
64
+ if (o.captureAfter !== undefined && (!Number.isFinite(o.captureAfter) || o.captureAfter < 0 || o.captureAfter > 10))
65
+ throw new AgentError('invalid_request', 'Capture delay must be 0...10 seconds.');
66
+ if (o.family !== undefined && !exports.widgetFamilies.includes(o.family))
67
+ throw new AgentError('invalid_request', 'Unsupported widget family.');
68
+ if (o.parameter !== undefined && (typeof o.parameter !== 'string' || o.parameter.length > 16384))
69
+ throw new AgentError('invalid_request', 'Invalid widget parameter.');
70
+ if (o.queryParameters !== undefined && (!o.queryParameters || typeof o.queryParameters !== 'object' || Array.isArray(o.queryParameters) || Buffer.byteLength(JSON.stringify(o.queryParameters)) > 65536))
71
+ throw new AgentError('invalid_request', 'Invalid query parameters.');
72
+ if (o.readyLog !== undefined && (value.method !== 'run' || !o.screenshot || typeof o.readyLog !== 'string' || !o.readyLog.length || Buffer.byteLength(o.readyLog) > 1024 || /[\r\n]/.test(o.readyLog)))
73
+ throw new AgentError('invalid_request', 'Ready log requires script screenshot mode and one exact line.');
74
+ if (o.expectedRevision !== undefined && (typeof o.expectedRevision !== 'string' || !/^[a-f0-9]{64}$/.test(o.expectedRevision)))
75
+ throw new AgentError('invalid_request', 'Invalid expected revision.');
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.');
78
+ if (value.method === 'widget.batch') {
79
+ if (!Array.isArray(o.cases) || o.cases.length < 1 || o.cases.length > 8)
80
+ throw new AgentError('invalid_request', 'Supply 1...8 widget cases.');
81
+ const ids = new Set();
82
+ for (const c of o.cases) {
83
+ if (!c || typeof c !== 'object' || typeof c.id !== 'string' || !/^[a-zA-Z0-9_-]{1,64}$/.test(c.id) || ids.has(c.id) || !exports.widgetFamilies.includes(c.family) || typeof c.screenshot !== 'boolean' || (c.parameter !== undefined && (typeof c.parameter !== 'string' || c.parameter.length > 16384)))
84
+ throw new AgentError('invalid_request', 'Invalid or duplicate widget case.');
85
+ ids.add(c.id);
86
+ }
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.');
90
+ return { ...value, options: o };
91
+ }
92
+ function validPackageName(value) { return typeof value === 'string' && value.length > 0 && Buffer.byteLength(value) < 256 && value !== '.' && value !== '..' && !value.startsWith('.') && !/[\/\\:\x00-\x1f\x7f]/.test(value); }
93
+ function safeRelativePath(value) {
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 !== '..');
95
+ }
96
+ function revisionForFiles(files) {
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(''));
98
+ }
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.');
106
+ const files = [];
107
+ let bytes = 0;
108
+ const stamps = [];
109
+ async function visit(relative) {
110
+ for (const name of (await fs_1.default.promises.readdir(path_1.default.join(root, relative))).sort()) {
111
+ const file = relative ? `${relative}/${name}` : name;
112
+ if ((0, util_1.isIgnoredPath)(file, ignore))
113
+ continue;
114
+ if (!safeRelativePath(file))
115
+ throw new AgentError('invalid_path', `Unsupported source path: ${file}`);
116
+ const full = path_1.default.join(root, file);
117
+ const before = await fs_1.default.promises.lstat(full);
118
+ if (before.isSymbolicLink())
119
+ throw new AgentError('invalid_path', `Source symlink: ${file}`);
120
+ if (before.isDirectory()) {
121
+ await visit(file);
122
+ continue;
123
+ }
124
+ if (!before.isFile())
125
+ throw new AgentError('invalid_path', `Not a regular file: ${file}`);
126
+ if (bytes + before.size > exports.MAX_SOURCE_BYTES || files.length >= exports.MAX_FILES)
127
+ throw new AgentError('source_limit', 'Source snapshot exceeds 8 MiB or 2000 files.');
128
+ const handle = await fs_1.default.promises.open(full, fs_1.default.constants.O_RDONLY | (fs_1.default.constants.O_NOFOLLOW || 0));
129
+ let data, after;
130
+ try {
131
+ const opened = await handle.stat();
132
+ if (!opened.isFile() || opened.ino !== before.ino)
133
+ throw new AgentError('source_changed', 'Source was replaced during capture.');
134
+ const buffer = Buffer.alloc(before.size + 1);
135
+ let read = 0;
136
+ while (read < buffer.length) {
137
+ const result = await handle.read(buffer, read, buffer.length - read, read);
138
+ if (!result.bytesRead)
139
+ break;
140
+ read += result.bytesRead;
141
+ }
142
+ data = buffer.subarray(0, read);
143
+ after = await handle.stat();
144
+ }
145
+ finally {
146
+ await handle.close();
147
+ }
148
+ const named = await fs_1.default.promises.lstat(full);
149
+ if (before.ino !== after.ino || before.ino !== named.ino || named.isSymbolicLink() || before.mtimeMs !== after.mtimeMs || before.size !== data.length || after.size !== data.length)
150
+ throw new AgentError('source_changed', 'Source changed while taking the snapshot; retry explicitly.');
151
+ stamps.push({ full, ino: after.ino, mtimeMs: after.mtimeMs, size: after.size });
152
+ bytes += data.length;
153
+ files.push({ path: file, sha256: (0, exports.hash)(data), data: data.toString('base64') });
154
+ }
155
+ }
156
+ await visit('');
157
+ for (const stamp of stamps) {
158
+ const final = await fs_1.default.promises.lstat(stamp.full);
159
+ if (!final.isFile() || final.isSymbolicLink() || final.ino !== stamp.ino || final.mtimeMs !== stamp.mtimeMs || final.size !== stamp.size)
160
+ throw new AgentError('source_changed', 'Source changed during the snapshot; retry explicitly.');
161
+ }
162
+ return { files, revision: revisionForFiles(files), ignore: [...ignore] };
163
+ }
164
+ exports.snapshotScript = snapshotSource;
165
+ /** @deprecated Protocol-v1 compatibility exports. */
166
+ exports.snapshotProject = snapshotSource;
167
+ exports.validProjectName = validPackageName;
168
+ function failure(error) {
169
+ return (0, dev_terms_1.scriptError)({ code: error instanceof AgentError ? error.code : 'internal_error', message: error instanceof Error ? error.message : String(error) });
170
+ }
171
+ /** A delayed watcher notification for bytes already applied by this job must
172
+ * not trigger a second automatic run. Changes made after the snapshot remain. */
173
+ function isAcknowledgedChange(workspace, script, relative, snapshot) {
174
+ if (!safeRelativePath(relative))
175
+ return false;
176
+ const expected = snapshot.files.find(file => file.path === relative);
177
+ const file = path_1.default.join(workspace, 'scripts', script, relative);
178
+ if (!fs_1.default.existsSync(file))
179
+ return expected === undefined;
180
+ if (!expected || fs_1.default.lstatSync(file).isSymbolicLink() || !fs_1.default.statSync(file).isFile())
181
+ return false;
182
+ try {
183
+ return (0, exports.hash)(fs_1.default.readFileSync(file)) === expected.sha256;
184
+ }
185
+ catch {
186
+ return false;
187
+ }
188
+ }
package/dist/cli.js CHANGED
@@ -40,7 +40,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
40
40
  const yargs_1 = __importDefault(require("yargs/yargs"));
41
41
  const helpers_1 = require("yargs/helpers");
42
42
  const start_server_1 = require("./start_server");
43
- (0, yargs_1.default)((0, helpers_1.hideBin)(process.argv))
43
+ const agent_cli_1 = require("./agent_cli");
44
+ (0, agent_cli_1.installAgentCommands)((0, yargs_1.default)((0, helpers_1.hideBin)(process.argv)))
44
45
  .parserConfiguration({
45
46
  "boolean-negation": false
46
47
  })
@@ -84,7 +85,7 @@ const start_server_1 = require("./start_server");
84
85
  startBonjourService: argv.bonjour,
85
86
  editorOverride: argv.editor,
86
87
  reconfigure: argv.reconfigure,
87
- });
88
+ }).catch(error => { console.error(error instanceof Error ? error.message : String(error)); process.exit(1); });
88
89
  })
89
90
  .command('migrate', 'Migrate the scripts in the workspace root directory to the scripts directory.', (yargs) => {
90
91
  return yargs
@@ -96,6 +97,18 @@ const start_server_1 = require("./start_server");
96
97
  const { migrateOldFiles } = await Promise.resolve().then(() => __importStar(require('./util')));
97
98
  await migrateOldFiles();
98
99
  process.exit(0);
100
+ })
101
+ .strict()
102
+ .fail((message, error) => {
103
+ const detail = error?.message ?? message;
104
+ const result = { status: 'failed', error: { code: 'invalid_usage', message: detail } };
105
+ if (process.argv.includes('--stream'))
106
+ console.log(JSON.stringify({ type: 'result', job: result }));
107
+ else if (process.argv.includes('--json'))
108
+ console.log(JSON.stringify(result));
109
+ else
110
+ console.error(detail);
111
+ process.exit(2);
99
112
  })
100
113
  .showHelpOnFail(true)
101
114
  .option('help', {
@@ -2,16 +2,21 @@ 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;
8
9
  static get(socketId: string): Controller | undefined;
10
+ private agentPauses;
11
+ private pendingAgentChanges;
12
+ private sendChange;
13
+ readonly skillSync: SkillSyncController;
9
14
  watcher: FSWatcher | null;
10
15
  scriptName: string | null;
11
16
  socket: Socket | null;
12
17
  config: ResolvedConfig;
13
18
  constructor(socket: Socket, config: ResolvedConfig);
14
- createWatcher(scriptName: string): void;
19
+ createWatcher(scriptName: string, ignoreInitial?: boolean): void;
15
20
  handleSyncScriptFromClient: (data: {
16
21
  [globalDtsFileName]: string;
17
22
  [scriptingDtsFileName]: string;