aegiscode 7.0.14 → 7.0.16

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 (109) hide show
  1. package/SOURCE-OFFER.txt +9 -0
  2. package/package.json +4 -7
  3. package/scripts/check.mjs +1 -52
  4. package/scripts/demo.mjs +1 -94
  5. package/scripts/predist.mjs +1 -75
  6. package/scripts/runtests.mjs +1 -56
  7. package/scripts/seal-gate.mjs +1 -74
  8. package/src/agents.js +1 -139
  9. package/src/app.js +1 -2932
  10. package/src/art.js +1 -289
  11. package/src/chatflow.js +1 -3020
  12. package/src/checkpoint.js +1 -90
  13. package/src/clipboard.js +1 -424
  14. package/src/cloudsync.js +1 -528
  15. package/src/commands.js +1 -4003
  16. package/src/config.js +1 -581
  17. package/src/connect.js +1 -349
  18. package/src/credentials.js +1 -33
  19. package/src/deps.js +1 -232
  20. package/src/devrun.js +1 -187
  21. package/src/diff.js +1 -333
  22. package/src/diffview.js +1 -296
  23. package/src/engine.js +1 -297
  24. package/src/entitlement.js +1 -355
  25. package/src/events.js +1 -707
  26. package/src/export.js +1 -67
  27. package/src/fingerprint.js +1 -592
  28. package/src/format.js +1 -259
  29. package/src/fuzzy.js +1 -119
  30. package/src/history.js +1 -401
  31. package/src/init.js +1 -175
  32. package/src/input.js +1 -139
  33. package/src/keys.js +1 -183
  34. package/src/markdown.js +1 -306
  35. package/src/models.js +1 -487
  36. package/src/naming.js +1 -229
  37. package/src/overlays.js +1 -461
  38. package/src/panels.js +1 -1418
  39. package/src/ping.js +1 -226
  40. package/src/presence.js +1 -238
  41. package/src/render.js +1 -515
  42. package/src/screen.js +1 -518
  43. package/src/screens.js +1 -896
  44. package/src/secret.js +1 -59
  45. package/src/securefs.js +1 -359
  46. package/src/settings.js +1 -155
  47. package/src/shared.js +1 -52
  48. package/src/sharedpaths.js +1 -53
  49. package/src/signup.js +1 -156
  50. package/src/summarize.js +1 -95
  51. package/src/sysdiag.js +1 -585
  52. package/src/system.js +1 -40
  53. package/src/theme.js +1 -570
  54. package/src/title.js +1 -220
  55. package/src/todos.js +1 -115
  56. package/src/tokens.js +1 -263
  57. package/src/topup.js +1 -210
  58. package/src/update.js +1 -181
  59. package/vendor/client/aegis.js +1 -2179
  60. package/vendor/client/attest.js +1 -442
  61. package/vendor/client/authorship-key.js +1 -410
  62. package/vendor/client/auto-provision.js +1 -134
  63. package/vendor/client/brain-catalog.js +1 -268
  64. package/vendor/client/byok-catalog.js +1 -230
  65. package/vendor/client/credentials.js +1 -494
  66. package/vendor/client/device-fingerprint.js +1 -141
  67. package/vendor/client/drive-connect.js +1 -110
  68. package/vendor/client/drive-upload.js +1 -174
  69. package/vendor/client/env-file.js +1 -1273
  70. package/vendor/client/fingerprint.js +1 -1064
  71. package/vendor/client/foreign-memory.js +1 -669
  72. package/vendor/client/google-signin.js +1 -133
  73. package/vendor/client/hooks.js +1 -430
  74. package/vendor/client/model-discovery.js +1 -373
  75. package/vendor/client/platform.js +1 -937
  76. package/vendor/client/prefs.js +1 -351
  77. package/vendor/client/presence-constants.js +1 -107
  78. package/vendor/client/presence.js +1 -438
  79. package/vendor/client/record-vault.js +3 -1055
  80. package/vendor/client/session-store.js +1 -548
  81. package/vendor/client/topup.js +1 -297
  82. package/vendor/client/touch.js +1 -458
  83. package/vendor/client/update.js +1 -704
  84. package/vendor/client/user-models.js +1 -381
  85. package/vendor/desktop/lib/local/agents.js +1 -105
  86. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  87. package/vendor/desktop/lib/local/claude-pro.js +1 -993
  88. package/vendor/desktop/lib/local/context.js +1 -95
  89. package/vendor/desktop/lib/local/engine.js +1 -3301
  90. package/vendor/desktop/lib/local/entitlement.js +1 -660
  91. package/vendor/desktop/lib/local/git-scope.js +1 -228
  92. package/vendor/desktop/lib/local/local.js +1 -2135
  93. package/vendor/desktop/lib/local/prompt.js +1 -275
  94. package/vendor/desktop/lib/local/queue.js +1 -560
  95. package/vendor/desktop/lib/local/session-rounds.js +1 -208
  96. package/vendor/desktop/lib/local/shell.js +1 -680
  97. package/vendor/desktop/lib/local/tools.js +1 -1238
  98. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  99. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  100. package/vendor/desktop/lib/settings.js +1 -890
  101. package/vendor/desktop/renderer/usage.js +1 -1239
  102. package/vendor/hosts/install.js +1 -638
  103. package/vendor/hosts/openai-shim.js +1 -515
  104. package/vendor/hosts/spec.js +1 -164
  105. package/vendor/hosts/targets.js +1 -346
  106. package/vendor/mcp/server.js +1 -221
  107. package/vendor/mcp/tools.js +1 -408
  108. package/vendor/one/src/child.js +1 -285
  109. package/vendor/one/src/permissions.js +1 -369
@@ -1,1047 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
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
- * autonomous.js — the unattended worker: what actually runs a queued task.
10
- *
11
- * `queue.js` stores tasks; this module is the half that turns one into work.
12
- * It owns three things no interactive turn has to think about:
13
- *
14
- * 1. THE OPERATING DIRECTIVE. An interactive turn can end on "let me check…"
15
- * or a question, because a human will read it and answer. A queued task
16
- * ends there only if nobody ever looks — so every queued turn runs under a
17
- * directive that says, in the model's own context: nobody is watching,
18
- * decide, act, verify, report; do not hand the work back. The round horizon
19
- * is stated too, so the model budgets its exploration instead of meeting
20
- * the cap by accident.
21
- *
22
- * 2. THE CARRY-OVER DIGEST. The AEGIS API is stateless per request, so a
23
- * drain is not literally one long conversation — but treating ten queued
24
- * tasks as ten unrelated strangers makes the ninth re-derive what the
25
- * second already learned. Each finished task appends a one-line digest
26
- * (what it was, what it touched, whether it was verified) to a carry string
27
- * that rides in front of the next task's prompt. Bounded and one line per
28
- * task: it is a briefing, not a transcript, and it must never grow into the
29
- * context it is meant to save.
30
- *
31
- * 3. ATTRIBUTED COMMITS. A queue drain can run in a checkout somebody else is
32
- * editing. `git add -A && git commit` in that situation commits THEIR
33
- * half-finished work under our message — the failure `git-scope.js` was
34
- * written for. So a task's `commit` flag commits only paths that this task's
35
- * own tool layer wrote (`writeFile`/`editFile` frames, recorded as they
36
- * land); everything else dirty is left alone, whether it was dirty before
37
- * the task (a peer's in-flight work) or a path this task never wrote.
38
- *
39
- * Two conditions, not one, and the second is not academic: commit 96fb64f
40
- * swept `desktop/electron-builder.yml` — a file another live session was
41
- * editing at that moment — into an unrelated commit, because "dirty before
42
- * and byte-identical now" cannot see a concurrent writer who edits DURING
43
- * the task window. Only positive attribution can, so a path this task never
44
- * wrote is never staged, and the paths left behind are reported.
45
- *
46
- * It does NOT own the model call itself: the caller passes the local engine
47
- * (`desktop/lib/local/engine.js`), which is the same tool loop the GUI and the
48
- * CLI chat in. One tool loop, three callers, no drift.
49
- *
50
- * THE APPROVAL GATE IS THE CALLER'S JOB. There is nobody to answer an approval
51
- * card in an unattended run, so the engine must be constructed with the gate
52
- * off (`getConfirmMode: () => false`). Rather than trust that, the worker
53
- * watches the turn's event stream: an approval request means a card nobody can
54
- * click, so it is reported as a failed task instead of a hang.
55
- */
56
-
57
- const queue = require('./queue.js');
58
- const gitScope = require('./git-scope.js');
59
-
60
- /** Default tool-round horizon for an unattended turn (matches the engine's). */
61
- const DEFAULT_ROUNDS = 40;
62
-
63
- /**
64
- * Consecutive tool-round-horizon stops a queued task gets before runOne gives
65
- * up on it as unable to converge and settles it 'error' instead of 'pending'.
66
- * Without this bound a task that never finishes would keep proceed()'s drain
67
- * loop picking it back up forever — proceed() defaults to no --max at all, so
68
- * nothing else would ever stop it.
69
- */
70
- const MAX_ROUND_STOPS = 3;
71
-
72
- /**
73
- * The engine tools that report the file they write, and the argument holding
74
- * it. This set is the attribution record for a task's commit: `exec` is absent
75
- * on purpose — a shell command names no paths, so a file it creates cannot be
76
- * attributed to this task, and guessing "anything new is ours" is precisely how
77
- * a concurrent writer's file gets committed.
78
- */
79
- const WRITE_TOOLS = new Set(['writeFile', 'editFile']);
80
-
81
- // ── Auto mode and the round horizon ─────────────────────────────────────────
82
- //
83
- // The two halves of "auto mode" the upstream engine (aegiscodex-dev) defines
84
- // are independent, and a host that wires only one of them is *not* running auto
85
- // mode — it is running "no approval cards", which is half the feature and all
86
- // the friction:
87
- //
88
- // 1. no approval keystroke per mutating tool call;
89
- // 2. a turn that hits its round horizon is EXTENDED silently a few times
90
- // before a human is asked.
91
- //
92
- // (1) is the posture (the desktop's Tool-approvals switch, the CLI's
93
- // /automode); (2) needs the arithmetic below, and the plugin's Electron host
94
- // had none of it — with auto mode ON, every horizon hit still raised the
95
- // blocking round card, which is precisely the question auto mode exists to stop
96
- // asking ("12 rounds — keep going?" answered the same way every time).
97
- //
98
- // Ported verbatim from the engine's src/autonomous.js (DEFAULT_AUTO_CONTINUES,
99
- // autoContinueLimit, autoRoundsDefault, autoContinuePlan) rather than vendored,
100
- // because this repo hosts no build of that ESM module — but with the SAME
101
- // numbers and the SAME env knobs, so a turn behaves identically in either
102
- // client. cli/src/chatflow.js carries the third copy, which is what the CLI
103
- // presenter uses to answer the ask.
104
-
105
- /** Automatic continuations an attended turn may take while auto mode is on. */
106
- const DEFAULT_AUTO_CONTINUES = 3;
107
-
108
- /**
109
- * The auto-continue allowance, honouring AEGIS_AUTO_CONTINUE_MAX.
110
- *
111
- * Bounded and pure, and a garbage value falls back to the default rather than
112
- * to 0: an unparseable env var must not silently switch auto mode off, because
113
- * the visible symptom of that ("why is it asking me again?") points nowhere
114
- * near the environment.
115
- */
116
- function autoContinueLimit(env = process.env) {
117
- const n = Number.parseInt(env && env.AEGIS_AUTO_CONTINUE_MAX, 10);
118
- return Number.isFinite(n) && n > 0 ? n : DEFAULT_AUTO_CONTINUES;
119
- }
120
-
121
- /**
122
- * Values of AEGIS_AUTO_ROUNDS that mean "start in manual mode". Anything else —
123
- * unset, empty, a typo like `flase` — leaves auto mode's default in place, so a
124
- * misspelt opt-out cannot silently disable the mode the operator asked for.
125
- * Same set, same reasoning, as the engine's AUTO_ROUNDS_OFF.
126
- */
127
- const AUTO_ROUNDS_OFF = new Set(['0', 'false', 'off', 'no']);
128
-
129
- /** False only when AEGIS_AUTO_ROUNDS explicitly says so. */
130
- function autoRoundsDefault(env = process.env) {
131
- const raw = env && env.AEGIS_AUTO_ROUNDS;
132
- if (raw === undefined || raw === null) return true;
133
- const val = String(raw).trim().toLowerCase();
134
- if (!val) return true;
135
- return !AUTO_ROUNDS_OFF.has(val);
136
- }
137
-
138
- /**
139
- * Decide what one round-horizon ask becomes while auto mode is on.
140
- *
141
- * Pure, because this is budget arithmetic on a keystroke-less path: the caller
142
- * only renders the answer and must not be trusted to keep the count. `used` is
143
- * the running tally the caller holds and echoes back, so an ask that IS shown
144
- * to the human resets it — the human was asked, so the next block of automatic
145
- * continuations starts clean.
146
- *
147
- * { auto: true, used: n } → answer the ask "yes" without a dialog
148
- * { auto: false, used: n } → show the real ask (allowance spent, or off)
149
- */
150
- function autoContinuePlan({ on = false, used = 0, limit = DEFAULT_AUTO_CONTINUES } = {}) {
151
- const cap = Number.isFinite(limit) && limit > 0 ? Math.floor(limit) : DEFAULT_AUTO_CONTINUES;
152
- const spent = Number.isFinite(used) && used > 0 ? Math.floor(used) : 0;
153
- if (!on) return { auto: false, used: spent, cap };
154
- if (spent >= cap) return { auto: false, used: 0, cap };
155
- return { auto: true, used: spent + 1, cap };
156
- }
157
-
158
- /** The path a file-writing tool call names, in either spelling the engine uses. */
159
- function writtenPath(tool) {
160
- const args = (tool && tool.args) || {};
161
- const p = args.file_path || args.path;
162
- return p ? String(p) : '';
163
- }
164
-
165
- /**
166
- * The default AEGIS Cloud model for autonomous work: the pooled brain, which
167
- * is the tier the server can fan out to multiple reasoning workers and
168
- * synthesise. `nexus-brain` is the canonical id the catalog itself prefers
169
- * (the other tier spellings are aliases of it — see offerableCatalog in
170
- * engine.js).
171
- *
172
- * The model id is only the tier. It is NOT what makes an autonomous task
173
- * expensive — the fan-out is, and the fan-out is opt-in per task (see
174
- * resolveFanout below). This used to be documented the other way round ("the
175
- * pooled brain ... autonomous tasks are exactly the ones worth that spend"),
176
- * and the worker sent `autonomous: true` on every queued task, so the most
177
- * expensive shape of the most expensive tier ran on one-line tasks too.
178
- */
179
- const DEFAULT_MODEL = 'nexus-brain';
180
-
181
- /**
182
- * THE QUEUE RUNS ON WHATEVER CLASS THE TASK NAMES — aegis, byok, or local —
183
- * the same three classes engine.js's interactive turns serve (engine.js's
184
- * exported `CLASSES`). This module does not `require('./engine.js')` to read
185
- * that list itself (same reason queue.js stays engine-free): duplicating the
186
- * three names here keeps both modules testable with no Electron, no network,
187
- * and no model.
188
- *
189
- * This used to be Aegis Cloud only, because runTask sent every turn out with
190
- * a hardcoded `class: 'aegis'` — a byok or local model id would have gone out
191
- * under the wrong transport and failed at the server, or worse, silently
192
- * picked up the wrong provider's key. Now `class` travels with the task
193
- * (`item.class`, defaulted to 'aegis' for every task that predates this field
194
- * — the CLI, a hand-written queue file, the old desktop card), and runTask
195
- * forwards it verbatim instead of overwriting it.
196
- *
197
- * Each class validates differently, because each has a different notion of
198
- * "no model stated is fine":
199
- * - 'aegis' has a real default (the pooled brain), so a blank model is
200
- * accepted and resolveModel fills it in. The accept-list is the
201
- * pooled-brain tier family — the one entry engine.js's offerableCatalog
202
- * offers for the Aegis Cloud class, plus the `-smart`/`-neo` tier
203
- * spellings the server still serves as aliases of it (mirrors
204
- * selectBrainEntry() there rather than re-deriving "anything starting
205
- * with nexus-": `nexus-fast` is not a tier the catalog has ever served).
206
- * - 'byok' and 'local' have no such default: a blank byok model cannot be
207
- * "whichever provider the pool picks" (there is no pool), and a blank
208
- * local model cannot be "whichever model is pulled" when the answer
209
- * depends on what the user's own daemon happens to have. Both REQUIRE an
210
- * explicit model, refused by name instead of silently resolving to
211
- * something nobody chose.
212
- * - 'pro' DOES have a default, but not one this app chooses: a blank model
213
- * means "the `claude` CLI picks for the subscription", which is what
214
- * `--model` omitted says (engine.js sends no flag for `default`). Once a
215
- * model IS stated it must be one of claude-pro.js's PRO_MODELS aliases —
216
- * the same list the model picker offers — because the child accepts only
217
- * those four spellings, and a `provider:model` id copied from a byok task
218
- * would otherwise be handed to `claude --model` and fail there.
219
- */
220
- const MODEL_CLASSES = Object.freeze(['aegis', 'byok', 'local', 'pro']);
221
-
222
- const AEGIS_MODEL_RE = /^(?:nexus|aegis)-brain(?:-(?:smart|neo))?$/;
223
- const AEGIS_MODEL_IDS = Object.freeze(['nexus-brain', 'aegis-brain']);
224
-
225
- /** True when `id` names an AEGIS Cloud pooled-brain tier. */
226
- function isAegisModel(id) {
227
- return AEGIS_MODEL_RE.test(String(id == null ? '' : id).trim());
228
- }
229
-
230
- /**
231
- * Normalize a task's stated class to one this module (and engine.js) knows.
232
- * Blank or absent — every task queued before this field existed — defaults to
233
- * 'aegis', the only class the queue ever ran before today.
234
- */
235
- function normalizeClass(cls) {
236
- const stated = String(cls == null ? '' : cls).trim().toLowerCase();
237
- return stated || 'aegis';
238
- }
239
-
240
- /**
241
- * Whether `id` is shaped "<provider>:<model>" — the only form engine.js's
242
- * byok class accepts (splitByokModel). Not re-deriving the live provider list
243
- * here (that is a catalog call, `listModels('byok')`, this module has no
244
- * business caching) — just enough of a shape check that a malformed id is
245
- * refused at the door instead of failing splitByokModel at the server with no
246
- * context.
247
- */
248
- function looksLikeByokModel(id) {
249
- const s = String(id == null ? '' : id).trim();
250
- const i = s.indexOf(':');
251
- return i > 0 && i < s.length - 1;
252
- }
253
-
254
- /**
255
- * Why a STATED (model, class) pair cannot be queued, or '' when it can.
256
- *
257
- * `cls` defaults to 'aegis' when omitted, so every existing caller of
258
- * `modelRefusal(id)` keeps its old behaviour verbatim.
259
- */
260
- function modelRefusal(id, cls) {
261
- const stated = String(id == null ? '' : id).trim();
262
- const normalized = normalizeClass(cls);
263
- if (!MODEL_CLASSES.includes(normalized)) {
264
- return `"${cls}" is not a model class the queue serves (${MODEL_CLASSES.join('/')})`;
265
- }
266
- if (normalized === 'aegis') {
267
- if (!stated || isAegisModel(stated)) return '';
268
- return (
269
- `the autonomous queue's Aegis Cloud class runs pooled-brain models only (${DEFAULT_MODEL}, ` +
270
- `${AEGIS_MODEL_IDS.join('/')} aliases); "${stated}" is not one`
271
- );
272
- }
273
- if (normalized === 'byok') {
274
- if (!stated) return 'a byok task needs a model, as "<provider>:<model>" (pick one from /models)';
275
- if (!looksLikeByokModel(stated)) {
276
- return `"${stated}" is not a byok model id — it must be "<provider>:<model>" (pick one from /models)`;
277
- }
278
- return '';
279
- }
280
- if (normalized === 'pro') {
281
- // The subscription route. A blank model is legal and meaningful: engine.js
282
- // sends no `--model` at all for 'default', so the child resolves the pick
283
- // itself. Anything STATED must be a PRO_MODELS alias, because those four
284
- // spellings are exactly what `claude --model` accepts — a byok-style
285
- // "provider:model" copied between tasks would be handed to the child and
286
- // fail there, three stages into a drain, with the queue's own file naming
287
- // something the queue never validated.
288
- if (!stated) return '';
289
- // Required lazily: claude-pro.js is a heavy sibling (child spawn, session
290
- // files) and this module is loaded by queue.js at every CLI start. The
291
- // require is a plain sibling path with no back-require, so there is no
292
- // cycle to guard — this is about load cost, not correctness.
293
- let aliases;
294
- try {
295
- aliases = require('./claude-pro.js').PRO_MODELS;
296
- } catch {
297
- // If the alias list cannot be read we cannot validate a stated model, and
298
- // accepting it unvalidated is the exact failure this arm exists to stop.
299
- return `a pro task's model cannot be checked right now — queue it with no --model to let the claude CLI pick`;
300
- }
301
- const ids = (Array.isArray(aliases) ? aliases : []).map((m) => String(m && m.id).trim());
302
- if (ids.includes(stated.toLowerCase())) return '';
303
- return (
304
- `the autonomous queue's Pro class runs the subscription through the claude CLI, ` +
305
- `which accepts only its own model aliases (${ids.join('/')}); "${stated}" is not one`
306
- );
307
- }
308
- // normalized === 'local'
309
- if (!stated) return 'a local task needs a model — the tag of whatever is pulled into the local daemon';
310
- return '';
311
- }
312
-
313
- /** Phrase match for "work autonomously" in a prompt or a queued task. */
314
- const AUTONOMOUS_REQUEST_RE =
315
- /\bautonomously\b|\bon your own\b|\bwithout asking\b|\bend[- ]to[- ]end\b|\bno (?:more )?questions\b|\bfully autonomous\b|\bqueue it\b/i;
316
-
317
- /** True when the user is asking for unattended execution. */
318
- function isAutonomousRequest(text) {
319
- return AUTONOMOUS_REQUEST_RE.test(String(text || ''));
320
- }
321
-
322
- /** The round horizon, honouring AEGIS_AUTONOMOUS_MAX_ROUNDS. */
323
- function maxRounds(env = process.env, stated) {
324
- const n = Number.parseInt(stated, 10);
325
- if (Number.isFinite(n) && n > 0) return n;
326
- const raw = Number.parseInt((env && env.AEGIS_AUTONOMOUS_MAX_ROUNDS) || '', 10);
327
- return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_ROUNDS;
328
- }
329
-
330
- /**
331
- * Make the horizon real for the engine, then put the environment back.
332
- *
333
- * A `maxRounds` field in the chat payload would be dead code: engine.js reads
334
- * the knob from `process.env` at turn time (engine.js:1024,
335
- * `AEGIS_AUTONOMOUS_MAX_ROUNDS`). Env, unlike a payload key, is process-wide, so
336
- * the restore has to wait for a promise to settle (a turn reads the knob many
337
- * rounds after the call is made) — hence the thenable branch below.
338
- */
339
- function withRoundHorizon(rounds, env, fn) {
340
- const key = 'AEGIS_AUTONOMOUS_MAX_ROUNDS';
341
- // Both objects: the caller's env carries the path/model defaults this worker
342
- // reads, and `process.env` is where engine.js reads the round cap. A test that
343
- // passes its own env still gets the knob on that object, and a real drain gets
344
- // it where the engine actually looks.
345
- const targets = [];
346
- for (const t of [env, process.env]) {
347
- if (t && targets.indexOf(t) === -1) targets.push(t);
348
- }
349
- const saved = targets.map((t) => ({
350
- target: t,
351
- had: Object.prototype.hasOwnProperty.call(t, key),
352
- prev: t[key],
353
- }));
354
- try {
355
- for (const t of targets) t[key] = String(rounds);
356
- } catch {
357
- /* a frozen/sealed env object is the caller's choice; the payload carries it too */
358
- }
359
- const restore = () => {
360
- for (const s of saved) {
361
- try {
362
- if (s.had) s.target[key] = s.prev;
363
- else delete s.target[key];
364
- } catch {
365
- /* nothing to restore on an object we could not write */
366
- }
367
- }
368
- };
369
- let out;
370
- try {
371
- out = fn();
372
- } catch (e) {
373
- restore();
374
- throw e;
375
- }
376
- if (out && typeof out.then === 'function') {
377
- return out.then(
378
- (value) => {
379
- restore();
380
- return value;
381
- },
382
- (err) => {
383
- restore();
384
- throw err;
385
- }
386
- );
387
- }
388
- restore();
389
- return out;
390
- }
391
-
392
- /**
393
- * The model an autonomous task runs on: an explicit pick wins, then an AEGIS
394
- * Cloud pin in the environment (so a systemd timer can choose a tier), then the
395
- * pooled brain. Never the interactive session's model — a queue survives the
396
- * session that queued it, so it cannot inherit that session's choice.
397
- *
398
- * TWO DIFFERENT TREATMENTS FOR TWO DIFFERENT SOURCES, on purpose:
399
- *
400
- * - a pick that came from the TASK is returned verbatim, even when it is
401
- * wrong. Substituting a correct model for a stated one is how a queue
402
- * "runs on nexus-brain" while the file says otherwise; the caller refuses
403
- * it out loud instead (modelRefusal, queue.addTask, and the pre-flight in
404
- * runTask).
405
- * - a non-Aegis value in the ENVIRONMENT is skipped, because AEGIS_MODEL is
406
- * shared with the interactive surfaces (which run direct providers), so a
407
- * stray value there is not a statement about the queue. Refusing every
408
- * task over it would break drains for a reason that is not the task's
409
- * fault; a fallback to the pooled brain keeps the drain honest and on-cloud.
410
- */
411
- function resolveModel({ model, env, cls } = {}) {
412
- const picked = String(model || '').trim();
413
- // byok/local have no cloud default to fall back to — modelRefusal already
414
- // guaranteed a non-empty, shaped model at queue time, so the task's own pick
415
- // is the only answer for either class.
416
- if (normalizeClass(cls) !== 'aegis') return picked;
417
- if (picked) return picked;
418
- const e = env || process.env;
419
- const fromEnv = String(e.AEGIS_AUTONOMOUS_MODEL || e.AEGIS_MODEL || '').trim();
420
- return isAegisModel(fromEnv) ? fromEnv : DEFAULT_MODEL;
421
- }
422
-
423
- /**
424
- * The environment pin the queue had to ignore, or '' when there was none.
425
- *
426
- * Reported (not silent) because an operator who exported
427
- * AEGIS_AUTONOMOUS_MODEL=deepseek-v4-flash asked for a model and is not getting
428
- * it: the queue falls back to the pool, and the one place that says so is this
429
- * string, which runTask emits as a note and the desktop card shows.
430
- */
431
- function ignoredEnvModel({ model, env, cls } = {}) {
432
- if (normalizeClass(cls) !== 'aegis') return ''; // AEGIS_AUTONOMOUS_MODEL is an Aegis-only pin
433
- if (String(model || '').trim()) return ''; // the task's own pick is what counts
434
- const e = env || process.env;
435
- const fromEnv = String(e.AEGIS_AUTONOMOUS_MODEL || e.AEGIS_MODEL || '').trim();
436
- if (!fromEnv || isAegisModel(fromEnv)) return '';
437
- const which = String(e.AEGIS_AUTONOMOUS_MODEL || '').trim() ? 'AEGIS_AUTONOMOUS_MODEL' : 'AEGIS_MODEL';
438
- return `${which}="${fromEnv}" is not an Aegis Cloud model — running on ${DEFAULT_MODEL} instead`;
439
- }
440
-
441
- /**
442
- * Whether a queued task runs the pooled-brain worker fan-out (aegis1
443
- * services/pool_brain.py) or one plain turn on the same tier.
444
- *
445
- * COST IS THE REASON THIS IS OPT-IN. The fan-out is the single biggest
446
- * multiplier this app can put on a bill: pool_brain spawns up to `workers`
447
- * reasoning workers plus a synthesis pass, re-sends the task context to every
448
- * one of them, and sizes each from the same effort ladder. A 3-worker
449
- * high-effort task is therefore roughly four full reasoning calls against a
450
- * 65536-token ladder, where the identical task single-pass is one call on the
451
- * medium rung. The fan-out earns that on genuinely open-ended investigation
452
- * ("why did X regress across this repo"); it is pure waste on a task that
453
- * already names the file to edit.
454
- *
455
- * Precedence: the task's own `autonomous: true` (or `singlePass: false`, the
456
- * explicit "fan me out") wins, then AEGIS_AUTONOMOUS_FANOUT=1 in the
457
- * environment, else single pass.
458
- */
459
- function resolveFanout(item = {}, env = process.env) {
460
- const it = item || {};
461
- if (it.autonomous === true || it.singlePass === false) return true;
462
- const e = env || process.env;
463
- return /^(1|true|yes|on)$/i.test(String(e.AEGIS_AUTONOMOUS_FANOUT || '').trim());
464
- }
465
-
466
- /**
467
- * Effort rung for an unattended turn.
468
- *
469
- * The rung is a spend knob, not a quality slider: the pooled class sizes its
470
- * whole budget ladder from it (aegis1 services/pool_brain.py pass_budgets:
471
- * low/medium/high -> 16384/32768/65536 tokens TOTAL across the fan-out), and
472
- * the engine uses it for any model that reasons against its own output budget.
473
- * `high` is the right rung for a fan-out — it is what buys a synthesis pass
474
- * worth reading — but on a single pass it is a 2x over medium for budget
475
- * nobody reads, so the default follows the shape of the task rather than
476
- * always being the most expensive rung. An explicit pick (item.effort) or
477
- * AEGIS_AUTONOMOUS_EFFORT still wins outright.
478
- */
479
- function resolveEffort({ effort, env, fanout } = {}) {
480
- const e = env || process.env;
481
- const stated = String(effort || e.AEGIS_AUTONOMOUS_EFFORT || '').trim();
482
- if (stated) return stated;
483
- return fanout ? 'high' : 'medium';
484
- }
485
-
486
- /**
487
- * The operating directive injected as the autonomous turn's prompt preamble.
488
- * Ported verbatim in spirit from the upstream engine reference so both
489
- * clients behave the same; duplicated rather than vendored because the plugin
490
- * hosts no ESM build of that module.
491
- */
492
- function autonomousDirective(rounds = DEFAULT_ROUNDS) {
493
- return [
494
- '# Autonomous mode',
495
- `You are running autonomously, not in a conversation: there is no user to answer a question or approve a plan. You have up to ${rounds} tool rounds this turn; use as many as the task needs.`,
496
- 'Work the task end to end:',
497
- '1. Plan in one line, then start acting in the same turn — never end a turn on a plan.',
498
- '2. Read only what you need to make the change (no fishing through the repo).',
499
- '2b. If this demand has been made before, establish whether it was met: check recalled memory, the queue file, PLAN.md, and git history for the earlier attempt. When it was fixed and the problem is back, state how it was fixed then and why it regressed, and fix that cause — a blind re-fix is a regression, not a resolution.',
500
- '3. Make the change with Write/Edit/Bash, then VERIFY it: re-read the result and run the relevant test/command.',
501
- '4. If verification fails, fix it and verify again — loop until it passes or you are genuinely blocked.',
502
- '5. Do not ask for permission, do not hand the work back, do not stop at "let me check…".',
503
- '6. Finish with a short report: what changed (file paths), the command you ran to verify, its result, and any remaining blocker.',
504
- ].join('\n');
505
- }
506
-
507
- /**
508
- * The digest line one finished task contributes to the next task's briefing.
509
- * Deliberately tiny: task text clipped, outcome as a mark, files as basenames.
510
- */
511
- function digestLine(item, result) {
512
- const task = String(item.task || '').replace(/\s+/g, ' ').trim().slice(0, 120);
513
- const paused = Boolean(result && result.ok && result.stoppedOnRounds);
514
- const mark = paused ? '⏸' : result && result.ok ? '✓' : '✗';
515
- const files = (result && Array.isArray(result.files) && result.files.slice(0, 6)) || [];
516
- const where = files.length ? ` — touched: ${files.join(', ')}${result.files.length > files.length ? ', …' : ''}` : '';
517
- const why = !result || result.ok ? '' : ` — ${String((result && result.error) || 'failed').slice(0, 120)}`;
518
- return `- #${item.id} ${mark} ${task}${where}${why}`;
519
- }
520
-
521
- /** Keep only the last `keep` digest lines, so the briefing cannot grow forever. */
522
- function appendDigest(carry, line, { keep = 6 } = {}) {
523
- const lines = String(carry || '')
524
- .split('\n')
525
- .filter(Boolean)
526
- .concat(line);
527
- return lines.slice(-keep).join('\n');
528
- }
529
-
530
- /**
531
- * The prompt a queued task actually sends: the directive, the briefing from
532
- * earlier tasks in the same drain (when there is one), then the task itself.
533
- */
534
- function taskPrompt(item, { carry = '', rounds = DEFAULT_ROUNDS } = {}) {
535
- const parts = [autonomousDirective(rounds)];
536
- if (carry) {
537
- parts.push(
538
- '# Earlier tasks in this run\n' +
539
- 'Work already done by this queue — do not redo it, build on it:\n' +
540
- carry
541
- );
542
- }
543
- parts.push('# Task\n' + String(item.task || '').trim());
544
- return parts.join('\n\n');
545
- }
546
-
547
- /** The assistant's visible text out of an OpenAI-shaped engine result. */
548
- function assistantText(res) {
549
- if (!res || typeof res !== 'object') return '';
550
- const choice = Array.isArray(res.choices) ? res.choices[0] : null;
551
- const content = choice && choice.message ? choice.message.content : res.content;
552
- if (typeof content === 'string') return content;
553
- if (Array.isArray(content)) {
554
- return content
555
- .map((p) => (typeof p === 'string' ? p : p && typeof p.text === 'string' ? p.text : ''))
556
- .join('');
557
- }
558
- return '';
559
- }
560
-
561
- /** A readable one-liner for whatever a failed turn threw. */
562
- function errorText(err) {
563
- if (!err) return 'unknown error';
564
- if (typeof err === 'string') return err;
565
- return String(err.message || err.error || err);
566
- }
567
-
568
- /**
569
- * Build the worker.
570
- *
571
- * @param {object} opts
572
- * @param {object} opts.engine The local engine (createLocalEngine()). MUST be
573
- * constructed with the approval gate off — see the module header.
574
- * @param {object} [opts.env] Environment for paths/model defaults (tests pass a temp one).
575
- * @param {function} [opts.log] `(event) => void` progress sink; also forwarded
576
- * the turn's own `{delta}` / `{tool}` frames.
577
- * @param {object} [opts.git] Injectable git-scope (tests).
578
- * @param {function} [opts.now] Clock.
579
- */
580
- function createQueueWorker({
581
- engine,
582
- env = process.env,
583
- log = () => {},
584
- git = gitScope,
585
- now = Date.now,
586
- // May a task fan out AT ALL this session? The default preserves every host's
587
- // behaviour (a CLI drain, a systemd timer: no entitlement, no clamp), and
588
- // main.js passes the queue's entitlement gate — see
589
- // desktop/lib/local/entitlement.js and Phase 4 of
590
- // docs/upgrade-conversion-plan.md.
591
- //
592
- // This exists because the fan-out is otherwise reachable around the desktop's
593
- // IPC gate: a task queued by the CLI or written into queue.jsonl by hand
594
- // carries `singlePass: false`, and main.js had already accepted it long
595
- // before anyone asked about entitlement. Refusing the whole task would be
596
- // worse than the leak (the free tier keeps working — that is a promise), so
597
- // the request is honoured as a SINGLE PASS and said out loud via a `note`
598
- // frame: the run is clamped, never silently different from what the card
599
- // shows.
600
- canFanOut = () => true,
601
- } = {}) {
602
- if (!engine || typeof engine.chat !== 'function') {
603
- throw new Error('autonomous: a local engine with chat() is required');
604
- }
605
- const emit = (event) => {
606
- try {
607
- log(event);
608
- } catch {
609
- /* a progress sink that throws (a closed stdout, a destroyed window) must
610
- never take the task down with it — the work is the point, not the log */
611
- }
612
- };
613
-
614
- /** `canFanOut` is host-supplied, so it is treated like any other injected
615
- * seam: a predicate that throws must not abort a drain — it fails CLOSED
616
- * (no fan-out), because the alternative is spending the multiplier the gate
617
- * exists to withhold. */
618
- const safeCanFanOut = () => {
619
- try {
620
- return canFanOut() !== false;
621
- } catch {
622
- return false;
623
- }
624
- };
625
-
626
- /**
627
- * Run ONE queued task. Never throws: a failed task is data (so the drain can
628
- * decide whether to continue), not an exception that aborts the queue.
629
- */
630
- async function runTask(item, { carry = '', commit } = {}) {
631
- const cwd = item.cwd || process.cwd();
632
- // The task's own (model, class) pair checked BEFORE the turn, not at the
633
- // server. An item whose model does not belong to its class (a hand-edited
634
- // queue file, a `--model` the CLI accepted before this rule existed,
635
- // another host's older build) would otherwise go out under a transport
636
- // that does not serve it: billed work if it happens to be a per-provider
637
- // spelling, an opaque server error otherwise, and for 'pro' a `claude
638
- // --model` that the child rejects. Failing here names the model and the
639
- // spellings that class accepts, and costs nothing.
640
- //
641
- // "Aegis Cloud or nothing" was this comment's old claim, and it stopped
642
- // being true when byok/local were added (9eeef09) — modelRefusal is what
643
- // actually enforces the rule now, per class, and it runs for all four.
644
- const cls = normalizeClass(item.class);
645
- const refusal = modelRefusal(item.model, cls);
646
- if (refusal) {
647
- const failed = { ok: false, error: refusal, model: item.model, class: cls, ms: 0 };
648
- emit({ type: 'finish', taskId: item.id, ok: false, result: failed });
649
- return failed;
650
- }
651
- const model = resolveModel({ model: item.model, env, cls });
652
- const ignored = ignoredEnvModel({ model: item.model, env, cls });
653
- if (ignored) emit({ type: 'note', taskId: item.id, note: ignored });
654
- // The pooled-brain fan-out is an Aegis Cloud mechanism (aegis1
655
- // services/pool_brain.py) — engine.js itself only honours `autonomous`
656
- // under `cls === 'aegis'` (engine.js:1524), so a byok/local task asking for
657
- // it is forced to a plain single pass HERE rather than relying on that
658
- // silent no-op, which would otherwise size the task's effort/round
659
- // reporting as if a fan-out it never got had been granted.
660
- const fanoutAsked = cls === 'aegis' && resolveFanout(item, env);
661
- // The clamp. `canFanOut()` is the entitlement answer (true everywhere
662
- // except a non-Pro desktop session), and it can only ever take a fan-out
663
- // AWAY: a task the session is not entitled to fan out runs as one plain
664
- // turn on the same tier, exactly like a `singlePass` task.
665
- const fanout = fanoutAsked && safeCanFanOut();
666
- if (fanoutAsked && !fanout) {
667
- emit({
668
- type: 'note',
669
- taskId: item.id,
670
- note:
671
- 'fan-out needs Pro (the cloud drain that keeps running after you close ' +
672
- 'the laptop) — this task ran as a single pass',
673
- });
674
- }
675
- const effort = resolveEffort({ effort: item.effort, env, fanout });
676
- const rounds = maxRounds(env, item.maxRounds);
677
- // Approval requests have no one to answer them here; see the header.
678
- let approvalAsked = null;
679
- let doneRounds = 0;
680
- // What THIS task's tool layer wrote. The commit uses it as the only
681
- // positive attribution available: a path in here that also differs from
682
- // the pre-task snapshot is ours, and everything else dirty is left alone
683
- // (see the module header, and git-scope.js's scopedCommit).
684
- const written = new Set();
685
- const onDelta = (chunk) => {
686
- if (!chunk || typeof chunk !== 'object') return;
687
- if (chunk.approval) {
688
- approvalAsked = chunk.approval;
689
- return;
690
- }
691
- if (chunk.tool) {
692
- if (chunk.tool.phase === 'done') {
693
- doneRounds += 1;
694
- // Recorded on `done` and only when it succeeded: "this path is mine"
695
- // is true once the write actually landed, and a refused or failed
696
- // write must not claim a path a concurrent writer is editing.
697
- if (WRITE_TOOLS.has(chunk.tool.name) && chunk.tool.ok !== false) {
698
- const p = writtenPath(chunk.tool);
699
- if (p) written.add(p);
700
- }
701
- }
702
- emit({ type: 'tool', taskId: item.id, tool: chunk.tool });
703
- return;
704
- }
705
- if (typeof chunk.delta === 'string') emit({ type: 'delta', taskId: item.id, text: chunk.delta });
706
- else if (typeof chunk.reasoning === 'string') emit({ type: 'reasoning', taskId: item.id, text: chunk.reasoning });
707
- };
708
-
709
- // Snapshot BEFORE the turn: without it there is no way to tell our edits
710
- // from a concurrent agent's, and scopedCommit refuses to sweep rather than
711
- // guess.
712
- const wantCommit = commit === undefined ? Boolean(item.commit) : Boolean(commit);
713
- const before = wantCommit ? safe(() => git.gitStatusSnapshot(cwd), null) : null;
714
-
715
- emit({ type: 'start', taskId: item.id, model, class: cls, cwd, rounds, fanout, effort });
716
- const started = now();
717
- let result;
718
- try {
719
- const res = await withRoundHorizon(rounds, env, () =>
720
- engine.chat(
721
- {
722
- class: cls,
723
- model,
724
- prompt: taskPrompt(item, { carry, rounds }),
725
- // The pooled-brain fan-out ("fan out this turn" in the GUI chat
726
- // header, and opt-in here): the server fans the round out to
727
- // several reasoning workers and synthesises. It costs about
728
- // workers+1 full reasoning calls, so it travels only when the task
729
- // asked for it — see resolveFanout above. A `singlePass` task is
730
- // the default for exactly that reason; the retry/write-up passes in
731
- // the engine send `brain: false` for the same one-call reason.
732
- autonomous: fanout,
733
- // THE OPT-OUT HAS TO BE SAID OUT LOUD, or the clamp above is
734
- // decoration. `autonomous: false` does NOT reach the wire as a
735
- // "no fan-out": engine.js derives its brain flag as
736
- // `opts.singlePass ? false : opts.autonomous ? true : undefined`, so
737
- // false-and-not-singlePass evaluates to `undefined`, and an absent
738
- // `brain` means "leave the model id's own default alone". The model
739
- // here IS `nexus-brain`, and aegis1 services/pool_brain.py
740
- // parse_brain_request enables the fan-out when
741
- // `is_brain_model(spec)` — no flag or worker count required:
742
- //
743
- // enabled = not flag_off and (is_brain_model(spec) or flag_on or ...)
744
- //
745
- // So a clamped task went out asking for the full workers+1
746
- // fan-out and got it, while the log said it ran as a single pass.
747
- // `brain: false` is the only instruction that outranks the model id
748
- // (pool_brain's own docstring: "the only way to ask for one provider
749
- // call on a brain id"), and `singlePass: true` is how a caller
750
- // produces it. This also fixes the plain `--single-pass` task, which
751
- // never reached the wire as one for the same reason.
752
- singlePass: !fanout,
753
- effort,
754
- workers: fanout ? item.workers || undefined : undefined,
755
- // The turn's working directory rides on `env`: engine.js reads the
756
- // tool loop's cwd from envFor(payload), so a top-level `cwd` field
757
- // is a directory the engine would ignore and every tool would run
758
- // in the host's own process.cwd() instead of the task's.
759
- env: { cwd },
760
- maxRounds: rounds,
761
- sessionId: sessionIdFor(item.id),
762
- stream: true,
763
- },
764
- onDelta
765
- )
766
- );
767
- const output = assistantText(res);
768
- result = {
769
- ok: true,
770
- output,
771
- usage: (res && res.usage) || null,
772
- stoppedOnRounds: Boolean(res && res.stoppedOnRounds),
773
- rounds: doneRounds || undefined,
774
- };
775
- if (approvalAsked) {
776
- // A gate that is up in an unattended run is a bug in the caller, and
777
- // it is better seen than hung on: the tool round cannot proceed past it,
778
- // and a card nobody can click is a task that never finishes.
779
- result.ok = false;
780
- result.error =
781
- `tool approval was requested for "${approvalAsked.tool || approvalAsked.name || 'a tool'}" ` +
782
- 'with no one to answer it — construct the queue engine with approvals disabled ' +
783
- '(getConfirmMode: () => false)';
784
- }
785
- } catch (e) {
786
- result = { ok: false, error: errorText(e) };
787
- }
788
- result.ms = Math.max(0, now() - started);
789
-
790
- if (wantCommit) {
791
- result.commit = safe(
792
- () =>
793
- git.scopedCommit(cwd, {
794
- message: commitMessage(item),
795
- before,
796
- // Positive attribution: the paths this task's tool layer reported
797
- // writing. Without it scopedCommit refuses to stage anything but
798
- // the pre-task-dirty-and-still-identical set, which cannot see a
799
- // concurrent writer editing mid-task (see the module header).
800
- written: [...written],
801
- }),
802
- { ok: false, error: 'git-scope unavailable' }
803
- );
804
- result.files = committedPaths(result.commit, written);
805
- }
806
-
807
- emit({ type: 'finish', taskId: item.id, ok: result.ok, result });
808
- return result;
809
- }
810
-
811
- /** `git-scope` is filesystem/git work: a throw there must not lose the task's outcome. */
812
- function safe(fn, fallback) {
813
- try {
814
- return fn();
815
- } catch {
816
- return fallback;
817
- }
818
- }
819
-
820
- /**
821
- * The paths this task changed: exactly what scopedCommit staged, which is
822
- * (written by this task) ∩ (differs from the pre-task snapshot). Reported
823
- * rather than recomputed from a fresh snapshot — a snapshot taken after the
824
- * commit cannot tell our work from a peer's next edit, and that difference is
825
- * the whole point of the attribution rule.
826
- */
827
- function committedPaths(commit, written) {
828
- if (!commit || commit.error) return [];
829
- if (Array.isArray(commit.paths)) return commit.paths;
830
- // No commit was made (skipped): report what we know we wrote, so a task's
831
- // digest still names the work even when the tree had nothing to commit.
832
- return [...written];
833
- }
834
-
835
- /**
836
- * Drain pending tasks, one at a time, until the queue is empty (or `max` is
837
- * reached). Rebases on the file between tasks, so a task added mid-drain —
838
- * by another window, another host, or a `reconcile` — is picked up in the
839
- * same run instead of waiting for the next one.
840
- */
841
- async function proceed({ commit, max = 0, stopOnError = false, carry = '' } = {}) {
842
- const lock = queue.acquireLock(env);
843
- if (!lock.ok) {
844
- emit({ type: 'locked', holder: lock.holder });
845
- return { ok: false, locked: true, holder: lock.holder, ran: [], carry };
846
- }
847
- const ran = [];
848
- try {
849
- for (;;) {
850
- if (max > 0 && ran.length >= max) break;
851
- // Re-read the FILE every iteration, never a snapshot taken before the
852
- // loop: a task added mid-drain (another window, another host, this run's
853
- // own `reconcile`) has to be picked up by the same drain, and a stale
854
- // in-memory list is exactly how it would be missed.
855
- const items = queue.loadQueue(env);
856
- const recovered = queue.recoverStale(items);
857
- // Persisted, not just fixed in memory: without this write the items
858
- // stay `running` in the file, and the next drain re-pends them all over
859
- // again (a task whose worker was killed would look alive forever to
860
- // every other reader).
861
- if (recovered.length) {
862
- queue.saveQueue(env, items);
863
- emit({ type: 'recovered', ids: recovered });
864
- }
865
- const next = queue.pending(items)[0];
866
- if (!next) break;
867
- const outcome = await runOne(next, { commit, carry });
868
- carry = outcome.carry;
869
- ran.push(outcome);
870
- if (!outcome.ok && stopOnError) break;
871
- }
872
- } finally {
873
- queue.releaseLock(env);
874
- }
875
- return { ok: true, ran, carry };
876
- }
877
-
878
- /** Claim one task from the file, run it, write the outcome back. */
879
- async function runOne(item, { commit, carry = '' } = {}) {
880
- const items = queue.loadQueue(env);
881
- const claimed = queue.markRunning(items, item.id, { now: now() });
882
- if (!claimed) return { ok: false, error: `unknown task #${item.id}`, carry };
883
- const priorRoundStops = Number(claimed.roundStops) || 0;
884
- queue.saveQueue(env, items);
885
-
886
- const raw = await runTask(claimed, { carry, commit });
887
-
888
- // A task that hit its tool-round horizon has NOT finished — engine.js's
889
- // session ledger (session-rounds.js) is holding the rest of the work
890
- // under this task's stable session id (sessionIdFor(item.id)), ready to
891
- // inject a continuation preamble the moment this item is dispatched
892
- // again. Settling it 'done' here (the old behavior) threw that away: the
893
- // queue believed the task was finished, so nothing ever sent the next
894
- // turn that would have consumed the resume, and a human had to notice
895
- // the output was incomplete and re-queue the whole task from scratch.
896
- //
897
- // Left 'pending' instead, so proceed()'s own drain loop picks it straight
898
- // back up — unless it has now failed to converge MAX_ROUND_STOPS times in
899
- // a row, at which point looping on it forever (an unattended proceed()
900
- // with no --max has no other cap at all) is worse than a visible error.
901
- const hitRoundCap = Boolean(raw.ok && raw.stoppedOnRounds);
902
- const roundStops = hitRoundCap ? priorRoundStops + 1 : 0;
903
- const exhausted = hitRoundCap && roundStops > MAX_ROUND_STOPS;
904
- const result = exhausted
905
- ? {
906
- ...raw,
907
- ok: false,
908
- error:
909
- `stopped at its tool-round horizon ${roundStops} times in a row without finishing — ` +
910
- 'raise AEGIS_AUTONOMOUS_MAX_ROUNDS or split the task into smaller ones',
911
- }
912
- : raw;
913
- const status = exhausted ? 'error' : hitRoundCap ? 'pending' : result.ok ? 'done' : 'error';
914
-
915
- const after = queue.loadQueue(env);
916
- queue.settle(after, claimed.id, {
917
- status,
918
- result: {
919
- ok: result.ok,
920
- output: result.output || '',
921
- usage: result.usage || null,
922
- ms: result.ms,
923
- commit: result.commit || null,
924
- files: result.files || [],
925
- },
926
- error: result.ok ? null : result.error,
927
- now: now(),
928
- });
929
- const settled = queue.findTask(after, claimed.id);
930
- if (settled) settled.roundStops = roundStops;
931
- queue.saveQueue(env, after);
932
- queue.appendRun(env, {
933
- id: claimed.id,
934
- task: claimed.task,
935
- cwd: claimed.cwd,
936
- model: resolveModel({ model: claimed.model, env }),
937
- status: status === 'pending' ? 'stopped' : status,
938
- at: new Date(now()).toISOString(),
939
- ms: result.ms,
940
- usage: result.usage || null,
941
- files: result.files || [],
942
- error: result.ok ? null : result.error,
943
- });
944
- return { ...result, id: claimed.id, carry: appendDigest(carry, digestLine(claimed, result)) };
945
- }
946
-
947
- /**
948
- * Queue the next unfinished PLAN.md phase (and optionally work it straight
949
- * away). The phase text is looked up rather than pasted, so the task points
950
- * the model at the spec instead of paraphrasing it — a paraphrase in the
951
- * prompt is a second spec that can disagree with the file.
952
- */
953
- async function reconcile({ cwd = process.cwd(), auto = false, commit, max = 0, stopOnError = false } = {}) {
954
- const plan = queue.reconcilePlan(cwd, { write: true });
955
- if (!plan.ok) return { ok: false, error: plan.reason };
956
- if (plan.healed && plan.healed.changed) {
957
- emit({ type: 'healed', phases: plan.healed.added });
958
- }
959
- if (plan.next == null) return { ok: true, exhausted: true };
960
-
961
- const marker = `Work Phase ${plan.next} from PLAN.md`;
962
- const items = queue.loadQueue(env);
963
- const existing = items.find(
964
- (i) => i.cwd === cwd && String(i.task).startsWith(marker) && i.status !== 'done'
965
- );
966
- if (existing) {
967
- emit({ type: 'already-queued', phase: plan.next, id: existing.id, status: existing.status });
968
- if (!auto) return { ok: true, phase: plan.next, id: existing.id, existing: true };
969
- } else {
970
- const item = queue.addTask(env, {
971
- task:
972
- `${marker} ("${plan.title}") at ${cwd}. Read the full "## Phase ${plan.next}" section in ` +
973
- 'PLAN.md at the repo root for the spec, exit criteria and constraints, and implement it ' +
974
- 'exactly as scoped there. Keep the repo\'s checks green (`npm run check`, plus that ' +
975
- `package's tests). When every exit criterion is met, mark the "## Phase ${plan.next}" ` +
976
- 'heading with ✅ in PLAN.md and update its line in the top Status checklist.',
977
- cwd,
978
- source: 'reconcile',
979
- model: resolveModel({ env }),
980
- });
981
- emit({ type: 'queued', phase: plan.next, id: item.id, title: plan.title });
982
- }
983
- if (!auto) return { ok: true, phase: plan.next, title: plan.title };
984
- const drained = await proceed({ commit, max, stopOnError });
985
- return { ok: true, phase: plan.next, title: plan.title, ...drained };
986
- }
987
-
988
- /**
989
- * The engine's session id for one task. Deterministic, because the engine
990
- * keeps its AbortController under this key (engine.js cancel()), so this is
991
- * the handle both writing the outcome and stopping the turn go through.
992
- */
993
- const sessionIdFor = (id) => `queue-${id}`;
994
-
995
- /**
996
- * Stop the task currently running. The engine owns cancellation through the
997
- * session id it registered, so this delegates instead of keeping a second
998
- * controller — a locally-held AbortSignal would be one the engine never reads.
999
- */
1000
- function cancel(id) {
1001
- if (id == null) return { ok: false, error: 'cancel needs a task id' };
1002
- if (typeof engine.cancel !== 'function') return { ok: false, error: 'this engine cannot cancel a turn' };
1003
- const res = engine.cancel(sessionIdFor(id));
1004
- return { ok: Boolean(res && res.ok), sessionId: sessionIdFor(id) };
1005
- }
1006
-
1007
- return { runTask, runOne, proceed, reconcile, cancel, sessionIdFor, resolveModel: (o) => resolveModel({ ...o, env }) };
1008
- }
1009
-
1010
- /** One-line commit message for a task: its first line, clipped, and labelled. */
1011
- function commitMessage(item) {
1012
- const first = String(item.task || 'queued task').split('\n')[0].replace(/\s+/g, ' ').trim();
1013
- return `autonomous: ${first.slice(0, 66)}${first.length > 66 ? '…' : ''}`;
1014
- }
1015
-
1016
- module.exports = {
1017
- DEFAULT_MODEL,
1018
- DEFAULT_ROUNDS,
1019
- MAX_ROUND_STOPS,
1020
- MODEL_CLASSES,
1021
- AEGIS_MODEL_IDS,
1022
- isAegisModel,
1023
- normalizeClass,
1024
- looksLikeByokModel,
1025
- modelRefusal,
1026
- WRITE_TOOLS,
1027
- writtenPath,
1028
- isAutonomousRequest,
1029
- maxRounds,
1030
- withRoundHorizon,
1031
- DEFAULT_AUTO_CONTINUES,
1032
- autoContinueLimit,
1033
- autoRoundsDefault,
1034
- autoContinuePlan,
1035
- resolveModel,
1036
- ignoredEnvModel,
1037
- resolveEffort,
1038
- resolveFanout,
1039
- autonomousDirective,
1040
- taskPrompt,
1041
- appendDigest,
1042
- digestLine,
1043
- assistantText,
1044
- errorText,
1045
- commitMessage,
1046
- createQueueWorker,
1047
- };
3
+ "use strict";const queue=require("./queue.js"),gitScope=require("./git-scope.js"),DEFAULT_ROUNDS=40,MAX_ROUND_STOPS=3,WRITE_TOOLS=new Set(["writeFile","editFile"]),DEFAULT_AUTO_CONTINUES=3;function autoContinueLimit(e=process.env){const t=Number.parseInt(e&&e.AEGIS_AUTO_CONTINUE_MAX,10);return Number.isFinite(t)&&t>0?t:3}const AUTO_ROUNDS_OFF=new Set(["0","false","off","no"]);function autoRoundsDefault(e=process.env){const t=e&&e.AEGIS_AUTO_ROUNDS;if(null==t)return!0;const o=String(t).trim().toLowerCase();return!o||!AUTO_ROUNDS_OFF.has(o)}function autoContinuePlan({on:e=!1,used:t=0,limit:o=3}={}){const n=Number.isFinite(o)&&o>0?Math.floor(o):3,r=Number.isFinite(t)&&t>0?Math.floor(t):0;return e?r>=n?{auto:!1,used:0,cap:n}:{auto:!0,used:r+1,cap:n}:{auto:!1,used:r,cap:n}}function writtenPath(e){const t=e&&e.args||{},o=t.file_path||t.path;return o?String(o):""}const DEFAULT_MODEL="nexus-brain",MODEL_CLASSES=Object.freeze(["aegis","byok","local","pro"]),AEGIS_MODEL_RE=/^(?:nexus|aegis)-brain(?:-(?:smart|neo))?$/,AEGIS_MODEL_IDS=Object.freeze(["nexus-brain","aegis-brain"]);function isAegisModel(e){return AEGIS_MODEL_RE.test(String(null==e?"":e).trim())}function normalizeClass(e){return String(null==e?"":e).trim().toLowerCase()||"aegis"}function looksLikeByokModel(e){const t=String(null==e?"":e).trim(),o=t.indexOf(":");return o>0&&o<t.length-1}function modelRefusal(e,t){const o=String(null==e?"":e).trim(),n=normalizeClass(t);if(!MODEL_CLASSES.includes(n))return`"${t}" is not a model class the queue serves (${MODEL_CLASSES.join("/")})`;if("aegis"===n)return!o||isAegisModel(o)?"":`the autonomous queue's Aegis Cloud class runs pooled-brain models only (${DEFAULT_MODEL}, ${AEGIS_MODEL_IDS.join("/")} aliases); "${o}" is not one`;if("byok"===n)return o?looksLikeByokModel(o)?"":`"${o}" is not a byok model id — it must be "<provider>:<model>" (pick one from /models)`:'a byok task needs a model, as "<provider>:<model>" (pick one from /models)';if("pro"===n){if(!o)return"";let e;try{e=require("./claude-pro.js").PRO_MODELS}catch{return"a pro task's model cannot be checked right now — queue it with no --model to let the claude CLI pick"}const t=(Array.isArray(e)?e:[]).map((e=>String(e&&e.id).trim()));return t.includes(o.toLowerCase())?"":`the autonomous queue's Pro class runs the subscription through the claude CLI, which accepts only its own model aliases (${t.join("/")}); "${o}" is not one`}return o?"":"a local task needs a model — the tag of whatever is pulled into the local daemon"}const AUTONOMOUS_REQUEST_RE=/\bautonomously\b|\bon your own\b|\bwithout asking\b|\bend[- ]to[- ]end\b|\bno (?:more )?questions\b|\bfully autonomous\b|\bqueue it\b/i;function isAutonomousRequest(e){return AUTONOMOUS_REQUEST_RE.test(String(e||""))}function maxRounds(e=process.env,t){const o=Number.parseInt(t,10);if(Number.isFinite(o)&&o>0)return o;const n=Number.parseInt(e&&e.AEGIS_AUTONOMOUS_MAX_ROUNDS||"",10);return Number.isFinite(n)&&n>0?n:DEFAULT_ROUNDS}function withRoundHorizon(e,t,o){const n="AEGIS_AUTONOMOUS_MAX_ROUNDS",r=[];for(const e of[t,process.env])e&&-1===r.indexOf(e)&&r.push(e);const s=r.map((e=>({target:e,had:Object.prototype.hasOwnProperty.call(e,n),prev:e[n]})));try{for(const t of r)t[n]=String(e)}catch{}const i=()=>{for(const e of s)try{e.had?e.target[n]=e.prev:delete e.target[n]}catch{}};let a;try{a=o()}catch(e){throw i(),e}return a&&"function"==typeof a.then?a.then((e=>(i(),e)),(e=>{throw i(),e})):(i(),a)}function resolveModel({model:e,env:t,cls:o}={}){const n=String(e||"").trim();if("aegis"!==normalizeClass(o))return n;if(n)return n;const r=t||process.env,s=String(r.AEGIS_AUTONOMOUS_MODEL||r.AEGIS_MODEL||"").trim();return isAegisModel(s)?s:DEFAULT_MODEL}function ignoredEnvModel({model:e,env:t,cls:o}={}){if("aegis"!==normalizeClass(o))return"";if(String(e||"").trim())return"";const n=t||process.env,r=String(n.AEGIS_AUTONOMOUS_MODEL||n.AEGIS_MODEL||"").trim();return!r||isAegisModel(r)?"":`${String(n.AEGIS_AUTONOMOUS_MODEL||"").trim()?"AEGIS_AUTONOMOUS_MODEL":"AEGIS_MODEL"}="${r}" is not an Aegis Cloud model — running on ${DEFAULT_MODEL} instead`}function resolveFanout(e={},t=process.env){const o=e||{};if(!0===o.autonomous||!1===o.singlePass)return!0;const n=t||process.env;return/^(1|true|yes|on)$/i.test(String(n.AEGIS_AUTONOMOUS_FANOUT||"").trim())}function resolveEffort({effort:e,env:t,fanout:o}={}){const n=t||process.env;return String(e||n.AEGIS_AUTONOMOUS_EFFORT||"").trim()||(o?"high":"medium")}function autonomousDirective(e=DEFAULT_ROUNDS){return["# Autonomous mode",`You are running autonomously, not in a conversation: there is no user to answer a question or approve a plan. You have up to ${e} tool rounds this turn; use as many as the task needs.`,"Work the task end to end:","1. Plan in one line, then start acting in the same turn — never end a turn on a plan.","2. Read only what you need to make the change (no fishing through the repo).","2b. If this demand has been made before, establish whether it was met: check recalled memory, the queue file, PLAN.md, and git history for the earlier attempt. When it was fixed and the problem is back, state how it was fixed then and why it regressed, and fix that cause — a blind re-fix is a regression, not a resolution.","3. Make the change with Write/Edit/Bash, then VERIFY it: re-read the result and run the relevant test/command.","4. If verification fails, fix it and verify again — loop until it passes or you are genuinely blocked.",'5. Do not ask for permission, do not hand the work back, do not stop at "let me check…".',"6. Finish with a short report: what changed (file paths), the command you ran to verify, its result, and any remaining blocker."].join("\n")}function digestLine(e,t){const o=String(e.task||"").replace(/\s+/g," ").trim().slice(0,120),n=Boolean(t&&t.ok&&t.stoppedOnRounds)?"⏸":t&&t.ok?"✓":"✗",r=t&&Array.isArray(t.files)&&t.files.slice(0,6)||[],s=r.length?` — touched: ${r.join(", ")}${t.files.length>r.length?", …":""}`:"",i=!t||t.ok?"":` — ${String(t&&t.error||"failed").slice(0,120)}`;return`- #${e.id} ${n} ${o}${s}${i}`}function appendDigest(e,t,{keep:o=6}={}){return String(e||"").split("\n").filter(Boolean).concat(t).slice(-o).join("\n")}function taskPrompt(e,{carry:t="",rounds:o=DEFAULT_ROUNDS}={}){const n=[autonomousDirective(o)];return t&&n.push("# Earlier tasks in this run\nWork already done by this queue — do not redo it, build on it:\n"+t),n.push("# Task\n"+String(e.task||"").trim()),n.join("\n\n")}function assistantText(e){if(!e||"object"!=typeof e)return"";const t=Array.isArray(e.choices)?e.choices[0]:null,o=t&&t.message?t.message.content:e.content;return"string"==typeof o?o:Array.isArray(o)?o.map((e=>"string"==typeof e?e:e&&"string"==typeof e.text?e.text:"")).join(""):""}function errorText(e){return e?"string"==typeof e?e:String(e.message||e.error||e):"unknown error"}function createQueueWorker({engine:e,env:t=process.env,log:o=(()=>{}),git:n=gitScope,now:r=Date.now,canFanOut:s=(()=>!0)}={}){if(!e||"function"!=typeof e.chat)throw new Error("autonomous: a local engine with chat() is required");const i=e=>{try{o(e)}catch{}},a=()=>{try{return!1!==s()}catch{return!1}};async function u(o,{carry:s="",commit:u}={}){const c=o.cwd||process.cwd(),d=normalizeClass(o.class),h=modelRefusal(o.model,d);if(h){const e={ok:!1,error:h,model:o.model,class:d,ms:0};return i({type:"finish",taskId:o.id,ok:!1,result:e}),e}const p=resolveModel({model:o.model,env:t,cls:d}),f=ignoredEnvModel({model:o.model,env:t,cls:d});f&&i({type:"note",taskId:o.id,note:f});const g="aegis"===d&&resolveFanout(o,t),k=g&&a();g&&!k&&i({type:"note",taskId:o.id,note:"fan-out needs Pro (the cloud drain that keeps running after you close the laptop) — this task ran as a single pass"});const O=resolveEffort({effort:o.effort,env:t,fanout:k}),S=maxRounds(t,o.maxRounds);let y=null,E=0;const A=new Set,_=e=>{if(e&&"object"==typeof e)if(e.approval)y=e.approval;else if(e.tool){if("done"===e.tool.phase&&(E+=1,WRITE_TOOLS.has(e.tool.name)&&!1!==e.tool.ok)){const t=writtenPath(e.tool);t&&A.add(t)}i({type:"tool",taskId:o.id,tool:e.tool})}else"string"==typeof e.delta?i({type:"delta",taskId:o.id,text:e.delta}):"string"==typeof e.reasoning&&i({type:"reasoning",taskId:o.id,text:e.reasoning})},v=void 0===u?Boolean(o.commit):Boolean(u),M=v?l((()=>n.gitStatusSnapshot(c)),null):null;i({type:"start",taskId:o.id,model:p,class:d,cwd:c,rounds:S,fanout:k,effort:O});const w=r();let D;try{const n=await withRoundHorizon(S,t,(()=>e.chat({class:d,model:p,prompt:taskPrompt(o,{carry:s,rounds:S}),autonomous:k,singlePass:!k,effort:O,workers:k&&o.workers||void 0,env:{cwd:c},maxRounds:S,sessionId:m(o.id),stream:!0},_)));D={ok:!0,output:assistantText(n),usage:n&&n.usage||null,stoppedOnRounds:Boolean(n&&n.stoppedOnRounds),rounds:E||void 0},y&&(D.ok=!1,D.error=`tool approval was requested for "${y.tool||y.name||"a tool"}" with no one to answer it — construct the queue engine with approvals disabled (getConfirmMode: () => false)`)}catch(e){D={ok:!1,error:errorText(e)}}return D.ms=Math.max(0,r()-w),v&&(D.commit=l((()=>n.scopedCommit(c,{message:commitMessage(o),before:M,written:[...A]})),{ok:!1,error:"git-scope unavailable"}),D.files=function(e,t){return!e||e.error?[]:Array.isArray(e.paths)?e.paths:[...t]}(D.commit,A)),i({type:"finish",taskId:o.id,ok:D.ok,result:D}),D}function l(e,t){try{return e()}catch{return t}}async function c({commit:e,max:o=0,stopOnError:n=!1,carry:r=""}={}){const s=queue.acquireLock(t);if(!s.ok)return i({type:"locked",holder:s.holder}),{ok:!1,locked:!0,holder:s.holder,ran:[],carry:r};const a=[];try{for(;!(o>0&&a.length>=o);){const o=queue.loadQueue(t),s=queue.recoverStale(o);s.length&&(queue.saveQueue(t,o),i({type:"recovered",ids:s}));const u=queue.pending(o)[0];if(!u)break;const l=await d(u,{commit:e,carry:r});if(r=l.carry,a.push(l),!l.ok&&n)break}}finally{queue.releaseLock(t)}return{ok:!0,ran:a,carry:r}}async function d(e,{commit:o,carry:n=""}={}){const s=queue.loadQueue(t),i=queue.markRunning(s,e.id,{now:r()});if(!i)return{ok:!1,error:`unknown task #${e.id}`,carry:n};const a=Number(i.roundStops)||0;queue.saveQueue(t,s);const l=await u(i,{carry:n,commit:o}),c=Boolean(l.ok&&l.stoppedOnRounds),d=c?a+1:0,m=c&&d>3,h=m?{...l,ok:!1,error:`stopped at its tool-round horizon ${d} times in a row without finishing — raise AEGIS_AUTONOMOUS_MAX_ROUNDS or split the task into smaller ones`}:l,p=m?"error":c?"pending":h.ok?"done":"error",f=queue.loadQueue(t);queue.settle(f,i.id,{status:p,result:{ok:h.ok,output:h.output||"",usage:h.usage||null,ms:h.ms,commit:h.commit||null,files:h.files||[]},error:h.ok?null:h.error,now:r()});const g=queue.findTask(f,i.id);return g&&(g.roundStops=d),queue.saveQueue(t,f),queue.appendRun(t,{id:i.id,task:i.task,cwd:i.cwd,model:resolveModel({model:i.model,env:t}),status:"pending"===p?"stopped":p,at:new Date(r()).toISOString(),ms:h.ms,usage:h.usage||null,files:h.files||[],error:h.ok?null:h.error}),{...h,id:i.id,carry:appendDigest(n,digestLine(i,h))}}const m=e=>`queue-${e}`;return{runTask:u,runOne:d,proceed:c,reconcile:async function({cwd:e=process.cwd(),auto:o=!1,commit:n,max:r=0,stopOnError:s=!1}={}){const a=queue.reconcilePlan(e,{write:!0});if(!a.ok)return{ok:!1,error:a.reason};if(a.healed&&a.healed.changed&&i({type:"healed",phases:a.healed.added}),null==a.next)return{ok:!0,exhausted:!0};const u=`Work Phase ${a.next} from PLAN.md`,l=queue.loadQueue(t).find((t=>t.cwd===e&&String(t.task).startsWith(u)&&"done"!==t.status));if(l){if(i({type:"already-queued",phase:a.next,id:l.id,status:l.status}),!o)return{ok:!0,phase:a.next,id:l.id,existing:!0}}else{const o=queue.addTask(t,{task:`${u} ("${a.title}") at ${e}. Read the full "## Phase ${a.next}" section in PLAN.md at the repo root for the spec, exit criteria and constraints, and implement it exactly as scoped there. Keep the repo's checks green (\`npm run check\`, plus that package's tests). When every exit criterion is met, mark the "## Phase ${a.next}" heading with ✅ in PLAN.md and update its line in the top Status checklist.`,cwd:e,source:"reconcile",model:resolveModel({env:t})});i({type:"queued",phase:a.next,id:o.id,title:a.title})}if(!o)return{ok:!0,phase:a.next,title:a.title};const d=await c({commit:n,max:r,stopOnError:s});return{ok:!0,phase:a.next,title:a.title,...d}},cancel:function(t){if(null==t)return{ok:!1,error:"cancel needs a task id"};if("function"!=typeof e.cancel)return{ok:!1,error:"this engine cannot cancel a turn"};const o=e.cancel(m(t));return{ok:Boolean(o&&o.ok),sessionId:m(t)}},sessionIdFor:m,resolveModel:e=>resolveModel({...e,env:t})}}function commitMessage(e){const t=String(e.task||"queued task").split("\n")[0].replace(/\s+/g," ").trim();return`autonomous: ${t.slice(0,66)}${t.length>66?"…":""}`}module.exports={DEFAULT_MODEL:DEFAULT_MODEL,DEFAULT_ROUNDS:DEFAULT_ROUNDS,MAX_ROUND_STOPS:3,MODEL_CLASSES:MODEL_CLASSES,AEGIS_MODEL_IDS:AEGIS_MODEL_IDS,isAegisModel:isAegisModel,normalizeClass:normalizeClass,looksLikeByokModel:looksLikeByokModel,modelRefusal:modelRefusal,WRITE_TOOLS:WRITE_TOOLS,writtenPath:writtenPath,isAutonomousRequest:isAutonomousRequest,maxRounds:maxRounds,withRoundHorizon:withRoundHorizon,DEFAULT_AUTO_CONTINUES:3,autoContinueLimit:autoContinueLimit,autoRoundsDefault:autoRoundsDefault,autoContinuePlan:autoContinuePlan,resolveModel:resolveModel,ignoredEnvModel:ignoredEnvModel,resolveEffort:resolveEffort,resolveFanout:resolveFanout,autonomousDirective:autonomousDirective,taskPrompt:taskPrompt,appendDigest:appendDigest,digestLine:digestLine,assistantText:assistantText,errorText:errorText,commitMessage:commitMessage,createQueueWorker:createQueueWorker};