@tnunamak/dalan 0.6.2 → 0.8.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 (74) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/CONTRIBUTING.md +4 -0
  3. package/PROTOCOL.md +2 -0
  4. package/README.md +81 -84
  5. package/bin/dalan.mjs +9 -0
  6. package/bin/dot-worker.mjs +29 -4
  7. package/contracts/adapter-qualification.schema.json +170 -0
  8. package/docs/chatgpt-worker-onboarding.md +10 -14
  9. package/docs/claude-worker-onboarding.md +9 -8
  10. package/docs/codex-to-muse.md +21 -35
  11. package/docs/connect-chatgpt.md +10 -16
  12. package/docs/dalan-upgrade.md +4 -2
  13. package/docs/local-agent-mcp.md +24 -4
  14. package/docs/local-agent-requester.md +46 -0
  15. package/docs/manual-setup.md +2 -2
  16. package/docs/operations.md +12 -13
  17. package/docs/pull-workers.md +1 -2
  18. package/docs/service-setup.md +110 -163
  19. package/docs/setup-reference.md +6 -6
  20. package/docs/t3-question-relationship.md +43 -0
  21. package/docs/t3-reverse-control.md +12 -8
  22. package/docs/t3-wake-fence-r4.md +42 -0
  23. package/docs/test-suite-isolation.md +204 -0
  24. package/docs/worker-clients.md +6 -4
  25. package/package.json +5 -3
  26. package/qualification/README.md +13 -0
  27. package/qualification/mcp.json +121 -0
  28. package/qualification/protocol-v0.json +127 -0
  29. package/scripts/dalan-try-selfcheck.mjs +8 -7
  30. package/scripts/worker-bridge-setup.mjs +91 -81
  31. package/src/admin-socket.mjs +2 -1
  32. package/src/answer-journal.mjs +200 -0
  33. package/src/as-store.mjs +5 -3
  34. package/src/as.mjs +35 -26
  35. package/src/auth-check.mjs +59 -0
  36. package/src/cli-help.mjs +16 -16
  37. package/src/client-approval.mjs +57 -0
  38. package/src/client-convenience.mjs +166 -0
  39. package/src/client-conveniences.json +106 -0
  40. package/src/client-conveniences.schema.json +97 -0
  41. package/src/connect-cli.mjs +5 -5
  42. package/src/default-home.mjs +36 -0
  43. package/src/destinations/index.mjs +6 -0
  44. package/src/destinations/none.mjs +3 -0
  45. package/src/destinations/t3.mjs +63 -6
  46. package/src/execution.mjs +20 -2
  47. package/src/follow-current.mjs +27 -0
  48. package/src/gozar-routes.mjs +315 -0
  49. package/src/host-budget.mjs +17 -11
  50. package/src/host-execution-policy.mjs +2 -2
  51. package/src/host-stop-reverify.mjs +6 -4
  52. package/src/integrator.mjs +3 -1
  53. package/src/redirect-policy.mjs +61 -0
  54. package/src/route-setting.mjs +71 -12
  55. package/src/server.mjs +64 -12
  56. package/src/service-auto-update.mjs +8 -1
  57. package/src/service-launchd.mjs +186 -0
  58. package/src/service-migrate-workers.mjs +12 -2
  59. package/src/service-update-runtime.mjs +40 -6
  60. package/src/service-update.mjs +20 -14
  61. package/src/service.mjs +211 -63
  62. package/src/setup.mjs +55 -44
  63. package/src/store.mjs +77 -14
  64. package/src/submission-policy.mjs +8 -4
  65. package/src/t3.mjs +21 -2
  66. package/src/tool-registry.mjs +54 -8
  67. package/src/try-exposure.mjs +7 -657
  68. package/src/try-hosted.mjs +71 -101
  69. package/src/try-selfcheck.mjs +15 -8
  70. package/src/try.mjs +9 -13
  71. package/src/workers.mjs +4 -3
  72. package/src/workspace.mjs +94 -15
  73. package/scripts/lib/expose-tailscale.mjs +0 -408
  74. package/src/try-hosted-clients.mjs +0 -46
@@ -1,24 +1,83 @@
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.
1
+ // The owner's saved public-route choice, written by `dalan setup`. One small file in the user's config directory, outside every
2
+ // trial home, so a deleted trial never loses it and a trial never writes it.
3
+ //
4
+ // Version 2 stores only what Dalan owns: the requirements it asked for, the Gozar state home, the Gozar route name (an opaque
5
+ // string that Dalan never interprets), the durable route id, the pinned origin and the bridge home. Everything about how a route is
6
+ // provided belongs to Gozar. A file of any other version fails closed: it is reported, never guessed at or rewritten.
4
7
  import fs from 'node:fs';
5
8
  import os from 'node:os';
6
9
  import path from 'node:path';
10
+ import { randomBytes } from 'node:crypto';
7
11
 
8
- export const ROUTE_CHOICES = ['tailscale', 'gozar', 'localhost.run'];
12
+ export const SETTING_VERSION = 2;
13
+ const KEYS = ['version', 'requirements', 'gozarHome', 'routeName', 'routeId', 'origin', 'bridgeHome'];
9
14
  export const routeSettingPath = (env = process.env) => path.join(env.XDG_CONFIG_HOME || path.join(env.HOME || os.homedir(), '.config'), 'dalan', 'route.json');
15
+ export const migrationJournalPath = (env = process.env) => path.join(path.dirname(routeSettingPath(env)), 'route-migration.json');
16
+
17
+ const isRecord = value => value !== null && typeof value === 'object' && !Array.isArray(value);
18
+ const nullableString = value => value === null || (typeof value === 'string' && value.length > 0);
19
+
20
+ // Throws a message when a setting is not exactly the version-2 shape.
21
+ export function validateSetting(value) {
22
+ if (!isRecord(value)) throw new Error('the saved route setting is not an object');
23
+ if (value.version !== SETTING_VERSION) throw new Error(`the saved route setting has version ${JSON.stringify(value.version)}; this Dalan reads version ${SETTING_VERSION}`);
24
+ const extra = Object.keys(value).filter(key => !KEYS.includes(key));
25
+ if (extra.length) throw new Error(`the saved route setting has unknown fields (${extra.join(', ')})`);
26
+ if (!isRecord(value.requirements)) throw new Error('the saved route setting has no requirements');
27
+ for (const key of ['gozarHome']) if (typeof value[key] !== 'string' || !path.isAbsolute(value[key])) throw new Error(`the saved route setting needs an absolute ${key}`);
28
+ for (const key of ['routeName', 'routeId', 'origin', 'bridgeHome']) if (!nullableString(value[key])) throw new Error(`the saved route setting has an invalid ${key}`);
29
+ if (value.origin !== null) {
30
+ let url; try { url = new URL(value.origin); } catch { /* checked below */ }
31
+ if (!url || url.protocol !== 'https:' || url.origin !== value.origin) throw new Error('the saved route setting origin is not an https origin');
32
+ }
33
+ return value;
34
+ }
35
+
36
+ // What the file holds: { state: 'none' } (no file), { state: 'current', setting } (version 2) or { state: 'legacy' | 'unreadable' }.
37
+ // A legacy file is any file that is not version 2 (the 0.6 shape had no version). It is never edited in place.
38
+ export function inspectRouteSetting(env = process.env) {
39
+ let text;
40
+ try { text = fs.readFileSync(routeSettingPath(env), 'utf8'); } catch (error) { if (error.code === 'ENOENT') return { state: 'none' }; return { state: 'unreadable', reason: error.code ?? error.message }; }
41
+ let value;
42
+ try { value = JSON.parse(text); } catch { return { state: 'unreadable', reason: 'not JSON' }; }
43
+ if (isRecord(value) && !('version' in value)) return { state: 'legacy', value };
44
+ try { return { state: 'current', setting: validateSetting(value) }; } catch (error) { return { state: 'unreadable', reason: error.message }; }
45
+ }
10
46
 
11
47
  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; }
48
+ const found = inspectRouteSetting(env);
49
+ return found.state === 'current' ? found.setting : null;
16
50
  }
17
51
 
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);
52
+ function writePrivateAtomic(file, text) {
21
53
  fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
22
- fs.writeFileSync(file, `${JSON.stringify({ route })}\n`, { mode: 0o600 });
54
+ const temporary = `${file}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`;
55
+ const fd = fs.openSync(temporary, 'wx', 0o600);
56
+ try { fs.writeSync(fd, text); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
57
+ fs.renameSync(temporary, file);
58
+ const dirFd = fs.openSync(path.dirname(file), 'r');
59
+ try { fs.fsyncSync(dirFd); } finally { fs.closeSync(dirFd); }
60
+ }
61
+
62
+ export function writeRouteSetting(setting, env = process.env) {
63
+ validateSetting(setting);
64
+ const file = routeSettingPath(env);
65
+ writePrivateAtomic(file, `${JSON.stringify(Object.fromEntries(KEYS.map(key => [key, setting[key]])))}\n`);
23
66
  return file;
24
67
  }
68
+
69
+ // ---- the migration journal ---------------------------------------------------------------------------------------------------------
70
+ // One fsynced record per step of a move from a 0.6 route: prepared, old-owner-fenced, gozar-adopted, dalan-committed. `transfer` is
71
+ // Gozar's opaque hand-back data, written before the old owner takes over again.
72
+ export const JOURNAL_PHASES = ['prepared', 'old-owner-fenced', 'gozar-adopted', 'dalan-committed'];
73
+ export function writeJournal(journal, env = process.env) {
74
+ if (!JOURNAL_PHASES.includes(journal.phase)) throw new Error(`unknown migration phase ${journal.phase}`);
75
+ writePrivateAtomic(migrationJournalPath(env), `${JSON.stringify({ version: 1, ...journal })}\n`);
76
+ }
77
+ export function readJournal(env = process.env) {
78
+ let value;
79
+ try { value = JSON.parse(fs.readFileSync(migrationJournalPath(env), 'utf8')); } catch (error) { if (error.code === 'ENOENT') return null; throw new Error(`the route migration journal is unreadable (${error.code ?? 'not JSON'}); leaving the old route untouched`); }
80
+ if (!isRecord(value) || value.version !== 1 || !JOURNAL_PHASES.includes(value.phase)) throw new Error('the route migration journal has an unknown version or phase; leaving the old route untouched');
81
+ return value;
82
+ }
83
+ export function removeJournal(env = process.env) { fs.rmSync(migrationJournalPath(env), { force: true }); }
package/src/server.mjs CHANGED
@@ -2,6 +2,7 @@ import { updateWindowOpen, refuseDuringUpdate } from './service-update-gate.mjs'
2
2
  import {routingPolicy,PULL_PAGE_PREFIX} from './pull-queue.mjs';
3
3
  import {inspect} from 'node:util';
4
4
  import { loopbackRequestAllowed } from './loopback.mjs';
5
+ import { normalizeRequestHost } from './gozar-routes.mjs';
5
6
  import { defaultPath,workspaceRoot,rootWarnings } from './paths.mjs';
6
7
  import { readEnv } from './env.mjs';
7
8
  import http from 'node:http';
@@ -14,7 +15,7 @@ import path from 'node:path';
14
15
  import os from 'node:os';
15
16
  import { randomBytes, randomUUID, createHash, timingSafeEqual } from 'node:crypto';
16
17
  import { loadWorkers, hasInstalledDatabase, legacyMarkerPath, seedWorkerRepos, resolveWorker, hasCapability, assertTarget, submitTarget } from './workers.mjs';
17
- import { Store, nonterminalOutcome, validateProtocol, loadRedeliveryLimits, resumeNudge } from './store.mjs';
18
+ import { Store, QUESTION_PURPOSES, nonterminalOutcome, validateProtocol, loadRedeliveryLimits, resumeNudge } from './store.mjs';
18
19
  import {protocolArtifactChunk} from './protocol-artifact-commands.mjs';
19
20
  import { sendWebhook, validSecret } from './webhooks.mjs';
20
21
  import { checkAlerts, publishAlert, redactNote } from './alerts.mjs';
@@ -33,7 +34,7 @@ import { compileWorkOrder, reasonsFromError, strongest } from './work-order.mjs'
33
34
  import { assertNoDeclaredConsumer, unprovenSource } from './consumers.mjs';
34
35
  import { preflightPR } from './pr-preflight.mjs';
35
36
  import { admitImplementation } from './check-readiness.mjs';
36
- import { parseExecution, parseRequiredCapabilities, admitHostExecution, withEvidence } from './execution.mjs';
37
+ import { parseExecution, parseRequiredCapabilities, admitHostExecution, admitAdapterCapabilities, ADAPTER_CAPABILITY_NAMES, withEvidence } from './execution.mjs';
37
38
  import { loadCapacity } from './projects.mjs';
38
39
  import { authConfig, assertPublicRouteAuth, isLoopbackBindHost, protectedResource, challenge, verifyBearer, needScope } from './auth.mjs';
39
40
  import { beginMcpOutcome, recordMcpResponse, pathShape, uaToken } from './mcp-outcome.mjs';
@@ -179,7 +180,7 @@ if(!t3ToolsEnabled)for(const [worker,profile] of workers.workers)if(profile.capa
179
180
  log({kind:'t3_tools_disabled',worker,setting:'DALAN_ENABLE_T3_TOOLS=1'});
180
181
  console.error(`dalan: startup WARNING: worker "${worker}" has t3 capability but reverse-control tools are off; set DALAN_ENABLE_T3_TOOLS=1`);
181
182
  }
182
- if(t3ToolsEnabled)for(const [worker,profile] of workers.workers)if(profile.capabilities.has('t3')) console.error(`dalan: startup NOTICE: worker "${worker}" holds the t3 capability: it can list, read and send to any T3 thread and project on this computer. Grant it only to your own harness.`);
183
+ if(t3ToolsEnabled)for(const [worker,profile] of workers.workers)if(profile.capabilities.has('t3')) console.error(`dalan: startup NOTICE: worker "${worker}" holds the t3 capability: its T3 authority is limited by live job destinations and tool grants.`);
183
184
  const startupPolicy=currentRepoPolicy();
184
185
  for(const worker of workers.workers.keys()) if(startupPolicy.repoPolicy(worker)?.repos.length===0) {
185
186
  const blocked=store.db.prepare("SELECT count(*) n FROM assignments WHERE target_worker=? AND status='queued' AND json_type(payload,'$.inputs[0].github_repo')='text'").get(worker).n;
@@ -321,6 +322,19 @@ function id(value,name='request_id') { const s=str(value,name,128); if(!/^[-\w]{
321
322
  function authorize(received,expected,label) { const a=Buffer.from(received||''),b=Buffer.from(expected); if(a.length!==b.length||!timingSafeEqual(a,b)) throw new Error(`invalid ${label}`); }
322
323
  function adminOwner(req,idValue) { store.owner(id(idValue),req.headers['x-owner-capability']); }
323
324
  function adminOperator(req) { authorize(req.headers['x-operator-key'],operatorKey,'operator key'); }
325
+ const questionPurpose=value=>{
326
+ if(value===undefined) return 'clarification';
327
+ if(!QUESTION_PURPOSES.includes(value)) throw new Error(`invalid purpose: use ${QUESTION_PURPOSES.join(' or ')}`);
328
+ return value;
329
+ };
330
+ // Any question with a purpose other than clarification is answered by a person holding the operator key. The owner
331
+ // capability alone, which a parent model may hold, is refused before anything is stored.
332
+ function requireOperatorForHumanQuestion(req,requestId,questionId) {
333
+ const purpose=store.questionPurpose(requestId,questionId);
334
+ if(purpose===null||purpose==='clarification') return;
335
+ try { adminOperator(req); }
336
+ catch { throw new Error(`FORBIDDEN: question ${questionId} on ${requestId} has purpose ${purpose}, reserved for a human; answering it needs the operator key, not the owner capability alone`); }
337
+ }
324
338
 
325
339
  const event = {
326
340
  name: 'assignment.available', description: 'An assignment or lightweight message is available. Claim assignments by request_id; read messages by message_id. Use list_pending after missed events.',
@@ -342,7 +356,7 @@ const tools = [
342
356
  { name:'get',description:'Read assignment, available_checks, cancellation, progress, report and delivery facts.',inputSchema:schema({request_id:string},['request_id']) },
343
357
  { name:'ack_message',description:'Acknowledge a lightweight message after reading it; no claim or finish is needed.',inputSchema:schema({message_id:string},['message_id']) },
344
358
  { name:'progress',description:'Append progress. Set blocker:true or start note with BLOCKED: or QUESTION: to forward a question to the owner thread. A note over 4096 bytes is cut.',inputSchema:schema({request_id:string,claim_id:string,note:message,blocker:bool},['request_id','claim_id','note']) },
345
- { name:'ask_question',description:'Ask an identified question under the current grant. The owner answers this question explicitly; ordinary notes do not answer it. Consume its answer before reporting completed.',inputSchema:schema({request_id:string,claim_id:string,question_id:{type:'string',minLength:1,maxLength:128},text:{type:'string',minLength:1,maxLength:4096}},['request_id','claim_id','question_id','text']) },
359
+ { name:'ask_question',description:'Ask an identified question under the current grant. The owner answers this question explicitly; ordinary notes do not answer it. Consume its answer before reporting completed. Set purpose to human_decision (a choice only a human may make), authentication (a sign-in only a human can complete) or tool_permission (a permission only a human may grant) when only a human may answer; no model can answer such a question for them.',inputSchema:schema({request_id:string,claim_id:string,question_id:{type:'string',minLength:1,maxLength:128},text:{type:'string',minLength:1,maxLength:4096},purpose:{type:'string',enum:['clarification','human_decision','authentication','tool_permission']}},['request_id','claim_id','question_id','text']) },
346
360
  { name:'consume_answer',description:'Read and durably consume the identified question answer under its original current grant. Refuses unanswered or stale-epoch questions.',inputSchema:schema({request_id:string,claim_id:string,question_id:{type:'string',minLength:1,maxLength:128}},['request_id','claim_id','question_id']) },
347
361
  { name:'finish',description:'Store a terminal worker report; completion is not owner acceptance. summary is optional: when absent it is the first line of result, and one over 4096 bytes is cut.',inputSchema:schema({request_id:string,claim_id:string,outcome:{type:'string',enum:['completed','blocked','failed']},summary:message,result:{type:'string',maxLength:262144},artifact_ids:{type:'array',items:string,maxItems:8}},['request_id','claim_id','outcome','result']) },
348
362
  { name:'list_files',description:"List files in this assignment's checked-out repository workspace. Read-only; scoped to the assignment. When truncated is true, pass next_cursor as cursor to get the next page.",inputSchema:schema({request_id:string,claim_id:string,path:string,limit:{type:'integer',minimum:1,maximum:200},cursor:{type:'string',maxLength:1024}},['request_id','claim_id']) },
@@ -418,6 +432,7 @@ const disabled=new Set(['list_files','read_file','apply_patch','run_check','work
418
432
  const readTools=new Set(['list_pending','get','list_files','read_file','workspace_result','list_tools','call_tool_read']);
419
433
  const t3ReadTools=new Set(['t3_thread_list','t3_thread_read','t3_thread_wait']);
420
434
  const t3Tools=new Set([...t3ReadTools,'t3_thread_create','t3_thread_send','t3_thread_set']);
435
+ if(t3ToolsEnabled)toolRegistry.initializeT3Grants([...t3Tools],workers.workers.keys());
421
436
  const notifyTools=new Set(['notify_owner']);
422
437
  // T3 tools use the existing scopes to preserve the current grant behavior.
423
438
  const scopeFor=name=>t3ReadTools.has(name)||readTools.has(name)?'dalan.read':'dalan.work';
@@ -740,7 +755,31 @@ async function dispatchTool(name,a,principal,notifyMeta) {
740
755
  return T3_READ_TOOLS_OFF;
741
756
  }
742
757
  const t3Arguments=name==='t3_thread_wait'?{...a,timeoutMs:Math.min(a.timeoutMs??90_000,90_000)}:a;
743
- const result=notifyTools.has(name) ? await notifyLedger.send(principal.worker,str(a.text,'text',1000),notificationKey,idempotencyKey=>publishAlert('Dalan message',a.text,log,{requirePublisher:true,idempotencyKey})) : await (await import('./t3-control.mjs')).runT3Tool(name,t3Arguments);
758
+ let result;
759
+ if(t3Tools.has(name)) {
760
+ const control=await import('./t3-control.mjs');
761
+ const t3=await import('./t3.mjs');
762
+ const authorize=()=>{
763
+ const threads=toolRegistry.t3Threads(name,principal);
764
+ if(name!=='t3_thread_list' && !threads.has(a.threadId)) throw new RegistryError('tool_unavailable','tool unavailable');
765
+ return threads;
766
+ };
767
+ // Linearization point: this synchronous live-grant read follows the last await before
768
+ // send/set invokes the CLI. A revoke committed before it refuses the effect. No claim
769
+ // is made about revokes after CLI dispatch cancelling an external effect.
770
+ authorize();
771
+ if(name==='t3_thread_list') {
772
+ const data=await t3.callT3(t3.listArgs({cwd:a.cwd,project:a.projectId,status:a.status,workspace_mode:a.workspaceMode}));
773
+ const threads=authorize();
774
+ result=control.compactThreadList({...data,threads:(data.threads??[]).filter(t=>threads.has(t.id))});
775
+ result._audit_ids={threadIds:result.threads.map(t=>t.id),projectIds:result.projects.map(p=>p.id)};
776
+ } else {
777
+ result=await control.runT3Tool(name,t3Arguments);
778
+ // Wait/read results require current authority. Writes linearize at dispatch:
779
+ // revocation afterward cannot turn a successful effect into a denied receipt.
780
+ if(t3ReadTools.has(name)) authorize();
781
+ }
782
+ } else result=await notifyLedger.send(principal.worker,str(a.text,'text',1000),notificationKey,idempotencyKey=>publishAlert('Dalan message',a.text,log,{requirePublisher:true,idempotencyKey}));
744
783
  t3Audit.appendT3Audit(store.db,audit,principal.subject,'success',result);
745
784
  if(result && typeof result==='object' && Object.hasOwn(result,'_audit_ids')) { const {_audit_ids,...publicResult}=result; return publicResult; }
746
785
  return result;
@@ -854,7 +893,7 @@ async function dispatchTool(name,a,principal,notifyMeta) {
854
893
  return {...receipt,...repaired.marks};
855
894
  }
856
895
  case 'ask_question': {
857
- const requestId=id(a.request_id),question=str(a.question_id,'question_id',128),text=str(a.text,'text',4096),receipt=store.askQuestion(requestId,id(a.claim_id,'claim_id'),question,text,subject,worker,commandContext('ask_question',{question,text}),connectionId);
896
+ const requestId=id(a.request_id),question=str(a.question_id,'question_id',128),text=str(a.text,'text',4096),purpose=questionPurpose(a.purpose),receipt=store.askQuestion(requestId,id(a.claim_id,'claim_id'),question,text,subject,worker,commandContext('ask_question',{question,text,...(purpose==='clarification'?{}:{purpose})}),connectionId,purpose);
858
897
  notifyAttachedWaiter(requestId);
859
898
  return receipt;
860
899
  }
@@ -967,6 +1006,7 @@ const publicServer=(as?createBuiltinHttpServer:http.createServer)(async(req,res)
967
1006
  if(updateWindowOpen()) return refuseDuringUpdate(res);
968
1007
  if(loopback && !loopbackRequestAllowed(req, `http://127.0.0.1:${port}`)) { log({kind:'mcp_inbound',status:403,route:'loopback',ua:uaToken(req)}); res.writeHead(403); res.end(); return; }
969
1008
  // Both authentication modes serve only the configured public Host, including discovery and verifier routes.
1009
+ if(as||oauth) normalizeRequestHost(req,new URL(as?as.publicUrl:oauth.OAUTH_AUDIENCE).origin); // a route may send the default port written out (name:443)
970
1010
  if(as ? !as.hostOk(req) : oauth&&req.headers.host!==new URL(oauth.OAUTH_AUDIENCE).host) { log({kind:'mcp_inbound',status:421,route:'host',ua:uaToken(req)}); res.writeHead(421); res.end(); return; }
971
1011
  if(verifyService?.(req,res)) return;
972
1012
  if(!as && req.url==='/.well-known/oauth-protected-resource' && oauthMetadata && req.method==='GET') return json(res,200,protectedResource(oauthMetadata));
@@ -1100,9 +1140,10 @@ const adminServer=http.createServer(async(req,res)=>{
1100
1140
  excludeSensitive:body.exclude_sensitive===true,sensitiveScopeOverride:body.sensitive_scope_override??null,target:target??'dot'},{
1101
1141
  render:renderAssignment,
1102
1142
  admitExecution:(p,r)=>{
1103
- if(r.requiredCapabilities&&r.jobExecution!=='host') throw new Error(`invalid required_capabilities: only execution=host jobs can require bridge capabilities (this job has execution=${r.jobExecution})`);
1143
+ const adapterRequired=r.jobExecution==='host'?r.requiredCapabilities?.filter(name=>ADAPTER_CAPABILITY_NAMES.includes(name)):r.requiredCapabilities;
1144
+ admitAdapterCapabilities(workers.workers.get(storedTarget??target??'dot')?.adapter,adapterRequired,catalogProfile);
1104
1145
  // No usable executor, or a required capability the backend does not declare verified: never degraded to a run without it.
1105
- if(r.jobExecution==='host'&&(p.execution_scope==='implementation'||r.requiredCapabilities)) admitHostExecution(r.requiredCapabilities);
1146
+ if(r.jobExecution==='host'&&(p.execution_scope==='implementation'||r.requiredCapabilities)) admitHostExecution(r.requiredCapabilities?.filter(name=>!ADAPTER_CAPABILITY_NAMES.includes(name)));
1106
1147
  },
1107
1148
  validate:(p,{warnings})=>validateSubmissionAsync(p,{sensitiveScopeOverride:body.sensitive_scope_override??null,warnings,excludeSensitive:body.exclude_sensitive===true,review:body.review===true,worker:storedTarget??target??'dot'}),
1108
1149
  admitReadiness:p=>{
@@ -1122,7 +1163,7 @@ const adminServer=http.createServer(async(req,res)=>{
1122
1163
  if(!dryRun&&(order.verdict==='reject'||order.verdict==='clarify'||order.blocking)) throw Object.assign(order.refusal,{verdict:order.verdict,reasons:order.reasons,bytes:order.bytes});
1123
1164
  payload=order.payload;
1124
1165
  }
1125
- const {environmentId}=(dryRun&&order&&order.verdict!=='admissible')?{}:await destination.validate(delivery);
1166
+ const {environmentId,generation}=(dryRun&&order&&order.verdict!=='admissible')?{}:await destination.validate(delivery);
1126
1167
  // An awaited repository/destination lookup may outlive a host policy edit.
1127
1168
  assertRepoAllowed(storedTarget??target??'dot',existingRequest?.assignment??payload);
1128
1169
  if(dryRun) store.checkRetry(submitted,delivery,environmentId,owner,body.review===true,body.background===true?'background':'normal',meta,submitted,target,explicitExecution,requiredCapabilities,commandKey,supersedes,destinationRevision);
@@ -1140,7 +1181,7 @@ const adminServer=http.createServer(async(req,res)=>{
1140
1181
  const readiness=order?.check_readiness??null;
1141
1182
  const preflight=order?.preflight??null;
1142
1183
  const defaultValidity=order?.defaultValidity??null;
1143
- const result=store.submit(payload,delivery,environmentId,owner,body.review===true,preflight,body.background===true?'background':'normal',meta,(()=>{const r=renderAssignment(submitted);return payload.brief!==r.brief||JSON.stringify(payload.scope_paths)!==JSON.stringify(r.scope_paths);})()?submitted:payload,body.max_queued??null,target,explicitExecution,workers.defaultExecution,requiredCapabilities,defaultValidity?.valid_until??null,commandKey,supersedes,destinationRevision);
1184
+ const result=store.submit(payload,delivery,environmentId,owner,body.review===true,preflight,body.background===true?'background':'normal',meta,(()=>{const r=renderAssignment(submitted);return payload.brief!==r.brief||JSON.stringify(payload.scope_paths)!==JSON.stringify(r.scope_paths);})()?submitted:payload,body.max_queued??null,target,explicitExecution,workers.defaultExecution,requiredCapabilities,defaultValidity?.valid_until??null,commandKey,supersedes,destinationRevision,null,generation??null);
1144
1185
  // Only a committed first replacement wakes the TARGET's already-attached waiter.
1145
1186
  if(supersedes&&!result.duplicate) {
1146
1187
  const targetId=supersedes.target_id,waiter=waiters.get(targetId);
@@ -1163,6 +1204,8 @@ const adminServer=http.createServer(async(req,res)=>{
1163
1204
  const got=maskedForOwner(withAvailableChecks(store.get(requestId)));
1164
1205
  if(url.searchParams.get('peek')!=='1') store.recordConsumed(requestId,'get');
1165
1206
  if(protocolServices&&store.isProtocolJob(requestId))got.protocol_stop=protocolServices.observation(requestId);
1207
+ // The owner needs the current revision to build a keyed, revision-checked command such as `dalan answer`. It is null for a job with no protocol revisions.
1208
+ got.protocol_revision=store.isProtocolJob(requestId)?store.protocolRevision(requestId):null;
1166
1209
  if(!workspaceEnabled||got.assignment?.execution_scope!=='implementation'||got.available_checks_error==='repository_policy_denied') return json(res,200,got);
1167
1210
  try { return json(res,200,{...got,check_metadata:workspace.checkMetadataFor(got.assignment,got.target_worker)}); }
1168
1211
  catch(error) { return json(res,200,{...got,check_metadata:null,check_metadata_error:publicErrorText(error,'check metadata')}); }
@@ -1217,7 +1260,7 @@ const adminServer=http.createServer(async(req,res)=>{
1217
1260
  const action=url.pathname.slice(7);
1218
1261
  if(action==='add') return json(res,200,toolRegistry.register(body.spec));
1219
1262
  if(action==='remove') return json(res,200,toolRegistry.remove(body.name));
1220
- if(action==='grant') { toolRegistry.grant(body.name,body.worker); return json(res,200,{name:body.name,worker:body.worker,granted:true}); }
1263
+ if(action==='grant') { toolRegistry.grant(body.name,body.worker,body.scope); return json(res,200,{name:body.name,worker:body.worker,granted:true}); }
1221
1264
  if(action==='revoke') { toolRegistry.revoke(body.name,body.worker); return json(res,200,{name:body.name,worker:body.worker,granted:false}); }
1222
1265
  } catch(error) { if(error instanceof RegistryError) throw new Error(`${error.code}: ${error.message}`); throw error; }
1223
1266
  }
@@ -1240,7 +1283,7 @@ const adminServer=http.createServer(async(req,res)=>{
1240
1283
  return json(res,200,store.integrated(id(body.id),body.reason===undefined||body.reason===null?null:str(body.reason,'reason',512)));
1241
1284
  }
1242
1285
  if(url.pathname==='/note'&&req.method==='POST') { const requestId=id(body.id); adminOwner(req,requestId); return json(res,200,store.note(requestId,body.text)); }
1243
- if(url.pathname==='/answer'&&req.method==='POST') { const requestId=id(body.id); adminOwner(req,requestId);return json(res,200,store.answerQuestion(requestId,str(body.question_id,'question_id',128),str(body.text,'text',4096),{key:body.command_key,revision:body.expected_revision},req.headers['x-owner-capability'])); }
1286
+ if(url.pathname==='/answer'&&req.method==='POST') { const requestId=id(body.id); adminOwner(req,requestId);const questionId=str(body.question_id,'question_id',128); requireOperatorForHumanQuestion(req,requestId,questionId);return json(res,200,store.answerQuestion(requestId,questionId,str(body.text,'text',4096),{key:body.command_key,revision:body.expected_revision},req.headers['x-owner-capability'])); }
1244
1287
  if(url.pathname==='/questions'&&req.method==='GET') { const requestId=id(url.searchParams.get('id'));adminOwner(req,requestId);return json(res,200,{request_id:requestId,questions:store.questions(requestId)}); }
1245
1288
  if(url.pathname==='/tell'&&req.method==='POST') return json(res,200,store.tell(str(body.text,'text',4096),body.worker===undefined&&workers.workers.has('dot')?'dot':submitTarget(workers,body.worker)??assertTarget(workers,'dot')));
1246
1289
  if(url.pathname==='/untell'&&req.method==='POST') return json(res,200,store.untell(id(body.message_id,'message_id'),body.worker===undefined?null:assertTarget(workers,body.worker)));
@@ -1476,6 +1519,15 @@ if(workspace) {
1476
1519
  setInterval(()=>{if(t3PostHandler.hasHeld())t3PostHandler.flushDue().catch(()=>{});},60000).unref();
1477
1520
  setInterval(maintain,500).unref(); maintain();
1478
1521
  setInterval(runDrain,500).unref(); runDrain();
1522
+ // A wake held because its parent was interrupted goes back to the queue once the parent runs again (see the T3 destination).
1523
+ let releasingHeld=false;
1524
+ const releaseHeldWakes=async()=>{
1525
+ if(releasingHeld||!store.heldDeliveries(1).length) return; releasingHeld=true;
1526
+ try { const destination=await destinations.for('t3'); if((await destination.releaseHeld()).length) runDrain(); }
1527
+ catch(error) { log({kind:'held_release_error',reason:String(error?.message??error).slice(0,300)}); }
1528
+ finally { releasingHeld=false; }
1529
+ };
1530
+ setInterval(releaseHeldWakes,Number(readEnv('DALAN_T3_HELD_RECHECK_MS'))||15000).unref();
1479
1531
  reconcileTick().catch(e=>log({kind:'reconciliation_error',reason:e.message}));
1480
1532
  setInterval(()=>reconcileTick().catch(e=>log({kind:'reconciliation_error',reason:e.message})),60000).unref();
1481
1533
  const retain=()=>{try{const r=retainLifecycle(store);if(r.rolled_up)log({kind:'lifecycle_rollup',...r});}catch(error){log({kind:'lifecycle_rollup_error',reason:error.message});}};
@@ -4,6 +4,7 @@ import { spawnSync } from 'node:child_process';
4
4
  import { defaultPath } from './paths.mjs';
5
5
  import { acquireUpdateLock } from './service-update-lock.mjs';
6
6
  import { writeAtomic } from './as-files.mjs';
7
+ import { setUpdateAgent } from './service-launchd.mjs';
7
8
 
8
9
  const safePath = /^[A-Za-z0-9_@+=:,./-]+$/;
9
10
 
@@ -28,7 +29,8 @@ export function autoUpdateUnits({ home, unit, node }) {
28
29
  }
29
30
 
30
31
  export async function setAutoUpdate({ home, enabled }, seams = {}) {
31
- if ((seams.platform ?? process.platform) !== 'linux') throw new Error('automatic service updates currently require Linux with a systemd user manager');
32
+ const platform = seams.platform ?? process.platform;
33
+ if (!['linux', 'darwin'].includes(platform)) throw new Error('automatic service updates need Linux with a systemd user manager or macOS with launchd');
32
34
  if (typeof enabled !== 'boolean') throw new Error('auto-update requires on or off');
33
35
  home = path.resolve(home);
34
36
  if (fs.realpathSync(home) !== home) throw new Error('service home must not use a symlink');
@@ -41,6 +43,11 @@ export async function setAutoUpdate({ home, enabled }, seams = {}) {
41
43
  const receipt = JSON.parse(fs.readFileSync(receiptFile, 'utf8'));
42
44
  if (receipt.home !== home || !receipt.unit_dir || !receipt.node) throw new Error('reinstall this service with the current Dalan release before enabling automatic updates');
43
45
  if (!safePath.test(receipt.unit_dir) || !path.isAbsolute(receipt.unit_dir) || fs.realpathSync(receipt.unit_dir) !== receipt.unit_dir) throw new Error('service unit directory must be a real absolute directory');
46
+ if (platform === 'darwin') {
47
+ const agent = setUpdateAgent({ receipt, home, node: receipt.node, enabled }, seams.launchd ?? {});
48
+ writeAtomic(receiptFile, `${JSON.stringify({ ...receipt, auto_update: enabled }, null, 2)}\n`);
49
+ return { home, auto_update: enabled, timer: agent.timer };
50
+ }
44
51
  const spawn = seams.spawn ?? spawnSync;
45
52
  const run = args => {
46
53
  const result = spawn('systemctl', ['--user', ...args], { encoding: 'utf8', env: seams.env ?? process.env, timeout: 30000, maxBuffer: 1024 * 1024 });
@@ -0,0 +1,186 @@
1
+ // The macOS service backend: a LaunchAgent for the bridge and a second one that runs `dalan service update` every day.
2
+ // Everything here is plist text (pure) plus a thin launchctl seam, so Linux tests can fake launchctl. The shape follows the agent
3
+ // that scripts/worker-bridge-setup.mjs already runs on macOS 26 (domain user/UID, Aqua and Background sessions, an explicit kickstart).
4
+ //
5
+ // Rules this backend keeps:
6
+ // - The agent runs node by absolute path. `nodePath()` in service.mjs picks the stable Homebrew or mise symlink when node is one of those, so a
7
+ // node upgrade keeps working; any other node is recorded as is, and a move of that binary needs `dalan service install` again.
8
+ // - It runs the package through the home's `current` symlink, so the updater switches versions by repointing that link and restarting.
9
+ // - launchd has no pre-start step, so the agent runs `dalan service recover` first in a shell, and starts the server only if that succeeds.
10
+ // - KeepAlive restarts after a crash or an error exit, never after a clean exit. Logs live under the service home.
11
+ import fs from 'node:fs';
12
+ import os from 'node:os';
13
+ import path from 'node:path';
14
+ import { spawnSync } from 'node:child_process';
15
+ import { createHash } from 'node:crypto';
16
+
17
+ export const MARKER = 'Generated by dalan service install';
18
+ const SESSION_TYPES = ['Aqua', 'Background'];
19
+ const SAFE_PATH = /^[A-Za-z0-9_@+=:,./-]+$/;
20
+ const fail = message => { throw new Error(message); };
21
+
22
+ export const launchdLabels = unit => ({ service: `org.dalan.${unit}`, update: `org.dalan.${unit}-update` });
23
+ export const launchAgentsDir = (env = process.env) => path.join(env.HOME || os.homedir(), 'Library', 'LaunchAgents');
24
+ const agentPath = (node) => [...new Set([path.dirname(node), '/opt/homebrew/bin', '/usr/local/bin', '/usr/bin', '/bin'])].join(':');
25
+ const xml = text => String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
26
+
27
+ function assertSafe(values) {
28
+ for (const [label, value] of Object.entries(values)) if (!path.isAbsolute(value) || !SAFE_PATH.test(value)) fail(`${label} is not a safe absolute path for a LaunchAgent: ${JSON.stringify(value)}`);
29
+ }
30
+
31
+ const dict = entries => ['<dict>', ...entries.flatMap(([key, value]) => [` <key>${xml(key)}</key>`, ...value.split('\n').map(line => ` ${line}`)]), '</dict>'].join('\n');
32
+ const str = value => `<string>${xml(value)}</string>`;
33
+ const arr = items => ['<array>', ...items.map(item => ` ${str(item)}`), '</array>'].join('\n');
34
+ const plist = (label, body) => ['<?xml version="1.0" encoding="UTF-8"?>',
35
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
36
+ `<!-- ${MARKER}. Remove with: dalan service uninstall -->`, '<plist version="1.0">', body, '</plist>', ''].join('\n');
37
+
38
+ export function servicePlist({ unit, node, home, port, enableWorkspace = false, enableT3 = false }) {
39
+ const current = path.join(home, 'current');
40
+ assertSafe({ home, node, current });
41
+ const { service } = launchdLabels(unit);
42
+ const env = { HOME: home, NODE_ENV: 'production', DALAN_AUTH_MODE: 'builtin', DALAN_BIND_HOST: '127.0.0.1', DALAN_GOZAR_SERVICE: '1', DALAN_CATALOG_PROFILE: 'stable',
43
+ DALAN_ENABLE_WORKSPACE: enableWorkspace ? '1' : '0', DALAN_ENABLE_T3_TOOLS: enableT3 ? '1' : '0', DALAN_PORT: String(port), PATH: agentPath(node) };
44
+ const start = `${node} ${current}/bin/dalan.mjs service recover --home ${home} --quiet && exec ${node} ${current}/src/server.mjs`;
45
+ return plist(service, dict([
46
+ ['Label', str(service)],
47
+ ['ProgramArguments', arr(['/bin/sh', '-c', start])],
48
+ ['WorkingDirectory', str(current)],
49
+ ['EnvironmentVariables', dict(Object.entries(env).map(([key, value]) => [key, str(value)]))],
50
+ ['RunAtLoad', '<true/>'],
51
+ ['KeepAlive', dict([['SuccessfulExit', '<false/>']])],
52
+ ['ThrottleInterval', '<integer>5</integer>'],
53
+ ['LimitLoadToSessionType', arr(SESSION_TYPES)],
54
+ ['UMask', '<integer>63</integer>'],
55
+ ['StandardOutPath', str(path.join(home, 'logs', 'bridge.out.log'))],
56
+ ['StandardErrorPath', str(path.join(home, 'logs', 'bridge.err.log'))],
57
+ ]));
58
+ }
59
+
60
+ // The update agent runs once a day at a fixed minute between 03:00 and 03:59 that depends on the home, so many installs do not call the registry together.
61
+ export const updateSchedule = home => ({ Hour: 3, Minute: parseInt(createHash('sha256').update(home).digest('hex').slice(0, 4), 16) % 60 });
62
+
63
+ export function updatePlist({ unit, node, home }) {
64
+ const current = path.join(home, 'current');
65
+ assertSafe({ home, node, current });
66
+ const { update } = launchdLabels(unit), when = updateSchedule(home);
67
+ return plist(update, dict([
68
+ ['Label', str(update)],
69
+ ['ProgramArguments', arr([node, `${current}/bin/dalan.mjs`, 'service', 'update', '--home', home, '--json'])],
70
+ ['EnvironmentVariables', dict([['PATH', str(agentPath(node))]])],
71
+ ['StartCalendarInterval', dict([['Hour', `<integer>${when.Hour}</integer>`], ['Minute', `<integer>${when.Minute}</integer>`]])],
72
+ ['ProcessType', str('Background')],
73
+ ['Nice', '<integer>19</integer>'],
74
+ ['LowPriorityIO', '<true/>'],
75
+ ['LimitLoadToSessionType', arr(SESSION_TYPES)],
76
+ ['UMask', '<integer>63</integer>'],
77
+ ['StandardOutPath', str(path.join(home, 'logs', 'update.out.log'))],
78
+ ['StandardErrorPath', str(path.join(home, 'logs', 'update.err.log'))],
79
+ ]));
80
+ }
81
+
82
+ // ---- launchctl --------------------------------------------------------------------------------------------------------------------------
83
+ export function launchctl(args, { spawn = spawnSync, env = process.env } = {}) {
84
+ const result = spawn('launchctl', args, { encoding: 'utf8', env, timeout: 30000, maxBuffer: 1024 * 1024 });
85
+ return { status: result.error ? -1 : (result.status ?? -1), stdout: result.stdout ?? '', stderr: result.error ? String(result.error.message) : (result.stderr ?? '') };
86
+ }
87
+ const uidOf = seams => (seams.uid ?? process.getuid?.());
88
+ const domainOf = seams => `user/${uidOf(seams)}`;
89
+ // Only launchctl's explicit missing-service diagnostic establishes absence.
90
+ export function queryAgent(label, seams = {}) {
91
+ const result = launchctl(['print', `${domainOf(seams)}/${label}`], seams);
92
+ const diagnostic = String(result.stderr || result.stdout).trim();
93
+ const absent = result.status > 0 && diagnostic.includes(`Could not find service "${label}" in domain`);
94
+ return { ...result, state: result.status === 0 ? 'loaded' : absent ? 'absent' : 'unknown' };
95
+ }
96
+ export function isLoaded(label, seams = {}) {
97
+ const result = queryAgent(label, seams);
98
+ if (result.state === 'unknown') fail(`Cannot determine whether launchd service ${label} is loaded; leaving its plist unchanged. launchctl print failed (exit ${result.status}): ${String(result.stderr || result.stdout).trim().slice(0, 500)}`);
99
+ return result.state === 'loaded';
100
+ }
101
+ const must = (result, what) => { if (result.status !== 0) fail(`${what} failed (exit ${result.status}): ${String(result.stderr || result.stdout).trim().slice(0, 500)}`); };
102
+
103
+ // Load the agent from its plist, then ask launchd to start it: on macOS 26 a bootstrapped agent can stay loaded and never spawn.
104
+ export function loadAgent({ label, plistFile, knownAbsent = false }, seams = {}) {
105
+ const domain = domainOf(seams);
106
+ if (knownAbsent || !isLoaded(label, seams)) must(launchctl(['bootstrap', domain, plistFile], seams), `launchctl bootstrap ${domain} ${plistFile}`);
107
+ const kick = launchctl(['kickstart', `${domain}/${label}`], seams);
108
+ return { kicked: kick.status === 0, detail: kick.status === 0 ? '' : String(kick.stderr).trim() };
109
+ }
110
+
111
+ export function unloadAgent({ label }, seams = {}) {
112
+ if (!isLoaded(label, seams)) return false;
113
+ must(launchctl(['bootout', `${domainOf(seams)}/${label}`], seams), `launchctl bootout ${label}`);
114
+ return true;
115
+ }
116
+
117
+ // The updater's three actions for a launchd service. `daemon-reload` has no launchd meaning: the plist does not change on update.
118
+ export function controlLaunchd(receipt, action, seams = {}) {
119
+ const { service } = launchdLabels(receipt.unit), plistFile = path.join(receipt.unit_dir, `${service}.plist`);
120
+ if (action === 'daemon-reload') return;
121
+ if (action === 'stop') { unloadAgent({ label: service }, seams); return; }
122
+ if (action === 'restart') {
123
+ if (isLoaded(service, seams)) must(launchctl(['kickstart', '-k', `${domainOf(seams)}/${service}`], seams), `launchctl kickstart -k ${service}`);
124
+ else {
125
+ const { kicked, detail } = loadAgent({ label: service, plistFile }, seams);
126
+ if (!kicked) fail(`launchctl kickstart ${service} failed: ${detail}`);
127
+ }
128
+ return;
129
+ }
130
+ fail('unsupported service action');
131
+ }
132
+
133
+ // ---- plist files ------------------------------------------------------------------------------------------------------------------------
134
+ // Read-only ownership/collision check. Return whether the generated plist needs writing.
135
+ export function preflightAgentFile(file, text) {
136
+ let existing = null;
137
+ try { const info = fs.lstatSync(file); if (!info.isFile() || info.isSymbolicLink()) fail(`${file} is not a regular file; refusing to replace it`); existing = fs.readFileSync(file, 'utf8'); } catch (error) { if (error.code !== 'ENOENT') throw error; }
138
+ if (existing === text) return false;
139
+ if (existing !== null && !existing.includes(MARKER)) fail(`${file} already exists and was not generated by dalan; refusing to overwrite it`);
140
+ return true;
141
+ }
142
+
143
+ // Recheck at write time too, so a collision introduced after preflight is still refused.
144
+ export function writeAgentFile(file, text) {
145
+ if (!preflightAgentFile(file, text)) return false;
146
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o755 });
147
+ const temp = `${file}.${process.pid}.tmp`;
148
+ fs.writeFileSync(temp, text, { mode: 0o644 });
149
+ fs.renameSync(temp, file);
150
+ return true;
151
+ }
152
+
153
+ export function lintPlist(file, { spawn = spawnSync } = {}) {
154
+ const result = spawn('plutil', ['-lint', file], { encoding: 'utf8' });
155
+ if (result.error) return null; // plutil is not installed (not macOS): not checked
156
+ return result.status === 0;
157
+ }
158
+
159
+ // Turn the daily update agent on or off. Off removes the agent from launchd and deletes its plist.
160
+ export function setUpdateAgent({ receipt, home, node, enabled }, seams = {}) {
161
+ const { update } = launchdLabels(receipt.unit), file = path.join(receipt.unit_dir, `${update}.plist`);
162
+ if (enabled) {
163
+ fs.mkdirSync(path.join(home, 'logs'), { recursive: true, mode: 0o700 });
164
+ const text = updatePlist({ unit: receipt.unit, node: receipt.node ?? node, home });
165
+ const changed = preflightAgentFile(file, text);
166
+ if (changed) unloadAgent({ label: update }, seams);
167
+ writeAgentFile(file, text);
168
+ if (changed || !isLoaded(update, seams)) must(launchctl(['bootstrap', domainOf(seams), file], seams), `launchctl bootstrap ${file}`);
169
+ } else {
170
+ unloadAgent({ label: update }, seams);
171
+ fs.rmSync(file, { force: true });
172
+ }
173
+ return { timer: update };
174
+ }
175
+
176
+ export function removeAgents({ unit, unit_dir: dir }, seams = {}) {
177
+ const { service, update } = launchdLabels(unit), removed = [];
178
+ // An unknown job must not allow even the other job's plist to be removed.
179
+ for (const label of [update, service]) isLoaded(label, seams);
180
+ for (const label of [update, service]) {
181
+ if (unloadAgent({ label }, seams)) removed.push(`unloaded ${label}`);
182
+ const file = path.join(dir, `${label}.plist`);
183
+ if (fs.existsSync(file)) { if (!fs.readFileSync(file, 'utf8').includes(MARKER)) fail(`${file} was not generated by dalan; leaving it`); fs.rmSync(file); removed.push(`removed ${file}`); }
184
+ }
185
+ return removed;
186
+ }
@@ -2,6 +2,7 @@
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { DatabaseSync } from 'node:sqlite';
5
+ import { loadCapacity } from './projects.mjs';
5
6
  import { loadEffectiveOwnerWorkers, parseWorkers, updateWorkerRepoPolicy, workerRepoMigrationFile } from './workers.mjs';
6
7
 
7
8
  function reenrollmentIntent(files, workers) {
@@ -45,9 +46,16 @@ export function migrateWorkers({ home, sources, sourceDbs = [], workspaceWorkers
45
46
  const workers = {};
46
47
  const grants = new Map();
47
48
  const deniedRepositories = [];
49
+ let limits = null;
48
50
  for (const source of sources) {
49
51
  const file = path.resolve(source);
50
52
  if (!fs.existsSync(file) && !fs.existsSync(workerRepoMigrationFile(file))) throw new Error(`no worker policy at ${file}`);
53
+ const sourceLimits = path.join(path.dirname(file), 'limits.json');
54
+ if (fs.existsSync(sourceLimits)) {
55
+ const capacity = loadCapacity(sourceLimits);
56
+ if (limits && limits.max_claimed_outer_assignments !== capacity) throw new Error('conflicting capacity limits in sources');
57
+ limits = { max_claimed_outer_assignments: capacity };
58
+ }
51
59
  const profile = loadEffectiveOwnerWorkers(file);
52
60
  deniedRepositories.push(...profile.deniedRepoGrants.map(item => ({ source: file, ...item })));
53
61
  for (const [name, worker] of profile.workers) {
@@ -80,8 +88,10 @@ export function migrateWorkers({ home, sources, sourceDbs = [], workspaceWorkers
80
88
  const config = path.join(home, '.config/dalan');
81
89
  const workersFile = path.join(config, 'workers.json');
82
90
  const manifestFile = path.join(config, 'service-migration.json');
91
+ const limitsFile = limits ? path.join(config, 'limits.json') : null;
83
92
  try {
84
93
  fs.mkdirSync(config, { recursive: true, mode: 0o700 });
94
+ if (limits) fs.writeFileSync(limitsFile, JSON.stringify(limits, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
85
95
  fs.writeFileSync(workersFile, JSON.stringify(value, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
86
96
  for (const [name, repos] of grants) for (const repo of repos) updateWorkerRepoPolicy(workersFile, name, 'allow', repo);
87
97
  fs.writeFileSync(manifestFile, JSON.stringify(manifest, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
@@ -89,7 +99,7 @@ export function migrateWorkers({ home, sources, sourceDbs = [], workspaceWorkers
89
99
  fs.rmSync(home, { recursive: true, force: true });
90
100
  throw error;
91
101
  }
92
- return { home, workers_file: workersFile, migration_manifest: manifestFile,
102
+ return { home, workers_file: workersFile, migration_manifest: manifestFile, limits, limits_file: limitsFile,
93
103
  workers: [...grants].map(([worker, repos]) => ({ worker, repos, workspaceAllowed: workers[worker].workspaceAllowed })),
94
104
  default_execution: 'none', reenrollment_required: true, denied_repositories: deniedRepositories };
95
105
  }
@@ -108,6 +118,6 @@ export function migrationMain(args = process.argv.slice(4)) {
108
118
  else workspaceWorkers.push(args[i]);
109
119
  }
110
120
  const result = migrateWorkers({ home, sources, sourceDbs, workspaceWorkers });
111
- process.stdout.write(json ? JSON.stringify(result) + '\n' : `Created ${result.workers.length} workers in ${result.home}; execution defaults to none. Re-enrol connectors, subscriptions and destination approvals using ${result.migration_manifest}. No sign-ins or jobs were copied.${result.denied_repositories.length ? ` Denied unaudited additions: ${result.denied_repositories.map(item => `${item.worker}: ${item.repos.join(', ')}`).join('; ')}.` : ''}\n`);
121
+ process.stdout.write(json ? JSON.stringify(result) + '\n' : `Created ${result.workers.length} workers in ${result.home}; execution defaults to none. Capacity limits: ${result.limits ? result.limits.max_claimed_outer_assignments : 'default (1; no limits file)'}. Re-enrol connectors, subscriptions and destination approvals using ${result.migration_manifest}. No sign-ins or jobs were copied.${result.denied_repositories.length ? ` Denied unaudited additions: ${result.denied_repositories.map(item => `${item.worker}: ${item.repos.join(', ')}`).join('; ')}.` : ''}\n`);
112
122
  return result;
113
123
  }