aegisone 1.0.24 → 1.0.26

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 (71) hide show
  1. package/README.md +2 -2
  2. package/package.json +1 -1
  3. package/scripts/predist.mjs +1 -1
  4. package/src/permissions.js +1 -1
  5. package/vendor/cli/bin/aegiscode.js +915 -2
  6. package/vendor/cli/package.json +1 -1
  7. package/vendor/cli/src/app.js +1 -1
  8. package/vendor/cli/src/autonomous.js +515 -1
  9. package/vendor/cli/src/caps.js +879 -1
  10. package/vendor/cli/src/chatflow.js +1 -1
  11. package/vendor/cli/src/commands.js +1 -1
  12. package/vendor/cli/src/engine.js +1 -1
  13. package/vendor/cli/src/gate.js +55 -1
  14. package/vendor/cli/src/history.js +1 -1
  15. package/vendor/cli/src/limits.js +190 -1
  16. package/vendor/cli/src/mcp.js +694 -1
  17. package/vendor/cli/src/models.js +1 -1
  18. package/vendor/cli/src/overlays.js +1 -1
  19. package/vendor/cli/src/permissions.js +290 -1
  20. package/vendor/cli/src/provenance.js +182 -2
  21. package/vendor/cli/src/provenance.lock.json +2 -2
  22. package/vendor/cli/vendor/client/aegis.js +1 -1
  23. package/vendor/cli/vendor/client/attest.js +1 -1
  24. package/vendor/cli/vendor/client/byok-catalog.js +1 -1
  25. package/vendor/cli/vendor/client/catalog-client.js +3 -0
  26. package/vendor/cli/vendor/client/conversation-export.js +3 -0
  27. package/vendor/cli/vendor/client/drive-upload.js +1 -1
  28. package/vendor/cli/vendor/client/session-store.js +1 -1
  29. package/vendor/cli/vendor/desktop/lib/local/attachments.js +3 -0
  30. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
  31. package/vendor/cli/vendor/desktop/lib/local/context.js +1 -1
  32. package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -1
  33. package/vendor/cli/vendor/desktop/lib/local/exec-plan.js +3 -0
  34. package/vendor/cli/vendor/desktop/lib/local/local.js +1 -1
  35. package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -1
  36. package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +1 -1
  37. package/vendor/cli/vendor/desktop/lib/local/shell.js +1 -1
  38. package/vendor/cli/vendor/desktop/lib/local/spill.js +3 -0
  39. package/vendor/cli/vendor/desktop/lib/local/tools.js +1 -1
  40. package/vendor/cli/vendor/one/src/permissions.js +1 -1
  41. package/vendor/desktop/lib/auto.js +1 -1
  42. package/vendor/desktop/lib/google-connect.js +1 -1
  43. package/vendor/desktop/lib/local/attachments.js +3 -0
  44. package/vendor/desktop/lib/local/claude-pro.js +1 -1
  45. package/vendor/desktop/lib/local/context.js +1 -1
  46. package/vendor/desktop/lib/local/engine.js +1 -1
  47. package/vendor/desktop/lib/local/exec-plan.js +3 -0
  48. package/vendor/desktop/lib/local/local.js +1 -1
  49. package/vendor/desktop/lib/local/prompt.js +1 -1
  50. package/vendor/desktop/lib/local/session-rounds.js +1 -1
  51. package/vendor/desktop/lib/local/shell.js +1 -1
  52. package/vendor/desktop/lib/local/spill.js +3 -0
  53. package/vendor/desktop/lib/local/tools.js +1 -1
  54. package/vendor/desktop/main.js +1 -1
  55. package/vendor/desktop/package.json +3 -2
  56. package/vendor/desktop/preload.js +1 -1
  57. package/vendor/desktop/renderer/app.js +1 -1
  58. package/vendor/desktop/renderer/budget.js +1 -1
  59. package/vendor/desktop/renderer/fingerprint.js +2 -2
  60. package/vendor/desktop/renderer/index.html +44 -4
  61. package/vendor/desktop/renderer/quick.html +4 -1
  62. package/vendor/desktop/renderer/quick.js +1 -1
  63. package/vendor/desktop/renderer/stream-policy.js +1 -1
  64. package/vendor/desktop/renderer/style.css +124 -0
  65. package/vendor/desktop/vendor/aegis.js +1 -1
  66. package/vendor/desktop/vendor/attest.js +1 -1
  67. package/vendor/desktop/vendor/byok-catalog.js +1 -1
  68. package/vendor/desktop/vendor/catalog-client.js +3 -0
  69. package/vendor/desktop/vendor/conversation-export.js +3 -0
  70. package/vendor/desktop/vendor/drive-upload.js +1 -1
  71. package/vendor/desktop/vendor/session-store.js +1 -1
@@ -1,3 +1,517 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const path=require("node:path"),{queue:queue,autonomous:autonomous}=require("./deps.js"),{createEngine:createEngine,proEnabled:proEnabled}=require("./engine.js"),{loadConfig:loadConfig}=require("./config.js"),{fmtElapsed:fmtElapsed}=require("./format.js"),limits=require("./limits.js"),SUBCOMMANDS=new Set(["add","list","run","proceed","reconcile","clear","retry","help"]),EXECUTES=new Set(["run","proceed","retry","reconcile"]);function parseFlags(e){const t={terms:[],json:!1,flags:{}},n=new Set(["cwd","model","effort","workers","max","max-rounds","source","class"]);for(let o=0;o<e.length;o++){const r=e[o];if("--json"!==r)if(r.startsWith("--")){const[s,i]=r.slice(2).split("="),a=s.trim();if(new Set(["commit","all","auto","stop-on-error","single-pass","help"]).has(a)){t.flags[a]=!0;continue}if(!n.has(a))throw new Error(`unknown option: --${a}`);const u=void 0!==i?i:e[++o];if(void 0===u)throw new Error(`--${a} needs a value`);t.flags[a]=u}else t.terms.push(r);else t.json=!0}return t}function intFlag(e,t){const n=e[t];if(void 0===n||""===n)return null;const o=Number.parseInt(n,10);return Number.isFinite(o)&&o>0?o:null}function taskLine(e){const t=e.model||"(default)",n=String(e.status||"?").padEnd(7),o=`#${e.id}`.padEnd(4),r=String(e.task||"").replace(/\s+/g," ").trim();return`${o} ${n} ${t} ${r.length>72?`${r.slice(0,71)}…`:r}`}function describeCounts(e){const t={pending:0,running:0,done:0,error:0};for(const n of e)void 0!==t[n.status]&&(t[n.status]+=1);return t}function printRunReport(e,t){for(const n of e){const e=Boolean(n.ok&&n.stoppedOnRounds),o=e?"⏸":n.ok?"✓":"✗",r=e?"paused — will resume":n.ok?"done":"failed";if(t.stdout.write(`aegiscode: ${o} #${n.id} ${r} (${fmtElapsed(n.ms)})`),n.commit&&n.commit.ok&&n.commit.staged?t.stdout.write(` — committed ${n.commit.staged} path(s)`):n.commit&&n.commit.skipped&&n.commit.reason&&t.stdout.write(` — no commit (${n.commit.reason})`),t.stdout.write("\n"),!n.ok&&n.error&&t.stderr.write(`aegiscode: #${n.id}: ${n.error}\n`),n.ok&&n.output){const e=String(n.output).trim();t.stdout.write(`${e.length>4e3?`${e.slice(0,4e3)}\n… [output clipped]`:e}\n`)}}}function buildEngine({io:e,quiet:t=!1}){const n=require("./credentials.js"),o=require("./deps.js").createClient(n.clientOptions({channel:"cli"}));if(!o.apiKey)return{error:`no AEGIS account key — ${n.HOW_TO_SET}, or set ${n.KEY_ENV}`};const r=createEngine({client:o,getConfirmMode:()=>!1,getProEnabled:()=>{try{return proEnabled(loadConfig())}catch{return!1}}});let s=null;try{s=require("./entitlement.js").createCliEntitlement({aegis:o})}catch{s=null}return{client:o,engine:r,entitlement:s}}function progressSink(e,{json:t}){return t?()=>{}:t=>{if(t&&"object"==typeof t)if("start"!==t.type)if("tool"===t.type&&t.tool&&"run"===t.tool.phase){const n=t.tool.args||{},o=n.command||n.pattern||autonomous.writtenPath(t.tool)||"",r=String(o).slice(0,100);e.stderr.write(` ⚙ ${t.tool.name}${r?` ${r}`:""}\n`)}else"healed"!==t.type?"note"===t.type&&t.note?e.stderr.write(` ⓘ ${t.note}\n`):"recovered"===t.type&&e.stdout.write(`aegiscode: re-queued task(s) ${t.ids.join(", ")} from a dead worker\n`):e.stdout.write(`aegiscode: PLAN.md status list healed for phase(s) ${t.phases.join(", ")}\n`);else e.stdout.write(`aegiscode: #${t.taskId} running on ${t.model} in ${t.cwd}\n`)}}async function runQueueCommand(e,t,n={}){const o=n.stdout||process.stdout,r=n.stderr||process.stderr,s={stdout:o,stderr:r};let i;try{i=parseFlags(t||[])}catch(e){return r.write(`aegiscode autonomous: ${e.message}\n`),2}const a=Boolean(n.json||i.json),u=(e,t)=>{a?o.write(`${JSON.stringify(e,null,2)}\n`):void 0!==t&&o.write(t.endsWith("\n")?t:`${t}\n`)};if("help"===e||!SUBCOMMANDS.has(e))return o.write(usageText()),"help"===e?0:2;if(EXECUTES.has(e)&&limits.armed())return limits.refuse();const l=i.flags.cwd?path.resolve(String(i.flags.cwd)):process.cwd();if("add"===e){const e=i.terms.join(" ").trim();if(!e)return r.write('aegiscode autonomous add: a task needs text — `aegiscode autonomous add "…"`\n'),2;let t;try{t=queue.addTask(process.env,{task:e,cwd:l,class:i.flags.class||null,model:i.flags.model||null,effort:i.flags.effort||null,workers:intFlag(i.flags,"workers"),maxRounds:intFlag(i.flags,"max-rounds"),singlePass:Boolean(i.flags["single-pass"]),commit:Boolean(i.flags.commit),source:i.flags.source||"cli"})}catch(e){return r.write(`aegiscode autonomous add: ${e.message}\n`),2}return u({ok:!0,id:t.id,item:t,queue:queue.queuePath(process.env)},`aegiscode: queued #${t.id} — ${queue.pendingCount(queue.loadQueue(process.env))} pending`),0}if("list"===e){const e=queue.loadQueue(process.env),t=describeCounts(e);if(a)u({ok:!0,file:queue.queuePath(process.env),counts:t,tasks:e,runs:queue.readRuns(process.env,{limit:10})});else{o.write(`queue: ${queue.queuePath(process.env)}\n`),o.write(`tasks: ${e.length} (${t.pending} pending, ${t.running} running, ${t.done} done, ${t.error} error)\n`);for(const t of e)o.write(`${taskLine(t)}\n`);e.length||o.write("(empty)\n")}return 0}if("clear"===e){const e=queue.clearQueue(process.env,{all:Boolean(i.flags.all)});return u({ok:!0,...e},`aegiscode: removed ${e.removed} finished task(s); ${e.kept} kept`),0}if("retry"===e){const e=i.terms[0];if(!e)return r.write("aegiscode autonomous retry: which task? `aegiscode autonomous retry <id>`\n"),2;const t=queue.retryTask(process.env,e);return t?(u({ok:!0,id:t.id,item:t},`aegiscode: #${t.id} is pending again`),0):(r.write(`aegiscode autonomous retry: no task #${e}\n`),1)}const d=buildEngine({io:n});if(d.error)return r.write(`aegiscode autonomous: ${d.error}\n`),2;if(d.entitlement)try{await d.entitlement.refresh()}catch{}const c=autonomous.createQueueWorker({engine:d.engine,env:process.env,log:progressSink(s,{json:a}),canFanOut:()=>{if(!d.entitlement)return!1;try{const e=d.entitlement.current();return Boolean(e&&!0===e.entitled)}catch{return!1}}});if(d.entitlement)try{const e=d.entitlement.current();e&&!1===e.entitled&&!1===e.degraded&&e.refusal&&(r.write(`aegiscode autonomous: ${e.refusal}\n`),r.write(" ↳ write tasks like: Do X autonomously\n"),r.write("balance"===e.wall?" ↳ unlock: top up the Token Bank, or upgrade to Unlimited\n":" ↳ unlock: Unlimited, or any Token Bank balance\n"),e.upgradeUrl&&r.write(` ${e.upgradeUrl}\n`))}catch{}const m=!!i.flags.commit||void 0,g=()=>{const e=queue.loadQueue(process.env).find((e=>"running"===e.status&&e.pid===process.pid));e&&c.cancel(e.id)};process.on("SIGINT",g);try{if("reconcile"===e){const e=await c.reconcile({cwd:l,auto:Boolean(i.flags.auto),commit:m,max:intFlag(i.flags,"max")||0,stopOnError:Boolean(i.flags["stop-on-error"])});return e.ok?(a||printRunReport(e.ran||[],s),u(e,e.exhausted?"aegiscode: every phase in PLAN.md is done — nothing to queue":`aegiscode: phase ${e.phase} queued${e.ran?` — ${e.ran.length} task(s) run`:""}`),0):(r.write(`aegiscode autonomous reconcile: ${e.error||"reconcile failed"}\n`),u(e,void 0),1)}if("proceed"===e||"run"===e){const t="run"===e?1:intFlag(i.flags,"max")||0,n=await c.proceed({commit:m,max:t,stopOnError:Boolean(i.flags["stop-on-error"])});if(n.locked)return r.write(`aegiscode autonomous: another drain holds the queue lock (pid ${n.holder&&n.holder.pid})\n`),u({ok:!1,locked:!0,holder:n.holder},void 0),1;a||printRunReport(n.ran,s);const o=n.ran.filter((e=>!e.ok)).length;return u({ok:0===o,ran:n.ran.map((e=>({id:e.id,ok:e.ok,error:e.error||null,ms:e.ms}))),failed:o},n.ran.length?`aegiscode: ${n.ran.length} task(s) run${o?`, ${o} failed`:""}`:"aegiscode: nothing pending"),o?1:0}}finally{process.removeListener("SIGINT",g)}return o.write(usageText()),2}function usageText(){return["aegiscode autonomous <command> — the unattended work queue","","Commands:",' add "<task>" queue a task (--cwd, --class, --model, --effort, --commit,'," --single-pass, --workers N, --max-rounds N)"," --class aegis|byok|local|pro (default aegis); --model must"," match the class (pro takes a claude alias, or none at all)"," list show queued tasks and the tail of the runs log"," run drain ONE task, then stop"," proceed drain every pending task (--max N, --stop-on-error, --commit)"," reconcile queue the next unfinished PLAN.md phase (--auto drains it)"," retry <id> put a finished task back in the queue"," clear drop finished tasks (--all empties the queue)","","Options:"," --json emit JSON instead of text (also on add/list/clear/retry)","","A drain runs with tool approval DISABLED (nobody is there to click a card),","one task at a time, and commits only the paths the task itself changed."].join("\n")+"\n"}module.exports={runQueueCommand:runQueueCommand,parseFlags:parseFlags,taskLine:taskLine,usageText:usageText,SUBCOMMANDS:SUBCOMMANDS};
3
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
+ // Conveying a modified copy, or running one as a network service, owes the
5
+ // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
+ 'use strict';
7
+
8
+ /**
9
+ * `aegiscode autonomous …` — the unattended host of the work queue.
10
+ *
11
+ * The queue itself (desktop/lib/local/queue.js) is a file, and the worker
12
+ * (desktop/lib/local/autonomous.js) drives the SAME engine the chat surfaces
13
+ * use. What is left for this module is the host: a subcommand surface a human
14
+ * or a timer can call, with the exit codes a script needs.
15
+ *
16
+ * Why the terminal is the unattended home rather than the GUI: a cron job, a
17
+ * systemd timer and `ssh box 'aegiscode autonomous proceed'` all need a process
18
+ * that starts, drains, and exits with a status — not a window somebody has to
19
+ * click. The desktop host can drain too, but only when the user asks it to.
20
+ *
21
+ * Reused, never reimplemented: the model call is cli/src/engine.js's
22
+ * createEngine (same tool loop as the GUI, confirm gate FORCED OFF), the task
23
+ * list is deps.queue (the file the GUI writes), and the commit rule is
24
+ * git-scope.js's scopedCommit. This file is argv → those calls, and the honest
25
+ * report of what came back.
26
+ *
27
+ * Exit codes (they are the point of a headless host):
28
+ * 0 everything asked for happened
29
+ * 1 a task failed, or another drain holds the lock
30
+ * 2 usage error, or no credential to run an unattended turn with
31
+ */
32
+
33
+ const path = require('node:path');
34
+
35
+ const { queue, autonomous } = require('./deps.js');
36
+ const { createEngine, proEnabled } = require('./engine.js');
37
+ const { loadConfig } = require('./config.js');
38
+ const { fmtElapsed } = require('./format.js');
39
+ const limits = require('./limits.js');
40
+
41
+ const SUBCOMMANDS = new Set([
42
+ 'add', 'list', 'run', 'proceed', 'reconcile', 'clear', 'retry', 'help',
43
+ ]);
44
+
45
+ /**
46
+ * The verbs that RUN something. `add`, `list` and `clear` decide nothing and
47
+ * stay available on a build that failed the interlock; these four act — `retry`
48
+ * re-arms a failed task, `reconcile` can chain straight into a drain, and
49
+ * `run`/`proceed` are the drain. See the guard in `runQueueCommand`.
50
+ */
51
+ const EXECUTES = new Set(['run', 'proceed', 'retry', 'reconcile']);
52
+
53
+ /**
54
+ * Parse the subcommand's own argv. Deliberately its own tiny parser rather than
55
+ * bin/aegiscode.js's: the top-level parser owns the one-shot/session flags, and
56
+ * a queue task's text must survive untouched (`aegiscode autonomous add "fix
57
+ * --json in the parser"` is a task, not a flag).
58
+ */
59
+ function parseFlags(argv) {
60
+ const opts = { terms: [], json: false, flags: {} };
61
+ const takesValue = new Set(['cwd', 'model', 'effort', 'workers', 'max', 'max-rounds', 'source', 'class']);
62
+ for (let i = 0; i < argv.length; i++) {
63
+ const a = argv[i];
64
+ if (a === '--json') {
65
+ opts.json = true;
66
+ continue;
67
+ }
68
+ if (a.startsWith('--')) {
69
+ const [rawName, inline] = a.slice(2).split('=');
70
+ const name = rawName.trim();
71
+ const bools = new Set(['commit', 'all', 'auto', 'stop-on-error', 'single-pass', 'help']);
72
+ if (bools.has(name)) {
73
+ opts.flags[name] = true;
74
+ continue;
75
+ }
76
+ if (!takesValue.has(name)) throw new Error(`unknown option: --${name}`);
77
+ const value = inline !== undefined ? inline : argv[++i];
78
+ if (value === undefined) throw new Error(`--${name} needs a value`);
79
+ opts.flags[name] = value;
80
+ continue;
81
+ }
82
+ opts.terms.push(a);
83
+ }
84
+ return opts;
85
+ }
86
+
87
+ /** `--max-rounds` / `--max-rounds=`: both spellings, one number. */
88
+ function intFlag(flags, name) {
89
+ const raw = flags[name];
90
+ if (raw === undefined || raw === '') return null;
91
+ const n = Number.parseInt(raw, 10);
92
+ return Number.isFinite(n) && n > 0 ? n : null;
93
+ }
94
+
95
+ /** The row a human reads for one queued task. */
96
+ function taskLine(item) {
97
+ const model = item.model || '(default)';
98
+ const status = String(item.status || '?').padEnd(7);
99
+ const at = `#${item.id}`.padEnd(4);
100
+ const task = String(item.task || '').replace(/\s+/g, ' ').trim();
101
+ const clipped = task.length > 72 ? `${task.slice(0, 71)}…` : task;
102
+ return `${at} ${status} ${model} ${clipped}`;
103
+ }
104
+
105
+ function describeCounts(items) {
106
+ const counts = { pending: 0, running: 0, done: 0, error: 0 };
107
+ for (const i of items) if (counts[i.status] !== undefined) counts[i.status] += 1;
108
+ return counts;
109
+ }
110
+
111
+ /**
112
+ * Human summary of a drain, from the outcomes the worker returned. Reported per
113
+ * task, because the one thing a timer's log has to answer is "which task
114
+ * failed, and why".
115
+ */
116
+ function printRunReport(ran, io) {
117
+ for (const r of ran) {
118
+ // stoppedOnRounds + ok means the task hit its tool-round horizon, not
119
+ // that it finished — the queue item is left 'pending' (autonomous.js's
120
+ // runOne) so a later proceed() resumes it. Calling that "done" would
121
+ // hide the exact case this whole mechanism exists to make visible.
122
+ const paused = Boolean(r.ok && r.stoppedOnRounds);
123
+ const mark = paused ? '⏸' : r.ok ? '✓' : '✗';
124
+ const label = paused ? 'paused — will resume' : r.ok ? 'done' : 'failed';
125
+ io.stdout.write(`aegiscode: ${mark} #${r.id} ${label} (${fmtElapsed(r.ms)})`);
126
+ if (r.commit && r.commit.ok && r.commit.staged) {
127
+ io.stdout.write(` — committed ${r.commit.staged} path(s)`);
128
+ } else if (r.commit && r.commit.skipped && r.commit.reason) {
129
+ io.stdout.write(` — no commit (${r.commit.reason})`);
130
+ }
131
+ io.stdout.write('\n');
132
+ if (!r.ok && r.error) io.stderr.write(`aegiscode: #${r.id}: ${r.error}\n`);
133
+ if (r.ok && r.output) {
134
+ const text = String(r.output).trim();
135
+ // The report the task wrote, kept to a readable length: a drain's log is
136
+ // read by a human deciding whether to trust the run.
137
+ io.stdout.write(`${text.length > 4000 ? `${text.slice(0, 4000)}\n… [output clipped]` : text}\n`);
138
+ }
139
+ }
140
+ }
141
+
142
+ /**
143
+ * The engine for an unattended turn: the CLI's own engine wrapper, with the
144
+ * approval gate pinned OFF.
145
+ *
146
+ * Not a nicety — a requirement of the task. There is nobody to click a card in
147
+ * a drain, and the engine's own answer to an unanswered card is to refuse the
148
+ * tool, so a gated drain would either hang the task or silently do nothing.
149
+ * `autonomous.js` still watches for an approval frame and fails the task
150
+ * loudly, which is how a future caller who forgets this gets told.
151
+ */
152
+ function buildEngine({ io, quiet = false }) {
153
+ const credentials = require('./credentials.js');
154
+ const client = require('./deps.js').createClient(credentials.clientOptions({ channel: 'cli' }));
155
+ if (!client.apiKey) {
156
+ return { error: `no AEGIS account key — ${credentials.HOW_TO_SET}, or set ${credentials.KEY_ENV}` };
157
+ }
158
+ // No `getClass` — deliberate (see engine.js chat()'s comment): a drain has
159
+ // no interactive session to read, so a queued task's own stated class is
160
+ // what runs. `getProEnabled` IS required even so, because liveClasses()
161
+ // treats a missing one as "off" and would strip `pro` out of the allowed
162
+ // set before the stated class is ever checked against it — leaving a
163
+ // `--class pro` task silently downgraded to DEFAULT_CLASS on every drain.
164
+ const engine = createEngine({
165
+ client,
166
+ getConfirmMode: () => false,
167
+ getProEnabled: () => {
168
+ try {
169
+ return proEnabled(loadConfig());
170
+ } catch {
171
+ return false;
172
+ }
173
+ },
174
+ });
175
+ // The Pro gate (Phase 7). Built from the SAME shared decision the desktop
176
+ // uses, bound to this host's channel so a refusal links `?s=cli` and not
177
+ // `?s=desktop` — see cli/src/entitlement.js. Passed to the worker below as
178
+ // `canFanOut`, which is the seam the shared worker already had and this host
179
+ // never supplied (so it defaulted to "yes" and the fan-out was free here).
180
+ let entitlement = null;
181
+ try {
182
+ entitlement = require('./entitlement.js').createCliEntitlement({ aegis: client });
183
+ } catch {
184
+ // A gate that cannot be built must not be a gate that says yes. The worker
185
+ // fails closed on a missing predicate (`safeCanFanOut`), so leaving this
186
+ // null clamps the drain to single passes rather than spending the fan-out.
187
+ entitlement = null;
188
+ }
189
+ return { client, engine, entitlement };
190
+ }
191
+
192
+ /** A progress sink for a headless drain: one line per step, never a chat delta. */
193
+ function progressSink(io, { json }) {
194
+ if (json) return () => {};
195
+ return (event) => {
196
+ if (!event || typeof event !== 'object') return;
197
+ if (event.type === 'start') {
198
+ io.stdout.write(`aegiscode: #${event.taskId} running on ${event.model} in ${event.cwd}\n`);
199
+ return;
200
+ }
201
+ if (event.type === 'tool' && event.tool && event.tool.phase === 'run') {
202
+ const args = event.tool.args || {};
203
+ // The engine spells a written file `file_path`, not `path` — knowledge
204
+ // the shared worker owns in writtenPath(). Asking it instead of
205
+ // re-listing the argument names here is what stops this line from
206
+ // printing `⚙ writeFile` with nothing after it, which is precisely what
207
+ // it did: an unattended drain could not say which file it wrote.
208
+ const what = args.command || args.pattern || autonomous.writtenPath(event.tool) || '';
209
+ const shown = String(what).slice(0, 100);
210
+ io.stderr.write(` ⚙ ${event.tool.name}${shown ? ` ${shown}` : ''}\n`);
211
+ return;
212
+ }
213
+ if (event.type === 'healed') {
214
+ io.stdout.write(`aegiscode: PLAN.md status list healed for phase(s) ${event.phases.join(', ')}\n`);
215
+ return;
216
+ }
217
+ // `note` is how the shared worker reports the fan-out clamp ("this task ran
218
+ // as a single pass"). It was emitted and then dropped on the floor here,
219
+ // which made the gate invisible from the terminal: a drain that silently
220
+ // ran one worker looked identical to one that was entitled to eight.
221
+ if (event.type === 'note' && event.note) {
222
+ io.stderr.write(` ⓘ ${event.note}\n`);
223
+ return;
224
+ }
225
+ if (event.type === 'recovered') {
226
+ io.stdout.write(`aegiscode: re-queued task(s) ${event.ids.join(', ')} from a dead worker\n`);
227
+ }
228
+ };
229
+ }
230
+
231
+ /**
232
+ * Run one queue subcommand.
233
+ *
234
+ * @param {string} command add|list|run|proceed|reconcile|clear|retry
235
+ * @param {string[]} argv the subcommand's own arguments
236
+ * @param {{stdout:any,stderr:any,json?:boolean}} io
237
+ * @returns {Promise<number>} process exit code
238
+ */
239
+ async function runQueueCommand(command, argv, io = {}) {
240
+ const stdout = io.stdout || process.stdout;
241
+ const stderr = io.stderr || process.stderr;
242
+ const out = { stdout, stderr };
243
+
244
+ let args;
245
+ try {
246
+ args = parseFlags(argv || []);
247
+ } catch (e) {
248
+ stderr.write(`aegiscode autonomous: ${e.message}\n`);
249
+ return 2;
250
+ }
251
+ const json = Boolean(io.json || args.json);
252
+ const emit = (payload, text) => {
253
+ if (json) stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
254
+ else if (text !== undefined) stdout.write(text.endsWith('\n') ? text : `${text}\n`);
255
+ };
256
+
257
+ if (command === 'help' || !SUBCOMMANDS.has(command)) {
258
+ stdout.write(usageText());
259
+ return command === 'help' ? 0 : 2;
260
+ }
261
+
262
+ // The interlock, asked here as well as at the entry point, and it is asked
263
+ // about the verbs that EXECUTE. This is the one surface where a machine acts
264
+ // with nobody answering: no prompt, no human to refuse a tool call, stdin on
265
+ // /dev/null under a timer. A build that is not the published one does not get
266
+ // to run a queue through it — it may still read `list` and append with `add`,
267
+ // because those decide nothing, but `run`/`proceed`/`retry` and installing the
268
+ // timer that repeats them are refused. See src/limits.js.
269
+ if (EXECUTES.has(command) && limits.armed()) return limits.refuse();
270
+
271
+ const cwd = args.flags.cwd ? path.resolve(String(args.flags.cwd)) : process.cwd();
272
+
273
+ if (command === 'add') {
274
+ const task = args.terms.join(' ').trim();
275
+ if (!task) {
276
+ stderr.write('aegiscode autonomous add: a task needs text — `aegiscode autonomous add "…"`\n');
277
+ return 2;
278
+ }
279
+ let item;
280
+ try {
281
+ item = queue.addTask(process.env, {
282
+ task,
283
+ cwd,
284
+ // WHICH TRANSPORT THIS TASK RUNS ON. Omitted means 'aegis' (queue.js
285
+ // normalizes a blank class, and every pre-existing task means the
286
+ // pooled brain). The flag exists so a Pro subscription — the class the
287
+ // desktop has had since claude-pro.js and the queue never did — can be
288
+ // queued from a timer: `--class pro` with no --model lets the claude
289
+ // CLI pick, `--class pro --model opus` pins one of its aliases.
290
+ class: args.flags.class || null,
291
+ model: args.flags.model || null,
292
+ effort: args.flags.effort || null,
293
+ workers: intFlag(args.flags, 'workers'),
294
+ maxRounds: intFlag(args.flags, 'max-rounds'),
295
+ singlePass: Boolean(args.flags['single-pass']),
296
+ commit: Boolean(args.flags.commit),
297
+ source: args.flags.source || 'cli',
298
+ });
299
+ } catch (e) {
300
+ stderr.write(`aegiscode autonomous add: ${e.message}\n`);
301
+ return 2;
302
+ }
303
+ emit({ ok: true, id: item.id, item, queue: queue.queuePath(process.env) },
304
+ `aegiscode: queued #${item.id} — ${queue.pendingCount(queue.loadQueue(process.env))} pending`);
305
+ return 0;
306
+ }
307
+
308
+ if (command === 'list') {
309
+ const items = queue.loadQueue(process.env);
310
+ const counts = describeCounts(items);
311
+ if (json) {
312
+ emit({ ok: true, file: queue.queuePath(process.env), counts, tasks: items, runs: queue.readRuns(process.env, { limit: 10 }) });
313
+ } else {
314
+ stdout.write(`queue: ${queue.queuePath(process.env)}\n`);
315
+ stdout.write(`tasks: ${items.length} (${counts.pending} pending, ${counts.running} running, ${counts.done} done, ${counts.error} error)\n`);
316
+ for (const item of items) stdout.write(`${taskLine(item)}\n`);
317
+ if (!items.length) stdout.write('(empty)\n');
318
+ }
319
+ return 0;
320
+ }
321
+
322
+ if (command === 'clear') {
323
+ const res = queue.clearQueue(process.env, { all: Boolean(args.flags.all) });
324
+ emit({ ok: true, ...res }, `aegiscode: removed ${res.removed} finished task(s); ${res.kept} kept`);
325
+ return 0;
326
+ }
327
+
328
+ if (command === 'retry') {
329
+ const id = args.terms[0];
330
+ if (!id) {
331
+ stderr.write('aegiscode autonomous retry: which task? `aegiscode autonomous retry <id>`\n');
332
+ return 2;
333
+ }
334
+ const item = queue.retryTask(process.env, id);
335
+ if (!item) {
336
+ stderr.write(`aegiscode autonomous retry: no task #${id}\n`);
337
+ return 1;
338
+ }
339
+ emit({ ok: true, id: item.id, item }, `aegiscode: #${item.id} is pending again`);
340
+ return 0;
341
+ }
342
+
343
+ // ── the three commands that need a model ─────────────────────────────────
344
+ const built = buildEngine({ io });
345
+ if (built.error) {
346
+ stderr.write(`aegiscode autonomous: ${built.error}\n`);
347
+ return 2;
348
+ }
349
+ // Read the gate BEFORE the first task, not lazily per task. A snapshot that
350
+ // was never refreshed reads as `unresolved`, which `current()` reports as
351
+ // free — so a PRO account would have its fan-out quietly clamped to a single
352
+ // pass for the whole drain. That is the gate failing in the direction that
353
+ // takes the paid feature away from the paying customer, so one awaited read
354
+ // happens up front and the rest of the drain answers from the cached
355
+ // snapshot (TTL a minute — see DEFAULT_TTL_MS; a drain must not probe per
356
+ // task).
357
+ if (built.entitlement) {
358
+ try {
359
+ await built.entitlement.refresh();
360
+ } catch {
361
+ // Unreachable leaves the snapshot unresolved, i.e. free. Fail-closed is
362
+ // the right direction: the alternative lets a network blip hand out the
363
+ // paid fan-out.
364
+ }
365
+ }
366
+ const worker = autonomous.createQueueWorker({
367
+ engine: built.engine,
368
+ env: process.env,
369
+ log: progressSink(out, { json }),
370
+ // THE SEAM THIS HOST NEVER SUPPLIED. `createQueueWorker` defaults this to
371
+ // `() => true`, so until now a fan-out asked for in the terminal — or
372
+ // written into queue.jsonl by hand, or left there by another host's older
373
+ // build — spent the multiplier the gate exists to withhold, with no window
374
+ // and nobody to ask. The shared worker already clamps it (`safeCanFanOut`),
375
+ // and a throwing predicate already fails closed; a gate that could not be
376
+ // BUILT at all must read the same way, hence the explicit null → false.
377
+ canFanOut: () => {
378
+ if (!built.entitlement) return false;
379
+ try {
380
+ const snap = built.entitlement.current();
381
+ return Boolean(snap && snap.entitled === true);
382
+ } catch {
383
+ return false;
384
+ }
385
+ },
386
+ });
387
+ // One promotion per drain, not one per task: the clamp note fires for every
388
+ // fanned-out task, and repeating a checkout link eight times in a log is
389
+ // spam, not promotion. Printed only for a READ WE ACTUALLY TRUST —
390
+ // `degraded` is the module's flag for "we did not get a real answer"
391
+ // (timeout, unparseable body, missing plan field), and an upsell printed on
392
+ // the strength of a timeout is a guess wearing a price tag. `unresolved` is
393
+ // the same rule one level up: the boot snapshot, which nobody asked.
394
+ if (built.entitlement) {
395
+ try {
396
+ const snap = built.entitlement.current();
397
+ if (snap && snap.entitled === false && snap.degraded === false && snap.refusal) {
398
+ stderr.write(`aegiscode autonomous: ${snap.refusal}\n`);
399
+ // The ask, in the message, as an example to write — not as a feature
400
+ // name to decode. `autonomously` is the word the drain actually reads
401
+ // (queue.js stores the inverse as `singlePass`), so the terminal shows
402
+ // the sentence to type.
403
+ stderr.write(' ↳ write tasks like: Do X autonomously\n');
404
+ // HOW to unlock, and it names BOTH routes because there are two:
405
+ // `entitlement.js` sets `entitled = pro || banked`, where the bank is
406
+ // the operator's own lever (aegis1 admin `add_funds`). Printing only
407
+ // "upgrade" would send a user with an empty bank to the plan page when
408
+ // topping up is the action that clears their wall — `snap.wall` is the
409
+ // module's own word for which wall this is, so the line follows it
410
+ // instead of guessing.
411
+ stderr.write(
412
+ snap.wall === 'balance'
413
+ ? ' ↳ unlock: top up the Token Bank, or upgrade to Unlimited\n'
414
+ : ' ↳ unlock: Unlimited, or any Token Bank balance\n'
415
+ );
416
+ if (snap.upgradeUrl) stderr.write(` ${snap.upgradeUrl}\n`);
417
+ }
418
+ } catch {
419
+ // A snapshot that cannot be read prints nothing — same rule as above.
420
+ }
421
+ }
422
+ const commit = args.flags.commit ? true : undefined;
423
+ const onSigint = () => {
424
+ // Ctrl-C stops the RUNNING turn, not the process: the task is settled back
425
+ // to `error` with a reason, so the queue does not keep a `running` item
426
+ // whose worker is gone.
427
+ const items = queue.loadQueue(process.env);
428
+ const running = items.find((i) => i.status === 'running' && i.pid === process.pid);
429
+ if (running) worker.cancel(running.id);
430
+ };
431
+ process.on('SIGINT', onSigint);
432
+
433
+ try {
434
+ if (command === 'reconcile') {
435
+ const res = await worker.reconcile({
436
+ cwd,
437
+ auto: Boolean(args.flags.auto),
438
+ commit,
439
+ max: intFlag(args.flags, 'max') || 0,
440
+ stopOnError: Boolean(args.flags['stop-on-error']),
441
+ });
442
+ // A reconcile that could not run has to SAY WHY on stderr. It used to
443
+ // fall through to the success line below, which printed
444
+ // "aegiscode: phase undefined queued" (res.phase is absent when there is
445
+ // no plan) and dropped res.error on the floor — the timer's log recorded
446
+ // a queueing that never happened and nothing about the missing PLAN.md
447
+ // that caused it. Exit code and message now agree.
448
+ if (!res.ok) {
449
+ stderr.write(`aegiscode autonomous reconcile: ${res.error || 'reconcile failed'}\n`);
450
+ emit(res, undefined);
451
+ return 1;
452
+ }
453
+ if (!json) printRunReport(res.ran || [], out);
454
+ emit(res, res.exhausted
455
+ ? 'aegiscode: every phase in PLAN.md is done — nothing to queue'
456
+ : `aegiscode: phase ${res.phase} queued${res.ran ? ` — ${res.ran.length} task(s) run` : ''}`);
457
+ return 0;
458
+ }
459
+
460
+ if (command === 'proceed' || command === 'run') {
461
+ const max = command === 'run' ? 1 : intFlag(args.flags, 'max') || 0;
462
+ const res = await worker.proceed({
463
+ commit,
464
+ max,
465
+ stopOnError: Boolean(args.flags['stop-on-error']),
466
+ });
467
+ if (res.locked) {
468
+ stderr.write(
469
+ `aegiscode autonomous: another drain holds the queue lock (pid ${res.holder && res.holder.pid})\n`
470
+ );
471
+ emit({ ok: false, locked: true, holder: res.holder }, undefined);
472
+ return 1;
473
+ }
474
+ if (!json) printRunReport(res.ran, out);
475
+ const failed = res.ran.filter((r) => !r.ok).length;
476
+ emit(
477
+ { ok: failed === 0, ran: res.ran.map((r) => ({ id: r.id, ok: r.ok, error: r.error || null, ms: r.ms })), failed },
478
+ res.ran.length
479
+ ? `aegiscode: ${res.ran.length} task(s) run${failed ? `, ${failed} failed` : ''}`
480
+ : 'aegiscode: nothing pending'
481
+ );
482
+ return failed ? 1 : 0;
483
+ }
484
+ } finally {
485
+ process.removeListener('SIGINT', onSigint);
486
+ }
487
+
488
+ stdout.write(usageText());
489
+ return 2;
490
+ }
491
+
492
+ /** The one place this surface is documented, printed by `help` and on misuse. */
493
+ function usageText() {
494
+ return [
495
+ 'aegiscode autonomous <command> — the unattended work queue',
496
+ '',
497
+ 'Commands:',
498
+ ' add "<task>" queue a task (--cwd, --class, --model, --effort, --commit,',
499
+ ' --single-pass, --workers N, --max-rounds N)',
500
+ ' --class aegis|byok|local|pro (default aegis); --model must',
501
+ ' match the class (pro takes a claude alias, or none at all)',
502
+ ' list show queued tasks and the tail of the runs log',
503
+ ' run drain ONE task, then stop',
504
+ ' proceed drain every pending task (--max N, --stop-on-error, --commit)',
505
+ ' reconcile queue the next unfinished PLAN.md phase (--auto drains it)',
506
+ ' retry <id> put a finished task back in the queue',
507
+ ' clear drop finished tasks (--all empties the queue)',
508
+ '',
509
+ 'Options:',
510
+ ' --json emit JSON instead of text (also on add/list/clear/retry)',
511
+ '',
512
+ 'A drain runs with tool approval DISABLED (nobody is there to click a card),',
513
+ 'one task at a time, and commits only the paths the task itself changed.',
514
+ ].join('\n') + '\n';
515
+ }
516
+
517
+ module.exports = { runQueueCommand, parseFlags, taskLine, usageText, SUBCOMMANDS };