@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
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// Proves a live `dalan try` public address works as a real OAuth client sees it, step by step, without claude.ai:
|
|
2
|
+
// discovery, dynamic registration with the client's published callback, PKCE authorize, the owner's approval in the trial
|
|
3
|
+
// terminal, the token exchange, then an authenticated MCP initialize, tools/list and one read-only tool call.
|
|
4
|
+
// One line per step. No token, authorization code, pairing code, secret path or URL is ever written to the output.
|
|
5
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
6
|
+
import { safeDiagnostic } from './diagnostic.mjs';
|
|
7
|
+
import { CLIENTS } from './try-hosted-clients.mjs';
|
|
8
|
+
import { authorizationServerMetadataUrl, onOrigin, TRIAL_ORIGIN_RULE } from './try-exposure.mjs';
|
|
9
|
+
import { mcpResponseText } from './mcp-sse.mjs';
|
|
10
|
+
|
|
11
|
+
const MCP_PROTOCOL = '2025-11-25';
|
|
12
|
+
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
13
|
+
|
|
14
|
+
export async function runSelfCheck({ url, client = 'claude', fetchImpl = fetch, say = () => {}, approveWaitMs = 300_000, requestMs = 30_000, signal } = {}) {
|
|
15
|
+
let mcp;
|
|
16
|
+
try { mcp = new URL(url); } catch { mcp = null; }
|
|
17
|
+
if (!mcp || !['https:', 'http:'].includes(mcp.protocol)) { // the message is fixed: the supplied text may be a credential
|
|
18
|
+
say('FAIL input: the trial URL is not a valid web address');
|
|
19
|
+
say('RESULT FAIL');
|
|
20
|
+
return { ok: false, results: [{ name: 'input', status: 'FAIL', detail: 'the trial URL is not a valid web address' }] };
|
|
21
|
+
}
|
|
22
|
+
const callback = CLIENTS[client].callbacks.find(c => typeof c === 'string'); // the client's stable, published callback
|
|
23
|
+
const results = [];
|
|
24
|
+
let failed = false;
|
|
25
|
+
const step = async (name, fn) => {
|
|
26
|
+
if (failed) { results.push({ name, status: 'SKIP' }); say(`SKIP ${name}`); return undefined; }
|
|
27
|
+
try {
|
|
28
|
+
const note = await fn();
|
|
29
|
+
results.push({ name, status: 'PASS' }); say(`PASS ${name}${note ? ` (${scrub(note)})` : ''}`);
|
|
30
|
+
} catch (error) {
|
|
31
|
+
const detail = scrub(safeDiagnostic(error?.name === 'AbortError' || error?.name === 'TimeoutError' ? 'cancelled or timed out' : error?.message, 200));
|
|
32
|
+
failed = true; results.push({ name, status: 'FAIL', detail });
|
|
33
|
+
say(`FAIL ${name}: ${detail}`);
|
|
34
|
+
}
|
|
35
|
+
return undefined;
|
|
36
|
+
};
|
|
37
|
+
// The secret path is part of the MCP URL; keep it, the origin-relative credentials and the full URL out of every line.
|
|
38
|
+
const secretPath = mcp.pathname.split('/')[1] ?? '';
|
|
39
|
+
const scrub = text => String(text).split(url).join('[url]').split(secretPath).join('[secret]');
|
|
40
|
+
// Every request has its own deadline, so a server that never finishes its answer cannot outlast the check.
|
|
41
|
+
const get = (u, init = {}) => fetchImpl(u, { redirect: 'manual', ...init, signal: signal ? AbortSignal.any([AbortSignal.timeout(requestMs), signal]) : AbortSignal.timeout(requestMs), headers: { connection: 'close', ...(init.headers ?? {}) } });
|
|
42
|
+
const json = async (res, label) => { try { return JSON.parse(await res.text()); } catch { throw new Error(`${label} is not JSON`); } };
|
|
43
|
+
const ctx = {};
|
|
44
|
+
|
|
45
|
+
await step('challenge: an unauthenticated MCP request is answered with an OAuth challenge', async () => {
|
|
46
|
+
const res = await get(url, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, body: '{"jsonrpc":"2.0","id":1,"method":"ping"}' });
|
|
47
|
+
if (res.status !== 401) throw new Error(`HTTP ${res.status}, not 401`);
|
|
48
|
+
const header = res.headers.get('www-authenticate') ?? '';
|
|
49
|
+
if (!/^Bearer/i.test(header)) throw new Error('no Bearer challenge');
|
|
50
|
+
ctx.metadataUrl = /resource_metadata="([^"]+)"/.exec(header)?.[1];
|
|
51
|
+
if (!ctx.metadataUrl) throw new Error('the challenge names no resource_metadata');
|
|
52
|
+
});
|
|
53
|
+
await step('discovery: protected-resource metadata names this resource and an authorization server', async () => {
|
|
54
|
+
const res = await get(ctx.metadataUrl);
|
|
55
|
+
if (res.status !== 200) throw new Error(`HTTP ${res.status}`);
|
|
56
|
+
const doc = await json(res, 'resource metadata');
|
|
57
|
+
if (doc.resource !== url) throw new Error('the resource is not the MCP URL');
|
|
58
|
+
if (!Array.isArray(doc.authorization_servers) || doc.authorization_servers.length === 0) throw new Error('no authorization server');
|
|
59
|
+
ctx.issuer = String(doc.authorization_servers[0]);
|
|
60
|
+
if (!onOrigin(mcp.origin, ctx.issuer)) throw new Error(`the issuer is on another origin (${TRIAL_ORIGIN_RULE})`);
|
|
61
|
+
});
|
|
62
|
+
await step('metadata: the issuer matches exactly and every endpoint is on the public origin', async () => {
|
|
63
|
+
const res = await get(authorizationServerMetadataUrl(ctx.issuer));
|
|
64
|
+
if (res.status !== 200) throw new Error(`HTTP ${res.status}`);
|
|
65
|
+
const meta = await json(res, 'authorization-server metadata');
|
|
66
|
+
if (meta.issuer !== ctx.issuer) throw new Error('the issuer in the metadata differs from the issuer in discovery');
|
|
67
|
+
for (const key of ['authorization_endpoint', 'token_endpoint', 'registration_endpoint']) if (typeof meta[key] !== 'string' || !onOrigin(mcp.origin, meta[key])) throw new Error(`${key} is missing or off this origin (${TRIAL_ORIGIN_RULE})`);
|
|
68
|
+
if (!meta.code_challenge_methods_supported?.includes('S256')) throw new Error('S256 is not supported');
|
|
69
|
+
ctx.meta = meta;
|
|
70
|
+
});
|
|
71
|
+
await step(`registration: ${client}'s published callback is accepted as a public client`, async () => {
|
|
72
|
+
const res = await get(ctx.meta.registration_endpoint, { method: 'POST', headers: { 'content-type': 'application/json' },
|
|
73
|
+
body: JSON.stringify({ redirect_uris: [callback], client_name: 'dalan self-check', token_endpoint_auth_method: 'none', grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'] }) });
|
|
74
|
+
if (res.status !== 201) throw new Error(`HTTP ${res.status}`);
|
|
75
|
+
const doc = await json(res, 'registration');
|
|
76
|
+
if (doc.token_endpoint_auth_method !== 'none') throw new Error(`token_endpoint_auth_method is ${safeDiagnostic(doc.token_endpoint_auth_method, 40)}, not none`);
|
|
77
|
+
if (Object.hasOwn(doc, 'client_secret')) throw new Error('a client secret was issued to a public client');
|
|
78
|
+
ctx.clientId = doc.client_id;
|
|
79
|
+
});
|
|
80
|
+
const cookies = new Map();
|
|
81
|
+
const send = async (u, init) => {
|
|
82
|
+
const cookie = [...cookies].map(([k, v]) => `${k}=${v}`).join('; ');
|
|
83
|
+
const res = await get(u, { ...init, headers: { ...(cookie ? { cookie } : {}) } });
|
|
84
|
+
for (const line of res.headers.getSetCookie?.() ?? []) { const [pair] = line.split(';'), i = pair.indexOf('='); if (pair.slice(i + 1) === '') cookies.delete(pair.slice(0, i)); else cookies.set(pair.slice(0, i), pair.slice(i + 1)); }
|
|
85
|
+
return res;
|
|
86
|
+
};
|
|
87
|
+
const here = location => new URL(location, mcp.origin).href;
|
|
88
|
+
const verifier = randomBytes(32).toString('base64url'), state = randomBytes(6).toString('hex');
|
|
89
|
+
await step('authorize: a PKCE request reaches the pairing page', async () => {
|
|
90
|
+
const authorize = new URL(ctx.meta.authorization_endpoint);
|
|
91
|
+
for (const [k, v] of Object.entries({ client_id: ctx.clientId, response_type: 'code', redirect_uri: callback, scope: 'dalan.read dalan.work', state, resource: url, code_challenge: createHash('sha256').update(verifier).digest('base64url'), code_challenge_method: 'S256' })) authorize.searchParams.set(k, v);
|
|
92
|
+
const first = await send(authorize.href);
|
|
93
|
+
ctx.interaction = first.headers.get('location');
|
|
94
|
+
if (first.status !== 303 || !ctx.interaction) throw new Error(`HTTP ${first.status}`);
|
|
95
|
+
const page = await (await send(here(ctx.interaction))).text();
|
|
96
|
+
if (!/class="code">[A-Z0-9-]+</.test(page)) throw new Error('the pairing page shows no code');
|
|
97
|
+
});
|
|
98
|
+
if (!failed) say(`WAIT approve the connection in the trial terminal (y); waiting up to ${Math.round(approveWaitMs / 1000)} s`);
|
|
99
|
+
await step('approval: the owner approved in the trial terminal', async () => {
|
|
100
|
+
const deadline = Date.now() + approveWaitMs;
|
|
101
|
+
for (;;) {
|
|
102
|
+
const done = await send(here(ctx.interaction));
|
|
103
|
+
if (done.status === 303) { ctx.resume = done.headers.get('location'); return; }
|
|
104
|
+
if (Date.now() > deadline) throw new Error('not approved in time');
|
|
105
|
+
signal?.throwIfAborted();
|
|
106
|
+
await sleep(500);
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
await step('callback: the redirect carries this request\'s state and a code, and the issuer if it names one', async () => {
|
|
110
|
+
const resume = await send(here(ctx.resume));
|
|
111
|
+
const back = new URL(resume.headers.get('location') ?? '', mcp.origin);
|
|
112
|
+
if (back.searchParams.get('state') !== state) throw new Error('the state does not match');
|
|
113
|
+
ctx.code = back.searchParams.get('code');
|
|
114
|
+
if (!ctx.code) throw new Error('no authorization code');
|
|
115
|
+
const iss = back.searchParams.get('iss');
|
|
116
|
+
if (iss !== null && iss !== ctx.issuer) throw new Error('the iss parameter differs from the issuer');
|
|
117
|
+
if (resume.status !== 302 && resume.status !== 303) throw new Error(`the redirect status is HTTP ${resume.status}`);
|
|
118
|
+
if (`${back.origin}${back.pathname}` !== callback) throw new Error('the redirect is not to the registered callback');
|
|
119
|
+
});
|
|
120
|
+
await step('token: the code is exchanged for a bearer token bound to this resource', async () => {
|
|
121
|
+
const res = await get(ctx.meta.token_endpoint, { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
|
122
|
+
body: new URLSearchParams({ client_id: ctx.clientId, grant_type: 'authorization_code', code: ctx.code, redirect_uri: callback, code_verifier: verifier, resource: url }) });
|
|
123
|
+
if (res.status !== 200) throw new Error(`HTTP ${res.status}`);
|
|
124
|
+
const doc = await json(res, 'token response');
|
|
125
|
+
if (typeof doc.access_token !== 'string' || doc.access_token === '') throw new Error('no access_token');
|
|
126
|
+
if (!/^bearer$/i.test(doc.token_type ?? '')) throw new Error(`token_type is ${safeDiagnostic(doc.token_type, 20)}`);
|
|
127
|
+
ctx.token = doc.access_token;
|
|
128
|
+
let audience = 'opaque token';
|
|
129
|
+
const parts = ctx.token.split('.');
|
|
130
|
+
if (parts.length === 3) {
|
|
131
|
+
try { const aud = JSON.parse(Buffer.from(parts[1], 'base64url').toString()).aud; if (![aud].flat().includes(url)) throw new Error('x'); audience = 'audience is this resource'; }
|
|
132
|
+
catch { throw new Error('the token\'s audience is not this resource'); }
|
|
133
|
+
}
|
|
134
|
+
return `${audience}; scope ${safeDiagnostic(doc.scope, 80)}; expires_in ${Number.isInteger(doc.expires_in) ? doc.expires_in : 'unset'}`;
|
|
135
|
+
});
|
|
136
|
+
let session = {};
|
|
137
|
+
const rpc = async (body, expect = 200) => {
|
|
138
|
+
const res = await get(url, { method: 'POST', body: JSON.stringify(body), headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', authorization: `Bearer ${ctx.token}`, ...session } });
|
|
139
|
+
const text = await res.text();
|
|
140
|
+
if (res.status !== expect) throw new Error(`HTTP ${res.status}`);
|
|
141
|
+
if (expect === 202) return null;
|
|
142
|
+
try { return { res, message: JSON.parse(mcpResponseText(text) ?? 'null') }; } catch { throw new Error('the reply is not JSON'); }
|
|
143
|
+
};
|
|
144
|
+
await step('mcp auth: a bearer token that was not issued here is refused', async () => {
|
|
145
|
+
const res = await get(url, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', authorization: `Bearer ${randomBytes(24).toString('base64url')}` }, body: '{"jsonrpc":"2.0","id":9,"method":"ping"}' });
|
|
146
|
+
if (res.status !== 401) throw new Error(`HTTP ${res.status}, not 401`);
|
|
147
|
+
});
|
|
148
|
+
await step('mcp initialize: the bearer token is accepted', async () => {
|
|
149
|
+
const { res, message } = await rpc({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: MCP_PROTOCOL, capabilities: {}, clientInfo: { name: 'dalan-self-check', version: '1' } } });
|
|
150
|
+
if (typeof message.result?.protocolVersion !== 'string') throw new Error('no protocol version in the reply');
|
|
151
|
+
session = { 'mcp-protocol-version': message.result.protocolVersion, ...(res.headers.get('mcp-session-id') ? { 'mcp-session-id': res.headers.get('mcp-session-id') } : {}) };
|
|
152
|
+
await rpc({ jsonrpc: '2.0', method: 'notifications/initialized' }, 202);
|
|
153
|
+
return `protocol ${safeDiagnostic(message.result.protocolVersion, 20)}`;
|
|
154
|
+
});
|
|
155
|
+
await step('mcp tools/list: the worker tools are listed', async () => {
|
|
156
|
+
const { message } = await rpc({ jsonrpc: '2.0', id: 2, method: 'tools/list', params: {} });
|
|
157
|
+
const names = (message.result?.tools ?? []).map(t => t.name);
|
|
158
|
+
if (!names.includes('list_pending')) throw new Error('list_pending is not listed');
|
|
159
|
+
return `${names.length} tools`;
|
|
160
|
+
});
|
|
161
|
+
await step('mcp tools/call: list_pending (read-only) returns', async () => {
|
|
162
|
+
const { message } = await rpc({ jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: 'list_pending', arguments: {} } });
|
|
163
|
+
if (message.result?.isError || !message.result?.content?.length) throw new Error('the tool call failed');
|
|
164
|
+
});
|
|
165
|
+
const ok = !failed;
|
|
166
|
+
say(ok ? 'RESULT PASS' : 'RESULT FAIL');
|
|
167
|
+
return { ok, results };
|
|
168
|
+
}
|
package/src/try.mjs
CHANGED
|
@@ -20,6 +20,7 @@ import { PAIRING_MINUTES, untrusted } from './as-files.mjs';
|
|
|
20
20
|
import { beginPairing, DEMO_REDIRECT, workJob, workRepositoryJob } from './demo-worker.mjs';
|
|
21
21
|
import { writeWorkerInstructions } from './worker-instructions.mjs';
|
|
22
22
|
import { SOCKET_PATH_LIMIT } from './admin-socket.mjs';
|
|
23
|
+
import { waitForChildExit } from './child-exit.mjs';
|
|
23
24
|
|
|
24
25
|
|
|
25
26
|
const repo = path.resolve(import.meta.dirname, '..');
|
|
@@ -28,7 +29,7 @@ const BRIEF = 'Report the exact phrase: bridge first report. Do not read files,
|
|
|
28
29
|
const REPORT = 'bridge first report';
|
|
29
30
|
const MARKER = '.dalan-trial';
|
|
30
31
|
const DEFAULT_CALLBACKS = ['http://127.0.0.1/callback', 'http://localhost/callback'];
|
|
31
|
-
const USAGE = 'usage: dalan try [--home DIR] [--port N] [--callback PATTERN]...';
|
|
32
|
+
const USAGE = 'usage: dalan try [--local | --public [--client chatgpt|claude] [--route auto|gozar|localhost.run|tailscale]] [--home DIR] [--port N] [--callback PATTERN]...';
|
|
32
33
|
const DEMO_REPO = 'dalan-demo/hello';
|
|
33
34
|
const DENIED_REPO = 'dalan-demo/other';
|
|
34
35
|
const DEMO_TITLE = 'Hello from the Dalan demo repository';
|
|
@@ -64,17 +65,29 @@ async function alternateTrial(preferPort) {
|
|
|
64
65
|
function formatTryError(error, context, alternate = null) {
|
|
65
66
|
const cause = safeDiagnostic(error?.message ?? String(error), 4000);
|
|
66
67
|
const cli = context.cli ?? `node ${context.shellCli}`;
|
|
67
|
-
const
|
|
68
|
+
const flags = context.tryFlags ?? ''; // a public trial restarts as a public trial
|
|
69
|
+
const newHome = label => alternate && commandBlock(label, `${cli} try${flags} --home ${shellQuote(alternate.home)}${alternate.port ? ` --port ${alternate.port}` : ''}`);
|
|
70
|
+
if (error?.tryKind === 'route_lost') {
|
|
71
|
+
const command = context.freshTrialCommand ?? `${cli} try${flags}`;
|
|
72
|
+
return `${cause}\nThe old connector URL cannot be used. Remove that connector, add the new URL from the fresh trial, then sign in and approve it again. Start fresh with:\n${commandBlock('', command).trimStart()}`;
|
|
73
|
+
}
|
|
68
74
|
const recover = (head, withNewHome) => [`${cause}${head}`, commandBlock('Read the log with:', `cat ${context.shellLog}`),
|
|
69
|
-
commandBlock('Retry this home with:', `${cli} try --home ${context.shellHome}`), withNewHome ? newHome('To try again in a new home instead, run:') : null].filter(Boolean).join('\n');
|
|
75
|
+
commandBlock('Retry this home with:', `${cli} try${flags} --home ${context.shellHome}`), withNewHome ? newHome('To try again in a new home instead, run:') : null].filter(Boolean).join('\n');
|
|
70
76
|
if (error?.tryKind === 'startup') return recover(`\nThe bridge did not start. Full log: ${context.logFile}`, true);
|
|
71
77
|
if (context.started) {
|
|
72
78
|
const invariant = error?.tryKind === 'invariant' ? '\nStop and report this failure; do not grant broader access.' : '';
|
|
73
79
|
return recover(`${invariant}\nServer log: ${context.logFile}`, error?.tryKind === 'unexpected');
|
|
74
80
|
}
|
|
75
81
|
if (error?.tryKind === 'already_running') return cause;
|
|
82
|
+
if (error?.tryKind === 'route_start') {
|
|
83
|
+
// The route, not the home, failed: the same home retries cleanly, and the other route or a local trial are the real alternatives.
|
|
84
|
+
const freshRelayHome = shellQuote(path.join(os.homedir(), '.local/share', `dalan-hosted-${randomUUID()}`));
|
|
85
|
+
const otherRoute = /--route tailscale\b/.test(flags) ? commandBlock('Or make a temporary public demo link with Gozar:', `${cli} try${flags.replace('--route tailscale', '--route gozar')} --home ${freshRelayHome}`) : null;
|
|
86
|
+
return [`${cause}\nThe public route did not start, so the bridge was not started.`, commandBlock('Try again with:', `${cli} try${flags} --home ${context.shellHome}`), otherRoute,
|
|
87
|
+
commandBlock('Or try on this computer only:', `${cli} try --local`)].filter(Boolean).join('\n');
|
|
88
|
+
}
|
|
76
89
|
const notStarted = `${cause}\nThe server has not started; no server log was created for this attempt.`;
|
|
77
|
-
if (error?.freePort && context.shellHome) return `${notStarted}\n${commandBlock('Stop that program, or run the trial on a free port:', `${cli} try --home ${context.shellHome} --port ${error.freePort}`)}`;
|
|
90
|
+
if (error?.freePort && context.shellHome) return `${notStarted}\n${commandBlock('Stop that program, or run the trial on a free port:', `${cli} try${flags} --home ${context.shellHome} --port ${error.freePort}`)}`;
|
|
78
91
|
return `${notStarted}\nFix the problem above, then run the command again.${alternate ? ` ${newHome('Or start a trial in a new home:')}` : ''}`;
|
|
79
92
|
}
|
|
80
93
|
|
|
@@ -87,16 +100,26 @@ export async function describeTryError(error, context) {
|
|
|
87
100
|
|
|
88
101
|
export function parseTryArgs(argv) {
|
|
89
102
|
const out = { home: null, port: null, callbacks: [] };
|
|
103
|
+
const choices = { '--client': ['chatgpt', 'claude'], '--route': ['auto', 'gozar', 'localhost.run', 'tailscale'] };
|
|
90
104
|
for (let i = 0; i < argv.length; i++) {
|
|
91
105
|
const [flag, value] = [argv[i], argv[i + 1]];
|
|
92
|
-
if (
|
|
106
|
+
if (flag === '--local' || flag === '--public') { out.mode = flag.slice(2); continue; }
|
|
107
|
+
if (!['--home', '--port', '--callback', '--client', '--route'].includes(flag)) throw new Error(`unknown option ${JSON.stringify(flag)}\n${USAGE}`);
|
|
93
108
|
if (value === undefined || value.startsWith('--')) throw new Error(`${flag} needs a value\n${USAGE}`);
|
|
94
109
|
i++;
|
|
95
110
|
if (flag === '--home') out.home = value;
|
|
96
111
|
else if (flag === '--callback') out.callbacks.push(value);
|
|
97
|
-
else if (
|
|
112
|
+
else if (flag in choices) {
|
|
113
|
+
if (!choices[flag].includes(value)) throw new Error(`${flag} must be one of: ${choices[flag].join(', ')}`);
|
|
114
|
+
out[flag.slice(2)] = value;
|
|
115
|
+
} else if (/^\d+$/.test(value) && Number(value) > 0 && Number(value) < 65536) out.port = Number(value);
|
|
98
116
|
else throw new Error('--port requires a number from 1 to 65535');
|
|
99
117
|
}
|
|
118
|
+
// Conflicts are refused here, before any file, process or route exists. --client and --route only make sense for a public trial.
|
|
119
|
+
const hostedOnly = ['client', 'route'].filter(key => out[key] !== undefined);
|
|
120
|
+
if (out.mode === 'local' && hostedOnly.length) throw new Error(`--local cannot be combined with --${hostedOnly[0]}; those options are for a public trial`);
|
|
121
|
+
if (hostedOnly.length && !out.mode) out.mode = 'public';
|
|
122
|
+
if (out.mode === 'public' && out.callbacks.length) throw new Error('--callback is for a local client; a public trial uses the selected client\'s own callback');
|
|
100
123
|
return out;
|
|
101
124
|
}
|
|
102
125
|
|
|
@@ -144,12 +167,21 @@ const portFree = port => new Promise(resolve => {
|
|
|
144
167
|
});
|
|
145
168
|
|
|
146
169
|
// Whether a bridge answers on this admin socket: then the trial bridge for that home is already running.
|
|
147
|
-
const socketAnswers = file => new Promise(resolve => {
|
|
148
|
-
const probe =
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
170
|
+
const socketAnswers = (file, connect = net.connect) => new Promise((resolve, reject) => {
|
|
171
|
+
const probe = connect(file);
|
|
172
|
+
let settled = false;
|
|
173
|
+
const finish = (settle, value) => {
|
|
174
|
+
if (settled) return;
|
|
175
|
+
settled = true;
|
|
176
|
+
probe.destroy();
|
|
177
|
+
settle(value);
|
|
178
|
+
};
|
|
179
|
+
probe.setTimeout(1000, () => finish(reject, Object.assign(new Error('admin socket inspection timed out'), { code: 'ETIMEDOUT' })));
|
|
180
|
+
probe.once('connect', () => finish(resolve, true));
|
|
181
|
+
probe.once('error', error => {
|
|
182
|
+
if (error.code === 'ENOENT' || error.code === 'ECONNREFUSED') finish(resolve, false);
|
|
183
|
+
else finish(reject, error);
|
|
184
|
+
});
|
|
153
185
|
});
|
|
154
186
|
|
|
155
187
|
// A free port is a hint: another process can take it before the server binds, so the caller retries on a bind failure.
|
|
@@ -229,8 +261,19 @@ async function prepareDemoRepository(home, signal, tryAgain) {
|
|
|
229
261
|
// The worker wrote the report; it reaches the terminal only through terminalSafe, right before the acceptance prompt.
|
|
230
262
|
export function finishedNotice(jobId, job) { return terminalSafe(`\n✔ Your worker finished ${jobId}. Report:\n${job.report?.result ?? '(empty)'}`); }
|
|
231
263
|
|
|
232
|
-
export async function runTry({ argv = [], env = process.env, out = process.stdout, input = process.stdin, signal, pickPort = choosePort, errorContext = {}, clock = { now: Date.now, sleep }, beforeCommand = null } = {}) {
|
|
264
|
+
export async function runTry({ argv = [], env = process.env, out = process.stdout, input = process.stdin, signal, pickPort = choosePort, errorContext = {}, clock = { now: Date.now, sleep }, beforeCommand = null, hosted = {} } = {}) {
|
|
233
265
|
const options = parseTryArgs(argv);
|
|
266
|
+
// The mode is asked only on a terminal. A pipe, CI or `< /dev/null` never opens a public route: it runs the local self-check.
|
|
267
|
+
const interactive = hosted.interactive ?? Boolean(input.isTTY && out.isTTY);
|
|
268
|
+
if (options.mode === 'public' || (!options.mode && interactive)) {
|
|
269
|
+
const hostedMode = await import('./try-hosted.mjs');
|
|
270
|
+
if (!options.mode) Object.assign(options, await hostedMode.chooseMode({ input, out, signal }));
|
|
271
|
+
if (options.mode === 'public') {
|
|
272
|
+
const cli = errorContext.cli ?? `node ${errorContext.shellCli ?? shellQuote(path.join(repo, 'bin/dalan.mjs'))}`;
|
|
273
|
+
if (!interactive) throw new Error(`Hosted setup needs an interactive terminal for the URL and connection approval. Run this in an interactive terminal:\n${commandLine(`${cli} try --public --client ${options.client ?? 'chatgpt'}`)}`);
|
|
274
|
+
return hostedMode.runHosted({ options, env, out, input, signal, errorContext, clock, deps: hosted, helpers: tryInternals });
|
|
275
|
+
}
|
|
276
|
+
}
|
|
234
277
|
const realHome = fs.realpathSync(os.homedir());
|
|
235
278
|
const home = prepareHome(options.home ?? env.DALAN_HOME ?? path.join(realHome, '.local/share/dalan-trial'), realHome);
|
|
236
279
|
errorContext.home = home;
|
|
@@ -348,9 +391,9 @@ export async function runTry({ argv = [], env = process.env, out = process.stdou
|
|
|
348
391
|
stream.setEncoding('utf8').on('data', chunk => persist(chunk));
|
|
349
392
|
return persist;
|
|
350
393
|
});
|
|
351
|
-
stopped =
|
|
352
|
-
|
|
353
|
-
|
|
394
|
+
stopped = waitForChildExit(child, {
|
|
395
|
+
onClose: () => { for (const flush of sinks) flush('', true); exited = true; },
|
|
396
|
+
onError: error => { fs.appendFileSync(logFile, `process error: ${safeDiagnostic(error.message, 1000)}\n`); },
|
|
354
397
|
});
|
|
355
398
|
};
|
|
356
399
|
const stop = async () => {
|
|
@@ -380,7 +423,7 @@ export async function runTry({ argv = [], env = process.env, out = process.stdou
|
|
|
380
423
|
for (let attempt = 1; ; attempt++) {
|
|
381
424
|
port = await pickPort({ requested: options.port, stored: storedPort, skip: tried });
|
|
382
425
|
tried.add(port);
|
|
383
|
-
if (freshHome) await dalan(['init', '--worker', WORKER, '--public-url', `http://127.0.0.1:${port}`]);
|
|
426
|
+
if (freshHome) await dalan(['init', '--worker', WORKER, '--enable-workspace', '--public-url', `http://127.0.0.1:${port}`]);
|
|
384
427
|
startServer();
|
|
385
428
|
if (await waitForListening()) break;
|
|
386
429
|
const logged = fs.readFileSync(logFile, 'utf8').trim();
|
|
@@ -576,6 +619,9 @@ export async function runTry({ argv = [], env = process.env, out = process.stdou
|
|
|
576
619
|
|
|
577
620
|
export { cliCommand };
|
|
578
621
|
|
|
622
|
+
// What the hosted flow shares with this one: the same home, port, quoting, approval and error rules.
|
|
623
|
+
export const tryInternals = { prepareHome, portFree, socketAnswers, choosePort, shellQuote, commandLine, commandBlock, MARKER, WORKER, parsePending, describeAttempt, formatTryError, alternateTrial, DIAGNOSE_AFTER_MS, DIAGNOSE_EVERY_MS, DIAGNOSE_LIMIT, POLL_MS, repo };
|
|
624
|
+
|
|
579
625
|
export async function main() {
|
|
580
626
|
const controller = new AbortController();
|
|
581
627
|
// The first signal starts the stop. Later ones are ignored so the cleanup can finish: npx forwards the terminal's
|
package/src/workers.mjs
CHANGED
|
@@ -62,7 +62,7 @@ export function parseWorkers(value,{builtin=false,builtinConnectionIds}={}) {
|
|
|
62
62
|
if(name==='pool'||name==='unknown') fail(`worker name "${name}" is reserved and unsupported`);
|
|
63
63
|
if(!/^[a-z][a-z0-9_-]{0,31}$/.test(name)) fail('invalid worker name');
|
|
64
64
|
if(Object.hasOwn(config??{},'pool')) fail(`${name}.pool is not supported`);
|
|
65
|
-
object(config,['connections','capabilities','guidance','repos','repo_access','denied_repos','destination']);
|
|
65
|
+
object(config,['connections','capabilities','guidance','repos','repo_access','denied_repos','destination','workspaceAllowed']);
|
|
66
66
|
const repoSettings=normalizeRepoSettings(config,name);
|
|
67
67
|
if(config.guidance!==undefined&&config.guidance!=='resume') fail(`${name}.guidance may only be "resume"`);
|
|
68
68
|
if(builtin&&config.connections!==undefined&&!(Array.isArray(config.connections)&&!config.connections.length)) fail(`${name}.connections must be absent in built-in mode; connections are recorded by dalan connect approve`);
|
|
@@ -78,9 +78,10 @@ export function parseWorkers(value,{builtin=false,builtinConnectionIds}={}) {
|
|
|
78
78
|
if(!result.connection_id) text(result.client_id);
|
|
79
79
|
return result;
|
|
80
80
|
});
|
|
81
|
+
if(config.workspaceAllowed!==undefined&&typeof config.workspaceAllowed!=='boolean') fail(`${name}.workspaceAllowed must be boolean`);
|
|
81
82
|
const caps=config.capabilities??[];
|
|
82
83
|
if(!Array.isArray(caps)||caps.some(c=>c!=='t3')) fail('capabilities may only contain t3');
|
|
83
|
-
workers.set(name,{connections,capabilities:new Set(caps),...(config.guidance?{guidance:config.guidance}:{}),...repoSettings,
|
|
84
|
+
workers.set(name,{connections,capabilities:new Set(caps),...(config.workspaceAllowed!==undefined?{workspaceAllowed:config.workspaceAllowed}:{}),...(config.guidance?{guidance:config.guidance}:{}),...repoSettings,
|
|
84
85
|
...(Object.hasOwn(config,'destination')?{destination:parseDestinationDeclaration(config.destination)}:{})});
|
|
85
86
|
}
|
|
86
87
|
if(!workers.size) fail('workers must not be empty');
|
|
@@ -181,6 +182,16 @@ export function loadOwnerWorkers(file=readEnv('DALAN_WORKERS_FILE')||defaultPath
|
|
|
181
182
|
return parseOwnerWorkers(JSON.parse(fs.readFileSync(file,'utf8')));
|
|
182
183
|
} catch(error) { if(error.code==='ENOENT') return legacyRepoProfile(file);throw error; }
|
|
183
184
|
}
|
|
185
|
+
// Read-only effective policy for export/migration. Never reconcile or checkpoint the source.
|
|
186
|
+
export function loadEffectiveOwnerWorkers(file) {
|
|
187
|
+
const profile=loadOwnerWorkers(file);
|
|
188
|
+
const current=new Map([...profile.workers.keys()].map(name=>[name,profile.repoPolicy(name).repos]));
|
|
189
|
+
const {applied,unaudited}=evaluateGrants(file,current,false,null);
|
|
190
|
+
return {...profile,deniedRepoGrants:unaudited,
|
|
191
|
+
repoPolicy(worker) {return profile.workers.has(worker)?{mode:'exact',repos:[...(applied.get(worker)??[])]}:null;},
|
|
192
|
+
allowsRepo(worker,repo) {return (applied.get(worker)??[]).some(pattern=>repoMatches(pattern,repo));},
|
|
193
|
+
};
|
|
194
|
+
}
|
|
184
195
|
function parseOwnerWorkers(value) {
|
|
185
196
|
const entries=Object.values(value?.workers??{});
|
|
186
197
|
// Built-in profiles permit both absent and empty connection arrays. Only persisted records imply external OAuth.
|
|
@@ -204,10 +215,10 @@ export function assertTarget(profile,worker) {
|
|
|
204
215
|
return worker;
|
|
205
216
|
}
|
|
206
217
|
// One source of truth for a fresh generic host: one named worker, no t3 capability, no host execution. Never overwrites.
|
|
207
|
-
export function writeGenericProfile(file,name) {
|
|
218
|
+
export function writeGenericProfile(file,name,{workspaceAllowed=false}={}) {
|
|
208
219
|
parseWorkers({workers:{[name]:{}}},{builtin:true});
|
|
209
220
|
fs.mkdirSync(path.dirname(file),{recursive:true,mode:0o700});
|
|
210
|
-
try { fs.writeFileSync(file,`${JSON.stringify({workers:{[name]:{repos:[]}},default_execution:'none'},null,2)}\n`,{mode:0o600,flag:'wx'}); }
|
|
221
|
+
try { fs.writeFileSync(file,`${JSON.stringify({workers:{[name]:{repos:[],...(workspaceAllowed?{workspaceAllowed:true}:{})}},default_execution:'none'},null,2)}\n`,{mode:0o600,flag:'wx'}); }
|
|
211
222
|
catch(error) { if(error.code==='EEXIST') throw new Error(`${file} already exists; init does not overwrite a worker profile`); throw error; }
|
|
212
223
|
fs.chmodSync(file,0o600);
|
|
213
224
|
return file;
|
|
@@ -258,15 +269,15 @@ function legacyRepoProfile(file,auditGrants=false) {
|
|
|
258
269
|
// The audit log is append-only text that a same-user process can delete. Every append therefore also records a checkpoint
|
|
259
270
|
// (byte length and SHA-256 of the log, last event id) in a private SQLite file beside it, and that file doubles as the
|
|
260
271
|
// lock that serializes every writer of the audit. A log that is missing, shorter than its checkpoint, or whose recorded
|
|
261
|
-
// prefix changed fails closed: no
|
|
262
|
-
// audited) the existing list is recorded once. A same-user actor who
|
|
263
|
-
// leaves an install that looks never-audited; that actor can equally
|
|
264
|
-
// detects accidents and one-sided tampering, not a full compromise
|
|
272
|
+
// prefix changed fails closed: no event from that history can establish grant authority until an owner recovers it.
|
|
273
|
+
// Without a checkpoint (an install that was never audited), the existing list is recorded once. A same-user actor who
|
|
274
|
+
// deletes the checkpoint file and the log together leaves an install that looks never-audited; that actor can equally
|
|
275
|
+
// rewrite workers.json and the queue, so this check detects accidents and one-sided tampering, not a full compromise.
|
|
265
276
|
const auditFileOf=workersFile=>path.join(path.dirname(workersFile),'workers-audit.jsonl');
|
|
266
277
|
const checkpointFileOf=workersFile=>path.join(path.dirname(workersFile),'workers-audit-checkpoint.sqlite');
|
|
267
278
|
const sha256=bytes=>createHash('sha256').update(bytes).digest('hex');
|
|
268
279
|
const CHECKPOINT_SQL='CREATE TABLE IF NOT EXISTS checkpoint(id INTEGER PRIMARY KEY CHECK(id=1),size INTEGER NOT NULL,sha256 TEXT NOT NULL,last_event_id TEXT)';
|
|
269
|
-
export const AUDIT_INTEGRITY_HINT='
|
|
280
|
+
export const AUDIT_INTEGRITY_HINT='The failed checkpoint makes every existing grant untrusted. Re-approve each grant you want with dalan worker allow NAME OWNER/REPO; the first allow or deny drops every current grant before applying that explicit change and establishing a new baseline.';
|
|
270
281
|
// Serializes read, compare and append for every writer of the audit (loaders and the worker allow/deny commands).
|
|
271
282
|
export function withAuditLock(workersFile,fn) {
|
|
272
283
|
if(!fs.existsSync(path.dirname(workersFile))) return fn(null);
|
|
@@ -318,26 +329,25 @@ function integrityFailure(history,checkpoint) {
|
|
|
318
329
|
function auditedRepoState(workersFile,db) {
|
|
319
330
|
const auditFile=auditFileOf(workersFile);
|
|
320
331
|
const history=readWorkerRepoHistory(auditFile,{workersFile,maxBytes:Infinity,keepRaw:true});
|
|
321
|
-
const state=new Map();
|
|
322
|
-
for(const event of history.events) if(event.after.mode==='exact') state.set(event.worker,event.after.repos);
|
|
323
|
-
let pending=new Set();
|
|
324
|
-
try {pending=new Set((readRepoMigration(workersFile)?.entries??[]).filter(entry=>entry.kind==='profile'&&!entry.complete).map(entry=>entry.worker));}
|
|
325
|
-
catch {/* readWorkerRepoHistory already reports an unreadable journal as incomplete */}
|
|
326
332
|
const checkpoint=readCheckpoint(workersFile,db);
|
|
327
|
-
|
|
333
|
+
const integrity_error=integrityFailure(history,checkpoint);
|
|
334
|
+
// A pending seed is also in history.events. If its checkpoint fails, an older seed cannot prove that no later
|
|
335
|
+
// revocation exists in the untrusted log, so discard every event as grant authority until owner recovery.
|
|
336
|
+
const events=integrity_error?[]:history.events;
|
|
337
|
+
const state=new Map();
|
|
338
|
+
for(const event of events) if(event.after.mode==='exact') state.set(event.worker,event.after.repos);
|
|
339
|
+
return {auditFile,history,state,checkpoint,integrity_error};
|
|
328
340
|
}
|
|
329
341
|
const repoKey=repo=>repo.toLowerCase();
|
|
330
342
|
const diffRepos=(from,to)=>{const keys=new Set(from.map(repoKey));return to.filter(repo=>!keys.has(repoKey(repo)));};
|
|
331
343
|
function evaluateGrants(workersFile,current,write,db) {
|
|
332
|
-
const {auditFile,history,state,
|
|
344
|
+
const {auditFile,history,state,checkpoint,integrity_error}=auditedRepoState(workersFile,db);
|
|
333
345
|
const applied=new Map(),unaudited=[];
|
|
334
346
|
let needsWrite=false;
|
|
335
347
|
for(const [worker,repos] of current) {
|
|
336
348
|
const audited=state.get(worker)??[];
|
|
337
349
|
const added=diffRepos(audited,repos),removed=diffRepos(repos,audited);
|
|
338
|
-
|
|
339
|
-
// seedWorkerRepos publishes before it marks the worker complete: the journal is the audit record for that list.
|
|
340
|
-
if(pending.has(worker)||(!added.length&&!removed.length)) {applied.set(worker,[...repos]);continue;}
|
|
350
|
+
if(!added.length&&!removed.length) {applied.set(worker,[...repos]);continue;}
|
|
341
351
|
let recorded=false;
|
|
342
352
|
if(write&&history.complete&&!integrity_error) {
|
|
343
353
|
needsWrite=true;
|
|
@@ -364,7 +374,7 @@ function reconcileGrants(workersFile,readCurrent,{write=true}={}) {
|
|
|
364
374
|
if(!write||!first.needsWrite) return first;
|
|
365
375
|
try {return withAuditLock(workersFile,db=>evaluateGrants(workersFile,readCurrent(),true,db));}
|
|
366
376
|
catch {
|
|
367
|
-
// The lock
|
|
377
|
+
// The lock is unusable: fail closed and apply none of this load's unaudited additions.
|
|
368
378
|
const denied=new Map(first.unaudited.map(item=>[item.worker,item.repos.map(repoKey)]));
|
|
369
379
|
return {...first,applied:new Map([...first.applied].map(([worker,repos])=>[worker,repos.filter(repo=>!(denied.get(worker)??[]).includes(repoKey(repo)))]))};
|
|
370
380
|
}
|
|
@@ -492,8 +502,8 @@ function currentGrants(file) {
|
|
|
492
502
|
const journal=readRepoMigration(file);
|
|
493
503
|
return new Map((journal?.entries??[]).filter(entry=>entry.kind==='legacy').map(entry=>[entry.worker,entry.repos]));
|
|
494
504
|
}
|
|
495
|
-
// After the audit log failed its checkpoint, the first allow or deny
|
|
496
|
-
//
|
|
505
|
+
// After the audit log failed its checkpoint, no event proves the latest grant state. The first allow or deny drops every
|
|
506
|
+
// current grant, applies only that explicit change, then records a new baseline. Other grants stay denied until
|
|
497
507
|
// the operator allows them again.
|
|
498
508
|
function resetAfterIntegrityFailure(file,db) {
|
|
499
509
|
const {auditFile,state,integrity_error,history}=auditedRepoState(file,db);
|
|
@@ -504,7 +514,7 @@ function resetAfterIntegrityFailure(file,db) {
|
|
|
504
514
|
const raw=JSON.parse(fs.readFileSync(file,'utf8'));
|
|
505
515
|
for(const [worker,setting] of Object.entries(raw.workers??{})) {
|
|
506
516
|
const audited=state.get(worker)??[],listed=Array.isArray(setting.repos)?setting.repos:[];
|
|
507
|
-
//
|
|
517
|
+
// Integrity failure provides no trusted grant state, so this intersection removes all current grants.
|
|
508
518
|
const kept=listed.filter(repo=>audited.some(k=>repoKey(k)===repoKey(repo)));
|
|
509
519
|
if(kept.length!==listed.length) {dropped.push({worker,repos:listed.filter(repo=>!kept.includes(repo))});setting.repos=kept;}
|
|
510
520
|
}
|
package/src/workspace.mjs
CHANGED
|
@@ -38,6 +38,10 @@ function missingDeclaredTestPath(dir,spec,origin) {
|
|
|
38
38
|
return null;
|
|
39
39
|
}
|
|
40
40
|
const yieldLoop=()=>new Promise(resolve=>setImmediate(resolve));
|
|
41
|
+
function pathExistsOrThrow(file) {
|
|
42
|
+
try { fs.lstatSync(file); return true; }
|
|
43
|
+
catch(error) { if(error.code==='ENOENT'||error.code==='ENOTDIR') return false; throw error; }
|
|
44
|
+
}
|
|
41
45
|
function spawnAsync(cmd,args,timeout=60000,env=process.env) { return new Promise(resolve=>{ let stderr='';const child=spawn(cmd,args,{stdio:['ignore','ignore','pipe'],timeout,env});child.stderr.on('data',b=>{if(stderr.length<300)stderr+=b;});child.on('error',error=>resolve({status:null,stderr:error.message}));child.on('close',status=>resolve({status,stderr})); }); }
|
|
42
46
|
async function gitAsync(args) { const r=await spawnAsync('git',args,10000,gitEnv()); if(r.status!==0) throw new Error(`git failed: ${r.stderr.slice(0,300)}`); }
|
|
43
47
|
// Go and uv write their module caches read-only, so make the tree writable before removing it.
|
|
@@ -294,7 +298,7 @@ export async function restoreOutsideWritable({dir,scratch,preTree,writable}) {
|
|
|
294
298
|
const errors=[];
|
|
295
299
|
// A path is removed or written only below real directories: a symlinked ancestor is itself a listed change and is handled on its own.
|
|
296
300
|
const parentsOf=name=>{const bytes=nameBytes(name),out=[];for(let i=0;i<bytes.length;i++) if(bytes[i]===0x2f) out.push(bytes.subarray(0,i));return out;};
|
|
297
|
-
const realParents=name=>{for(const parent of parentsOf(name)){try{if(!fs.lstatSync(Buffer.concat([Buffer.from(dir+path.sep),parent])).isDirectory()) return false;}catch{return
|
|
301
|
+
const realParents=name=>{for(const parent of parentsOf(name)){try{if(!fs.lstatSync(Buffer.concat([Buffer.from(dir+path.sep),parent])).isDirectory()) return false;}catch{return false;}}return true;};
|
|
298
302
|
for(const entry of outside.filter(e=>e.status==='A')) {
|
|
299
303
|
if(!realParents(entry.path)) continue;
|
|
300
304
|
try{fs.rmSync(absBytes(dir,entry.path),{recursive:true,force:true});}catch(error){errors.push(`${entry.path}: ${error.code||error.message}`);continue;}
|
|
@@ -585,7 +589,10 @@ export class Workspace {
|
|
|
585
589
|
async sweepMirrors(pressure,minFree) {
|
|
586
590
|
const db=this.store.db,inUse=new Set();
|
|
587
591
|
for(const row of db.prepare("SELECT request_id,payload,target_worker FROM assignments WHERE status IN ('queued','claimed')").all()) { try{inUse.add(mirrorPath(payloadRepo(row.payload),{worker:row.target_worker||'dot'}));}catch{} }
|
|
588
|
-
|
|
592
|
+
let unknownWorkspaceMirror=false;
|
|
593
|
+
for(const row of db.prepare('SELECT request_id,path FROM workspaces').all()) { const common=savedWorkspaceMirror(row.path,row.request_id);if(common) inUse.add(common);else unknownWorkspaceMirror=true; }
|
|
594
|
+
// A workspace whose .git pointer could not be read may still depend on any mirror.
|
|
595
|
+
if(unknownWorkspaceMirror) return 0;
|
|
589
596
|
const found=[];
|
|
590
597
|
const visit=async dir=>{
|
|
591
598
|
if(path.basename(dir).includes('.evicting-')) { await removeCache(dir);return; }
|
|
@@ -666,7 +673,7 @@ export class Workspace {
|
|
|
666
673
|
const cache=path.join(caches,row.request_id);if(fs.existsSync(cache)) { await removeCache(cache);if(!fs.existsSync(cache)) summary.caches_removed++; }
|
|
667
674
|
if(!expired&&!row.fetched_at) { if(!pressure) continue; if(!(pressure=await this.freeBytes()<minFree)) continue; if(!(row=idle())) continue; }
|
|
668
675
|
if(row.path!==path.join(worktrees,row.request_id)) throw Object.assign(new Error('workspace cleanup path mismatch'),{request_id:requestId,summary});
|
|
669
|
-
if(
|
|
676
|
+
if(pathExistsOrThrow(row.path)) await gitAsync(['-C',mirror,'worktree','remove','--force',row.path]);
|
|
670
677
|
db.prepare('DELETE FROM workspaces WHERE request_id=?').run(row.request_id);fs.rmSync(this.ignoredWrittenFile(row.request_id),{force:true});summary.workspaces_removed++;
|
|
671
678
|
} catch(error) { if(error.summary) throw error;failed({request_id:requestId},error); }
|
|
672
679
|
}
|