arena-bridge 0.18.16 → 0.19.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/CHANGELOG.md +17 -0
- package/package.json +1 -1
- package/src/cli.mjs +71 -5
- package/src/config.mjs +26 -6
- package/src/engine.mjs +6 -0
- package/src/errors.mjs +1 -0
- package/src/hub.mjs +99 -4
- package/src/schema.mjs +38 -0
- package/src/state.mjs +6 -6
- package/src/version.mjs +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,23 @@ All notable changes to this project are documented here.
|
|
|
4
4
|
The format follows [Keep a Changelog](https://keepachangelog.com/) and the project uses
|
|
5
5
|
[Semantic Versioning](https://semver.org/).
|
|
6
6
|
|
|
7
|
+
## 0.19.1
|
|
8
|
+
|
|
9
|
+
### Fixed
|
|
10
|
+
- Removed the remaining Swift compiler warnings from the macOS app build.
|
|
11
|
+
- Config and runtime state recover a valid temporary atomic-write file after an interrupted replacement.
|
|
12
|
+
|
|
13
|
+
### Changed
|
|
14
|
+
- Node CI now runs on versions 18, 20, and 24 on both Ubuntu and macOS.
|
|
15
|
+
|
|
16
|
+
## 0.19.0
|
|
17
|
+
|
|
18
|
+
### Added
|
|
19
|
+
- Tool calls are validated against the published schemas before handlers run, including required fields, types, and unknown arguments.
|
|
20
|
+
- `config validate` checks mode, URLs, limits, tokens, tunnel settings, Telegram settings, and core runtime values.
|
|
21
|
+
- Hub mode now exposes the same health, config, approval polling, and audit read endpoints as direct mode.
|
|
22
|
+
- Added the retryable `DEVICE_BUSY` error for bounded hub queues.
|
|
23
|
+
|
|
7
24
|
## 0.18.16
|
|
8
25
|
|
|
9
26
|
### Fixed
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "arena-bridge",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.19.1",
|
|
4
4
|
"description": "Give a cloud AI agent (Arena.ai Agent Mode, Claude, Cursor, ...) controlled access to your own machine over HTTP/MCP: files, shell, Chrome and the macOS desktop, with an approval gate, trust windows and an audit log.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
package/src/cli.mjs
CHANGED
|
@@ -36,6 +36,63 @@ import {
|
|
|
36
36
|
|
|
37
37
|
const REPEATABLE_FLAGS = new Set(['root']);
|
|
38
38
|
|
|
39
|
+
export function validateConfig(cfg = {}) {
|
|
40
|
+
const errors = [];
|
|
41
|
+
const add = (message) => errors.push(message);
|
|
42
|
+
const nonEmptyString = (name, value) => {
|
|
43
|
+
if (typeof value !== 'string' || !value.trim()) add(`${name} must be a non-empty string`);
|
|
44
|
+
};
|
|
45
|
+
const integerRange = (name, value, min, max) => {
|
|
46
|
+
if (!Number.isInteger(value) || value < min || value > max) add(`${name} must be an integer from ${min} to ${max}`);
|
|
47
|
+
};
|
|
48
|
+
const urlValue = (name, value, required = false) => {
|
|
49
|
+
if (value == null || value === '') {
|
|
50
|
+
if (required) add(`${name} is required`);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
try {
|
|
54
|
+
const parsed = new URL(String(value));
|
|
55
|
+
if (!['http:', 'https:'].includes(parsed.protocol)) add(`${name} must use http or https`);
|
|
56
|
+
} catch {
|
|
57
|
+
add(`${name} must be a valid URL`);
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
if (!['direct', 'hub'].includes(cfg.mode)) add(`mode must be direct or hub`);
|
|
62
|
+
nonEmptyString('host', cfg.host);
|
|
63
|
+
integerRange('port', Number(cfg.port), 1, 65535);
|
|
64
|
+
nonEmptyString('device', cfg.device);
|
|
65
|
+
for (const key of ['token', 'deviceToken', 'localToken']) nonEmptyString(key, cfg[key]);
|
|
66
|
+
if (!Array.isArray(cfg.roots) || cfg.roots.some((value) => typeof value !== 'string')) add('roots must be an array of strings');
|
|
67
|
+
if (!Array.isArray(cfg.protected) || cfg.protected.some((value) => typeof value !== 'string')) add('protected must be an array of strings');
|
|
68
|
+
for (const key of ['requireApproval', 'allowShell', 'audit', 'exposeDeviceInHealth']) {
|
|
69
|
+
if (typeof cfg[key] !== 'boolean') add(`${key} must be boolean`);
|
|
70
|
+
}
|
|
71
|
+
integerRange('approvalWaitSec', Number(cfg.approvalWaitSec), 0, 3600);
|
|
72
|
+
integerRange('approvalTtlSec', Number(cfg.approvalTtlSec), 1, 86400);
|
|
73
|
+
integerRange('maxOutputBytes', Number(cfg.maxOutputBytes), 1, 256 * 1024 * 1024);
|
|
74
|
+
integerRange('maxUploadBytes', Number(cfg.maxUploadBytes), 1, 256 * 1024 * 1024);
|
|
75
|
+
integerRange('commandTimeoutSec', Number(cfg.commandTimeoutSec), 1, 1800);
|
|
76
|
+
urlValue('hub', cfg.hub, cfg.mode === 'hub');
|
|
77
|
+
urlValue('publicUrl', cfg.publicUrl);
|
|
78
|
+
|
|
79
|
+
if (!cfg.tunnel || typeof cfg.tunnel !== 'object' || Array.isArray(cfg.tunnel)) add('tunnel must be an object');
|
|
80
|
+
else {
|
|
81
|
+
nonEmptyString('tunnel.bin', cfg.tunnel.bin);
|
|
82
|
+
if (cfg.tunnel.domain != null && (typeof cfg.tunnel.domain !== 'string' || /\s/.test(cfg.tunnel.domain))) add('tunnel.domain must be a hostname without spaces');
|
|
83
|
+
if (cfg.tunnel.authtoken != null && typeof cfg.tunnel.authtoken !== 'string') add('tunnel.authtoken must be a string or null');
|
|
84
|
+
}
|
|
85
|
+
if (cfg.peekabooPath != null && typeof cfg.peekabooPath !== 'string') add('peekabooPath must be a string or null');
|
|
86
|
+
if (!cfg.telegram || typeof cfg.telegram !== 'object' || Array.isArray(cfg.telegram)) add('telegram must be an object');
|
|
87
|
+
else {
|
|
88
|
+
if (typeof cfg.telegram.enabled !== 'boolean') add('telegram.enabled must be boolean');
|
|
89
|
+
if (!Array.isArray(cfg.telegram.chatIds) || cfg.telegram.chatIds.some((id) => typeof id !== 'string' || !id.trim())) add('telegram.chatIds must be an array of non-empty strings');
|
|
90
|
+
if (typeof cfg.telegram.poll !== 'boolean') add('telegram.poll must be boolean');
|
|
91
|
+
if (cfg.telegram.enabled && (!cfg.telegram.botToken || !cfg.telegram.chatIds.length)) add('enabled Telegram requires botToken and at least one chat id');
|
|
92
|
+
}
|
|
93
|
+
return errors;
|
|
94
|
+
}
|
|
95
|
+
|
|
39
96
|
export function parseArgs(argv) {
|
|
40
97
|
const out = { _: [], flags: {} };
|
|
41
98
|
const set = (key, value) => {
|
|
@@ -854,7 +911,19 @@ function cmdRotate(args) {
|
|
|
854
911
|
|
|
855
912
|
function cmdConfig(args) {
|
|
856
913
|
const sub = args._[1] || 'list';
|
|
857
|
-
|
|
914
|
+
let cfg;
|
|
915
|
+
try {
|
|
916
|
+
cfg = loadConfig();
|
|
917
|
+
} catch (e) {
|
|
918
|
+
if (sub === 'validate') {
|
|
919
|
+
const errors = [e.message];
|
|
920
|
+
if (args.flags.json) console.log(JSON.stringify({ ok: false, errors }, null, 2));
|
|
921
|
+
else { console.log('✗ config issues:'); for (const error of errors) console.log(` - ${error}`); }
|
|
922
|
+
process.exitCode = 1;
|
|
923
|
+
return;
|
|
924
|
+
}
|
|
925
|
+
throw e;
|
|
926
|
+
}
|
|
858
927
|
if (sub === 'list' || sub === 'show') {
|
|
859
928
|
const out = { ...cfg };
|
|
860
929
|
delete out.configPath;
|
|
@@ -931,10 +1000,7 @@ function cmdConfig(args) {
|
|
|
931
1000
|
}
|
|
932
1001
|
if (sub === 'validate') {
|
|
933
1002
|
const isJson = !!(args.flags.json);
|
|
934
|
-
const errs =
|
|
935
|
-
if (!cfg.token) errs.push('token missing — run arena-bridge init');
|
|
936
|
-
if (!cfg.deviceToken) errs.push('deviceToken missing');
|
|
937
|
-
if (!Number.isFinite(Number(cfg.port)) || Number(cfg.port) < 1 || Number(cfg.port) > 65535) errs.push(`port invalid: ${cfg.port}`);
|
|
1003
|
+
const errs = validateConfig(cfg);
|
|
938
1004
|
if (isJson) console.log(JSON.stringify({ ok: errs.length===0, errors: errs }, null, 2));
|
|
939
1005
|
else { if (!errs.length) console.log('✓ config valid'); else { console.log('✗ config issues:'); for (const e of errs) console.log(` - ${e}`); process.exitCode=1; } }
|
|
940
1006
|
return;
|
package/src/config.mjs
CHANGED
|
@@ -71,11 +71,31 @@ export function ensureDirs() {
|
|
|
71
71
|
fs.mkdirSync(APPROVALS_DIR, { recursive: true, mode: 0o700 });
|
|
72
72
|
}
|
|
73
73
|
|
|
74
|
+
function readJson(file) {
|
|
75
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Read an atomic file and recover a complete temporary replacement after interruption. */
|
|
79
|
+
export function readJsonWithRecovery(file) {
|
|
80
|
+
try {
|
|
81
|
+
return readJson(file);
|
|
82
|
+
} catch (primaryError) {
|
|
83
|
+
const tmp = `${file}.tmp`;
|
|
84
|
+
try {
|
|
85
|
+
const recovered = readJson(tmp);
|
|
86
|
+
fs.renameSync(tmp, file);
|
|
87
|
+
return recovered;
|
|
88
|
+
} catch {
|
|
89
|
+
throw primaryError;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
74
94
|
export function loadConfig() {
|
|
75
95
|
let fileCfg = {};
|
|
76
|
-
if (fs.existsSync(CONFIG_PATH)) {
|
|
96
|
+
if (fs.existsSync(CONFIG_PATH) || fs.existsSync(`${CONFIG_PATH}.tmp`)) {
|
|
77
97
|
try {
|
|
78
|
-
fileCfg =
|
|
98
|
+
fileCfg = readJsonWithRecovery(CONFIG_PATH);
|
|
79
99
|
} catch (e) {
|
|
80
100
|
throw new Error(`Invalid config file ${CONFIG_PATH}: ${e.message}`);
|
|
81
101
|
}
|
|
@@ -83,8 +103,8 @@ export function loadConfig() {
|
|
|
83
103
|
// Merge state (publicUrl) — state wins if config doesn't have it, for backward compat
|
|
84
104
|
try {
|
|
85
105
|
const statePath = path.join(CONFIG_DIR, 'state.json');
|
|
86
|
-
|
|
87
|
-
|
|
106
|
+
if (fs.existsSync(statePath) || fs.existsSync(`${statePath}.tmp`)) {
|
|
107
|
+
const state = readJsonWithRecovery(statePath);
|
|
88
108
|
if (state.publicUrl && !fileCfg.publicUrl) fileCfg.publicUrl = state.publicUrl;
|
|
89
109
|
// also expose state for debug
|
|
90
110
|
fileCfg._state = state;
|
|
@@ -104,7 +124,7 @@ export function saveConfig(cfg) {
|
|
|
104
124
|
try {
|
|
105
125
|
const statePath = path.join(CONFIG_DIR, 'state.json');
|
|
106
126
|
let state = {};
|
|
107
|
-
try { state =
|
|
127
|
+
try { state = readJsonWithRecovery(statePath); } catch {}
|
|
108
128
|
if (cfg.publicUrl) state.publicUrl = cfg.publicUrl;
|
|
109
129
|
else delete state.publicUrl;
|
|
110
130
|
fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
|
|
@@ -114,7 +134,7 @@ export function saveConfig(cfg) {
|
|
|
114
134
|
} catch {}
|
|
115
135
|
}
|
|
116
136
|
let existing = {};
|
|
117
|
-
try { existing =
|
|
137
|
+
try { existing = readJsonWithRecovery(CONFIG_PATH); } catch {}
|
|
118
138
|
const out = { ...existing };
|
|
119
139
|
for (const [k, v] of Object.entries(cfg)) {
|
|
120
140
|
if (k === 'configPath' || k === '_state' || k === 'publicUrl') continue;
|
package/src/engine.mjs
CHANGED
|
@@ -10,6 +10,7 @@ import { BrowserManager, cleanupOrphanChromes } from './browser.mjs';
|
|
|
10
10
|
import { macTools } from './mac.mjs';
|
|
11
11
|
import { trustState, trustAllows } from './trust.mjs';
|
|
12
12
|
import { errorResponse } from './errors.mjs';
|
|
13
|
+
import { validateArgs } from './schema.mjs';
|
|
13
14
|
import { telegramTools } from './telegram.mjs';
|
|
14
15
|
|
|
15
16
|
/* ------------------------------------------------------------------ *
|
|
@@ -72,6 +73,11 @@ export class Engine {
|
|
|
72
73
|
record({ kind: 'call', status: 'rejected', error: 'UNKNOWN_TOOL', via: 'direct' });
|
|
73
74
|
return errorResponse('UNKNOWN_TOOL', { message: `unknown tool: ${name}`, tool: name, hint });
|
|
74
75
|
}
|
|
76
|
+
const valid = validateArgs(tool.schema, tool.required, args);
|
|
77
|
+
if (!valid.ok) {
|
|
78
|
+
record({ kind: 'call', status: 'rejected', error: 'INVALID_ARGS', via: 'validation' });
|
|
79
|
+
return errorResponse('INVALID_ARGS', { message: valid.message, field: valid.field });
|
|
80
|
+
}
|
|
75
81
|
const started = Date.now();
|
|
76
82
|
let approval = null;
|
|
77
83
|
const entryId = `${new Date().toISOString().replace(/[:.]/g, '-')}-${String(name).replace(/[^\w.-]/g, '_')}-${Math.random()
|
package/src/errors.mjs
CHANGED
|
@@ -17,6 +17,7 @@ export const ERROR_CODES = {
|
|
|
17
17
|
UNKNOWN_TOOL: { message: 'unknown tool', hint: 'GET /tools for catalog', retryable: false },
|
|
18
18
|
INVALID_ARGS: { message: 'arguments are missing or malformed', hint: 'check the tool schema in GET /tools', retryable: false },
|
|
19
19
|
RATE_LIMITED: { message: 'too many calls in a short time', hint: 'wait a second and retry', retryable: true },
|
|
20
|
+
DEVICE_BUSY: { message: 'the target device queue is full', hint: 'wait and retry the call', retryable: true },
|
|
20
21
|
};
|
|
21
22
|
|
|
22
23
|
export function errorResponse(code, extra = {}) {
|
package/src/hub.mjs
CHANGED
|
@@ -1,16 +1,20 @@
|
|
|
1
1
|
import http from 'node:http';
|
|
2
2
|
import { VERSION } from './version.mjs';
|
|
3
3
|
import crypto from 'node:crypto';
|
|
4
|
-
import { sendJson, sendText, readJson, readBody, isAuthorized, bearer, safeEqual, actorFor } from './http.mjs';
|
|
4
|
+
import { sendJson, sendText, sendRaw, readJson, readBody, isAuthorized, bearer, safeEqual, actorFor } from './http.mjs';
|
|
5
5
|
import { handleMcp } from './mcp.mjs';
|
|
6
6
|
import { buildPrompt } from './prompt.mjs';
|
|
7
7
|
import { toolCatalog } from './engine.mjs';
|
|
8
8
|
import { listApprovals, decide } from './approvals.mjs';
|
|
9
9
|
import { checkPath } from './policy.mjs';
|
|
10
|
-
import { loadConfig } from './config.mjs';
|
|
10
|
+
import { loadConfig, CONFIG_DIR } from './config.mjs';
|
|
11
11
|
import fsp from 'node:fs/promises';
|
|
12
|
-
import
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import { audit, auditPage, auditDir, findEntry, headCursor, lean, readArtifact, tailAudit } from './audit.mjs';
|
|
13
15
|
import { sourceOf, describeSource, admitUnauthorized } from './source.mjs';
|
|
16
|
+
import { errorResponse } from './errors.mjs';
|
|
17
|
+
import { trustState } from './trust.mjs';
|
|
14
18
|
|
|
15
19
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
16
20
|
const MAX_QUEUED_PER_DEVICE = 100;
|
|
@@ -46,7 +50,7 @@ export function createHubServer(cfg) {
|
|
|
46
50
|
const dispatch = (device, tool, args, timeoutSec = 120, source = null) => {
|
|
47
51
|
const q = queues.get(device) || [];
|
|
48
52
|
if (q.length >= MAX_QUEUED_PER_DEVICE) {
|
|
49
|
-
return Promise.resolve(
|
|
53
|
+
return Promise.resolve(errorResponse('DEVICE_BUSY', { reason: `device "${device}" has too many queued jobs` }));
|
|
50
54
|
}
|
|
51
55
|
return new Promise((resolve) => {
|
|
52
56
|
const id = crypto.randomUUID();
|
|
@@ -104,10 +108,27 @@ export function createHubServer(cfg) {
|
|
|
104
108
|
|
|
105
109
|
try {
|
|
106
110
|
if (p === '/health') {
|
|
111
|
+
const current = loadConfig();
|
|
112
|
+
let pending = 0, auditCount = 0, logSize = 0;
|
|
113
|
+
try { pending = listApprovals().filter((item) => item.status === 'pending').length; } catch {}
|
|
114
|
+
try { auditCount = tailAudit(500).length; } catch {}
|
|
115
|
+
try {
|
|
116
|
+
const log = path.join(CONFIG_DIR, 'logs', 'bridge.log');
|
|
117
|
+
if (fs.existsSync(log)) logSize = fs.statSync(log).size;
|
|
118
|
+
} catch {}
|
|
107
119
|
return sendJson(res, 200, {
|
|
108
120
|
ok: true,
|
|
109
121
|
mode: 'hub',
|
|
110
122
|
version: VERSION,
|
|
123
|
+
device: current.device,
|
|
124
|
+
uptime_sec: Math.round(process.uptime()),
|
|
125
|
+
pending_approvals: pending,
|
|
126
|
+
trust_active: !!trustState().active,
|
|
127
|
+
audit_count: auditCount,
|
|
128
|
+
log_size: logSize,
|
|
129
|
+
has_public_url: !!current.publicUrl,
|
|
130
|
+
public_url: current.publicUrl ?? null,
|
|
131
|
+
tunnel_alive: null,
|
|
111
132
|
devices: [...devices.keys()],
|
|
112
133
|
});
|
|
113
134
|
}
|
|
@@ -182,6 +203,80 @@ export function createHubServer(cfg) {
|
|
|
182
203
|
return sendJson(res, 200, { ok: true, approvals: listApprovals() });
|
|
183
204
|
}
|
|
184
205
|
|
|
206
|
+
if (req.method === 'GET' && /^\/approvals\/[\w-]+$/.test(p)) {
|
|
207
|
+
const id = p.split('/').pop();
|
|
208
|
+
const approval = listApprovals().find((item) => item.id === id);
|
|
209
|
+
if (!approval) return sendJson(res, 404, { ok: false, error: 'approval_not_found' });
|
|
210
|
+
return sendJson(res, 200, { ok: true, approval });
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
if (req.method === 'GET' && p === '/config') {
|
|
214
|
+
const current = loadConfig();
|
|
215
|
+
return sendJson(res, 200, {
|
|
216
|
+
ok: true,
|
|
217
|
+
device: current.device,
|
|
218
|
+
roots: current.roots,
|
|
219
|
+
protected_count: current.protected.length,
|
|
220
|
+
requireApproval: current.requireApproval,
|
|
221
|
+
allowShell: current.allowShell,
|
|
222
|
+
approvalWaitSec: current.approvalWaitSec,
|
|
223
|
+
maxOutputBytes: current.maxOutputBytes,
|
|
224
|
+
telegram: {
|
|
225
|
+
enabled: !!current.telegram?.enabled,
|
|
226
|
+
chat_ids: current.telegram?.chatIds || [],
|
|
227
|
+
},
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
if (req.method === 'GET' && p === '/audit') {
|
|
232
|
+
const q = url.searchParams;
|
|
233
|
+
const raw = q.get('limit');
|
|
234
|
+
const limit = raw === null || raw === '' ? 100 : Number(raw);
|
|
235
|
+
if (!Number.isFinite(limit) || limit <= 0) return sendJson(res, 400, { ok: false, error: 'invalid limit' });
|
|
236
|
+
const page = auditPage({
|
|
237
|
+
limit: Math.min(500, Math.floor(limit)),
|
|
238
|
+
before: q.get('before') || undefined,
|
|
239
|
+
after: q.get('after') || undefined,
|
|
240
|
+
tool: q.get('tool') || undefined,
|
|
241
|
+
kind: q.get('kind') || undefined,
|
|
242
|
+
level: q.get('level') || undefined,
|
|
243
|
+
});
|
|
244
|
+
if (page.error) return sendJson(res, 400, { ok: false, error: page.error });
|
|
245
|
+
return sendJson(res, 200, {
|
|
246
|
+
ok: true,
|
|
247
|
+
entries: page.entries.map(lean),
|
|
248
|
+
next: page.next,
|
|
249
|
+
has_more: page.has_more,
|
|
250
|
+
reset: page.reset,
|
|
251
|
+
head: headCursor(),
|
|
252
|
+
artifacts_dir: auditDir(),
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
if (req.method === 'GET' && p === '/audit/entry') {
|
|
257
|
+
const id = url.searchParams.get('id');
|
|
258
|
+
if (!id) return sendJson(res, 400, { ok: false, error: 'id query parameter is required' });
|
|
259
|
+
const entry = findEntry(id);
|
|
260
|
+
if (!entry) return sendJson(res, 404, { ok: false, error: 'entry_not_found' });
|
|
261
|
+
return sendJson(res, 200, { ok: true, entry });
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
if (req.method === 'GET' && p === '/audit/artifact') {
|
|
265
|
+
const entry = url.searchParams.get('entry');
|
|
266
|
+
const file = url.searchParams.get('file');
|
|
267
|
+
if (!entry || !file) return sendJson(res, 400, { ok: false, error: 'entry and file query parameters are required' });
|
|
268
|
+
const art = readArtifact(entry, file);
|
|
269
|
+
if (!art) return sendJson(res, 404, { ok: false, error: 'artifact_not_found' });
|
|
270
|
+
const type = /\.png$/i.test(art.file)
|
|
271
|
+
? 'image/png'
|
|
272
|
+
: /\.jpe?g$/i.test(art.file)
|
|
273
|
+
? 'image/jpeg'
|
|
274
|
+
: /\.json$/i.test(art.file)
|
|
275
|
+
? 'application/json; charset=utf-8'
|
|
276
|
+
: 'text/plain; charset=utf-8';
|
|
277
|
+
return sendRaw(res, 200, art.data, type);
|
|
278
|
+
}
|
|
279
|
+
|
|
185
280
|
const approveMatch = /^\/approvals\/([\w-]+)$/.exec(p);
|
|
186
281
|
if (req.method === 'POST' && approveMatch) {
|
|
187
282
|
// settling a request is a local-only privilege: the agent token must not self-approve
|
package/src/schema.mjs
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
function actualType(value) {
|
|
2
|
+
if (value === null) return 'null';
|
|
3
|
+
if (Array.isArray(value)) return 'array';
|
|
4
|
+
return typeof value;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
function matchesType(value, type) {
|
|
8
|
+
if (type === 'number') return typeof value === 'number' && Number.isFinite(value);
|
|
9
|
+
if (type === 'object') return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
10
|
+
if (type === 'array') return Array.isArray(value);
|
|
11
|
+
return actualType(value) === type;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Validate the shallow JSON schemas exposed by the tool catalog. */
|
|
15
|
+
export function validateArgs(schema, required = [], args) {
|
|
16
|
+
if (!matchesType(args, 'object')) {
|
|
17
|
+
return { ok: false, field: null, message: `arguments must be an object, got ${actualType(args)}` };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const properties = schema?.properties || {};
|
|
21
|
+
for (const key of Object.keys(args)) {
|
|
22
|
+
if (schema?.additionalProperties === false && !Object.hasOwn(properties, key)) {
|
|
23
|
+
return { ok: false, field: key, message: `unknown argument: ${key}` };
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
for (const key of required || []) {
|
|
27
|
+
if (!Object.hasOwn(args, key) || args[key] === undefined) {
|
|
28
|
+
return { ok: false, field: key, message: `argument is required: ${key}` };
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
for (const [key, spec] of Object.entries(properties)) {
|
|
32
|
+
if (!Object.hasOwn(args, key) || args[key] === undefined || !spec?.type) continue;
|
|
33
|
+
if (!matchesType(args[key], spec.type)) {
|
|
34
|
+
return { ok: false, field: key, message: `argument ${key} must be ${spec.type}, got ${actualType(args[key])}` };
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return { ok: true };
|
|
38
|
+
}
|
package/src/state.mjs
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
-
import { CONFIG_DIR, CONFIG_PATH } from './config.mjs';
|
|
3
|
+
import { CONFIG_DIR, CONFIG_PATH, readJsonWithRecovery } from './config.mjs';
|
|
4
4
|
|
|
5
5
|
export const STATE_PATH = path.join(CONFIG_DIR, 'state.json');
|
|
6
6
|
|
|
7
7
|
export function loadState() {
|
|
8
8
|
try {
|
|
9
|
-
if (fs.existsSync(STATE_PATH)) {
|
|
10
|
-
return
|
|
9
|
+
if (fs.existsSync(STATE_PATH) || fs.existsSync(`${STATE_PATH}.tmp`)) {
|
|
10
|
+
return readJsonWithRecovery(STATE_PATH);
|
|
11
11
|
}
|
|
12
12
|
} catch {}
|
|
13
13
|
return {};
|
|
@@ -15,11 +15,11 @@ export function loadState() {
|
|
|
15
15
|
|
|
16
16
|
export function saveState(patch) {
|
|
17
17
|
let cur = {};
|
|
18
|
-
try { cur =
|
|
18
|
+
try { cur = readJsonWithRecovery(STATE_PATH); } catch {}
|
|
19
19
|
// migrate publicUrl from config.json if present and not in state
|
|
20
20
|
if (!cur.publicUrl && fs.existsSync(CONFIG_PATH)) {
|
|
21
21
|
try {
|
|
22
|
-
const cfg =
|
|
22
|
+
const cfg = readJsonWithRecovery(CONFIG_PATH);
|
|
23
23
|
if (cfg.publicUrl) {
|
|
24
24
|
cur.publicUrl = cfg.publicUrl;
|
|
25
25
|
// remove from config to complete migration (best effort)
|
|
@@ -125,7 +125,7 @@ export function stopPid(pid, waitMs = 3000) {
|
|
|
125
125
|
|
|
126
126
|
export function clearStateKey(key) {
|
|
127
127
|
let cur = {};
|
|
128
|
-
try { cur =
|
|
128
|
+
try { cur = readJsonWithRecovery(STATE_PATH); } catch {}
|
|
129
129
|
if (key in cur) {
|
|
130
130
|
delete cur[key];
|
|
131
131
|
const tmp = STATE_PATH + '.tmp';
|