scripting-cli 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,118 @@
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.invokeAgentCommand = invokeAgentCommand;
7
+ exports.installAgentCommands = installAgentCommands;
8
+ const path_1 = __importDefault(require("path"));
9
+ const fs_1 = __importDefault(require("fs"));
10
+ const agent_protocol_1 = require("./agent_protocol");
11
+ const agent_control_1 = require("./agent_control");
12
+ async function invokeAgentCommand(command, output, json, stream = false) {
13
+ const state = (0, agent_control_1.loadControl)(process.cwd());
14
+ const info = await (0, agent_control_1.controlRequest)(state, '/v1/info');
15
+ if (info.result.workspace !== state.workspace)
16
+ throw new agent_protocol_1.AgentError('workspace_mismatch', 'The running server belongs to another workspace.');
17
+ let job = (await (0, agent_control_1.controlRequest)(state, '/v1/requests', command)).result;
18
+ const cancel = () => { void (0, agent_control_1.controlRequest)(state, `/v1/jobs/${job.runId}/cancel`, {}).catch(() => { }); };
19
+ process.once('SIGINT', cancel);
20
+ let cursor = 0, reportedLogLimit = false;
21
+ const emitEvents = async () => {
22
+ if (!stream)
23
+ return;
24
+ const page = (await (0, agent_control_1.controlRequest)(state, `/v1/jobs/${job.runId}/events?after=${cursor}`)).result;
25
+ if (page.logsTruncated && !reportedLogLimit) {
26
+ console.log(JSON.stringify({ type: 'gap', runId: job.runId, reason: 'stream_log_budget' }));
27
+ reportedLogLimit = true;
28
+ }
29
+ if (page.truncated)
30
+ console.log(JSON.stringify({ type: 'gap', runId: job.runId, after: cursor, reason: 'event_retention_limit' }));
31
+ for (const event of page.events)
32
+ console.log(JSON.stringify(event));
33
+ cursor = page.nextCursor;
34
+ };
35
+ try {
36
+ while (!['completed', 'failed', 'cancelled'].includes(job.status)) {
37
+ await emitEvents();
38
+ await new Promise(r => setTimeout(r, 200));
39
+ job = (await (0, agent_control_1.controlRequest)(state, `/v1/jobs/${job.runId}`)).result;
40
+ }
41
+ await emitEvents();
42
+ if (job.result?.artifacts?.length)
43
+ job.result = (0, agent_control_1.materializeArtifacts)(job.result, job.runId, output);
44
+ if (stream)
45
+ console.log(JSON.stringify({ type: 'result', seq: cursor + 1, runId: job.runId, job }));
46
+ else if (json)
47
+ console.log(JSON.stringify(job));
48
+ else
49
+ console.log(JSON.stringify(job, null, 2));
50
+ process.exitCode = job.status === 'completed' ? 0 : job.status === 'cancelled' ? 130 : ['execution_timeout', 'device_timeout'].includes(job.error?.code) ? 124 : 1;
51
+ }
52
+ finally {
53
+ process.removeListener('SIGINT', cancel);
54
+ }
55
+ }
56
+ function common(y) {
57
+ return y.option('device', { type: 'string', describe: 'Target device ID; required when several devices are connected' })
58
+ .option('json', { type: 'boolean', default: false, describe: 'Print one JSON result' })
59
+ .option('output', { type: 'string', default: 'artifacts', describe: 'Screenshot output directory' });
60
+ }
61
+ function streaming(y) { return common(y).option('stream', { type: 'boolean', default: false, describe: 'Print progress/log/diagnostic JSONL events and one final result' }); }
62
+ function runOptions(y, script = true) {
63
+ const options = streaming(y).positional('project', { type: 'string', describe: 'Currently selected App debug project' })
64
+ .option('screenshot', { type: 'boolean', default: false })
65
+ .option('timeout', { type: 'number', default: 30, describe: 'Overall run deadline in seconds, 1...120' })
66
+ .option('no-sync', { type: 'boolean', default: false, describe: 'Use the last acknowledged App revision' });
67
+ return script ? options.option('capture-after', { type: 'number', default: 2, describe: 'Seconds after a script view is available before capture' }).option('ready-log', { type: 'string', describe: 'Wait for this exact console.log line from the current script before capture' }).option('query-parameters', { type: 'string', describe: 'JSON object passed to the script' }) : options;
68
+ }
69
+ const handler = (build) => async (a) => {
70
+ try {
71
+ const command = build(a);
72
+ command.options = { ...command.options, events: a.stream ?? false };
73
+ await invokeAgentCommand(command, path_1.default.resolve(a.output ?? 'artifacts'), a.json ?? false, a.stream ?? false);
74
+ }
75
+ catch (e) {
76
+ const result = { status: 'failed', error: (0, agent_protocol_1.failure)(e) };
77
+ console.log(JSON.stringify(a.stream ? { type: 'result', job: result } : result, a.json || a.stream ? undefined : null, a.json || a.stream ? undefined : 2));
78
+ process.exitCode = 1;
79
+ }
80
+ };
81
+ function installAgentCommands(y) {
82
+ return y.command('skill', 'Print the portable Scripting development SKILL.md', () => { }, () => console.log(fs_1.default.readFileSync(path_1.default.join(__dirname, '../skills/scripting-development/SKILL.md'), 'utf8'))).command('devices', 'List connected devices and their current responsiveness', common, async (a) => {
83
+ try {
84
+ const value = await (0, agent_control_1.controlRequest)((0, agent_control_1.loadControl)(process.cwd()), '/v1/devices');
85
+ console.log(JSON.stringify(value.result, null, a.json ? undefined : 2));
86
+ }
87
+ catch (e) {
88
+ console.log(JSON.stringify({ status: 'failed', error: (0, agent_protocol_1.failure)(e) }));
89
+ process.exitCode = 1;
90
+ }
91
+ }).command('status', 'Query the selected App debug session', y => streaming(y), handler(a => ({ method: 'status', device: a.device })))
92
+ .command('docs <action> [value]', 'Search docs or read a returned document ID', y => streaming(y).positional('action', { choices: ['search', 'get'] }).positional('value', { type: 'string' }).option('lang', { choices: ['en', 'zh'], default: 'en' }).option('limit', { type: 'number', default: 20 }), handler(a => ({ method: a.action === 'search' ? 'docs.search' : 'docs.get', device: a.device, query: a.action === 'search' ? a.value : undefined, docId: a.action === 'get' ? a.value : undefined, lang: a.lang, limit: a.limit })))
93
+ .command('api <action> <symbol>', 'Read an exact Scripting API declaration', y => streaming(y).positional('action', { choices: ['get'] }).positional('symbol', { type: 'string' }), handler(a => ({ method: 'api.get', device: a.device, symbol: a.symbol })))
94
+ .command('run [project]', 'Sync and execute the current debug project', y => runOptions(y), handler(a => ({ method: 'run', device: a.device, project: a.project, options: { screenshot: a.screenshot, captureAfter: a.captureAfter, readyLog: a.readyLog, timeout: a.timeout, noSync: a['no-sync'], queryParameters: a['query-parameters'] ? JSON.parse(a['query-parameters']) : undefined } })))
95
+ .command('widget [project]', 'Render the current project widget and close its preview', y => runOptions(y, false).option('family', { type: 'string', default: 'systemSmall' }).option('parameter', { type: 'string' }), handler(a => ({ method: 'widget', device: a.device, project: a.project, options: { screenshot: a.screenshot, timeout: a.timeout, noSync: a['no-sync'], family: a.family, parameter: a.parameter } })))
96
+ .command('widget-batch [project]', 'Render 1...8 widget cases from a JSON file', y => streaming(y).positional('project', { type: 'string' }).option('timeout', { type: 'number', default: 30 }).option('no-sync', { type: 'boolean', default: false }).option('cases', { type: 'string', demandOption: true }), handler(a => {
97
+ const stat = fs_1.default.statSync(a.cases);
98
+ if (stat.size > 128 * 1024)
99
+ throw new agent_protocol_1.AgentError('invalid_request', 'Case manifest exceeds 128 KiB.');
100
+ const cases = JSON.parse(fs_1.default.readFileSync(a.cases, 'utf8'));
101
+ return { method: 'widget.batch', device: a.device, project: a.project, options: { timeout: a.timeout, noSync: a['no-sync'], cases } };
102
+ }))
103
+ .command('projects <action> [name]', 'List, inspect, create or attach an App project', y => streaming(y).positional('action', { choices: ['list', 'inspect', 'create', 'attach'] }).positional('name', { type: 'string' }).option('replace', { type: 'boolean', default: false }).option('expected-revision', { type: 'string' }).option('timeout', { type: 'number', default: 30 }), handler(a => ({ method: `projects.${a.action}`, device: a.device, project: a.name, options: { replace: a.replace, expectedRevision: a.expectedRevision, timeout: a.timeout } })))
104
+ .command('jobs <action> <id>', 'Read a recent result or cancel an owned run', y => common(y).positional('action', { choices: ['show', 'cancel', 'events'] }).positional('id', { type: 'string' }).option('after', { type: 'number', default: 0 }), async (a) => {
105
+ try {
106
+ const state = (0, agent_control_1.loadControl)(process.cwd());
107
+ const route = `/v1/jobs/${encodeURIComponent(a.id)}${a.action === 'cancel' ? '/cancel' : a.action === 'events' ? `/events?after=${a.after}` : ''}`;
108
+ let job = (await (0, agent_control_1.controlRequest)(state, route, a.action === 'cancel' ? {} : undefined)).result;
109
+ if (job.result?.artifacts?.length)
110
+ job.result = (0, agent_control_1.materializeArtifacts)(job.result, job.runId, path_1.default.resolve(a.output));
111
+ console.log(JSON.stringify(job, null, a.json ? undefined : 2));
112
+ }
113
+ catch (e) {
114
+ console.log(JSON.stringify({ status: 'failed', error: (0, agent_protocol_1.failure)(e) }));
115
+ process.exitCode = 1;
116
+ }
117
+ });
118
+ }
@@ -0,0 +1,16 @@
1
+ import { AgentBroker } from './agent_broker';
2
+ export interface ControlState {
3
+ protocolVersion: 1;
4
+ port: number;
5
+ token: string;
6
+ instanceId: string;
7
+ workspace: string;
8
+ }
9
+ export declare function statePath(workspace: string): string;
10
+ export declare function loadControl(workspace: string): ControlState;
11
+ export declare function controlRequest(state: ControlState, route: string, body?: unknown): Promise<any>;
12
+ export declare function startAgentControl(broker: AgentBroker): Promise<{
13
+ state: ControlState;
14
+ close: () => Promise<void>;
15
+ }>;
16
+ export declare function materializeArtifacts(result: any, runId: string, output: string): any;
@@ -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,66 @@
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
+ events?: boolean;
30
+ readyLog?: string;
31
+ cases?: WidgetCase[];
32
+ replace?: boolean;
33
+ expectedRevision?: string;
34
+ timeout?: number;
35
+ screenshot?: boolean;
36
+ captureAfter?: number;
37
+ family?: string;
38
+ parameter?: string;
39
+ noSync?: boolean;
40
+ queryParameters?: Record<string, unknown>;
41
+ }
42
+ export interface AgentCommand {
43
+ method: string;
44
+ device?: string;
45
+ project?: string;
46
+ options?: AgentOptions;
47
+ query?: string;
48
+ docId?: string;
49
+ symbol?: string;
50
+ lang?: string;
51
+ limit?: number;
52
+ requestId?: string;
53
+ }
54
+ export declare const methods: string[];
55
+ export declare function validateCommand(value: any): AgentCommand;
56
+ export declare function validProjectName(value: unknown): value is string;
57
+ export declare function safeRelativePath(value: string): boolean;
58
+ export declare function revisionForFiles(files: Pick<SourceFile, 'path' | 'sha256'>[]): string;
59
+ export declare function snapshotProject(workspace: string, project: string, ignore: string[]): Promise<SourceSnapshot>;
60
+ export declare function failure(error: unknown): {
61
+ code: string;
62
+ message: string;
63
+ };
64
+ /** A delayed watcher notification for bytes already applied by this job must
65
+ * not trigger a second automatic run. Changes made after the snapshot remain. */
66
+ export declare function isAcknowledgedChange(workspace: string, project: string, relative: string, snapshot: SourceSnapshot): boolean;
@@ -0,0 +1,175 @@
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.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.validProjectName = validProjectName;
9
+ exports.safeRelativePath = safeRelativePath;
10
+ exports.revisionForFiles = revisionForFiles;
11
+ exports.snapshotProject = snapshotProject;
12
+ exports.failure = failure;
13
+ exports.isAcknowledgedChange = isAcknowledgedChange;
14
+ const fs_1 = __importDefault(require("fs"));
15
+ const path_1 = __importDefault(require("path"));
16
+ const crypto_1 = __importDefault(require("crypto"));
17
+ const util_1 = require("./util");
18
+ exports.PROTOCOL_VERSION = 1;
19
+ exports.MAX_SOURCE_BYTES = 8 * 1024 * 1024;
20
+ exports.MAX_FILES = 2000;
21
+ exports.MAX_IMAGE_BYTES = 8 * 1024 * 1024;
22
+ exports.widgetFamilies = ['systemSmall', 'systemMedium', 'systemLarge', 'systemExtraLarge', 'accessoryCircular', 'accessoryRectangular', 'accessoryInline'];
23
+ class AgentError extends Error {
24
+ code;
25
+ constructor(code, message) {
26
+ super(message);
27
+ this.code = code;
28
+ }
29
+ }
30
+ exports.AgentError = AgentError;
31
+ const hash = (bytes) => crypto_1.default.createHash('sha256').update(bytes).digest('hex');
32
+ exports.hash = hash;
33
+ exports.methods = ['status', 'docs.search', 'docs.get', 'api.get', 'run', 'widget', 'widget.batch', 'projects.list', 'projects.inspect', 'projects.create', 'projects.attach'];
34
+ function validateCommand(value) {
35
+ if (!value || typeof value !== 'object' || Array.isArray(value) || !exports.methods.includes(value.method))
36
+ throw new AgentError('invalid_request', 'Unknown command.');
37
+ for (const key of ['device', 'project', 'query', 'docId', 'symbol', 'requestId']) {
38
+ if (value[key] !== undefined && (typeof value[key] !== 'string' || value[key].length > 1024))
39
+ throw new AgentError('invalid_request', `Invalid ${key}.`);
40
+ }
41
+ if (value.lang !== undefined && !['en', 'zh'].includes(value.lang))
42
+ throw new AgentError('invalid_request', 'Language must be en or zh.');
43
+ if (value.limit !== undefined && (!Number.isInteger(value.limit) || value.limit < 1 || value.limit > 50))
44
+ throw new AgentError('invalid_request', 'Limit must be 1...50.');
45
+ if (value.method === 'docs.get' && !value.docId)
46
+ throw new AgentError('invalid_request', 'A document ID is required.');
47
+ if (value.method === 'api.get' && !value.symbol)
48
+ throw new AgentError('invalid_request', 'An API symbol is required.');
49
+ const o = value.options ?? {};
50
+ if (!o || typeof o !== 'object' || Array.isArray(o))
51
+ throw new AgentError('invalid_request', 'Invalid options.');
52
+ for (const k of ['screenshot', 'noSync', 'replace', 'events'])
53
+ if (o[k] !== undefined && typeof o[k] !== 'boolean')
54
+ throw new AgentError('invalid_request', `Invalid ${k}.`);
55
+ if (o.timeout !== undefined && (!Number.isFinite(o.timeout) || o.timeout < 1 || o.timeout > 120))
56
+ throw new AgentError('invalid_request', 'Timeout must be 1...120 seconds.');
57
+ if (o.captureAfter !== undefined && (!Number.isFinite(o.captureAfter) || o.captureAfter < 0 || o.captureAfter > 10))
58
+ throw new AgentError('invalid_request', 'Capture delay must be 0...10 seconds.');
59
+ if (o.family !== undefined && !exports.widgetFamilies.includes(o.family))
60
+ throw new AgentError('invalid_request', 'Unsupported widget family.');
61
+ if (o.parameter !== undefined && (typeof o.parameter !== 'string' || o.parameter.length > 16384))
62
+ throw new AgentError('invalid_request', 'Invalid widget parameter.');
63
+ if (o.queryParameters !== undefined && (!o.queryParameters || typeof o.queryParameters !== 'object' || Array.isArray(o.queryParameters) || Buffer.byteLength(JSON.stringify(o.queryParameters)) > 65536))
64
+ throw new AgentError('invalid_request', 'Invalid query parameters.');
65
+ 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)))
66
+ throw new AgentError('invalid_request', 'Ready log requires script screenshot mode and one exact line.');
67
+ if (o.expectedRevision !== undefined && (typeof o.expectedRevision !== 'string' || !/^[a-f0-9]{64}$/.test(o.expectedRevision)))
68
+ throw new AgentError('invalid_request', 'Invalid expected revision.');
69
+ if (value.method.startsWith('projects.') && value.method !== 'projects.list' && !validProjectName(value.project))
70
+ throw new AgentError('invalid_project', 'A safe project name is required.');
71
+ if (value.method === 'widget.batch') {
72
+ if (!Array.isArray(o.cases) || o.cases.length < 1 || o.cases.length > 8)
73
+ throw new AgentError('invalid_request', 'Supply 1...8 widget cases.');
74
+ const ids = new Set();
75
+ for (const c of o.cases) {
76
+ 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)))
77
+ throw new AgentError('invalid_request', 'Invalid or duplicate widget case.');
78
+ ids.add(c.id);
79
+ }
80
+ }
81
+ return { ...value, options: o };
82
+ }
83
+ function validProjectName(value) { return typeof value === 'string' && value.length > 0 && Buffer.byteLength(value) < 256 && value !== '.' && value !== '..' && !value.startsWith('.') && !/[\/\\:\x00-\x1f\x7f]/.test(value); }
84
+ function safeRelativePath(value) {
85
+ 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
+ }
87
+ function revisionForFiles(files) {
88
+ 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
+ }
90
+ async function snapshotProject(workspace, project, ignore) {
91
+ if (!validProjectName(project))
92
+ throw new AgentError('invalid_project', 'Invalid project name.');
93
+ const root = path_1.default.join(workspace, 'scripts', project);
94
+ const scripts = await fs_1.default.promises.realpath(path_1.default.join(workspace, 'scripts'));
95
+ if ((await fs_1.default.promises.realpath(root)) !== path_1.default.join(scripts, project) || (await fs_1.default.promises.lstat(root)).isSymbolicLink())
96
+ throw new AgentError('invalid_project', 'Project symlinks are unsupported.');
97
+ const files = [];
98
+ let bytes = 0;
99
+ const stamps = [];
100
+ async function visit(relative) {
101
+ for (const name of (await fs_1.default.promises.readdir(path_1.default.join(root, relative))).sort()) {
102
+ const file = relative ? `${relative}/${name}` : name;
103
+ if ((0, util_1.isIgnoredPath)(file, ignore))
104
+ continue;
105
+ if (!safeRelativePath(file))
106
+ throw new AgentError('invalid_path', `Unsupported source path: ${file}`);
107
+ const full = path_1.default.join(root, file);
108
+ const before = await fs_1.default.promises.lstat(full);
109
+ if (before.isSymbolicLink())
110
+ throw new AgentError('invalid_path', `Source symlink: ${file}`);
111
+ if (before.isDirectory()) {
112
+ await visit(file);
113
+ continue;
114
+ }
115
+ if (!before.isFile())
116
+ throw new AgentError('invalid_path', `Not a regular file: ${file}`);
117
+ if (bytes + before.size > exports.MAX_SOURCE_BYTES || files.length >= exports.MAX_FILES)
118
+ throw new AgentError('source_limit', 'Source snapshot exceeds 8 MiB or 2000 files.');
119
+ const handle = await fs_1.default.promises.open(full, fs_1.default.constants.O_RDONLY | (fs_1.default.constants.O_NOFOLLOW || 0));
120
+ let data, after;
121
+ try {
122
+ const opened = await handle.stat();
123
+ if (!opened.isFile() || opened.ino !== before.ino)
124
+ throw new AgentError('source_changed', 'Source was replaced during capture.');
125
+ const buffer = Buffer.alloc(before.size + 1);
126
+ let read = 0;
127
+ while (read < buffer.length) {
128
+ const result = await handle.read(buffer, read, buffer.length - read, read);
129
+ if (!result.bytesRead)
130
+ break;
131
+ read += result.bytesRead;
132
+ }
133
+ data = buffer.subarray(0, read);
134
+ after = await handle.stat();
135
+ }
136
+ finally {
137
+ await handle.close();
138
+ }
139
+ const named = await fs_1.default.promises.lstat(full);
140
+ if (before.ino !== after.ino || before.ino !== named.ino || named.isSymbolicLink() || before.mtimeMs !== after.mtimeMs || before.size !== data.length || after.size !== data.length)
141
+ throw new AgentError('source_changed', 'Source changed while taking the snapshot; retry explicitly.');
142
+ stamps.push({ full, ino: after.ino, mtimeMs: after.mtimeMs, size: after.size });
143
+ bytes += data.length;
144
+ files.push({ path: file, sha256: (0, exports.hash)(data), data: data.toString('base64') });
145
+ }
146
+ }
147
+ await visit('');
148
+ for (const stamp of stamps) {
149
+ const final = await fs_1.default.promises.lstat(stamp.full);
150
+ if (!final.isFile() || final.isSymbolicLink() || final.ino !== stamp.ino || final.mtimeMs !== stamp.mtimeMs || final.size !== stamp.size)
151
+ throw new AgentError('source_changed', 'Source changed during the snapshot; retry explicitly.');
152
+ }
153
+ return { files, revision: revisionForFiles(files), ignore: [...ignore] };
154
+ }
155
+ function failure(error) {
156
+ return { code: error instanceof AgentError ? error.code : 'internal_error', message: error instanceof Error ? error.message : String(error) };
157
+ }
158
+ /** A delayed watcher notification for bytes already applied by this job must
159
+ * not trigger a second automatic run. Changes made after the snapshot remain. */
160
+ function isAcknowledgedChange(workspace, project, relative, snapshot) {
161
+ if (!safeRelativePath(relative))
162
+ return false;
163
+ const expected = snapshot.files.find(file => file.path === relative);
164
+ const file = path_1.default.join(workspace, 'scripts', project, relative);
165
+ if (!fs_1.default.existsSync(file))
166
+ return expected === undefined;
167
+ if (!expected || fs_1.default.lstatSync(file).isSymbolicLink() || !fs_1.default.statSync(file).isFile())
168
+ return false;
169
+ try {
170
+ return (0, exports.hash)(fs_1.default.readFileSync(file)) === expected.sha256;
171
+ }
172
+ catch {
173
+ return false;
174
+ }
175
+ }
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', {
@@ -6,12 +6,15 @@ export declare class Controller {
6
6
  private static instances;
7
7
  static create(socket: Socket, config: ResolvedConfig): Controller;
8
8
  static get(socketId: string): Controller | undefined;
9
+ private agentPauses;
10
+ private pendingAgentChanges;
11
+ private sendChange;
9
12
  watcher: FSWatcher | null;
10
13
  scriptName: string | null;
11
14
  socket: Socket | null;
12
15
  config: ResolvedConfig;
13
16
  constructor(socket: Socket, config: ResolvedConfig);
14
- createWatcher(scriptName: string): void;
17
+ createWatcher(scriptName: string, ignoreInitial?: boolean): void;
15
18
  handleSyncScriptFromClient: (data: {
16
19
  [globalDtsFileName]: string;
17
20
  [scriptingDtsFileName]: string;