@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.
Files changed (62) hide show
  1. package/CHANGELOG.md +29 -25
  2. package/PROTOCOL.md +16 -4
  3. package/README.md +127 -260
  4. package/SECURITY.md +1 -1
  5. package/bin/dalan.mjs +5 -0
  6. package/bin/dot-worker.mjs +35 -26
  7. package/docs/chatgpt-worker-onboarding.md +5 -5
  8. package/docs/claude-worker-onboarding.md +5 -5
  9. package/docs/codex-to-muse.md +175 -0
  10. package/docs/connect-chatgpt.md +9 -4
  11. package/docs/connection-longevity.md +7 -1
  12. package/docs/dalan-upgrade.md +17 -13
  13. package/docs/deadman.md +5 -3
  14. package/docs/local-agent-mcp.md +8 -6
  15. package/docs/manual-setup.md +8 -8
  16. package/docs/mirror-fetch.md +1 -2
  17. package/docs/operations.md +90 -42
  18. package/docs/operator-duties.md +1 -1
  19. package/docs/owner-integrator.md +2 -2
  20. package/docs/portable-auth-profile.md +12 -14
  21. package/docs/pr-head-reviewer.md +21 -5
  22. package/docs/pr-preflight.md +2 -0
  23. package/docs/pull-queue.md +131 -0
  24. package/docs/pull-workers.md +7 -10
  25. package/docs/redaction.md +1 -1
  26. package/docs/service-setup.md +56 -3
  27. package/docs/setup-reference.md +1 -1
  28. package/docs/t3-integration.md +2 -0
  29. package/docs/t3-result-retry-delivery.md +2 -2
  30. package/docs/t3-reverse-control.md +7 -7
  31. package/docs/usage.md +19 -15
  32. package/docs/worker-clients.md +18 -13
  33. package/package.json +3 -1
  34. package/scripts/dalan-try-selfcheck.mjs +29 -0
  35. package/scripts/worker-bridge-setup.mjs +1 -1
  36. package/src/acp-bridge.mjs +18 -12
  37. package/src/as.mjs +41 -0
  38. package/src/child-exit.mjs +18 -0
  39. package/src/child-registry.mjs +94 -0
  40. package/src/cli-help.mjs +25 -11
  41. package/src/demo-worker.mjs +2 -2
  42. package/src/drained-owner.mjs +26 -0
  43. package/src/drained-slot.mjs +20 -3
  44. package/src/mcp-outcome.mjs +10 -1
  45. package/src/mcp-sse.mjs +62 -0
  46. package/src/pr-head-reviewer.mjs +3 -3
  47. package/src/process-inspection.mjs +36 -0
  48. package/src/pull-queue.mjs +159 -0
  49. package/src/route-setting.mjs +24 -0
  50. package/src/server.mjs +157 -29
  51. package/src/service-migrate-workers.mjs +113 -0
  52. package/src/service.mjs +388 -0
  53. package/src/setup.mjs +63 -0
  54. package/src/store.mjs +21 -9
  55. package/src/tool-registry.mjs +3 -1
  56. package/src/try-exposure.mjs +908 -0
  57. package/src/try-hosted-clients.mjs +46 -0
  58. package/src/try-hosted.mjs +444 -0
  59. package/src/try-selfcheck.mjs +168 -0
  60. package/src/try.mjs +63 -17
  61. package/src/workers.mjs +33 -23
  62. package/src/workspace.mjs +10 -3
@@ -0,0 +1,62 @@
1
+ const HEARTBEAT = ': keepalive\n\n';
2
+
3
+ export function acceptsMcpEventStream(accept) {
4
+ return typeof accept === 'string' && accept.split(',').some(entry => {
5
+ const [mediaType, ...parameters] = entry.trim().toLowerCase().split(';').map(part => part.trim());
6
+ if (mediaType !== 'text/event-stream') return false;
7
+ const quality = parameters.find(parameter => parameter.startsWith('q='));
8
+ return !quality || Number(quality.slice(2)) > 0;
9
+ });
10
+ }
11
+
12
+ export function beginMcpEventStream(res, { heartbeatMs = 20_000, setIntervalFn = setInterval, clearIntervalFn = clearInterval } = {}) {
13
+ let active = true, timer = null, writtenBytes = 0;
14
+ const stop = () => {
15
+ if (!active) return;
16
+ active = false;
17
+ if (timer !== null) clearIntervalFn(timer);
18
+ };
19
+ res.once('close', stop);
20
+ res.once('finish', stop);
21
+ res.once('error', stop);
22
+ res.writeHead(200, { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-cache, no-transform' });
23
+ const heartbeat = () => {
24
+ if (!active || res.destroyed) { stop(); return; }
25
+ res.write(HEARTBEAT);
26
+ writtenBytes += Buffer.byteLength(HEARTBEAT);
27
+ };
28
+ heartbeat();
29
+ if(active) {
30
+ timer = setIntervalFn(heartbeat, heartbeatMs);
31
+ timer?.unref?.();
32
+ }
33
+ return {
34
+ finish(jsonText, beforeEnd = () => {}) {
35
+ if (!active || res.destroyed) { stop(); return 0; }
36
+ const frame = `event: message\ndata: ${jsonText}\n\n`;
37
+ const bytes = writtenBytes + Buffer.byteLength(frame);
38
+ stop();
39
+ beforeEnd(bytes);
40
+ res.write(frame);
41
+ res.end();
42
+ return bytes;
43
+ },
44
+ close: stop,
45
+ };
46
+ }
47
+
48
+ export function mcpResponseText(text) {
49
+ const normalized = String(text).replace(/\r\n?/g, '\n');
50
+ const lines = normalized.split('\n');
51
+ if (!lines.some(line => line.startsWith(':') || /^(?:data|event|id|retry):/.test(line))) return normalized;
52
+ const frames = [];
53
+ let data = [];
54
+ const endFrame = () => { if (data.length) frames.push(data.join('\n')); data = []; };
55
+ for (const line of lines) {
56
+ if (line === '') { endFrame(); continue; }
57
+ if (line.startsWith(':')) continue;
58
+ if (line.startsWith('data:')) data.push(line.slice(5).replace(/^ /, ''));
59
+ }
60
+ endFrame();
61
+ return frames.at(-1);
62
+ }
@@ -586,9 +586,9 @@ export function acquireLock(dir) {
586
586
  try { fs.writeFileSync(file, String(process.pid), { flag: 'wx' }); return () => { try { fs.unlinkSync(file); } catch { /* gone */ } }; }
587
587
  catch (e) {
588
588
  if (e.code !== 'EEXIST') throw e;
589
- const pid = Number(fs.readFileSync(file, 'utf8'));
590
- let alive = true; try { process.kill(pid, 0); } catch (err) { alive = err.code === 'EPERM'; }
591
- if (alive) return null;
589
+ const raw = fs.readFileSync(file, 'utf8').trim();
590
+ if (!/^[1-9]\d*$/.test(raw) || !Number.isSafeInteger(Number(raw))) return null;
591
+ try { process.kill(Number(raw), 0); return null; } catch (err) { if (err.code !== 'ESRCH') return null; }
592
592
  try { fs.unlinkSync(file); } catch { /* raced */ }
593
593
  }
594
594
  }
@@ -0,0 +1,36 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+
4
+ // Inspection failure is not evidence of exit. Read Linux start ticks on both sides of ps so command and identity belong
5
+ // to the same process. macOS supplies its start timestamp and command in one ps snapshot, with a fixed locale and timezone.
6
+ export const processCommand = (pid, { platform = process.platform, run = spawnSync, readFile = fs.readFileSync, probe = pid => process.kill(pid, 0) } = {}) => {
7
+ const unknown = { state: 'unknown' }, absent = { state: 'absent' };
8
+ if (!Number.isInteger(pid) || pid <= 0) return unknown;
9
+ const startTicks = () => {
10
+ const stat = readFile(`/proc/${pid}/stat`, 'utf8');
11
+ const fields = stat.slice(stat.lastIndexOf(')') + 2).trim().split(/\s+/);
12
+ if (!/^\d+$/.test(fields[19] ?? '')) throw new Error('invalid process start time');
13
+ return fields[19];
14
+ };
15
+ try {
16
+ const before = platform === 'linux' ? startTicks() : null;
17
+ if (!['linux', 'darwin'].includes(platform)) return unknown;
18
+ const out = run('ps', ['-p', String(pid), '-o', platform === 'darwin' ? 'lstart=,command=' : 'command='], { encoding: 'utf8', timeout: 5000, env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' } });
19
+ if (out.error || out.status !== 0 || !out.stdout?.trim()) {
20
+ // Even ps exit 1 can be an inspection failure; only ESRCH confirms absence.
21
+ try { probe(pid); } catch (error) { if (error.code === 'ESRCH') return absent; }
22
+ return unknown;
23
+ }
24
+ if (platform === 'linux') {
25
+ const after = startTicks();
26
+ return before === after ? { state: 'present', command: out.stdout.trim(), start: before } : unknown;
27
+ }
28
+ const match = /^(\w{3}\s+\w{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s+(.+)$/.exec(out.stdout.trim());
29
+ return match ? { state: 'present', command: match[2], start: match[1].replace(/\s+/g, ' ') } : unknown;
30
+ } catch (error) {
31
+ if (['ENOENT', 'ESRCH'].includes(error.code)) {
32
+ try { probe(pid); } catch (probeError) { if (probeError.code === 'ESRCH') return absent; }
33
+ }
34
+ return unknown;
35
+ }
36
+ };
@@ -0,0 +1,159 @@
1
+ import {createHash, timingSafeEqual, randomBytes,createCipheriv,createDecipheriv} from 'node:crypto';
2
+
3
+ const digest=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
4
+ const canonical=value=>Array.isArray(value)?value.map(canonical):value&&typeof value==='object'?Object.fromEntries(Object.keys(value).sort().map(key=>[key,canonical(value[key])])):value;
5
+ export const PULL_PAGE_PREFIX='pullpage_';
6
+ export function routingPolicy(value,assignment) {
7
+ if(!value||typeof value!=='object'||Array.isArray(value)||Object.keys(value).some(key=>!['version','allowed_workers','fan_out','deadline_at'].includes(key))) throw new Error('invalid routing policy: supported fields are version, allowed_workers, fan_out, deadline_at');
8
+ if(value.version!==1||value.fan_out!==undefined&&value.fan_out!==1) throw new Error('routing v1 supports version=1 and fan_out=1 only');
9
+ const names=value.allowed_workers;
10
+ if(!Array.isArray(names)||!names.length||names.length>100||names.some(name=>typeof name!=='string'||!(/^[a-z][a-z0-9_-]{0,31}$/).test(name))||new Set(names).size!==names.length) throw new Error('routing requires 1-100 distinct explicit allowed_workers');
11
+ if(assignment.execution_scope!=='read-only'||Object.hasOwn(assignment,'protocol')) throw new Error('routing v1 supports read-only assignments without protocol only');
12
+ const deadline=value.deadline_at??assignment.valid_until;
13
+ if(typeof deadline!=='string'||!/^\d{4}-\d\d-\d\dT.*(?:Z|[+-]\d\d:\d\d)$/.test(deadline)||!Number.isFinite(Date.parse(deadline))) throw new Error('routing requires an explicit RFC3339 deadline_at or assignment.valid_until');
14
+ const assignmentDeadline=assignment.valid_until===undefined?null:Date.parse(assignment.valid_until);
15
+ if(assignmentDeadline!==null&&!Number.isFinite(assignmentDeadline))throw new Error('invalid assignment valid_until');
16
+ return {version:1,allowed_workers:[...names].sort(),fan_out:1,deadline_at:new Date(Math.min(Date.parse(deadline),assignmentDeadline??Infinity)).toISOString()};
17
+ }
18
+ export function migratePullQueue(db) {
19
+ db.exec(`CREATE TABLE policy_work_orders (
20
+ work_order_id TEXT PRIMARY KEY, request_id TEXT NOT NULL UNIQUE, intent_digest TEXT NOT NULL,
21
+ owner_hash TEXT NOT NULL, payload TEXT NOT NULL, options TEXT NOT NULL, routing TEXT NOT NULL,
22
+ approvals TEXT NOT NULL, created_at TEXT NOT NULL, priority TEXT NOT NULL,
23
+ state TEXT NOT NULL DEFAULT 'queued', owner_read_at TEXT, cancelled_at TEXT, cancelled_reason TEXT,
24
+ child_request_id TEXT UNIQUE REFERENCES assignments(request_id),
25
+ receipt TEXT, worker TEXT, subject TEXT, connection_id TEXT, acquisition_id TEXT
26
+ ); CREATE INDEX policy_work_backlog ON policy_work_orders(state,priority,created_at);
27
+ CREATE TRIGGER policy_work_intent_immutable BEFORE UPDATE OF work_order_id,request_id,intent_digest,owner_hash,payload,options,routing,approvals,created_at,priority ON policy_work_orders BEGIN SELECT RAISE(ABORT,'policy work intent is immutable'); END;`);
28
+ }
29
+
30
+ // A work order reserves the submitted request ID. Its one execution child takes
31
+ // that ID at acquisition, so the owner's durable capability and wait path survive.
32
+ export class PullQueue {
33
+ constructor(store) {
34
+ this.store=store;this.db=store.db;
35
+ this.db.prepare("INSERT OR IGNORE INTO bridge_state(key,value) VALUES('pull_cursor_key',?)").run(randomBytes(32).toString('hex'));
36
+ this.cursorKey=Buffer.from(this.db.prepare("SELECT value FROM bridge_state WHERE key='pull_cursor_key'").get().value,'hex');
37
+ }
38
+ cursor(worker,value) {
39
+ const nonce=randomBytes(12),cipher=createCipheriv('aes-256-gcm',this.cursorKey,nonce);cipher.setAAD(Buffer.from(worker));
40
+ const encrypted=Buffer.concat([cipher.update(JSON.stringify(value)),cipher.final()]);
41
+ return PULL_PAGE_PREFIX+Buffer.concat([nonce,cipher.getAuthTag(),encrypted]).toString('base64url');
42
+ }
43
+ readCursor(worker,cursor) {
44
+ try {
45
+ const bytes=Buffer.from(cursor.slice(PULL_PAGE_PREFIX.length),'base64url'),decipher=createDecipheriv('aes-256-gcm',this.cursorKey,bytes.subarray(0,12));
46
+ decipher.setAAD(Buffer.from(worker));decipher.setAuthTag(bytes.subarray(12,28));
47
+ const value=JSON.parse(Buffer.concat([decipher.update(bytes.subarray(28)),decipher.final()]).toString());
48
+ if(!Array.isArray(value)||value.length!==3||value.some(n=>!Number.isSafeInteger(n)||n<0)||value[1]>1||value[2]>value[0])throw new Error();
49
+ return value;
50
+ }catch{throw new Error('assignment not found');}
51
+ }
52
+ row(id) { return this.db.prepare('SELECT rowid AS sequence,* FROM policy_work_orders WHERE request_id=?').get(id); }
53
+ ownerRow(id) { return this.row(id); }
54
+ inbox(id) {
55
+ const row=this.row(id);if(!row||row.child_request_id)return null;
56
+ const projected=this.project(row);
57
+ return {target_worker:null,work_order_id:row.work_order_id,brief:projected.assignment.brief,created_at:row.created_at,finished_at:null,outcome:null,consumed:false,decision:null,delivered_t3:false,
58
+ cancelled_at:projected.cancelled_at,cancelled_reason:projected.cancelled_reason,cancelled_by_owner:row.state==='cancelled',read:row.owner_read_at!==null,failure_type:projected.cancelled_reason==='expired'?'expired':row.state==='cancelled'?'owner_cancelled':null,failure_type_source:projected.cancelled_reason==='expired'?'bridge_observed_transition':row.state==='cancelled'?'bridge_observed_transition':null,unanswered_blocker:null};
59
+ }
60
+ consume(id) {
61
+ const row=this.row(id);if(!row||row.child_request_id)return;
62
+ if(this.project(row).status==='cancelled')this.db.prepare('UPDATE policy_work_orders SET owner_read_at=COALESCE(owner_read_at,?) WHERE request_id=?').run(this.store.stamp(),id);
63
+ }
64
+ assertOwner(row,token) {
65
+ const got=createHash('sha256').update(token??'').digest();
66
+ if(!row||!timingSafeEqual(got,Buffer.from(row.owner_hash,'hex'))) throw new Error('invalid owner capability');
67
+ }
68
+ project(row) {
69
+ const assignment=JSON.parse(row.payload),routing=JSON.parse(row.routing),options=JSON.parse(row.options);
70
+ const expired=row.state==='queued'&&Date.parse(routing.deadline_at)<=this.store.nowMs();
71
+ return {request_id:row.request_id,work_order_id:row.work_order_id,child_request_id:row.child_request_id,
72
+ status:expired?'cancelled':row.state,assignment,routing,created_at:row.created_at,
73
+ target_worker:null,execution:options.execution,delivery_mode:options.delivery.mode==='t3'?`t3:${options.delivery.threadId}`:'none',
74
+ thread_id:options.delivery.threadId??null,environment_id:options.environmentId??null,
75
+ valid_until:routing.deadline_at,cancelled_at:row.cancelled_at,cancelled_reason:row.cancelled_reason??(expired?'expired':null),
76
+ claim:null,report:null,progress:[],owner_notes:[],delivery:[],lifecycle_events:[],required_capabilities:[]};
77
+ }
78
+ submit(payload,identity,options,routing,approvals,ownerToken,{dryRun=false}={}) {
79
+ const ownerHash=createHash('sha256').update(ownerToken).digest('hex');
80
+ const intent=digest(canonical({identity,options,routing,approvals}));
81
+ return this.store.inTransaction(()=>{
82
+ const old=this.row(payload.request_id);
83
+ if(old) {
84
+ this.assertOwner(old,ownerToken);
85
+ if(old.intent_digest!==intent) throw new Error('request_id conflict');
86
+ return {request_id:old.request_id,work_order_id:old.work_order_id,status:old.child_request_id?this.store.get(old.child_request_id).status:this.project(old).status,duplicate:true,...(dryRun?{dry_run:true,stored:false,verdict:'admissible'}:{})};
87
+ }
88
+ if(this.store.hasAssignment(payload.request_id)) throw new Error('request_id conflict');
89
+ if(Date.parse(routing.deadline_at)<=this.store.nowMs()) throw new Error('routing deadline expired');
90
+ const workId='work_'+digest(payload.request_id).slice(0,32);
91
+ if(!dryRun) this.db.prepare('INSERT INTO policy_work_orders(work_order_id,request_id,intent_digest,owner_hash,payload,options,routing,approvals,created_at,priority) VALUES(?,?,?,?,?,?,?,?,?,?)').run(workId,payload.request_id,intent,ownerHash,JSON.stringify(payload),JSON.stringify(options),JSON.stringify(routing),JSON.stringify(approvals),this.store.stamp(),options.priority);
92
+ return {request_id:payload.request_id,work_order_id:workId,status:'queued',duplicate:false,...(dryRun?{dry_run:true,stored:false,verdict:'admissible'}:{})};
93
+ });
94
+ }
95
+ eligible(row,worker,admit) {
96
+ if(!row||!JSON.parse(row.routing).allowed_workers.includes(worker)) return false;
97
+ try { admit(worker,JSON.parse(row.payload),JSON.parse(row.options).execution,JSON.parse(row.approvals)[worker]); return true; } catch { return false; }
98
+ }
99
+ get(id,worker,admit) {
100
+ const row=this.row(id);
101
+ if(!row||row.state!=='queued'||Date.parse(JSON.parse(row.routing).deadline_at)<=this.store.nowMs()||!this.eligible(row,worker,admit)) throw new Error('assignment not found');
102
+ return {...this.project(row),guidance:'Claim this request_id with a fresh acquisition_id. The receipt names the immutable execution child; use its request_id and claim_id for all later tools.'};
103
+ }
104
+ list(worker,admit,cursor=null) {
105
+ let after=0,rank=0,snapshot=this.db.prepare('SELECT COALESCE(max(rowid),0) n FROM policy_work_orders').get().n;
106
+ if(cursor)[snapshot,rank,after]=this.readCursor(worker,cursor);
107
+ const rows=this.db.prepare("SELECT rowid AS sequence,CASE priority WHEN 'normal' THEN 0 ELSE 1 END AS rank,* FROM policy_work_orders WHERE state='queued' AND rowid<=? AND (CASE priority WHEN 'normal' THEN 0 ELSE 1 END>? OR (CASE priority WHEN 'normal' THEN 0 ELSE 1 END=? AND rowid>?)) ORDER BY rank,rowid").iterate(snapshot,rank,rank,after);
108
+ const items=[];let next=null;
109
+ for(const row of rows) {
110
+ if(Date.parse(JSON.parse(row.routing).deadline_at)<=this.store.nowMs()||!this.eligible(row,worker,admit)) continue;
111
+ if(items.length===50) { const last=items.at(-1);next=this.cursor(worker,[snapshot,last._rank,last._sequence]);break; }
112
+ items.push({request_id:row.request_id,work_order_id:row.work_order_id,title:JSON.parse(row.payload).brief.slice(0,160),created_at:row.created_at,priority:row.priority,deadline_at:JSON.parse(row.routing).deadline_at,remaining_result_slots:1,_sequence:row.sequence,_rank:row.rank});
113
+ }
114
+ return {items:items.map(({_sequence,_rank,...item})=>item),next_page_request_id:next,guidance:'Use get with next_page_request_id to read the next page. Use claim with an offered request_id and fresh acquisition_id to acquire its single result slot. Capacity limits claims, not this backlog.'};
115
+ }
116
+ acquire(id,{worker,subject,connectionId,claimant,acquisitionId,leaseMs,capacity,preflight,admit}) {
117
+ if(typeof acquisitionId!=='string'||!(/^[A-Za-z0-9_-]{1,128}$/).test(acquisitionId)) throw new Error('policy work requires a fresh acquisition_id');
118
+ return this.store.transaction(()=>{
119
+ const row=this.row(id);
120
+ if(!row||!JSON.parse(row.routing).allowed_workers.includes(worker)) throw new Error('assignment not found');
121
+ if(row.child_request_id) {
122
+ if(row.worker!==worker||row.subject!==subject||row.connection_id!==(connectionId??null)||row.acquisition_id!==acquisitionId) throw new Error('work order already acquired');
123
+ if(this.store.get(id).status!=='claimed')throw new Error('assignment finished or cancelled');
124
+ const receipt=JSON.parse(row.receipt),held=this.db.prepare('SELECT * FROM claims WHERE request_id=?').get(id);
125
+ if(held?.claimant!==claimant||held?.lease_ms!==(leaseMs??this.store.limits.leaseMs))throw new Error('acquisition_id conflict');
126
+ this.store.assertClaim(id,receipt.claim_id,subject,worker);
127
+ this.store.assertRetryConnection(id,held,worker,connectionId);
128
+ return {...receipt,duplicate:true};
129
+ }
130
+ if(row.state!=='queued') throw new Error('assignment cancelled');
131
+ const payload=JSON.parse(row.payload),options=JSON.parse(row.options),routing=JSON.parse(row.routing),approval=JSON.parse(row.approvals)[worker];
132
+ if(Date.parse(routing.deadline_at)<=this.store.nowMs()) throw new Error('routing deadline expired');
133
+ admit(worker,payload,options.execution,approval);
134
+ // Both insert and ordinary claim join this transaction. A failed capacity,
135
+ // destination or preflight check leaves no child and no consumed slot.
136
+ this.store.submitInTransaction({...payload,valid_until:routing.deadline_at},options.delivery,options.environmentId,'',options.review,preflight,options.priority,options.meta,payload,null,worker,options.execution,options.execution,null,null,null,null,approval??null,row.owner_hash);
137
+ const claimed=this.store.claimInTransaction(id,claimant,subject,capacity,preflight,worker,acquisitionId,leaseMs??this.store.limits.leaseMs,connectionId);
138
+ if(!claimed.claim_id) throw new Error('policy child admission refused');
139
+ const held=this.db.prepare('SELECT * FROM claims WHERE request_id=?').get(id);
140
+ const receipt={...claimed,lease_expires_at:this.store.leaseExpiresAt(held),work_order_id:row.work_order_id,child_request_id:id};
141
+ this.db.prepare("UPDATE policy_work_orders SET state='acquired',child_request_id=?,receipt=?,worker=?,subject=?,connection_id=?,acquisition_id=? WHERE request_id=?").run(id,JSON.stringify(receipt),worker,subject,connectionId??null,acquisitionId,id);
142
+ return receipt;
143
+ });
144
+ }
145
+ cancel(id,reason=null) {
146
+ return this.store.inTransaction(()=>{
147
+ const row=this.row(id);if(!row||row.child_request_id) return null;
148
+ this.db.prepare("UPDATE policy_work_orders SET state='cancelled',cancelled_at=COALESCE(cancelled_at,?),cancelled_reason=COALESCE(cancelled_reason,?) WHERE request_id=?").run(this.store.stamp(),reason,id);
149
+ return {request_id:id,status:'cancelled',cancellation_requested:true,authority_revoked:true,compute_stopped:false};
150
+ });
151
+ }
152
+ sweepExpired(limit=100) {
153
+ return this.store.inTransaction(()=>{
154
+ const rows=this.db.prepare("SELECT request_id FROM policy_work_orders WHERE state='queued' AND json_extract(routing,'$.deadline_at')<=? ORDER BY json_extract(routing,'$.deadline_at'),rowid LIMIT ?").all(this.store.stamp(),limit);
155
+ for(const row of rows)this.cancel(row.request_id,'expired');
156
+ return rows.map(row=>row.request_id);
157
+ });
158
+ }
159
+ }
@@ -0,0 +1,24 @@
1
+ // The owner's saved choice of public route, written by `dalan setup`. One small file in the user's config directory, outside every
2
+ // trial home, so a trial that is deleted never loses it and a trial never writes it. Values: 'tailscale' or 'gozar'. The old
3
+ // 'localhost.run' value remains readable so existing installs keep selecting the trial relay. No file means no saved choice.
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+
8
+ export const ROUTE_CHOICES = ['tailscale', 'gozar', 'localhost.run'];
9
+ export const routeSettingPath = (env = process.env) => path.join(env.XDG_CONFIG_HOME || path.join(env.HOME || os.homedir(), '.config'), 'dalan', 'route.json');
10
+
11
+ export function readRouteSetting(env = process.env) {
12
+ try {
13
+ const route = JSON.parse(fs.readFileSync(routeSettingPath(env), 'utf8'))?.route;
14
+ return ROUTE_CHOICES.includes(route) ? route : null;
15
+ } catch { return null; }
16
+ }
17
+
18
+ export function writeRouteSetting(route, env = process.env) {
19
+ if (!ROUTE_CHOICES.includes(route)) throw new Error(`unknown route ${JSON.stringify(route)}`);
20
+ const file = routeSettingPath(env);
21
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
22
+ fs.writeFileSync(file, `${JSON.stringify({ route })}\n`, { mode: 0o600 });
23
+ return file;
24
+ }