@tnunamak/dalan 0.8.1 → 0.8.3
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 +61 -2
- package/CONTRIBUTING.md +2 -0
- package/README.md +8 -12
- package/bin/dalan.mjs +25 -4
- package/bin/dot-acp-agent.mjs +572 -76
- package/bin/dot-alert.mjs +9 -3
- package/bin/dot-deadman.mjs +3 -1
- package/bin/dot-heartbeat.mjs +14 -7
- package/bin/dot-pr-reviewer.mjs +3 -31
- package/bin/dot-worker.mjs +121 -34
- package/contracts/adapter-qualification.schema.json +94 -7
- package/docs/chatgpt-worker-onboarding.md +1 -1
- package/docs/codex-to-muse.md +2 -2
- package/docs/connect-chatgpt.md +1 -1
- package/docs/connection-longevity.md +2 -2
- package/docs/dalan-upgrade.md +8 -5
- package/docs/deadman.md +4 -0
- package/docs/design/authority-matrix.md +18 -0
- package/docs/design/failure-table.md +87 -0
- package/docs/design/identities.md +22 -0
- package/docs/design/pnpm-prepared-dependencies.md +64 -0
- package/docs/design/reuse-ledger.md +75 -0
- package/docs/design/target-architecture-v2.md +434 -0
- package/docs/local-agent-mcp.md +14 -0
- package/docs/local-agent-requester.md +2 -1
- package/docs/manual-setup.md +1 -1
- package/docs/operations.md +77 -14
- package/docs/pull-workers.md +11 -1
- package/docs/service-setup.md +10 -10
- package/docs/t3-integration.md +4 -2
- package/docs/t3-reverse-control.md +5 -5
- package/docs/test-suite-isolation.md +7 -6
- package/docs/trials/chatgpt-agent.md +47 -0
- package/docs/trials/claude-code-requester.md +68 -0
- package/docs/trials/muse.md +46 -0
- package/docs/usage.md +21 -7
- package/docs/worker-clients.md +1 -1
- package/integrations/t3/acp-kit/src/errors.mjs +6 -2
- package/integrations/t3/acp-kit/src/lock.mjs +46 -17
- package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
- package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
- package/package.json +4 -3
- package/packages/job-core/protocol/canonical.mjs +45 -7
- package/packages/job-core/transitions.mjs +4 -2
- package/scripts/upgrade-drain.mjs +96 -8
- package/scripts/worker-bridge-setup.mjs +215 -120
- package/src/ack-ledger.mjs +7 -1
- package/src/acp-bridge.mjs +256 -28
- package/src/admin-socket.mjs +32 -3
- package/src/alerts.mjs +17 -8
- package/src/answer-journal-retention.mjs +82 -0
- package/src/answer-journal.mjs +6 -4
- package/src/as-store.mjs +51 -6
- package/src/as.mjs +27 -5
- package/src/catalog-switch-inventory.mjs +70 -0
- package/src/check-response.mjs +4 -1
- package/src/cli-help.mjs +14 -3
- package/src/cli-name.mjs +13 -1
- package/src/connect-cli.mjs +159 -4
- package/src/deadman.mjs +8 -5
- package/src/delivery.mjs +2 -19
- package/src/destinations/index.mjs +75 -14
- package/src/drain-runner.mjs +5 -1
- package/src/follow-current.mjs +3 -1
- package/src/get-summary.mjs +11 -2
- package/src/git-env.mjs +1 -1
- package/src/gozar-routes.mjs +313 -94
- package/src/host-budget-storage.py +56 -6
- package/src/host-budget.mjs +98 -15
- package/src/host-execution-policy.mjs +17 -6
- package/src/legacy-names.mjs +0 -2
- package/src/lifecycle.mjs +44 -9
- package/src/loopback-probe.mjs +46 -0
- package/src/mcp-outcome.mjs +3 -1
- package/src/mcp-sse.mjs +2 -1
- package/src/mcp-stdio.mjs +192 -30
- package/src/patch-apply.mjs +212 -7
- package/src/phase-trace.mjs +73 -0
- package/src/prepared-go-modules.mjs +127 -0
- package/src/prepared-node-modules.mjs +225 -38
- package/src/prepared-pnpm.mjs +276 -0
- package/src/prepared-store-prune.mjs +52 -0
- package/src/projects.mjs +59 -7
- package/src/protocol-artifact-commands.mjs +28 -0
- package/src/protocol-finish.mjs +3 -2
- package/src/publication-authority.mjs +22 -0
- package/src/publish-plan.mjs +2 -2
- package/src/pull-queue.mjs +55 -20
- package/src/read-api.mjs +127 -0
- package/src/redaction.mjs +173 -0
- package/src/rejections.mjs +19 -3
- package/src/route-custody.mjs +90 -0
- package/src/route-publication.mjs +50 -0
- package/src/route-setup.mjs +184 -0
- package/src/schema-subset.mjs +5 -3
- package/src/server.mjs +503 -98
- package/src/service-launchd.mjs +5 -1
- package/src/service-update-lock.mjs +7 -4
- package/src/service-update-runtime.mjs +136 -21
- package/src/service-update.mjs +207 -51
- package/src/service.mjs +276 -77
- package/src/setup.mjs +48 -25
- package/src/signal.mjs +1 -1
- package/src/status-evidence.mjs +18 -5
- package/src/store.mjs +876 -120
- package/src/submission-policy.mjs +257 -56
- package/src/t3-control.mjs +1 -1
- package/src/t3.mjs +14 -8
- package/src/terminal-safe.mjs +9 -7
- package/src/tool-registry.mjs +134 -41
- package/src/try-exposure.mjs +53 -86
- package/src/try-hosted.mjs +257 -70
- package/src/try.mjs +48 -22
- package/src/work-order.mjs +11 -6
- package/src/worker-instructions.mjs +26 -4
- package/src/worker-runs.mjs +35 -0
- package/src/workers.mjs +34 -7
- package/src/workspace.mjs +354 -54
- package/systemd/dot-deadman.service +3 -1
- package/docs/dot-pr-reviewer.config.example.json +0 -9
- package/docs/pr-head-reviewer.md +0 -70
- package/src/pr-head-reviewer.mjs +0 -596
- package/systemd/dot-pr-reviewer.service +0 -11
- package/systemd/dot-pr-reviewer.timer +0 -10
package/src/try.mjs
CHANGED
|
@@ -19,7 +19,7 @@ import { registerSecret } from './redaction.mjs';
|
|
|
19
19
|
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
|
-
import {
|
|
22
|
+
import { adminSocketPath, adminSocketPathError } from './admin-socket.mjs';
|
|
23
23
|
import { waitForChildExit } from './child-exit.mjs';
|
|
24
24
|
|
|
25
25
|
|
|
@@ -55,7 +55,7 @@ async function alternateTrial(preferPort) {
|
|
|
55
55
|
for (const base of [fs.realpathSync(os.homedir()), fs.realpathSync(os.tmpdir())]) {
|
|
56
56
|
for (let n = 2; n < 100; n++) {
|
|
57
57
|
const home = path.join(base, `.dalan-trial-${n}`);
|
|
58
|
-
if (fs.existsSync(home) ||
|
|
58
|
+
if (fs.existsSync(home) || adminSocketPathError(adminSocketPath(defaultPath(home, '.local/share/dot-bridge')))) continue;
|
|
59
59
|
return { home, port: await free(null) };
|
|
60
60
|
}
|
|
61
61
|
}
|
|
@@ -98,11 +98,18 @@ export async function describeTryError(error, context) {
|
|
|
98
98
|
return formatTryError(error, context, await alternateTrial(error?.alternatePort).catch(() => null));
|
|
99
99
|
}
|
|
100
100
|
|
|
101
|
+
const PUBLIC_CALLBACK_ERROR = "--callback is for a local client; a public trial uses the MCP client's own callback";
|
|
102
|
+
|
|
101
103
|
export function parseTryArgs(argv) {
|
|
102
104
|
const out = { home: null, port: null, callbacks: [] };
|
|
103
105
|
for (let i = 0; i < argv.length; i++) {
|
|
104
106
|
const [flag, value] = [argv[i], argv[i + 1]];
|
|
105
|
-
if (flag === '--local' || flag === '--public') {
|
|
107
|
+
if (flag === '--local' || flag === '--public') {
|
|
108
|
+
const mode = flag.slice(2);
|
|
109
|
+
if (out.mode && out.mode !== mode) throw new Error('--local cannot be combined with --public');
|
|
110
|
+
out.mode = mode;
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
106
113
|
if (!['--home', '--port', '--callback', '--route'].includes(flag)) throw new Error(`unknown option ${JSON.stringify(flag)}\n${USAGE}`);
|
|
107
114
|
if (value === undefined || value.startsWith('--')) throw new Error(`${flag} needs a value\n${USAGE}`);
|
|
108
115
|
i++;
|
|
@@ -115,7 +122,7 @@ export function parseTryArgs(argv) {
|
|
|
115
122
|
// Conflicts are refused here, before any file, process or route exists. --client and --route only make sense for a public trial.
|
|
116
123
|
if (out.mode === 'local' && out.route !== undefined) throw new Error('--local cannot be combined with --route; that option is for a public trial');
|
|
117
124
|
if (out.route !== undefined && !out.mode) out.mode = 'public';
|
|
118
|
-
if (out.mode === 'public' && out.callbacks.length) throw new Error(
|
|
125
|
+
if (out.mode === 'public' && out.callbacks.length) throw new Error(PUBLIC_CALLBACK_ERROR);
|
|
119
126
|
return out;
|
|
120
127
|
}
|
|
121
128
|
|
|
@@ -128,9 +135,10 @@ export function parsePending(result) {
|
|
|
128
135
|
const pending = result.pending.map(p => {
|
|
129
136
|
for (const key of ['code', 'client_id', 'redirect_uri']) if (typeof p?.[key] !== 'string' || !p[key]) throw bad(`attempt without ${key}`);
|
|
130
137
|
if (!Array.isArray(p.scopes)) throw bad('attempt without scopes');
|
|
138
|
+
if (p.scopes.some(scope => typeof scope !== 'string' || scope.length === 0)) throw bad('attempt with invalid scopes');
|
|
131
139
|
return {
|
|
132
140
|
code: p.code, worker: typeof p.worker === 'string' ? p.worker : '', client_id: p.client_id, client_name: typeof p.client_name === 'string' ? p.client_name : '', redirect_uri: p.redirect_uri,
|
|
133
|
-
resource: typeof p.resource === 'string' ? p.resource : '', scopes: p.scopes
|
|
141
|
+
resource: typeof p.resource === 'string' ? p.resource : '', scopes: [...p.scopes], superseded: p.superseded === true, native: p.native === true,
|
|
134
142
|
expires_in_seconds: Number.isFinite(p.expires_in_seconds) ? p.expires_in_seconds : null,
|
|
135
143
|
};
|
|
136
144
|
});
|
|
@@ -214,8 +222,6 @@ function prepareHome(candidate, realHome) {
|
|
|
214
222
|
throw new Error(`${home} already holds files that a trial did not create (it could be a real Dalan home); choose a new or empty directory with --home DIR`);
|
|
215
223
|
}
|
|
216
224
|
}
|
|
217
|
-
const socket = defaultPath(home, '.local/share/dot-bridge', 'admin.sock');
|
|
218
|
-
if (Buffer.byteLength(socket) > SOCKET_PATH_LIMIT) throw new Error(`the trial home path is too long for the bridge's admin socket (${Buffer.byteLength(socket)} bytes, limit ${SOCKET_PATH_LIMIT}); choose a shorter --home DIR`);
|
|
219
225
|
fs.mkdirSync(home, { recursive: true, mode: 0o700 });
|
|
220
226
|
fs.chmodSync(home, 0o700);
|
|
221
227
|
fs.writeFileSync(path.join(home, MARKER), 'created by `dalan try`\n', { mode: 0o600 });
|
|
@@ -255,19 +261,36 @@ async function prepareDemoRepository(home, signal, tryAgain) {
|
|
|
255
261
|
// `pickPort` and `clock` are seams for tests: the first stands in for the free-port search so a lost race can be reproduced,
|
|
256
262
|
// the second for the time and the wait between polls so minutes of waiting need no real minutes.
|
|
257
263
|
// The worker wrote the report; it reaches the terminal only through terminalSafe, right before the acceptance prompt.
|
|
258
|
-
export function finishedNotice(jobId, job) {
|
|
264
|
+
export function finishedNotice(jobId, job) {
|
|
265
|
+
if (job.report?.outcome !== 'completed') {
|
|
266
|
+
return terminalSafe(`\nYour worker did not complete ${jobId}. Outcome: ${job.report?.outcome ?? 'unknown'}. Summary:\n${job.report?.summary ?? job.report?.result ?? '(empty)'}`);
|
|
267
|
+
}
|
|
268
|
+
return terminalSafe(`\n✔ Your worker finished ${jobId}. Report:\n${job.report?.result ?? '(empty)'}`);
|
|
269
|
+
}
|
|
259
270
|
|
|
260
|
-
|
|
271
|
+
// Shared by runTry and its no-network regression: no non-completed report reaches ask or accept.
|
|
272
|
+
export async function reviewFinishedJob(jobId, job, { say, ask, accept, exited, stopRequested, ownCommand }) {
|
|
273
|
+
say(finishedNotice(jobId, job));
|
|
274
|
+
if (job.report?.outcome !== 'completed') return true;
|
|
275
|
+
const answer = await ask('Accept this result? [y/N] ');
|
|
276
|
+
if (exited() && !stopRequested()) return false;
|
|
277
|
+
if (answer?.trim().toLowerCase() === 'y') { await accept(); say('Recorded as accepted.'); }
|
|
278
|
+
else say(stopRequested() ? '\nNot recorded.' : `Not recorded. Decide later while the bridge runs:\n${commandLine(ownCommand('decide', jobId, 'accepted'))}`);
|
|
279
|
+
return true;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
export async function runTry({ argv = [], env = process.env, out = process.stdout, input = process.stdin, signal, pickPort = choosePort, errorContext = {}, clock = { now: () => performance.now(), sleep }, beforeCommand = null, hosted = {}, spawnServer = spawn } = {}) {
|
|
261
283
|
const options = parseTryArgs(argv);
|
|
262
284
|
// 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.
|
|
263
285
|
const interactive = hosted.interactive ?? Boolean(input.isTTY && out.isTTY);
|
|
264
286
|
if (options.mode === 'public' || (!options.mode && interactive)) {
|
|
265
287
|
const hostedMode = await import('./try-hosted.mjs');
|
|
266
|
-
if (!options.mode) Object.assign(options, await hostedMode.chooseMode({ input, out, signal }));
|
|
288
|
+
if (!options.mode) Object.assign(options, await (hosted.chooseMode ?? hostedMode.chooseMode)({ input, out, signal }));
|
|
267
289
|
if (options.mode === 'public') {
|
|
290
|
+
if (options.callbacks.length) throw new Error(PUBLIC_CALLBACK_ERROR);
|
|
268
291
|
const cli = errorContext.cli ?? `node ${errorContext.shellCli ?? shellQuote(path.join(repo, 'bin/dalan.mjs'))}`;
|
|
269
292
|
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${options.route !== undefined ? ` --route ${shellQuote(options.route)}` : ''}`)}`);
|
|
270
|
-
return hostedMode.runHosted({ options, env, out, input, signal, errorContext, clock, deps: hosted, helpers: tryInternals });
|
|
293
|
+
return (hosted.runHosted ?? hostedMode.runHosted)({ options, env, out, input, signal, errorContext, clock, deps: hosted, helpers: tryInternals });
|
|
271
294
|
}
|
|
272
295
|
}
|
|
273
296
|
const realHome = fs.realpathSync(os.homedir());
|
|
@@ -288,7 +311,7 @@ export async function runTry({ argv = [], env = process.env, out = process.stdou
|
|
|
288
311
|
let storedPort = null;
|
|
289
312
|
try { storedPort = Number(new URL(JSON.parse(fs.readFileSync(path.join(configDir, 'as.json'), 'utf8')).public_url).port) || null; } catch { /* a new home */ }
|
|
290
313
|
// This home's own bridge already holds its port. Say so before anything below touches the running trial's grant or files.
|
|
291
|
-
if (storedPort && !await portFree(storedPort) && await socketAnswers(defaultPath(home, '.local/share/dot-bridge'
|
|
314
|
+
if (storedPort && !await portFree(storedPort) && await socketAnswers(adminSocketPath(defaultPath(home, '.local/share/dot-bridge')))) {
|
|
292
315
|
const error = new Error(`the trial bridge for this home is already running on http://127.0.0.1:${storedPort}. Use it from another terminal (export DALAN_HOME=${shellHome}), or stop it with Ctrl-C in its terminal first.`);
|
|
293
316
|
error.tryKind = 'already_running';
|
|
294
317
|
throw error;
|
|
@@ -380,7 +403,7 @@ export async function runTry({ argv = [], env = process.env, out = process.stdou
|
|
|
380
403
|
exited = false;
|
|
381
404
|
fs.closeSync(log);
|
|
382
405
|
// Server output is sanitized line by line before it is persisted; a partial line is held until it completes.
|
|
383
|
-
server =
|
|
406
|
+
server = spawnServer(process.execPath, [path.join(repo, 'src/server.mjs')], { env: { ...baseEnv, DALAN_PORT: String(port) }, cwd: repo, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
384
407
|
const child = server;
|
|
385
408
|
const sinks = [child.stdout, child.stderr].map(stream => {
|
|
386
409
|
const persist = createLineMasker(text => fs.appendFileSync(logFile, text));
|
|
@@ -407,9 +430,12 @@ export async function runTry({ argv = [], env = process.env, out = process.stdou
|
|
|
407
430
|
return true;
|
|
408
431
|
};
|
|
409
432
|
|
|
410
|
-
let cleaned = false;
|
|
433
|
+
let cleaned = false, startupCleanupFailed = false;
|
|
411
434
|
try {
|
|
412
|
-
await cleanupTrial()
|
|
435
|
+
if (!await cleanupTrial()) {
|
|
436
|
+
startupCleanupFailed = true;
|
|
437
|
+
throw new Error(`Previous trial cleanup failed in ${home}. Correct the cleanup error above, then retry ${cli} try --home ${shellHome}.`);
|
|
438
|
+
}
|
|
413
439
|
signal?.throwIfAborted();
|
|
414
440
|
demoRepo = await prepareDemoRepository(home, signal, `${cli} try --home ${shellHome}`);
|
|
415
441
|
if (demoRepo.bare) baseEnv.DALAN_GITHUB_URL_DALAN_DEMO_HELLO = demoRepo.bare;
|
|
@@ -425,7 +451,7 @@ export async function runTry({ argv = [], env = process.env, out = process.stdou
|
|
|
425
451
|
const logged = fs.readFileSync(logFile, 'utf8').trim();
|
|
426
452
|
const tail = logged.split('\n').slice(-5).join('\n');
|
|
427
453
|
await stop();
|
|
428
|
-
if (attempt < 3 && freshHome && !options.port && /EADDRINUSE/.test(logged)) { fs.rmSync(configDir, { recursive: true, force: true }); continue; }
|
|
454
|
+
if (attempt < 3 && freshHome && !options.port && /(?:^|\n)(?:Error:[ \t]*)?listen EADDRINUSE(?=[: \t\r\n]|$)/.test(logged)) { fs.rmSync(configDir, { recursive: true, force: true }); continue; }
|
|
429
455
|
const error = new Error(`the bridge did not start; last log lines:\n${tail}`);
|
|
430
456
|
error.tryKind = 'startup';
|
|
431
457
|
throw error;
|
|
@@ -542,11 +568,11 @@ export async function runTry({ argv = [], env = process.env, out = process.stdou
|
|
|
542
568
|
while (!exited && !stopRequested()) {
|
|
543
569
|
const current = await job(jobId);
|
|
544
570
|
if (current.status === 'finished') {
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
571
|
+
const reviewed = await reviewFinishedJob(jobId, current, {
|
|
572
|
+
say, ask, accept: () => dalan(['decide', jobId, 'accepted']),
|
|
573
|
+
exited: () => exited, stopRequested, ownCommand,
|
|
574
|
+
});
|
|
575
|
+
if (!reviewed) break;
|
|
550
576
|
if (!stopRequested()) { say('The bridge stays up. Ctrl-C stops it.'); await untilStopRequested(); }
|
|
551
577
|
break;
|
|
552
578
|
}
|
|
@@ -607,7 +633,7 @@ export async function runTry({ argv = [], env = process.env, out = process.stdou
|
|
|
607
633
|
} finally {
|
|
608
634
|
lines.close();
|
|
609
635
|
await stop();
|
|
610
|
-
cleaned = await cleanupTrial();
|
|
636
|
+
if (!startupCleanupFailed) cleaned = await cleanupTrial();
|
|
611
637
|
}
|
|
612
638
|
say(`Stopped. Trial home kept at ${home}; delete it to start over.${cleaned ? ' The demo grant and files are removed.' : ''}`);
|
|
613
639
|
say(`Next steps (connect your own worker, repository jobs, other machines): ${docsUrl('README.md', 'next-steps')}`);
|
package/src/work-order.mjs
CHANGED
|
@@ -171,17 +171,20 @@ export async function compileWorkOrder(request, deps) {
|
|
|
171
171
|
const reasons = [];
|
|
172
172
|
let refusal = null;
|
|
173
173
|
let payload = null, expanded = null, readiness = null, preflight = null;
|
|
174
|
+
const now=deps.now??Date.now;
|
|
175
|
+
const checkDeadline=assignment=>{
|
|
176
|
+
if(assignment?.valid_until==null) return;
|
|
177
|
+
const deadline=typeof assignment.valid_until==='string'?Date.parse(assignment.valid_until):NaN;
|
|
178
|
+
if(!Number.isFinite(deadline)) fail(new Error('invalid valid_until'));
|
|
179
|
+
else if(deadline<=now()) fail(new Error('valid_until has expired'));
|
|
180
|
+
};
|
|
174
181
|
const fail = error => {
|
|
175
182
|
if (error?.code === 'DOT_BRIDGE_INFRASTRUCTURE') throw error;
|
|
176
183
|
refusal ??= error;
|
|
177
184
|
reasons.push(...reasonsFromError(error));
|
|
178
185
|
};
|
|
179
186
|
try { payload = deps.render(request.assignment); } catch (error) { fail(error); }
|
|
180
|
-
|
|
181
|
-
const deadline=typeof payload.valid_until==='string'?Date.parse(payload.valid_until):NaN;
|
|
182
|
-
if(!Number.isFinite(deadline)) fail(new Error('invalid valid_until'));
|
|
183
|
-
else if(deadline<=Date.now()) fail(new Error('valid_until has expired'));
|
|
184
|
-
}
|
|
187
|
+
checkDeadline(payload);
|
|
185
188
|
if (payload && !reasons.length && deps.shapeOk) {
|
|
186
189
|
try { deps.shapeOk(payload); } catch (error) { fail(error); }
|
|
187
190
|
}
|
|
@@ -198,6 +201,7 @@ export async function compileWorkOrder(request, deps) {
|
|
|
198
201
|
try { preflight = (await deps.preflight?.(expanded)) ?? null; } catch (error) { fail(error); }
|
|
199
202
|
}
|
|
200
203
|
}
|
|
204
|
+
if (!reasons.some(r => r.verdict === 'reject' || r.verdict === 'clarify')) checkDeadline(expanded ?? payload);
|
|
201
205
|
// State-dependent reasons never hide a rejection: they are added only when the order itself is sound.
|
|
202
206
|
let retryAfter = null, state = null;
|
|
203
207
|
if (!reasons.some(r => r.verdict === 'reject' || r.verdict === 'clarify')) {
|
|
@@ -206,7 +210,8 @@ export async function compileWorkOrder(request, deps) {
|
|
|
206
210
|
if (state.worker_break) reasons.push({ verdict: 'defer', code: 'usage_break', field: 'worker', message: `the worker is on a usage break since ${state.worker_break.since}`, fix: 'the work will queue and start after the usage break; use --refuse-defer to leave it unsubmitted', retry: true });
|
|
207
211
|
const threshold = request.deferQueued ?? deps.deferQueued ?? null;
|
|
208
212
|
if (threshold !== null && state.queued >= threshold) reasons.push({ verdict: 'defer', code: 'queue_depth', field: 'worker', message: `${state.queued} items are queued for the worker (defer threshold ${threshold})`, fix: 'the work will queue; use --refuse-defer to leave it unsubmitted', retry: true });
|
|
209
|
-
|
|
213
|
+
const capQueued = state.queued_same_priority ?? state.queued; // max_queued counts the submission's own priority, as atomic admission does
|
|
214
|
+
if (request.maxQueued != null && capQueued >= request.maxQueued && !reasons.some(r => r.code === 'queue_depth')) reasons.push({ verdict: 'defer', code: 'queue_full', field: 'max_queued', message: `worker queue is full (${capQueued} queued, in-flight cap ${request.maxQueued})`, fix: 'wait for queued work to drain, or use --refuse-defer to leave it unsubmitted', retry: true });
|
|
210
215
|
}
|
|
211
216
|
// A malformed field cannot be counted or admitted: a typed rejection, not a crash or a success-shaped count.
|
|
212
217
|
for (const field of new Set([...malformedFields(payload), ...malformedFields(expanded)])) {
|
|
@@ -5,11 +5,14 @@ import path from 'node:path';
|
|
|
5
5
|
// opencode's own prompt suggests an `execute` tool that the opencode worker recipe denies (it runs code that can
|
|
6
6
|
// reach the network); a model that follows the suggestion writes the call as text and stops. This text prevents that.
|
|
7
7
|
// `dalan try` and the service setup both write it next to resource-url, so one recipe path works for both.
|
|
8
|
+
export const WORKER_QUESTION_GUIDANCE = 'When a choice blocks the job, use list_tools and call_tool_write to ask the owner with ask_question, then use consume_answer when the answer is ready. Wait for the answer before proceeding.';
|
|
9
|
+
|
|
8
10
|
export const WORKER_INSTRUCTIONS = `# Dalan worker
|
|
9
11
|
|
|
10
12
|
You work for a Dalan bridge. Its tools are MCP tools such as \`list_pending\`, \`get\`, \`claim\`, \`progress\` and \`finish\`. Your client may show them with the server's name in front, such as \`local_claim\`.
|
|
11
13
|
|
|
12
14
|
- Call tools only as structured tool calls. Never write a tool call as text.
|
|
15
|
+
- ${WORKER_QUESTION_GUIDANCE}
|
|
13
16
|
- There is no \`execute\` tool for this worker. Call every tool directly.
|
|
14
17
|
- If no Dalan tool is in your tool list yet, call \`opencode_list_mcp_resources\` once; the Dalan tools are then available.
|
|
15
18
|
`;
|
|
@@ -17,10 +20,29 @@ You work for a Dalan bridge. Its tools are MCP tools such as \`list_pending\`, \
|
|
|
17
20
|
export const WORKER_INSTRUCTIONS_FILE = 'worker-instructions.md';
|
|
18
21
|
|
|
19
22
|
// Writes the guidance into a bridge home (mode 0600), replacing an older copy.
|
|
20
|
-
export function writeWorkerInstructions(home) {
|
|
23
|
+
export function writeWorkerInstructions(home, { fs: io = fs } = {}) {
|
|
21
24
|
const file = path.join(home, WORKER_INSTRUCTIONS_FILE);
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
+
const temp = path.join(home, `.${WORKER_INSTRUCTIONS_FILE}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`);
|
|
26
|
+
let fd;
|
|
27
|
+
let created = false;
|
|
28
|
+
try {
|
|
29
|
+
// Exclusivity refuses a pre-existing name (including a symlink). All writes
|
|
30
|
+
// and mode changes use this descriptor, never the published target path.
|
|
31
|
+
fd = io.openSync(temp, 'wx', 0o600);
|
|
32
|
+
created = true;
|
|
33
|
+
io.writeFileSync(fd, WORKER_INSTRUCTIONS);
|
|
34
|
+
io.fchmodSync(fd, 0o600);
|
|
35
|
+
io.fsyncSync(fd);
|
|
36
|
+
io.closeSync(fd);
|
|
37
|
+
fd = undefined;
|
|
38
|
+
// A sibling rename replaces the target name, including a symlink itself.
|
|
39
|
+
io.renameSync(temp, file);
|
|
40
|
+
created = false;
|
|
41
|
+
} catch (error) {
|
|
42
|
+
if (fd !== undefined) { try { io.closeSync(fd); } catch {} }
|
|
43
|
+
// Do not remove a name we failed to create exclusively.
|
|
44
|
+
if (created) { try { io.rmSync(temp, { force: true }); } catch {} }
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
25
47
|
return file;
|
|
26
48
|
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// What a worker with its own computer reports about the code it ran. Every field is the worker's own statement
|
|
2
|
+
// (worker_reported). The bridge's own check runs are a separate record and keep their own label.
|
|
3
|
+
export const WORKER_RUNS_MAX = 8, RUN_COMMAND_MAX = 512, RUN_TAIL_MAX = 8192, RUN_LIMIT_MAX = 1024;
|
|
4
|
+
const text = (value, label, max, allowEmpty) => {
|
|
5
|
+
if (typeof value !== 'string' || (!allowEmpty && !value.trim()) || Buffer.byteLength(value) > max) throw new Error(`invalid runs: ${label} must be a${allowEmpty ? '' : ' non-empty'} string of at most ${max} bytes`);
|
|
6
|
+
return value;
|
|
7
|
+
};
|
|
8
|
+
export function parseWorkerRuns(runs, runLimit, redact = value => value) {
|
|
9
|
+
if (runs !== undefined && (!Array.isArray(runs) || runs.length > WORKER_RUNS_MAX)) throw new Error(`invalid runs: expected at most ${WORKER_RUNS_MAX} entries`);
|
|
10
|
+
const parsed = (runs ?? []).map(run => {
|
|
11
|
+
if (!run || typeof run !== 'object' || Array.isArray(run) || Object.keys(run).some(key => !['command', 'exit_code', 'output_tail'].includes(key))) throw new Error('invalid runs: each run is {command, exit_code, output_tail}');
|
|
12
|
+
if (!Number.isInteger(run.exit_code)) throw new Error('invalid runs: exit_code must be an integer');
|
|
13
|
+
return { command: redact(text(run.command, 'command', RUN_COMMAND_MAX, false)), exit_code: run.exit_code, output_tail: redact(text(run.output_tail ?? '', 'output_tail', RUN_TAIL_MAX, true)) };
|
|
14
|
+
});
|
|
15
|
+
const limit = runLimit === undefined ? null : redact(text(runLimit, 'run_limit', RUN_LIMIT_MAX, false));
|
|
16
|
+
return { runs: parsed, run_limit: limit };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// The hosted session a job ran in, as the worker says it ended. A session is a start and an end the worker reports;
|
|
20
|
+
// the time between a claim and a report is a different measurement and is never used in its place.
|
|
21
|
+
export const SESSION_MAX_MS = 24 * 3600 * 1000, SESSION_FUTURE_SLACK_MS = 60 * 1000;
|
|
22
|
+
export function parseWorkerSession(session, nowMs) {
|
|
23
|
+
if (session === undefined) return null;
|
|
24
|
+
if (!session || typeof session !== 'object' || Array.isArray(session) || Object.keys(session).some(key => !['started_at', 'ended_at'].includes(key))) throw new Error('invalid session: expected {started_at, ended_at}');
|
|
25
|
+
const instant = (value, label) => {
|
|
26
|
+
const ms = typeof value === 'string' && /^\d{4}-\d\d-\d\dT[\d:.]+Z$/.test(value) ? Date.parse(value) : NaN;
|
|
27
|
+
if (!Number.isFinite(ms)) throw new Error(`invalid session: ${label} must be a UTC ISO timestamp`);
|
|
28
|
+
return ms;
|
|
29
|
+
};
|
|
30
|
+
const start = instant(session.started_at, 'started_at'), end = instant(session.ended_at, 'ended_at');
|
|
31
|
+
if (end < start) throw new Error('invalid session: ended_at is before started_at');
|
|
32
|
+
if (end > nowMs + SESSION_FUTURE_SLACK_MS) throw new Error('invalid session: ended_at is in the future');
|
|
33
|
+
if (end - start > SESSION_MAX_MS) throw new Error('invalid session: longer than 24 hours is not a hosted session');
|
|
34
|
+
return { started_at: new Date(start).toISOString(), ended_at: new Date(end).toISOString(), duration_ms: end - start };
|
|
35
|
+
}
|
package/src/workers.mjs
CHANGED
|
@@ -18,16 +18,29 @@ export function ensureWorkerRelationship(db,worker,pattern='outbound_only') {
|
|
|
18
18
|
SELECT ?,?,?,?,?,?,? WHERE NOT EXISTS (SELECT 1 FROM relationships WHERE counterpart_ref=?)`)
|
|
19
19
|
.run(`rel_${randomUUID()}`,JSON.stringify(['requester']),worker,pattern,'unknown','none',new Date().toISOString(),worker);
|
|
20
20
|
}
|
|
21
|
-
// finish_handoff: true | {wait_ms}. A finishing worker is handed its next job in the reply, or waits up to wait_ms for one.
|
|
21
|
+
// finish_handoff: true | {wait_ms, max_jobs, idle_lease_ms, lease, only_when_empty}. A finishing worker is handed its next job in the reply, or waits up to wait_ms for one.
|
|
22
|
+
// idle_lease_ms (1000..120000, default 120000) is how long a handed job may stay untouched before it returns to the queue.
|
|
23
|
+
// max_jobs (1..8, default 1) is how many jobs one finish may hand over: it refills every lane the finish frees, up to the free lanes.
|
|
24
|
+
// only_when_empty (default false): hand a job over only when nothing was queued at the finish, that is, after the wait. With work queued the
|
|
25
|
+
// reply is the plain list hint, and the worker claims for itself. A worker that lists and claims by itself after every finish ignores a handed
|
|
26
|
+
// job most of the time, and the ignored claim hides the job for idle_lease_ms.
|
|
22
27
|
// ChatGPT documents no tool-call timeout and users report about 60 s, so the wait stays well below that.
|
|
23
|
-
export const FINISH_HANDOFF_WAIT_MS=20000, FINISH_HANDOFF_MAX_WAIT_MS=45000;
|
|
28
|
+
export const FINISH_HANDOFF_WAIT_MS=20000, FINISH_HANDOFF_MAX_WAIT_MS=45000, FINISH_HANDOFF_MAX_JOBS=8, FINISH_HANDOFF_MIN_IDLE_LEASE_MS=1000, FINISH_HANDOFF_MAX_IDLE_LEASE_MS=120000;
|
|
24
29
|
function parseFinishHandoff(value,name) {
|
|
25
30
|
if(value===undefined||value===false) return null;
|
|
26
|
-
if(value===true) return {waitMs:FINISH_HANDOFF_WAIT_MS};
|
|
27
|
-
object(value,['wait_ms']);
|
|
31
|
+
if(value===true) return {waitMs:FINISH_HANDOFF_WAIT_MS,maxJobs:1,idleLeaseMs:FINISH_HANDOFF_MAX_IDLE_LEASE_MS};
|
|
32
|
+
object(value,['wait_ms','max_jobs','idle_lease_ms','only_when_empty','lease']);
|
|
33
|
+
const lease=value.lease===undefined?'idle':value.lease;
|
|
34
|
+
if(lease!=='idle'&&lease!=='working') fail(`${name}.finish_handoff.lease must be 'idle' or 'working'`);
|
|
35
|
+
if(lease==='working'&&value.idle_lease_ms!==undefined) fail(`${name}.finish_handoff.idle_lease_ms cannot be used with lease 'working'`);
|
|
28
36
|
const waitMs=value.wait_ms===undefined?FINISH_HANDOFF_WAIT_MS:value.wait_ms;
|
|
29
37
|
if(!Number.isInteger(waitMs)||waitMs<0||waitMs>FINISH_HANDOFF_MAX_WAIT_MS) fail(`${name}.finish_handoff.wait_ms must be an integer from 0 to ${FINISH_HANDOFF_MAX_WAIT_MS}`);
|
|
30
|
-
|
|
38
|
+
const maxJobs=value.max_jobs===undefined?1:value.max_jobs;
|
|
39
|
+
if(!Number.isInteger(maxJobs)||maxJobs<1||maxJobs>FINISH_HANDOFF_MAX_JOBS) fail(`${name}.finish_handoff.max_jobs must be an integer from 1 to ${FINISH_HANDOFF_MAX_JOBS}`);
|
|
40
|
+
const idleLeaseMs=value.idle_lease_ms===undefined?FINISH_HANDOFF_MAX_IDLE_LEASE_MS:value.idle_lease_ms;
|
|
41
|
+
if(!Number.isInteger(idleLeaseMs)||idleLeaseMs<FINISH_HANDOFF_MIN_IDLE_LEASE_MS||idleLeaseMs>FINISH_HANDOFF_MAX_IDLE_LEASE_MS) fail(`${name}.finish_handoff.idle_lease_ms must be an integer from ${FINISH_HANDOFF_MIN_IDLE_LEASE_MS} to ${FINISH_HANDOFF_MAX_IDLE_LEASE_MS}`);
|
|
42
|
+
if(value.only_when_empty!==undefined&&typeof value.only_when_empty!=='boolean') fail(`${name}.finish_handoff.only_when_empty must be true or false`);
|
|
43
|
+
return {waitMs,maxJobs,...(lease==='working'?{lease}:{idleLeaseMs}),...(value.only_when_empty?{onlyWhenEmpty:true}:{})};
|
|
31
44
|
}
|
|
32
45
|
const repoPart=/^[A-Za-z0-9_.-]+$/;
|
|
33
46
|
function validRepoName(repo) {
|
|
@@ -414,6 +427,20 @@ export function inspectGrantAudit(file) {
|
|
|
414
427
|
.map(event=>({event_id:event.event_id,at:event.at,worker:event.worker,repos:diffRepos(event.before.repos??[],event.after.repos??[])}));
|
|
415
428
|
return {unaudited,recorded,history_error:history.error,integrity_error:integrity_error??null};
|
|
416
429
|
}
|
|
430
|
+
function canonicalMigrationTime(value) {
|
|
431
|
+
const ms=typeof value==='string'?Date.parse(value):NaN;
|
|
432
|
+
if(!Number.isFinite(ms)||new Date(ms).toISOString()!==value) fail('invalid repository migration time: expected canonical UTC timestamp');
|
|
433
|
+
return value;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
function syncAndRenameWorkerPolicy(temp,file) {
|
|
437
|
+
const fd=fs.openSync(temp,'r');
|
|
438
|
+
try {fs.fsyncSync(fd);} finally {fs.closeSync(fd);}
|
|
439
|
+
fs.renameSync(temp,file);
|
|
440
|
+
const dir=fs.openSync(path.dirname(file),'r');
|
|
441
|
+
try {fs.fsyncSync(dir);} finally {fs.closeSync(dir);}
|
|
442
|
+
}
|
|
443
|
+
|
|
417
444
|
export function seedWorkerRepos(file,db,{existingInstall=true,migrationNow=new Date().toISOString()}={}) {
|
|
418
445
|
let journal=readRepoMigration(file);
|
|
419
446
|
if(!journal) {
|
|
@@ -421,7 +448,7 @@ export function seedWorkerRepos(file,db,{existingInstall=true,migrationNow=new D
|
|
|
421
448
|
const names=raw?Object.keys(raw.workers):['dot'];
|
|
422
449
|
const entries=[];
|
|
423
450
|
// One instant for the whole migration, so a job cannot expire between two workers' scans.
|
|
424
|
-
|
|
451
|
+
migrationNow=canonicalMigrationTime(migrationNow);
|
|
425
452
|
if(existingInstall)for(const worker of names) {
|
|
426
453
|
if(raw&&Object.hasOwn(raw.workers[worker],'repos'))continue;
|
|
427
454
|
const repos=new Map(),queuedRepositories=new Map();
|
|
@@ -582,7 +609,7 @@ function applyWorkerRepoPolicy(file,name,action,repo,db) {
|
|
|
582
609
|
try {
|
|
583
610
|
fs.writeFileSync(temp,`${JSON.stringify(raw,null,2)}\n`,{mode:0o600,flag:'wx'});
|
|
584
611
|
fs.chmodSync(temp,0o600);
|
|
585
|
-
|
|
612
|
+
syncAndRenameWorkerPolicy(temp,file);
|
|
586
613
|
} finally { fs.rmSync(temp,{force:true}); }
|
|
587
614
|
},db);
|
|
588
615
|
return after;
|