@tnunamak/dalan 0.5.2 → 0.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.
- package/CHANGELOG.md +29 -25
- package/PROTOCOL.md +16 -4
- package/README.md +127 -260
- package/SECURITY.md +1 -1
- package/bin/dalan.mjs +5 -0
- package/bin/dot-worker.mjs +35 -26
- package/docs/chatgpt-worker-onboarding.md +5 -5
- package/docs/claude-worker-onboarding.md +5 -5
- package/docs/codex-to-muse.md +175 -0
- package/docs/connect-chatgpt.md +9 -4
- package/docs/connection-longevity.md +7 -1
- package/docs/dalan-upgrade.md +17 -13
- package/docs/deadman.md +5 -3
- package/docs/local-agent-mcp.md +8 -6
- package/docs/manual-setup.md +8 -8
- package/docs/mirror-fetch.md +1 -2
- package/docs/operations.md +90 -42
- package/docs/operator-duties.md +1 -1
- package/docs/owner-integrator.md +2 -2
- package/docs/portable-auth-profile.md +12 -14
- package/docs/pr-head-reviewer.md +21 -5
- package/docs/pr-preflight.md +2 -0
- package/docs/pull-queue.md +131 -0
- package/docs/pull-workers.md +7 -10
- package/docs/redaction.md +1 -1
- package/docs/service-setup.md +56 -3
- package/docs/setup-reference.md +1 -1
- package/docs/t3-integration.md +2 -0
- package/docs/t3-result-retry-delivery.md +2 -2
- package/docs/t3-reverse-control.md +7 -7
- package/docs/usage.md +19 -15
- package/docs/worker-clients.md +18 -13
- package/package.json +3 -1
- package/scripts/dalan-try-selfcheck.mjs +29 -0
- package/scripts/worker-bridge-setup.mjs +1 -1
- package/src/acp-bridge.mjs +18 -12
- package/src/as.mjs +41 -0
- package/src/child-exit.mjs +18 -0
- package/src/child-registry.mjs +94 -0
- package/src/cli-help.mjs +25 -11
- package/src/demo-worker.mjs +2 -2
- package/src/drained-owner.mjs +26 -0
- package/src/drained-slot.mjs +20 -3
- package/src/mcp-outcome.mjs +10 -1
- package/src/mcp-sse.mjs +62 -0
- package/src/pr-head-reviewer.mjs +3 -3
- package/src/process-inspection.mjs +36 -0
- package/src/pull-queue.mjs +159 -0
- package/src/route-setting.mjs +24 -0
- package/src/server.mjs +157 -29
- package/src/service-migrate-workers.mjs +113 -0
- package/src/service.mjs +388 -0
- package/src/setup.mjs +63 -0
- package/src/store.mjs +21 -9
- package/src/tool-registry.mjs +3 -1
- package/src/try-exposure.mjs +908 -0
- package/src/try-hosted-clients.mjs +46 -0
- package/src/try-hosted.mjs +444 -0
- package/src/try-selfcheck.mjs +168 -0
- package/src/try.mjs +63 -17
- package/src/workers.mjs +33 -23
- package/src/workspace.mjs +10 -3
package/src/service.mjs
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import net from 'node:net';
|
|
5
|
+
import { spawnSync } from 'node:child_process';
|
|
6
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import { isIP } from 'node:net';
|
|
9
|
+
import { defaultPath } from './paths.mjs';
|
|
10
|
+
import { initAsFiles } from './as-files.mjs';
|
|
11
|
+
import { parseWorkers } from './workers.mjs';
|
|
12
|
+
import { parseArgs } from '../scripts/live-trial/common.mjs';
|
|
13
|
+
|
|
14
|
+
const REPO = fileURLToPath(new URL('..', import.meta.url));
|
|
15
|
+
const SAFE_PATH = /^[A-Za-z0-9_@+=:,./-]+$/;
|
|
16
|
+
const fail = message => { throw new Error(message); };
|
|
17
|
+
|
|
18
|
+
function parseOrigin(value) {
|
|
19
|
+
let url;
|
|
20
|
+
try { url = new URL(value); } catch { fail('--public-url must be an HTTPS origin'); }
|
|
21
|
+
if (url.protocol !== 'https:' || url.username || url.password || url.pathname !== '/' || url.search || url.hash || value !== url.origin) {
|
|
22
|
+
fail('--public-url must contain only https://, a host and an optional port');
|
|
23
|
+
}
|
|
24
|
+
return url.origin;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function parseTarget(value) {
|
|
28
|
+
const match = /^((?:\d{1,3}\.){3}\d{1,3}):(\d{1,5})$/.exec(value ?? '');
|
|
29
|
+
if (!match || isIP(match[1]) !== 4 || match[1].split('.').some(part => Number(part) > 255)) {
|
|
30
|
+
fail('--target must be an IPv4 address and port, such as 127.0.0.1:8789');
|
|
31
|
+
}
|
|
32
|
+
const port = Number(match[2]);
|
|
33
|
+
if (port < 1 || port > 65535) fail('--target port must be 1 through 65535');
|
|
34
|
+
return { host: match[1], port, value: `${match[1]}:${port}` };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function validateTopology({ port, target, lanPort = null, verifyCmd }) {
|
|
38
|
+
if (!Number.isInteger(port) || port < 1024 || port > 65535) fail('--port must be a fixed port from 1024 through 65535');
|
|
39
|
+
if (lanPort !== null && (!Number.isInteger(lanPort) || lanPort < 1024 || lanPort > 65535)) fail('--lan-port must be a port from 1024 through 65535');
|
|
40
|
+
const direct = target.host === '127.0.0.1' && target.port === port;
|
|
41
|
+
if (!direct && lanPort !== target.port) fail('a forwarded --target requires --lan-port matching its port');
|
|
42
|
+
if (direct && lanPort !== null) fail('--lan-port needs a separate --target address and port');
|
|
43
|
+
if (!direct && target.port === port && target.host === '0.0.0.0') fail('same-port --target must not use wildcard 0.0.0.0; it collides with the loopback listener');
|
|
44
|
+
if (verifyCmd != null && (typeof verifyCmd !== 'string' || !verifyCmd.trim() || verifyCmd.length > 4096)) fail('--verify-cmd must be a nonempty command of at most 4096 characters');
|
|
45
|
+
if (target.port !== port && !(typeof verifyCmd === 'string' && verifyCmd.trim())) fail('translated target ports require an explicit nonempty --verify-cmd; challenge verification binds the receiving port');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function parseOptions(argv, env) {
|
|
49
|
+
const parsed = parseArgs(argv, {
|
|
50
|
+
values: ['--home', '--public-url', '--port', '--target', '--worker', '--verify-cmd', '--gozar-bin', '--lan-port'],
|
|
51
|
+
flags: ['--write-units-only', '--enable-workspace', '--enable-t3', '--json', '--help'],
|
|
52
|
+
});
|
|
53
|
+
if (parsed._.length) fail(`unexpected argument ${parsed._[0]}`);
|
|
54
|
+
if (parsed['--help']) return { help: true };
|
|
55
|
+
const home = path.resolve(parsed['--home'] ?? path.join(os.homedir(), '.local/share/dalan-service'));
|
|
56
|
+
if (!SAFE_PATH.test(home)) fail('--home contains characters that cannot be written safely in a systemd unit');
|
|
57
|
+
const origin = parseOrigin(parsed['--public-url']);
|
|
58
|
+
const port = Number(parsed['--port']);
|
|
59
|
+
if (!Number.isInteger(port) || port < 1024 || port > 65535) fail('--port must be a fixed port from 1024 through 65535');
|
|
60
|
+
const target = parseTarget(parsed['--target']);
|
|
61
|
+
const lanPort = parsed['--lan-port'] === undefined ? null : Number(parsed['--lan-port']);
|
|
62
|
+
validateTopology({ port, target, lanPort, verifyCmd: parsed['--verify-cmd'] });
|
|
63
|
+
const workers = [];
|
|
64
|
+
for (let i = 0; i < argv.length; i++) {
|
|
65
|
+
if (argv[i] === '--worker') workers.push(argv[++i]);
|
|
66
|
+
else if (argv[i].startsWith('--worker=')) workers.push(argv[i].slice('--worker='.length));
|
|
67
|
+
}
|
|
68
|
+
if (workers.some(name => typeof name !== 'string' || !/^[a-z][a-z0-9_-]{0,31}$/.test(name) || ['pool', 'unknown'].includes(name))) {
|
|
69
|
+
fail('--worker must be a lowercase name of up to 32 letters, digits, - or _');
|
|
70
|
+
}
|
|
71
|
+
if (new Set(workers).size !== workers.length) fail('--worker names must be unique');
|
|
72
|
+
if (parsed['--verify-cmd']?.length > 4096) fail('--verify-cmd is too long');
|
|
73
|
+
const gozarBin = parsed['--gozar-bin'] ?? env.GOZAR_BIN ?? 'gozar';
|
|
74
|
+
if (!gozarBin || gozarBin.startsWith('-')) fail('--gozar-bin must name a command');
|
|
75
|
+
return { home, origin, port, target, lanPort, enableWorkspace: parsed['--enable-workspace'] === true, enableT3: parsed['--enable-t3'] === true, workers, verifyCmd: parsed['--verify-cmd'] ?? null,
|
|
76
|
+
gozarBin, writeUnitsOnly: parsed['--write-units-only'] === true, json: parsed['--json'] === true };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function assertRealDirectoryPath(target, { owner = false } = {}) {
|
|
80
|
+
const absolute = path.resolve(target), root = path.parse(absolute).root;
|
|
81
|
+
let current = root, deepest = null;
|
|
82
|
+
for (const part of absolute.slice(root.length).split(path.sep).filter(Boolean)) {
|
|
83
|
+
current = path.join(current, part);
|
|
84
|
+
let info;
|
|
85
|
+
try { info = fs.lstatSync(current); } catch (error) { if (error.code === 'ENOENT') continue; throw error; }
|
|
86
|
+
if (info.isSymbolicLink() || !info.isDirectory() || fs.realpathSync(current) !== current) {
|
|
87
|
+
fail(`${current} is not a real directory; refusing to write through a symlink`);
|
|
88
|
+
}
|
|
89
|
+
deepest = { path: current, info };
|
|
90
|
+
}
|
|
91
|
+
if (owner && deepest && typeof process.getuid === 'function' && deepest.info.uid !== process.getuid()) fail(`${deepest.path} is not owned by the current user`);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function nodePath(execPath) {
|
|
95
|
+
let real;
|
|
96
|
+
try { real = fs.realpathSync(execPath); } catch { return execPath; }
|
|
97
|
+
const userHome = os.userInfo().homedir || os.homedir();
|
|
98
|
+
const candidates = ['/opt/homebrew/bin/node', '/usr/local/bin/node', path.join(userHome, '.local/share/mise/installs/node/lts/bin/node')];
|
|
99
|
+
for (const candidate of candidates) {
|
|
100
|
+
try { if (fs.realpathSync(candidate) === real) return candidate; } catch { /* candidate is not installed */ }
|
|
101
|
+
}
|
|
102
|
+
return execPath;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function unitName(home) { return `dalan-${createHash('sha256').update(home).digest('hex').slice(0, 10)}`; }
|
|
106
|
+
|
|
107
|
+
function unitFiles(o, { home, repo = REPO, node = nodePath(process.execPath), proxy = null } = {}) {
|
|
108
|
+
const name = unitName(home);
|
|
109
|
+
for (const [label, value] of [['home', home], ['repo', repo], ['node', node]]) {
|
|
110
|
+
if (!SAFE_PATH.test(value)) fail(`${label} contains characters that cannot be written safely in a systemd unit`);
|
|
111
|
+
}
|
|
112
|
+
const base = {
|
|
113
|
+
[`${name}.service`]: [
|
|
114
|
+
'[Unit]', 'Description=Dalan worker bridge', 'After=network-online.target', '', '[Service]',
|
|
115
|
+
`WorkingDirectory=${repo}`, `ExecStart=${node} ${path.join(repo, 'src/server.mjs')}`,
|
|
116
|
+
`Environment=HOME=${home}`, 'Environment=NODE_ENV=production', 'Environment=DALAN_AUTH_MODE=builtin',
|
|
117
|
+
'Environment=DALAN_BIND_HOST=127.0.0.1', 'Environment=DALAN_GOZAR_SERVICE=1', 'Environment=DALAN_CATALOG_PROFILE=stable',
|
|
118
|
+
`Environment=DALAN_ENABLE_WORKSPACE=${o.enableWorkspace ? '1' : '0'}`, `Environment=DALAN_ENABLE_T3_TOOLS=${o.enableT3 ? '1' : '0'}`,
|
|
119
|
+
`Environment=DALAN_PORT=${o.port}`, `Environment=PATH=${[path.dirname(node), '/usr/local/bin', '/usr/bin', '/bin'].join(':')}`,
|
|
120
|
+
'UnsetEnvironment=OPENAI_API_KEY ANTHROPIC_API_KEY DALAN_LOOPBACK DOT_BRIDGE_LOOPBACK DALAN_WORKERS_FILE DOT_BRIDGE_WORKERS_FILE', 'Restart=on-failure', 'RestartSec=3', 'UMask=0077', '',
|
|
121
|
+
'[Install]', 'WantedBy=default.target', '',
|
|
122
|
+
].join('\n'),
|
|
123
|
+
};
|
|
124
|
+
const enable = [`${name}.service`];
|
|
125
|
+
const isDirect = o.target.host === '127.0.0.1' && o.target.port === o.port;
|
|
126
|
+
if (!isDirect) {
|
|
127
|
+
if (!proxy || !SAFE_PATH.test(proxy)) fail('systemd-socket-proxyd is required when --target is not 127.0.0.1:<port>');
|
|
128
|
+
base[`${name}-target.socket`] = [
|
|
129
|
+
'[Unit]', 'Description=Gozar target for Dalan', '', '[Socket]',
|
|
130
|
+
`ListenStream=${o.target.host}:${o.target.port}`, 'FreeBind=true', '', '[Install]', 'WantedBy=sockets.target', '',
|
|
131
|
+
].join('\n');
|
|
132
|
+
base[`${name}-target.service`] = [
|
|
133
|
+
'[Unit]', 'Description=Forward Gozar target to the Dalan bridge', `Requires=${name}.service`, `After=${name}.service`, '', '[Service]',
|
|
134
|
+
`ExecStart=${proxy} 127.0.0.1:${o.port}`, 'Restart=on-failure', '',
|
|
135
|
+
].join('\n');
|
|
136
|
+
enable.push(`${name}-target.socket`);
|
|
137
|
+
}
|
|
138
|
+
return { files: base, enable, name };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function findProxy() {
|
|
142
|
+
return ['/usr/lib/systemd/systemd-socket-proxyd', '/lib/systemd/systemd-socket-proxyd'].find(file => fs.existsSync(file)) ?? null;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function profileFor(home, workers) {
|
|
146
|
+
const file = path.join(defaultPath(home, '.config/dot-bridge'), 'workers.json');
|
|
147
|
+
if (fs.existsSync(file)) {
|
|
148
|
+
const stat = fs.lstatSync(file);
|
|
149
|
+
if (!stat.isFile() || stat.isSymbolicLink() || (stat.mode & 0o777) !== 0o600) fail(`${file} must be a private regular file`);
|
|
150
|
+
let profile;
|
|
151
|
+
try { profile = parseWorkers(JSON.parse(fs.readFileSync(file, 'utf8')), { builtin: true }); }
|
|
152
|
+
catch (error) { fail(`${file} is not a built-in OAuth worker profile: ${error.message}`); }
|
|
153
|
+
if (!profile.workers.size || profile.legacy) fail(`${file} must contain a built-in OAuth worker profile`);
|
|
154
|
+
const configuredWorkers = [...profile.workers.keys()].sort();
|
|
155
|
+
if (workers.length && JSON.stringify([...workers].sort()) !== JSON.stringify(configuredWorkers)) {
|
|
156
|
+
fail(`${file} already exists; omit --worker or pass its exact worker set, and keep its workers and repository grants`);
|
|
157
|
+
}
|
|
158
|
+
return { file, workers: [...profile.workers.keys()], existing: true };
|
|
159
|
+
}
|
|
160
|
+
if (!workers.length) fail(`no ${file}; run dalan service migrate-workers first or pass --worker NAME`);
|
|
161
|
+
const value = { workers: Object.fromEntries(workers.map(name => [name, { repos: [] }])), default_execution: 'none' };
|
|
162
|
+
parseWorkers(value, { builtin: true });
|
|
163
|
+
return { file, workers, value, existing: false };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const POLICY_HOME_FILES = new Set([
|
|
167
|
+
'service-migration.json', 'workers.json', 'workers-audit.jsonl', 'workers-audit-checkpoint.sqlite',
|
|
168
|
+
'workers-audit-checkpoint.sqlite-wal', 'workers-audit-checkpoint.sqlite-shm', 'workers-repos.json',
|
|
169
|
+
]);
|
|
170
|
+
const WORKSPACE_RUNTIME_DIRS = new Set(['artifacts', 'caches', 'host-receipts', 'mirrors', 'run', 'worktrees']);
|
|
171
|
+
const WORKSPACE_RUNTIME_FILES = new Map([['github-askpass', 0o700]]);
|
|
172
|
+
|
|
173
|
+
function installReceipt(home, configDir, o, workers) {
|
|
174
|
+
return { schema_version: 1, home, origin: o.origin, port: o.port, target: o.target.value, enable_workspace: !!o.enableWorkspace, enable_t3: !!o.enableT3,
|
|
175
|
+
unit: unitName(home), workers: [...workers].sort(), created_at: new Date().toISOString() };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function validateWorkspaceRuntime(home) {
|
|
179
|
+
const scratch = path.join(home, '.tmp');
|
|
180
|
+
const runtime = path.join(scratch, 'dalan');
|
|
181
|
+
for (const directory of [scratch, runtime]) assertRealDirectoryPath(directory, { owner: true });
|
|
182
|
+
const scratchEntries = fs.readdirSync(scratch);
|
|
183
|
+
if (scratchEntries.length !== 1 || scratchEntries[0] !== 'dalan') fail(`${scratch} contains data outside Dalan runtime scratch`);
|
|
184
|
+
if ((fs.lstatSync(runtime).mode & 0o777) !== 0o700) fail(`${runtime} must be private`);
|
|
185
|
+
const runtimeEntries = fs.readdirSync(runtime).sort();
|
|
186
|
+
for (const name of runtimeEntries) {
|
|
187
|
+
const entry = path.join(runtime, name);
|
|
188
|
+
if (!WORKSPACE_RUNTIME_DIRS.has(name) && !WORKSPACE_RUNTIME_FILES.has(name)) fail(`${runtime} contains an unknown Dalan workspace entry`);
|
|
189
|
+
const info = fs.lstatSync(entry);
|
|
190
|
+
if (WORKSPACE_RUNTIME_FILES.has(name)) {
|
|
191
|
+
const owned = typeof process.getuid !== 'function' || info.uid === process.getuid();
|
|
192
|
+
if (!info.isFile() || info.isSymbolicLink() || !owned || (info.mode & 0o777) !== WORKSPACE_RUNTIME_FILES.get(name)) {
|
|
193
|
+
fail(`${entry} must be a private regular Dalan file`);
|
|
194
|
+
}
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
assertRealDirectoryPath(entry, { owner: true });
|
|
198
|
+
if ((info.mode & 0o777) !== 0o700) fail(`${entry} must be private`);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function checkHomeScope(home, configDir, o, workers) {
|
|
203
|
+
if (!fs.existsSync(home)) return { receiptFile: path.join(configDir, 'service-install.json'), hasReceipt: false };
|
|
204
|
+
const rootEntries = fs.readdirSync(home);
|
|
205
|
+
if (!rootEntries.length) return { receiptFile: path.join(configDir, 'service-install.json'), hasReceipt: false };
|
|
206
|
+
const rootAllowed = ['.config', '.local', '.tmp', 'resource-url'];
|
|
207
|
+
if (rootEntries.some(name => !rootAllowed.includes(name))) fail(`${home} contains unrelated data; use a fresh home or one created by dalan service migrate-workers`);
|
|
208
|
+
if (!rootEntries.includes('.config')) fail(`${home} has no Dalan config directory; refusing to adopt it`);
|
|
209
|
+
const configRoot = path.join(home, '.config');
|
|
210
|
+
if (fs.lstatSync(configRoot).isSymbolicLink() || !fs.lstatSync(configRoot).isDirectory()) fail(`${configRoot} must be a real directory`);
|
|
211
|
+
const configEntries = fs.readdirSync(configRoot);
|
|
212
|
+
const configName = path.basename(configDir);
|
|
213
|
+
if (configEntries.some(name => name !== configName)) fail(`${home} contains config outside the service home; refusing to adopt it`);
|
|
214
|
+
if (!configEntries.length) {
|
|
215
|
+
if (rootEntries.includes('.local') || rootEntries.includes('.tmp') || rootEntries.includes('resource-url')) fail(`${home} already contains bridge data; use a fresh home or one created by dalan service migrate-workers`);
|
|
216
|
+
return { receiptFile: path.join(configDir, 'service-install.json'), hasReceipt: false };
|
|
217
|
+
}
|
|
218
|
+
const configInfo = fs.lstatSync(configDir);
|
|
219
|
+
if (configInfo.isSymbolicLink() || !configInfo.isDirectory()) fail(`${configDir} must be a real directory`);
|
|
220
|
+
const receiptFile = path.join(configDir, 'service-install.json');
|
|
221
|
+
const entries = fs.readdirSync(configDir);
|
|
222
|
+
const hasReceipt = entries.includes('service-install.json');
|
|
223
|
+
if (hasReceipt) {
|
|
224
|
+
const info = fs.lstatSync(receiptFile);
|
|
225
|
+
if (!info.isFile() || info.isSymbolicLink() || (info.mode & 0o777) !== 0o600) fail(`${receiptFile} must be a private regular file`);
|
|
226
|
+
let existing;
|
|
227
|
+
try { existing = JSON.parse(fs.readFileSync(receiptFile, 'utf8')); } catch { fail(`${receiptFile} is not valid JSON`); }
|
|
228
|
+
const wanted = installReceipt(home, configDir, o, workers);
|
|
229
|
+
for (const field of ['schema_version', 'home', 'origin', 'port', 'target', 'enable_workspace', 'enable_t3', 'unit', 'workers']) {
|
|
230
|
+
if (JSON.stringify(existing[field]) !== JSON.stringify(wanted[field])) fail(`${receiptFile} belongs to a different service configuration (${field}); refusing to change it`);
|
|
231
|
+
}
|
|
232
|
+
if (rootEntries.includes('.tmp')) validateWorkspaceRuntime(home);
|
|
233
|
+
if (rootEntries.includes('.local')) assertRealDirectoryPath(defaultPath(home, '.local/share/dot-bridge'));
|
|
234
|
+
return { receiptFile, hasReceipt };
|
|
235
|
+
}
|
|
236
|
+
if (rootEntries.includes('.local') || rootEntries.includes('.tmp') || rootEntries.includes('resource-url')) fail(`${home} already contains bridge data; use a fresh home or one created by dalan service migrate-workers`);
|
|
237
|
+
for (const name of entries) {
|
|
238
|
+
if (POLICY_HOME_FILES.has(name) || hasReceipt && name === 'service-install.json') continue;
|
|
239
|
+
fail(`${configDir}/${name} is outside a fresh or migrated policy-only home; refusing to adopt it`);
|
|
240
|
+
}
|
|
241
|
+
if (entries.length && !entries.includes('workers.json')) fail(`${configDir} has no worker policy; refusing to adopt it`);
|
|
242
|
+
return { receiptFile, hasReceipt };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function writePrivate(file, text) {
|
|
246
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
247
|
+
try { fs.writeFileSync(file, text, { mode: 0o600, flag: 'wx' }); }
|
|
248
|
+
catch (error) {
|
|
249
|
+
if (error.code !== 'EEXIST') throw error;
|
|
250
|
+
const info = fs.lstatSync(file);
|
|
251
|
+
if (!info.isFile() || info.isSymbolicLink() || (info.mode & 0o777) !== 0o600 || fs.readFileSync(file, 'utf8') !== text) {
|
|
252
|
+
fail(`${file} already exists with different or unsafe contents; refusing to replace it`);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function prepareHome(o, profile) {
|
|
258
|
+
fs.mkdirSync(o.home, { recursive: true, mode: 0o700 });
|
|
259
|
+
fs.chmodSync(o.home, 0o700);
|
|
260
|
+
const config = defaultPath(o.home, '.config/dot-bridge');
|
|
261
|
+
fs.mkdirSync(config, { recursive: true, mode: 0o700 });
|
|
262
|
+
if (!profile.existing) writePrivate(profile.file, `${JSON.stringify(profile.value, null, 2)}\n`);
|
|
263
|
+
initAsFiles(config, { publicUrl: o.origin });
|
|
264
|
+
const envFile = path.join(config, 'env');
|
|
265
|
+
if (!fs.existsSync(envFile)) writePrivate(envFile, `BRIDGE_PATH_SECRET=${randomBytes(32).toString('hex')}\n`);
|
|
266
|
+
const envInfo = fs.lstatSync(envFile);
|
|
267
|
+
const envText = fs.readFileSync(envFile, 'utf8');
|
|
268
|
+
const secret = /^BRIDGE_PATH_SECRET=([a-f0-9]{64})\n?$/.exec(envText)?.[1];
|
|
269
|
+
if (!envInfo.isFile() || envInfo.isSymbolicLink() || (envInfo.mode & 0o777) !== 0o600 || !secret) fail(`${envFile} is not a private bridge secret file`);
|
|
270
|
+
const resourceFile = path.join(o.home, 'resource-url');
|
|
271
|
+
writePrivate(resourceFile, `${o.origin}/${secret}/mcp\n`);
|
|
272
|
+
return { config, resourceFile, secret };
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function writeUnits(dir, files) {
|
|
276
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
277
|
+
for (const [name, text] of Object.entries(files)) {
|
|
278
|
+
const file = path.join(dir, name);
|
|
279
|
+
try { fs.writeFileSync(file, text, { mode: 0o644, flag: 'wx' }); }
|
|
280
|
+
catch (error) {
|
|
281
|
+
if (error.code !== 'EEXIST') throw error;
|
|
282
|
+
if (!fs.lstatSync(file).isFile() || fs.readFileSync(file, 'utf8') !== text) fail(`${file} already exists with different contents; refusing to replace it`);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function runCommand(command, args, { env, spawn = spawnSync, timeout = 30000 } = {}) {
|
|
288
|
+
const result = spawn(command, args, { encoding: 'utf8', env, timeout, maxBuffer: 1024 * 1024 });
|
|
289
|
+
if (result.error) throw new Error(`${command} ${args.join(' ')} could not run: ${result.error.message}`);
|
|
290
|
+
if (result.status !== 0) throw new Error(`${command} ${args.join(' ')} failed (exit ${result.status ?? result.signal}): ${(result.stderr || result.stdout || '').trim().slice(0, 1000)}`);
|
|
291
|
+
return result.stdout ?? '';
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function socketIsReady(socketPath, timeoutMs = 30000) {
|
|
295
|
+
return new Promise(resolve => {
|
|
296
|
+
const started = Date.now();
|
|
297
|
+
const attempt = () => {
|
|
298
|
+
const probe = net.connect(socketPath);
|
|
299
|
+
const done = ready => { probe.destroy(); if (ready) resolve(true); else if (Date.now() - started >= timeoutMs) resolve(false); else setTimeout(attempt, 200); };
|
|
300
|
+
probe.once('connect', () => done(true));
|
|
301
|
+
probe.once('error', () => done(false));
|
|
302
|
+
probe.setTimeout(1000, () => done(false));
|
|
303
|
+
};
|
|
304
|
+
attempt();
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
export async function installService(o, seams = {}) {
|
|
309
|
+
const env = seams.env ?? process.env;
|
|
310
|
+
if ((seams.platform ?? process.platform) !== 'linux') fail('dalan service install currently requires Linux with a systemd user manager');
|
|
311
|
+
if (!path.isAbsolute(o.home) || !SAFE_PATH.test(o.home)) fail('--home must be an absolute systemd-safe path');
|
|
312
|
+
const target = parseTarget(typeof o.target === 'string' ? o.target : `${o.target?.host}:${o.target?.port}`);
|
|
313
|
+
o = { ...o, target };
|
|
314
|
+
validateTopology(o);
|
|
315
|
+
assertRealDirectoryPath(path.dirname(o.home), { owner: true });
|
|
316
|
+
assertRealDirectoryPath(o.home, { owner: true });
|
|
317
|
+
const profile = profileFor(o.home, o.workers ?? []);
|
|
318
|
+
assertRealDirectoryPath(path.dirname(profile.file));
|
|
319
|
+
const unitDir = path.join(env.XDG_CONFIG_HOME && path.isAbsolute(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : path.join(os.homedir(), '.config'), 'systemd/user');
|
|
320
|
+
assertRealDirectoryPath(unitDir, { owner: true });
|
|
321
|
+
const configDir = path.dirname(profile.file);
|
|
322
|
+
const homeScope = checkHomeScope(o.home, configDir, o, profile.workers);
|
|
323
|
+
const proxy = o.target.host === '127.0.0.1' && o.target.port === o.port ? null : (seams.proxy ?? findProxy());
|
|
324
|
+
const { files, enable, name } = unitFiles(o, { home: o.home, repo: seams.repo ?? REPO, node: seams.node ?? nodePath(process.execPath), proxy });
|
|
325
|
+
// Check every collision before creating the bridge home or the first unit file.
|
|
326
|
+
for (const [filename, text] of Object.entries(files)) {
|
|
327
|
+
const file = path.join(unitDir, filename);
|
|
328
|
+
if (fs.existsSync(file) && (!fs.lstatSync(file).isFile() || fs.readFileSync(file, 'utf8') !== text)) fail(`${file} already exists with different contents; refusing to overwrite it`);
|
|
329
|
+
}
|
|
330
|
+
if (o.writeUnitsOnly) {
|
|
331
|
+
writeUnits(unitDir, files);
|
|
332
|
+
return { schema_version: 1, home: o.home, unit: `${name}.service`, units: Object.keys(files), target: o.target.value, started: false, route: null };
|
|
333
|
+
}
|
|
334
|
+
const spawn = seams.spawn ?? spawnSync;
|
|
335
|
+
runCommand('systemctl', ['--user', 'show-environment'], { env, spawn });
|
|
336
|
+
fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });
|
|
337
|
+
if (!homeScope.hasReceipt) writePrivate(homeScope.receiptFile, `${JSON.stringify(installReceipt(o.home, configDir, o, profile.workers), null, 2)}\n`);
|
|
338
|
+
const homeFiles = prepareHome(o, profile);
|
|
339
|
+
writeUnits(unitDir, files);
|
|
340
|
+
runCommand('systemctl', ['--user', 'daemon-reload'], { env, spawn });
|
|
341
|
+
runCommand('systemctl', ['--user', 'enable', '--now', ...enable], { env, spawn });
|
|
342
|
+
const dataDir = defaultPath(o.home, '.local/share/dot-bridge');
|
|
343
|
+
const ready = await (seams.waitForSocket ?? socketIsReady)(path.join(dataDir, 'admin.sock'), seams.socketTimeoutMs ?? 30000);
|
|
344
|
+
if (!ready) fail(`Dalan did not start on its admin socket; the unit and home remain for inspection: systemctl --user status ${name}.service`);
|
|
345
|
+
const gozarArgs = ['service', 'add', '--origin', o.origin, '--target', o.target.value];
|
|
346
|
+
if (o.verifyCmd) gozarArgs.push('--verify-cmd', o.verifyCmd);
|
|
347
|
+
gozarArgs.push('--json');
|
|
348
|
+
const output = runCommand(o.gozarBin ?? env.GOZAR_BIN ?? 'gozar', gozarArgs, { env, spawn, timeout: 120000 });
|
|
349
|
+
let routeReply;
|
|
350
|
+
try { routeReply = JSON.parse(output); } catch { fail('Gozar returned invalid JSON for service add; the bridge is running but its route is unverified'); }
|
|
351
|
+
if (routeReply?.schemaVersion !== 1 || routeReply?.route?.origin !== o.origin || routeReply?.route?.target !== o.target.value) {
|
|
352
|
+
fail('Gozar returned a service route that does not match the requested origin and target; the bridge is running but its route is unverified');
|
|
353
|
+
}
|
|
354
|
+
if (routeReply.route.verification?.status !== 'verified') {
|
|
355
|
+
fail(`Gozar did not verify the service route; the bridge is running and the service route needs repair: ${JSON.stringify(routeReply).slice(0, 1500)}`);
|
|
356
|
+
}
|
|
357
|
+
return { schema_version: 1, home: o.home, unit: `${name}.service`, units: Object.keys(files), port: o.port,
|
|
358
|
+
workers: profile.workers, public_url: `${o.origin}/<secret>/mcp`, resource_url_file: homeFiles.resourceFile,
|
|
359
|
+
target: o.target.value, started: true, route: routeReply.route };
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
export async function serviceMain(argv, seams = {}) {
|
|
363
|
+
const [action, ...args] = argv;
|
|
364
|
+
if (action === 'migrate-workers') {
|
|
365
|
+
const { migrationMain } = await import('./service-migrate-workers.mjs');
|
|
366
|
+
return migrationMain(args);
|
|
367
|
+
}
|
|
368
|
+
if (action === 'help' || action === '--help' || !action) {
|
|
369
|
+
(seams.out ?? console.log)('Usage: dalan service install --home DIR --public-url https://HOST --port N --target HOST:PORT [--lan-port N] [--enable-workspace] [--enable-t3] [--worker NAME ...] [--verify-cmd COMMAND] [--write-units-only]\n dalan service migrate-workers --home DIR --source workers.json [--source workers.json ...]');
|
|
370
|
+
return null;
|
|
371
|
+
}
|
|
372
|
+
if (action !== 'install') fail('use dalan service install or dalan service migrate-workers');
|
|
373
|
+
const o = parseOptions(args, seams.env ?? process.env);
|
|
374
|
+
if (o.help) return serviceMain(['help'], seams);
|
|
375
|
+
const result = await installService(o, seams);
|
|
376
|
+
if (o.json) (seams.out ?? console.log)(JSON.stringify(result));
|
|
377
|
+
else {
|
|
378
|
+
(seams.out ?? console.log)(`Service: ${result.unit} (${result.started ? 'active' : 'unit files written'})`);
|
|
379
|
+
(seams.out ?? console.log)(`Home: ${result.home}`);
|
|
380
|
+
(seams.out ?? console.log)(`Public MCP URL: ${result.public_url ?? `${o.origin}/<secret>/mcp`}`);
|
|
381
|
+
(seams.out ?? console.log)(`Private URL file: ${result.resource_url_file ?? path.join(result.home, 'resource-url')}`);
|
|
382
|
+
(seams.out ?? console.log)(`Gozar target: ${result.target}`);
|
|
383
|
+
if (result.route) (seams.out ?? console.log)(`Gozar route: ${result.route.verification.status}`);
|
|
384
|
+
}
|
|
385
|
+
return result;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
export { parseOrigin, parseTarget, unitFiles };
|
package/src/setup.mjs
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// `dalan setup`: choose the saved public route. It detects what Tailscale can do and asks as little as possible:
|
|
2
|
+
// Tailscale ready for Funnel -> one yes/no question; not found -> one short choice. `dalan try --public` asks for relay consent
|
|
3
|
+
// before it exposes the temporary demo link.
|
|
4
|
+
import readline from 'node:readline';
|
|
5
|
+
import { INSTALL_URL, defaultTailscale, preflight, whichOnPath } from '../scripts/lib/expose-tailscale.mjs';
|
|
6
|
+
import { readRouteSetting, writeRouteSetting } from './route-setting.mjs';
|
|
7
|
+
|
|
8
|
+
// What this computer's Tailscale can do now: { ok, node } or { ok: false, installed, reason }.
|
|
9
|
+
// The address is the OAuth issuer, so a new address is a new sign-in identity: nothing from a trial carries over.
|
|
10
|
+
export const SWITCH_NOTE = 'Next: run `dalan try --public`, then in your MCP client remove the trial connector and add the new URL it prints; a new address cannot reuse the trial sign-in.';
|
|
11
|
+
|
|
12
|
+
export function detectTailscale({ env = process.env, tailscale = defaultTailscale, which = name => whichOnPath(name, env), platform = process.platform, mac } = {}) {
|
|
13
|
+
if (!which('tailscale')) return { ok: false, installed: false, reason: 'Tailscale is not installed.' };
|
|
14
|
+
try {
|
|
15
|
+
const found = preflight({ tailscale, platform, mac });
|
|
16
|
+
return { ok: true, node: found.dnsName.split('.')[0], dnsName: found.dnsName };
|
|
17
|
+
} catch (error) { return { ok: false, installed: true, reason: String(error.message).split('\n')[0] }; }
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export async function runSetup({ env = process.env, out = process.stdout, input = process.stdin, interactive = Boolean(process.stdin.isTTY), detect = () => detectTailscale({ env }) } = {}) {
|
|
21
|
+
const say = line => out.write(`${line}\n`);
|
|
22
|
+
const found = detect();
|
|
23
|
+
const saved = readRouteSetting(env);
|
|
24
|
+
const lines = interactive ? readline.createInterface({ input }) : null;
|
|
25
|
+
const ask = question => new Promise(resolve => {
|
|
26
|
+
let done = false;
|
|
27
|
+
const finish = answer => { if (!done) { done = true; lines.off('close', onClose); resolve(answer); } };
|
|
28
|
+
const onClose = () => finish(null);
|
|
29
|
+
out.write(question); lines.once('line', finish); lines.once('close', onClose);
|
|
30
|
+
});
|
|
31
|
+
try {
|
|
32
|
+
if (found.ok) {
|
|
33
|
+
if (!interactive) { say(`Tailscale is ready on this computer (${found.node}). Run \`dalan setup\` in a terminal to use it.`); return { route: saved, changed: false }; }
|
|
34
|
+
const answer = ((await ask(`Use Tailscale (${found.node}) for a stable address? [Y/n] `)) ?? '').trim().toLowerCase();
|
|
35
|
+
if (answer === '' || answer === 'y' || answer === 'yes') {
|
|
36
|
+
writeRouteSetting('tailscale', env);
|
|
37
|
+
say('Saved Tailscale for public runs. Reuse the same node and public address to keep the connector identity; changing that address requires a new sign-in.');
|
|
38
|
+
say(SWITCH_NOTE);
|
|
39
|
+
return { route: 'tailscale', changed: saved !== 'tailscale' };
|
|
40
|
+
}
|
|
41
|
+
writeRouteSetting('gozar', env);
|
|
42
|
+
say('Saved. `dalan try --public` uses Gozar for a temporary demo link. It can change or stop without warning. Run `dalan setup` again to switch.');
|
|
43
|
+
return { route: 'gozar', changed: saved !== 'gozar' };
|
|
44
|
+
}
|
|
45
|
+
say(found.reason);
|
|
46
|
+
say('For daily use, pick one:');
|
|
47
|
+
say(` 1. Tailscale (recommended): install it from ${INSTALL_URL}, run \`tailscale up\`, then run \`dalan setup\` again.`);
|
|
48
|
+
say(' 2. Use Gozar for a temporary demo link: it can change or stop without warning.');
|
|
49
|
+
if (!interactive) return { route: saved, changed: false };
|
|
50
|
+
const answer = ((await ask('Choose [1]: ')) ?? '').trim();
|
|
51
|
+
if (answer === '2') {
|
|
52
|
+
writeRouteSetting('gozar', env);
|
|
53
|
+
say('Saved. `dalan try --public` uses Gozar for a temporary demo link. It can change or stop without warning.');
|
|
54
|
+
return { route: 'gozar', changed: saved !== 'gozar' };
|
|
55
|
+
}
|
|
56
|
+
say('Nothing saved. Install Tailscale, then run `dalan setup` again.');
|
|
57
|
+
return { route: saved, changed: false };
|
|
58
|
+
} finally { lines?.close(); }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export async function main() {
|
|
62
|
+
try { await runSetup(); } catch (error) { process.stderr.write(`dalan: ${error.message}\n`); process.exitCode = 1; }
|
|
63
|
+
}
|
package/src/store.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {PullQueue,migratePullQueue,PULL_PAGE_PREFIX} from './pull-queue.mjs';
|
|
1
2
|
import { defaultPath } from './paths.mjs';
|
|
2
3
|
import { readEnv } from './env.mjs';
|
|
3
4
|
import { validateOwnerNote } from './submission-policy.mjs';
|
|
@@ -49,7 +50,7 @@ function waiterOwnerGone(attemptId) {
|
|
|
49
50
|
return !!(owner.boot&&owner.start&¤t.boot&¤t.start&&(owner.boot!==current.boot||owner.start!==current.start));
|
|
50
51
|
}
|
|
51
52
|
|
|
52
|
-
const SUPPORTED_SCHEMA_VERSION =
|
|
53
|
+
const SUPPORTED_SCHEMA_VERSION = 66;
|
|
53
54
|
const monotonicMs=()=>Number(process.hrtime.bigint())/1e6;
|
|
54
55
|
function systemBootId() {
|
|
55
56
|
if(process.platform!=='linux') return null;
|
|
@@ -330,6 +331,7 @@ export class Store {
|
|
|
330
331
|
CREATE TABLE IF NOT EXISTS bridge_state (key TEXT PRIMARY KEY,value TEXT NOT NULL) WITHOUT ROWID;
|
|
331
332
|
CREATE INDEX IF NOT EXISTS notifications_due ON notifications(state,next_at);`);
|
|
332
333
|
this.migrate();
|
|
334
|
+
this.pullQueue=new PullQueue(this);
|
|
333
335
|
this.initializeLeaseClock();
|
|
334
336
|
this.initializeSubscriptionStorage();
|
|
335
337
|
} catch(error) { this.db.close(); throw error; } finally { storage?.release(); }
|
|
@@ -921,6 +923,7 @@ export class Store {
|
|
|
921
923
|
if(this.db.prepare("SELECT 1 FROM pragma_table_info('assignments') WHERE name='skipped_by_dot_at'").get()) this.db.exec('ALTER TABLE assignments RENAME COLUMN skipped_by_dot_at TO skipped_at;');
|
|
922
924
|
this.db.exec('PRAGMA user_version=65;');
|
|
923
925
|
}
|
|
926
|
+
if(version<66) { migratePullQueue(this.db); this.db.exec('PRAGMA user_version=66;'); }
|
|
924
927
|
// Which spelling of the fix-loop source this database stores. Schemas created before the rename list the earlier
|
|
925
928
|
// spelling in the CHECK constraint on assignments.source; newer schemas list only the neutral one.
|
|
926
929
|
this.legacyFixNames=!!this.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='assignments' AND instr(sql,?)>0").get(`'${legacyFixLoopName}'`);
|
|
@@ -1091,7 +1094,7 @@ export class Store {
|
|
|
1091
1094
|
expired_lower_bounds:evidence.expired_lower_bounds,window_days:days,factor:QUEUE_WINDOW.factor,floor_ms:QUEUE_WINDOW.minMs,cap_ms:QUEUE_WINDOW.maxMs,worker,kind};
|
|
1092
1095
|
}
|
|
1093
1096
|
owner(id, token) {
|
|
1094
|
-
const row = this.db.prepare('SELECT owner_hash FROM assignments WHERE request_id=?').get(id);
|
|
1097
|
+
const row = this.db.prepare('SELECT owner_hash FROM assignments WHERE request_id=?').get(id)??this.pullQueue.ownerRow(id);
|
|
1095
1098
|
if (!row) throw new Error('assignment not found');
|
|
1096
1099
|
if (!row.owner_hash) throw new Error('legacy request requires operator adoption');
|
|
1097
1100
|
const got = Buffer.from(hash(token || ''), 'hex'), expected = Buffer.from(row.owner_hash, 'hex');
|
|
@@ -1242,7 +1245,10 @@ export class Store {
|
|
|
1242
1245
|
return {request_id:payload.request_id,status:old.status,duplicate:true,...(approval?{destination_approval:approval}:{})};
|
|
1243
1246
|
}
|
|
1244
1247
|
// identity: the assignment as the submitter sent it, when the stored payload differs (scope narrowing); a retry then still matches.
|
|
1245
|
-
submit(
|
|
1248
|
+
submit(...args) { return this.transaction(()=>this.submitInTransaction(...args)); }
|
|
1249
|
+
submitInTransaction(payload, deliveryOrThreadId, environmentId, ownerToken, review=false, preflight=null, priority='normal', meta=null, identity=payload, maxQueued=null, targetWorker=undefined, execution=null, defaultExecution='host', requiredCapabilities=null, defaultValidUntil=null, commandKey=null, supersedes=null, destinationRevision=null, inheritedOwnerHash=null) {
|
|
1250
|
+
if(!this.db.isTransaction) throw new Error('transaction_required');
|
|
1251
|
+
if(payload.request_id.startsWith(PULL_PAGE_PREFIX)||!inheritedOwnerHash&&this.pullQueue.row(payload.request_id)) throw new Error('request_id reserved for policy work');
|
|
1246
1252
|
const protocol=!this.hasAssignment(payload.request_id)&&Object.hasOwn(payload,'protocol')?validateProtocol(payload.protocol):null;
|
|
1247
1253
|
if(protocol)identity={...identity,protocol};
|
|
1248
1254
|
if(targetWorker==='pool') throw new Error('worker \"pool\" is not supported');
|
|
@@ -1252,7 +1258,7 @@ export class Store {
|
|
|
1252
1258
|
if(!['normal','background'].includes(priority)) throw new Error('invalid priority');
|
|
1253
1259
|
const retry=this.checkRetry(payload,delivery,environmentId,ownerToken,review,priority,meta,identity,targetWorker,execution,requiredCapabilities,commandKey,supersedes,destinationRevision);
|
|
1254
1260
|
if(retry) return retry;
|
|
1255
|
-
const id=payload.request_id, body=JSON.stringify(payload),payloadHash=hash(JSON.stringify(canonical(identity))),ownerHash=hash(ownerToken);
|
|
1261
|
+
const id=payload.request_id, body=JSON.stringify(payload),payloadHash=hash(JSON.stringify(canonical(identity))),ownerHash=inheritedOwnerHash??hash(ownerToken);
|
|
1256
1262
|
// checkRetry validated this target in the same transaction; only counts containing it gain room.
|
|
1257
1263
|
const supersededId=supersedes?.target_id??null;
|
|
1258
1264
|
if(destinationRevision!==null&&(typeof destinationRevision!=='string'||!/^sha256:[a-f0-9]{64}$/.test(destinationRevision)))throw new Error('invalid destination_revision');
|
|
@@ -1318,7 +1324,7 @@ export class Store {
|
|
|
1318
1324
|
this.db.prepare('INSERT INTO owner_submit_commands(request_id,key_digest,intent_digest,receipt,owner_hash) VALUES(?,?,?,?,?)').run(id,hash(commandKey),intent,JSON.stringify(receipt),ownerHash);
|
|
1319
1325
|
}
|
|
1320
1326
|
return receipt;
|
|
1321
|
-
}
|
|
1327
|
+
}
|
|
1322
1328
|
// Fills objective columns of rows that have none, only with tuples verifyObjective proves against the stored payload.
|
|
1323
1329
|
// Idempotent: a row that already carries any objective column is never rewritten.
|
|
1324
1330
|
backfillObjectives(tuples, {dryRun=false}={}) { return this.transaction(() => {
|
|
@@ -1827,7 +1833,7 @@ export class Store {
|
|
|
1827
1833
|
}
|
|
1828
1834
|
failureFields(id) {
|
|
1829
1835
|
const a=this.db.prepare('SELECT status,cancelled_reason FROM assignments WHERE request_id=?').get(id);
|
|
1830
|
-
if(!a) return {failure_type:'unknown',failure_type_source:'unknown'};
|
|
1836
|
+
if(!a) {const policy=this.pullQueue.inbox(id);return policy?{failure_type:policy.failure_type,failure_type_source:policy.failure_type_source}:{failure_type:'unknown',failure_type_source:'unknown'};}
|
|
1831
1837
|
const report=this.db.prepare('SELECT outcome,summary,result FROM reports WHERE request_id=?').get(id);
|
|
1832
1838
|
const failedReport=!!report&&report.outcome!=='completed';
|
|
1833
1839
|
const checkFailedObserved=!!this.db.prepare("SELECT 1 FROM lifecycle_events WHERE request_id=? AND type='check_failed' LIMIT 1").get(id);
|
|
@@ -2024,7 +2030,7 @@ export class Store {
|
|
|
2024
2030
|
this.db.prepare("UPDATE notifications SET state='suppressed',last_error='subscription revoked' WHERE subscription_id=? AND state IN ('pending','failed')").run(id);
|
|
2025
2031
|
}); }
|
|
2026
2032
|
get(id) {
|
|
2027
|
-
const a=this.db.prepare('SELECT * FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found');
|
|
2033
|
+
const a=this.db.prepare('SELECT * FROM assignments WHERE request_id=?').get(id); if(!a) { const work=this.pullQueue.row(id);if(work)return this.pullQueue.project(work);throw new Error('assignment not found'); }
|
|
2028
2034
|
this.assertProtocolAvailable(id);
|
|
2029
2035
|
const claimRow=this.db.prepare('SELECT * FROM claims WHERE request_id=?').get(id);
|
|
2030
2036
|
const claim=claimRow&&(({acquisition_id,tool_calls,last_tool,last_tool_at,last_tool_error,first_workspace_tool_at,destination_revision,...rest})=>({...rest,...(destination_revision?{destination_revision}:{}),lease_expires_at:this.leaseExpiresAt(claimRow),activity:Store.toolActivity(claimRow)}))(claimRow);
|
|
@@ -2040,7 +2046,7 @@ export class Store {
|
|
|
2040
2046
|
const supersedes=this.db.prepare('SELECT target_id AS request_id,created_at FROM submit_supersedes WHERE request_id=?').get(id)??null;
|
|
2041
2047
|
const superseded_by=this.db.prepare('SELECT request_id,created_at FROM submit_supersedes WHERE target_id=?').get(id)??null;
|
|
2042
2048
|
const authorityRevoked=!!a.cancelled_at||this.isProtocolJob(id)&&a.status==='finished';
|
|
2043
|
-
return {...this.destinationFields(id),request_id:id,supersedes,superseded_by,target_worker:a.target_worker,assignment:JSON.parse(a.payload),delivery_mode:a.delivery,t3_muted:this.deliveryMuted(id),thread_id:a.thread_id||null,environment_id:a.environment_id||null,status:a.status,execution:a.execution,required_capabilities:a.required_capabilities?JSON.parse(a.required_capabilities):[],review:!!a.review,created_at:a.created_at,valid_until:a.valid_until??null,valid_until_source:a.valid_until_source??null,expiry_requeues:a.expiry_requeues??0,...this.failureFields(id),cancelled_at:a.cancelled_at,cancelled_reason:a.cancelled_reason??null,cancellation_requested:!!a.cancelled_at,authority_revoked:authorityRevoked,...this.sandboxStop(id,authorityRevoked),claim,progress,lifecycle_events:this.db.prepare("SELECT type,at,actor,reason FROM lifecycle_events WHERE request_id=? ORDER BY id").all(id),report:report??null,late_evidence,delivery,watch,owner_notes:this.ownerNotes(id),worker_break_notices:this.breakNotices(id),claim_denied:this.claimDenial(id),skipped_by_worker:a.skipped_at?{at:a.skipped_at,listed_count:a.listed_count,passed_over:a.passed_over}:null,pr_preflights:this.db.prepare("SELECT phase,evidence FROM pr_preflights WHERE request_id=? ORDER BY CASE phase WHEN 'submit' THEN 0 ELSE 1 END").all(id).map(row=>({phase:row.phase,...JSON.parse(row.evidence)}))};
|
|
2049
|
+
return {...this.destinationFields(id),...(this.pullQueue.row(id)?{work_order_id:this.pullQueue.row(id).work_order_id,child_request_id:id}:{}),request_id:id,supersedes,superseded_by,target_worker:a.target_worker,assignment:JSON.parse(a.payload),delivery_mode:a.delivery,t3_muted:this.deliveryMuted(id),thread_id:a.thread_id||null,environment_id:a.environment_id||null,status:a.status,execution:a.execution,required_capabilities:a.required_capabilities?JSON.parse(a.required_capabilities):[],review:!!a.review,created_at:a.created_at,valid_until:a.valid_until??null,valid_until_source:a.valid_until_source??null,expiry_requeues:a.expiry_requeues??0,...this.failureFields(id),cancelled_at:a.cancelled_at,cancelled_reason:a.cancelled_reason??null,cancellation_requested:!!a.cancelled_at,authority_revoked:authorityRevoked,...this.sandboxStop(id,authorityRevoked),claim,progress,lifecycle_events:this.db.prepare("SELECT type,at,actor,reason FROM lifecycle_events WHERE request_id=? ORDER BY id").all(id),report:report??null,late_evidence,delivery,watch,owner_notes:this.ownerNotes(id),worker_break_notices:this.breakNotices(id),claim_denied:this.claimDenial(id),skipped_by_worker:a.skipped_at?{at:a.skipped_at,listed_count:a.listed_count,passed_over:a.passed_over}:null,pr_preflights:this.db.prepare("SELECT phase,evidence FROM pr_preflights WHERE request_id=? ORDER BY CASE phase WHEN 'submit' THEN 0 ELSE 1 END").all(id).map(row=>({phase:row.phase,...JSON.parse(row.evidence)}))};
|
|
2044
2050
|
}
|
|
2045
2051
|
recordPrPreflight(id,phase,assignment,evidence,replace=false) {
|
|
2046
2052
|
assertPreflight(assignment,evidence,this.nowMs());
|
|
@@ -2648,6 +2654,7 @@ export class Store {
|
|
|
2648
2654
|
return {receipt_id:receipt,request_id:id,duplicate:false,late:false,...Store.resultAuthority(false),...this.nextQueued(this.freeLanes(claim.subject,claim.worker),id,worker)};
|
|
2649
2655
|
}
|
|
2650
2656
|
cancel(id,reason=null,ctx=null,ownerToken=null) {
|
|
2657
|
+
const workCancelled=this.pullQueue.cancel(id,reason);if(workCancelled)return workCancelled;
|
|
2651
2658
|
return this.isProtocolJob(id)?cancelProtocolJob(this,id,reason,ownerToken,ctx):this.transaction(()=>this.cancelInTransaction(id,reason));
|
|
2652
2659
|
}
|
|
2653
2660
|
cancelInTransaction(id,reason=null) {
|
|
@@ -2667,6 +2674,8 @@ export class Store {
|
|
|
2667
2674
|
// Returns the resulting state either way: cancelled:true when this call cancelled it, false when it was already claimed,
|
|
2668
2675
|
// finished or cancelled (the status then says which). A claimed row keeps running; nothing is revoked.
|
|
2669
2676
|
cancelIfQueued(id) { return this.transaction(() => {
|
|
2677
|
+
const pendingWork=this.pullQueue.row(id);
|
|
2678
|
+
if(pendingWork&&!pendingWork.child_request_id) {const status=this.pullQueue.project(pendingWork).status;if(status!=='queued')return {request_id:id,status,cancelled:false};return {...this.pullQueue.cancel(id),cancelled:true};}
|
|
2670
2679
|
this.assertProtocolAvailable(id);
|
|
2671
2680
|
if(this.isProtocolJob(id)) throw new Error('protocol jobs require keyed /cancel with command_key and expected_revision');
|
|
2672
2681
|
const a=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found');
|
|
@@ -2726,6 +2735,7 @@ export class Store {
|
|
|
2726
2735
|
this.db.prepare("UPDATE watches SET state='suppressed',updated_at=? WHERE request_id=? AND state IN ('armed','fired')").run(at,row.request_id);
|
|
2727
2736
|
cancelled.push(row.request_id);
|
|
2728
2737
|
}
|
|
2738
|
+
cancelled.push(...this.pullQueue.sweepExpired(Math.max(0,limit-rows.length)));
|
|
2729
2739
|
cancelled.requeued=requeued;
|
|
2730
2740
|
return cancelled;
|
|
2731
2741
|
}); }
|
|
@@ -2842,6 +2852,7 @@ export class Store {
|
|
|
2842
2852
|
}); }
|
|
2843
2853
|
// The owner received a finished report (wait delivery or admin get). Only the first receipt per request counts.
|
|
2844
2854
|
consumeOnce(id,via) {
|
|
2855
|
+
this.pullQueue.consume(id);
|
|
2845
2856
|
this.db.prepare("UPDATE assignments SET owner_read_at=? WHERE request_id=? AND status='cancelled' AND owner_read_at IS NULL").run(this.stamp(),id);
|
|
2846
2857
|
if(this.db.prepare("SELECT status FROM assignments WHERE request_id=?").get(id)?.status!=='finished') return false;
|
|
2847
2858
|
if(this.db.prepare("SELECT 1 FROM lifecycle_events WHERE request_id=? AND type='consumed' LIMIT 1").get(id)) return false;
|
|
@@ -2850,6 +2861,7 @@ export class Store {
|
|
|
2850
2861
|
}
|
|
2851
2862
|
// Read-only view of one request for the owner's inbox: what the owner has and has not seen. Writes nothing.
|
|
2852
2863
|
ownerInbox(id) {
|
|
2864
|
+
const policyInbox=this.pullQueue.inbox(id);if(policyInbox)return policyInbox;
|
|
2853
2865
|
const a=this.db.prepare('SELECT status,payload,target_worker,created_at,cancelled_at,cancelled_reason,owner_read_at FROM assignments WHERE request_id=?').get(id);
|
|
2854
2866
|
const one=(sql,...p)=>this.db.prepare(sql).get(...p);
|
|
2855
2867
|
const report=one('SELECT outcome,created_at FROM reports WHERE request_id=?',id);
|
|
@@ -2872,7 +2884,7 @@ export class Store {
|
|
|
2872
2884
|
}
|
|
2873
2885
|
// Owner action for `dalan inbox --mark-read`: the same read marker as get, without fetching the result. True when it was unread.
|
|
2874
2886
|
markInboxRead(id,via) { return this.transaction(() => {
|
|
2875
|
-
const status=this.
|
|
2887
|
+
const status=this.get(id).status, v=this.ownerInbox(id);
|
|
2876
2888
|
const unread=status==='finished'?!v.consumed:status==='cancelled'?!v.read:false;
|
|
2877
2889
|
this.consumeOnce(id,via); return unread;
|
|
2878
2890
|
}); }
|
package/src/tool-registry.mjs
CHANGED
|
@@ -69,7 +69,9 @@ export function createToolRegistry({ store, now = Date.now, handlers = {}, audit
|
|
|
69
69
|
name: row.name, description: row.description, input_schema: JSON.parse(row.input_schema), class: toolClass(row), handler: JSON.parse(row.handler),
|
|
70
70
|
caller: worker, grants: db.prepare('SELECT tool FROM tool_grants WHERE worker=? ORDER BY tool').all(worker).map(g => g.tool),
|
|
71
71
|
}));
|
|
72
|
-
|
|
72
|
+
// Owner views retain the registration/audit definition hash; only worker views pin caller grants.
|
|
73
|
+
// Never bind an absent owner caller to the worker-specific SQLite query.
|
|
74
|
+
const view = (row, worker) => ({ name: row.name, description: row.description, input_schema: JSON.parse(row.input_schema), class: toolClass(row), schema_hash: worker === undefined ? row.schema_hash : callerHash(row, worker) });
|
|
73
75
|
|
|
74
76
|
// An authority change and the discarding of the messages queued under it commit together or not at all, so no crash can
|
|
75
77
|
// leave an old message that a later register, grant or enable of the same tool would deliver.
|