aegiscode 6.5.5 → 6.5.7

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.
@@ -47,6 +47,28 @@ const toolsModule = require('./tools.js');
47
47
  const promptModule = require('./prompt.js');
48
48
  const { ShellSession } = require('./shell.js');
49
49
  const { agentSystemPrompt, agentRoleLabel } = require('./agents.js');
50
+ // Cooperative working-tree sharing (see each module's header). The lock
51
+ // serialises two hosts that start a turn on one checkout close together; the
52
+ // guard is the load-bearing half — it refuses a tree-wide git operation while
53
+ // another session's uncommitted work is present, which is the operation that
54
+ // destroyed a peer's file for real. Both live beside the engine because the
55
+ // CLI vendors this directory wholesale (cli/scripts/predist.mjs), so the GUI
56
+ // and the terminal get one implementation rather than two that drift.
57
+ const { beginTurnGuard, recordWrite, blocksDestructive } = require('./turn-guard.js');
58
+ const { acquireWorktreeLock, releaseWorktreeLock } = require('./worktree-lock.js');
59
+
60
+ /**
61
+ * How long a turn waits for the working-tree lock before running anyway.
62
+ *
63
+ * Short on purpose. This engine serves interactive hosts — a desktop window
64
+ * and a terminal — where stalling for the lock's own 11-minute default would
65
+ * be a worse failure than contending: the user is watching a spinner. So the
66
+ * lock is best-effort mutual exclusion for turns that start near-simultaneously
67
+ * (the common overlap), and the turn guard covers everything after that. A
68
+ * non-interactive caller that can afford to queue should pass
69
+ * `payload.worktreeWaitMs` with the long DEFAULT_WORKTREE_WAIT_MS instead.
70
+ */
71
+ const WORKTREE_LOCK_WAIT_MS = 1500;
50
72
 
51
73
  /** Classes whose transport is a user-supplied endpoint + credential. */
52
74
  const CUSTOM_CLASSES = Object.freeze(['openai-compat', 'anthropic']);
@@ -70,22 +92,30 @@ const CLASSES = [
70
92
  /**
71
93
  * Mirrors aegiscodex-dev's src/backend.js DEEPSEEK_REASONING_MODEL_RE +
72
94
  * EFFORT_TOKEN_BUDGET verbatim. DeepSeek's reasoning models (deepseek-flash,
73
- * deepseek-v4-pro, the deprecated deepseek-reasoner, and the legacy
74
- * v4-flash/v4.1-flash aliases some configs still carry) spend part of
75
- * max_tokens on hidden chain-of-thought before ever emitting visible
76
- * content — DeepSeek counts reasoning tokens against the same budget as
77
- * content. At the renderer's 4k default (index.html's max-tokens select),
78
- * any non-trivial question can burn the whole budget reasoning and finish
79
- * with empty content: no error, no tool calls, just a turn that "completes"
80
- * with nothing to show for it (the empty-response bug). A user pointing the
81
- * Custom OpenAI-compatible class straight at DeepSeek's API hits exactly
82
- * this, so the request floors to the same effort budget aegiscodex-dev uses
83
- * for its own direct DeepSeek calls instead of shipping whatever the
84
- * dropdown happens to have selected.
95
+ * i.e. "Flash 4.1", deepseek-v4-pro, the deprecated deepseek-reasoner, and the
96
+ * legacy v4-flash/v4.1-flash aliases some configs still carry) spend part of
97
+ * the budget on hidden chain-of-thought before ever emitting visible content —
98
+ * DeepSeek counts reasoning tokens against the same budget as content. Under
99
+ * the renderer's removed 4k dropdown default, any non-trivial question could
100
+ * burn the whole budget reasoning and finish with empty content: no error, no
101
+ * tool calls, just a turn that "completes" with nothing to show for it (the
102
+ * empty-response bug). A user pointing the Custom OpenAI-compatible class
103
+ * straight at DeepSeek's API hits exactly this, so the request is sized by the
104
+ * same effort budget aegiscodex-dev uses for its own direct DeepSeek calls.
105
+ *
106
+ * desktop/renderer/budget.js carries the renderer's copy of these two
107
+ * constants plus budgetFor() below; test/budget.test.mjs requires both and
108
+ * asserts they agree, so the mirror cannot drift silently.
85
109
  */
86
110
  const DEEPSEEK_REASONING_MODEL_RE = /^deepseek-(v4(\.\d+)?-(flash|pro)|flash|pro|reasoner)$/;
87
111
  const EFFORT_TOKEN_BUDGET = { low: 8192, medium: 16384, high: 32768 };
88
112
 
113
+ /** The one class whose wire format REQUIRES a stated `max_tokens`: Anthropic's
114
+ * Messages API 400s without it, so that field is derived from the effort rung
115
+ * rather than invented by the transport (which is what a blanket
116
+ * `max_tokens: maxTokens || 4096` did — see providers.anthropicMessages). */
117
+ const REQUIRES_STATED_BUDGET = new Set(['anthropic']);
118
+
89
119
  /**
90
120
  * Idle-stream budget for a pooled brain call ("work autonomously"). The
91
121
  * generic watchdog in vendor/aegis.js kills a stream that goes 60s without a
@@ -109,38 +139,38 @@ const EFFORT_TOKEN_BUDGET = { low: 8192, medium: 16384, high: 32768 };
109
139
  const AUTONOMOUS_IDLE_TIMEOUT_MS = 15 * 60_000;
110
140
 
111
141
  /**
112
- * The budget a DeepSeek reasoning model runs on, resolved from EXACTLY ONE
113
- * authority per call.
114
- *
115
- * A caller-stated number IS the budget, and is returned verbatim. For the
116
- * non-pooled classes the renderer's max-tokens dropdown is the only budget
117
- * control on offer — updateBudgetControls hides the effort row for them — so
118
- * silently raising that number to an effort rung is precisely what made the
119
- * figure beside the dropdown untrustworthy. The old form was
120
- * `Math.max(stated, EFFORT_TOKEN_BUDGET[eff])`, which could only ever raise a
121
- * deliberate cap: a caller asking for 1024 ran on 32768, and the number the
122
- * UI displayed was never the number the call used.
123
- *
124
- * The effort rung is the DEFAULT, consulted only when no number was stated at
125
- * all (the pooled class, which the renderer sends `effort` for and which the
126
- * server sizes itself). This is the same rule doubledBudget() follows for its
127
- * truncation retry: a stated cap is never overridden, by a rung or an order of
128
- * magnitude.
142
+ * The budget a request travels with, resolved from EXACTLY ONE authority per
143
+ * call — the engine-side half of the rule desktop/renderer/budget.js mirrors
144
+ * and test/budget.test.mjs compares the two halves of, so neither can drift.
129
145
  *
130
- * Truncated and empty turns are handled where they belong — the doubled-budget
131
- * retry plus emptyTurnError — rather than by inflating the caller's ceiling up
132
- * front. Escalating on a demonstrated empty turn is strictly cheaper than
133
- * pre-emptively granting the top rung to every reasoning call.
146
+ * 1. a caller-stated number IS the budget and is returned verbatim. It is a
147
+ * deliberate liability ceiling (aegis1 pass_budgets honours it downward:
148
+ * total = min(ladder, max_tokens x passes)) and no rung may raise it — the
149
+ * old `Math.max(stated, EFFORT_TOKEN_BUDGET[eff])` form did exactly that,
150
+ * so a caller asking for 1024 silently ran on 32768.
151
+ * 2. with nothing stated, a model that reasons against its own output budget
152
+ * (DeepSeek bills hidden chain-of-thought against the SAME budget as the
153
+ * answer) or a class whose wire format REQUIRES the field (Anthropic's
154
+ * Messages API) gets the Effort rung. This is why the renderer's
155
+ * max-tokens dropdown was removed rather than fixed: at its 4k default a
156
+ * reasoning model spent the entire budget thinking and finished empty —
157
+ * no error, no tool call, just a "completed" turn with nothing in it.
158
+ * 3. otherwise `undefined` — no `max_tokens` goes on the wire and the
159
+ * provider's own output limit governs. The transport used to fill this
160
+ * gap with an invented 4096 default, which is the defect in (2).
134
161
  *
135
- * Everything else (non-DeepSeek models, non-reasoning DeepSeek ids like
136
- * deepseek-chat) passes through untouched.
162
+ * Truncated and empty turns are still handled where they belong — the
163
+ * doubled-budget retry plus emptyTurnError — rather than by inflating the
164
+ * caller's ceiling up front.
137
165
  */
138
- function reasoningBudget(model, maxTokens, effort) {
139
- if (!DEEPSEEK_REASONING_MODEL_RE.test(String(model || ''))) return maxTokens;
166
+ function reasoningBudget(cls, model, maxTokens, effort) {
140
167
  const stated = Number(maxTokens);
141
168
  if (Number.isFinite(stated) && stated > 0) return stated;
142
- const eff = effort === 'low' || effort === 'medium' ? effort : 'high';
143
- return EFFORT_TOKEN_BUDGET[eff];
169
+ if (DEEPSEEK_REASONING_MODEL_RE.test(String(model || '')) || REQUIRES_STATED_BUDGET.has(cls)) {
170
+ const eff = effort === 'low' || effort === 'medium' ? effort : 'high';
171
+ return EFFORT_TOKEN_BUDGET[eff];
172
+ }
173
+ return undefined;
144
174
  }
145
175
 
146
176
  /** Relay model entries arrive as ids or objects; keep only real model ids. */
@@ -279,6 +309,33 @@ function doubledBudget(maxTokens) {
279
309
  return n > 0 ? n * 2 : 8192;
280
310
  }
281
311
 
312
+ /**
313
+ * The cap the CALLER stated, or `undefined` meaning "none was stated".
314
+ *
315
+ * The two branches resolve one question — whose number is this? — and the
316
+ * first is the fix. An internal re-entry (runSubagent's nested chat()) passes
317
+ * `statedMaxTokens` explicitly, because the `maxTokens` it holds is the rung
318
+ * reasoningBudget() derived from `effort`: a number the server is about to
319
+ * derive for itself. Re-reading that value as the caller's own is what put a
320
+ * guessed 32768 on the wire as a *ceiling over* aegis1's ladder
321
+ * (pass_budgets: total = min(ladder, max_tokens x passes)) — so a
322
+ * high-effort subagent silently ran at 8192 and the ladder the UI advertised
323
+ * was not the budget the call used.
324
+ *
325
+ * A non-numeric or non-positive value means "nothing stated" — never a 0- or
326
+ * NaN-token ceiling.
327
+ */
328
+ function statedCapOf(payload) {
329
+ const asCap = (v) => {
330
+ const n = Number(v);
331
+ return Number.isFinite(n) && n > 0 ? n : undefined;
332
+ };
333
+ if (payload && Object.prototype.hasOwnProperty.call(payload, 'statedMaxTokens')) {
334
+ return asCap(payload.statedMaxTokens);
335
+ }
336
+ return asCap(payload && payload.maxTokens);
337
+ }
338
+
282
339
  /**
283
340
  * The follow-up shown to a model that ended its turn with neither text nor a
284
341
  * tool call. Sent as a plain user message (never as a tool result — there is
@@ -305,9 +362,9 @@ const EMPTY_TURN_NUDGE =
305
362
  function emptyTurnError({ cls, model, maxTokens, finishReason }) {
306
363
  const err = new Error(
307
364
  `The model returned no answer after ${cls}/${model} was asked to summarise its results ` +
308
- `(stop reason: ${finishReason || 'none'}, max_tokens: ${maxTokens}). The token budget ` +
309
- 'was most likely consumed before any visible text — raise the max-tokens setting, ' +
310
- 'or lower effort.'
365
+ `(stop reason: ${finishReason || 'none'}, max_tokens: ${maxTokens || 'unstated'}). The token budget ` +
366
+ 'was most likely consumed before any visible text — raise the Effort rung, which is ' +
367
+ 'what sizes this call, or ask for a smaller piece of work.'
311
368
  );
312
369
  err.status = 502;
313
370
  return err;
@@ -346,6 +403,15 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
346
403
  // In-memory only, on purpose — never persisted, so a restart (or
347
404
  // newChat()'s clearSessionApprovals) always starts from a clean gate.
348
405
  const sessionAllowlists = new Map(); // rootSessionId -> Set<toolName>
406
+ // Denials are remembered for the same reason allows are, mirroring it for
407
+ // the other answer. Without this, a "Deny" was forgotten the instant it was
408
+ // given: the model read `… the user denied the request`, re-planned, called
409
+ // the SAME tool again, and the gate raised a SECOND card — so one "no" cost
410
+ // the user a prompt per round for up to maxRounds (24 chat / 40 autonomous)
411
+ // rounds, each round re-sending the whole conversation to the provider. A
412
+ // gate that only remembers "yes" turns a single click into a retry storm;
413
+ // remembering "no" makes the first answer stick.
414
+ const sessionDenials = new Map(); // rootSessionId -> Set<toolName>
349
415
  const pendingApprovals = new Map(); // approvalId -> { resolve }
350
416
 
351
417
  function sessionAllows(rootId, name) {
@@ -358,10 +424,44 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
358
424
  sessionAllowlists.get(rootId).add(name);
359
425
  }
360
426
 
427
+ /** Has this conversation already refused this tool? Checked before the card
428
+ * is raised, so a repeat call is refused outright instead of re-prompting. */
429
+ function sessionDenies(rootId, name) {
430
+ const set = sessionDenials.get(rootId);
431
+ return Boolean(set && set.has(name));
432
+ }
433
+
434
+ function denyForSession(rootId, name) {
435
+ if (!sessionDenials.has(rootId)) sessionDenials.set(rootId, new Set());
436
+ sessionDenials.get(rootId).add(name);
437
+ }
438
+
439
+ /**
440
+ * The text a refused tool hands back to the model. The old one-line
441
+ * `"<tool> was not executed — the user denied the request."` read to a
442
+ * capable agent as a transient failure to route around: it would apologise,
443
+ * pick a different command that does the same thing, and call the gate
444
+ * again. This says the durable part out loud (the refusal covers the rest of
445
+ * the conversation, not just that call) and asks for the one response that
446
+ * actually helps — say what you need and stop, so the user can re-enable it.
447
+ */
448
+ function denialText(name) {
449
+ return (
450
+ `${name} was not executed — the user denied this tool for this conversation. ` +
451
+ `Do NOT retry it and do NOT attempt the same effect by another route ` +
452
+ `(another command, a writeFile instead of an edit, a subagent). ` +
453
+ `Stop calling tools and reply in plain text: say what you were trying to do, ` +
454
+ `what you need, and that the user can re-enable ${name} to let it proceed.`
455
+ );
456
+ }
457
+
361
458
  /** newChat() in the renderer calls this so a fresh conversation never
362
- * inherits a prior thread's blanket allows. */
459
+ * inherits a prior thread's blanket allows — or its refusals. A new chat is
460
+ * a new gate in both directions: leaving denials behind would silently
461
+ * refuse a tool in a thread where the user never said no. */
363
462
  function clearSessionApprovals(rootSessionId) {
364
463
  sessionAllowlists.delete(rootSessionId);
464
+ sessionDenials.delete(rootSessionId);
365
465
  return { ok: true };
366
466
  }
367
467
 
@@ -379,22 +479,28 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
379
479
 
380
480
  /**
381
481
  * Ask the renderer to approve one mutating tool call. Resolves 'once',
382
- * 'session' or 'deny'. Sent over `rootOnDelta` (see chat()) as an
383
- * `{ approval }` chunk so it rides the exact same streaming channel as
384
- * tool-activity chunks — no new IPC surface needed on the push side, only
385
- * on the reply side (respondApproval). Fails safe: no listener able to
386
- * ever answer (no onDelta, or the turn was aborted) resolves 'deny'
387
- * instead of hanging the tool round forever.
482
+ * 'session' or 'deny' (an explicit choice by the user) — or 'cancel' when
483
+ * nobody ever answered: no listener able to reply, or the turn was aborted.
484
+ * 'cancel' is kept apart from 'deny' on purpose. Both refuse the call, but
485
+ * only 'deny' is a decision the user made, so only 'deny' may be remembered
486
+ * as "this conversation said no" (see sessionDenials). Folding the two
487
+ * together — which is what the old fail-safe did, resolving 'deny' for an
488
+ * abort — would let a cancelled turn permanently refuse a tool the user
489
+ * never ruled on. Sent over `rootOnDelta` (see chat()) as an `{ approval }`
490
+ * chunk so it rides the exact same streaming channel as tool-activity
491
+ * chunks — no new IPC surface needed on the push side, only on the reply
492
+ * side (respondApproval). Fails safe: an unanswered request refuses the
493
+ * call instead of hanging the tool round forever.
388
494
  */
389
495
  function requestApproval(rootSessionId, rootOnDelta, signal, info) {
390
496
  return new Promise((resolve) => {
391
497
  if (signal && signal.aborted) {
392
- resolve('deny');
498
+ resolve('cancel');
393
499
  return;
394
500
  }
395
501
  const id = randomUUID();
396
502
  let settled = false;
397
- const onAbort = () => finish('deny');
503
+ const onAbort = () => finish('cancel');
398
504
  const finish = (decision) => {
399
505
  if (settled) return;
400
506
  settled = true;
@@ -405,7 +511,7 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
405
511
  if (signal) signal.addEventListener('abort', onAbort, { once: true });
406
512
  pendingApprovals.set(id, { resolve: finish });
407
513
  if (typeof rootOnDelta !== 'function') {
408
- finish('deny');
514
+ finish('cancel');
409
515
  return;
410
516
  }
411
517
  rootOnDelta({
@@ -435,11 +541,51 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
435
541
  * runs straight through exactly like a session-allowed one, so "don't ask"
436
542
  * is one switch rather than a per-tool blanket allow in every conversation.
437
543
  */
544
+ /**
545
+ * The single place a tool executor is called from the chat loop, so the
546
+ * turn guard cannot be bypassed by reaching a different branch (there are
547
+ * four `return`s in gatedExecuteTool below; all of them come through here).
548
+ *
549
+ * exec is *checked* before running and writeFile/editFile are *recorded*
550
+ * after, and the asymmetry is the point: a refusal has to happen before the
551
+ * command runs, while "this path is mine" is only true once the write
552
+ * actually happened — recording a denied or preview-failed write would hide
553
+ * a genuinely foreign file behind a claim of ownership.
554
+ *
555
+ * A refusal is returned as an ordinary tool error, so the model reads it and
556
+ * adapts (name the paths, or don't do it) with no new IPC or renderer
557
+ * channel — the same reason it works identically in the GUI and the CLI.
558
+ */
559
+ async function guardedExecute(name, args, toolCtx) {
560
+ const guard = toolCtx && toolCtx.guard;
561
+ if (guard && name === 'exec') {
562
+ const verdict = blocksDestructive(guard, args && args.command);
563
+ if (!verdict.ok) return { ok: false, error: verdict.reason };
564
+ }
565
+ // Awaited, not merely returned: "this path is mine" is only true once the
566
+ // write actually landed, and `executeTool` is async — inspecting `.ok` on
567
+ // an un-awaited promise would read undefined and record every write,
568
+ // including the ones that failed. Ownership is load-bearing in the other
569
+ // direction too: a path wrongly claimed stops being reported as foreign.
570
+ const result = await T.executeTool(name, args, toolCtx);
571
+ if (guard && (name === 'writeFile' || name === 'editFile') && result && result.ok !== false) {
572
+ recordWrite(guard, args && args.path);
573
+ }
574
+ return result;
575
+ }
576
+
438
577
  async function gatedExecuteTool(call, { toolCtx, rootSessionId, rootOnDelta, signal }) {
439
578
  const { name, args } = call;
440
- if (!T.MUTATING_TOOLS.has(name)) return T.executeTool(name, args, toolCtx);
441
- if (!confirmModeEnabled()) return T.executeTool(name, args, toolCtx);
442
- if (sessionAllows(rootSessionId, name)) return T.executeTool(name, args, toolCtx);
579
+ if (!T.MUTATING_TOOLS.has(name)) return guardedExecute(name, args, toolCtx);
580
+ if (!confirmModeEnabled()) return guardedExecute(name, args, toolCtx);
581
+ if (sessionAllows(rootSessionId, name)) return guardedExecute(name, args, toolCtx);
582
+ // Already refused in this conversation: refuse again WITHOUT raising a
583
+ // second card. Before this, the model's retry after a denial re-prompted
584
+ // the user for the same tool — one "no" produced a card per round for up
585
+ // to maxRounds rounds, each one a billed provider call re-sending the
586
+ // whole conversation. Checked after the confirm-mode short-circuit so
587
+ // turning the gate off still overrides an earlier refusal.
588
+ if (sessionDenies(rootSessionId, name)) return { ok: false, error: denialText(name) };
443
589
 
444
590
  let preview = null;
445
591
  if (name === 'writeFile' || name === 'editFile') {
@@ -453,13 +599,30 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
453
599
  diff: preview && preview.diff,
454
600
  });
455
601
 
602
+ // Only a click is remembered. 'cancel' (aborted turn / nobody able to
603
+ // answer) refuses this call but must not write a durable "no" the user
604
+ // never gave.
456
605
  if (decision === 'deny') {
457
- return { ok: false, error: `${name} was not executed — the user denied the request.` };
606
+ denyForSession(rootSessionId, name);
607
+ return { ok: false, error: denialText(name) };
608
+ }
609
+ if (decision !== 'session' && decision !== 'once') {
610
+ return { ok: false, error: `${name} was not executed — the request was cancelled.` };
458
611
  }
459
612
  if (decision === 'session') allowForSession(rootSessionId, name);
460
613
 
461
- if (preview) return T.applyChecked(name, args, preview);
462
- return T.executeTool(name, args, toolCtx);
614
+ if (preview) {
615
+ const res = T.applyChecked(name, args, preview);
616
+ // Recorded on the same condition as guardedExecute's path: only a write
617
+ // that landed is this session's. (The previous form returned here
618
+ // unconditionally, making every line below it unreachable — the
619
+ // approved-write path recorded nothing at all.)
620
+ if (res && res.ok !== false && toolCtx && toolCtx.guard) {
621
+ recordWrite(toolCtx.guard, args && args.path);
622
+ }
623
+ return res;
624
+ }
625
+ return guardedExecute(name, args, toolCtx);
463
626
  }
464
627
 
465
628
  /**
@@ -571,8 +734,9 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
571
734
  // derived number states one decision twice — and the copies had already
572
735
  // drifted: 974adc5 doubled aegis1's ladder while this side stood still,
573
736
  // leaving the client capping below the budget it displayed. The cap was
574
- // never the one the renderer showed either (updateBudgetControls hides
575
- // the max-tokens dropdown for the pooled class). Omitting the field is
737
+ // never the one the renderer showed either (the Max tokens dropdown
738
+ // that used to claim a figure for the pooled class is gone — see
739
+ // desktop/renderer/budget.js). Omitting the field is
576
740
  // what tells aegis1 "no cap stated — let effort decide", the same
577
741
  // contract aegiscodex-dev sends.
578
742
  //
@@ -716,7 +880,7 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
716
880
  async function chat(payload, onDelta) {
717
881
  const cls = payload && payload.class;
718
882
  const model = payload && payload.model;
719
- const maxTokens = reasoningBudget(model, payload && payload.maxTokens, payload && payload.effort);
883
+ const maxTokens = reasoningBudget(cls, model, payload && payload.maxTokens, payload && payload.effort);
720
884
  // The caller's OWN number, kept apart from `maxTokens` above. That one
721
885
  // collapses two different facts into a single value — "the caller stated
722
886
  // 4096" and "effort implies 32768" — and the pooled path must treat them
@@ -725,7 +889,10 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
725
889
  // an effort-derived one is the server's own arithmetic stated twice, and
726
890
  // sending it is how the two copies came to disagree. So the pooled call
727
891
  // forwards only what the caller actually asked for.
728
- const statedMaxTokens = Number(payload && payload.maxTokens) > 0 ? Number(payload.maxTokens) : undefined;
892
+ // ...and it is read through statedCapOf(), so a nested chat() that states
893
+ // the key overrides its own derived `maxTokens` instead of being mistaken
894
+ // for a caller who asked for that number (see statedCapOf).
895
+ const statedMaxTokens = statedCapOf(payload);
729
896
  // "Work autonomously" — routes this call through aegis1's pool_brain
730
897
  // worker fan-out (services/pool_brain.py: N reasoning workers + a
731
898
  // synthesis pass) instead of a single provider call. UI-gated to the
@@ -1042,7 +1209,8 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
1042
1209
  for (const call of calls) {
1043
1210
  const result = call.name === T.SUBAGENT_TOOL
1044
1211
  ? await runSubagent(call.args, {
1045
- cls, model, maxTokens, mode: payload && payload.mode, parentSignal: signal, depth, rootSessionId, rootOnDelta,
1212
+ cls, model, statedMaxTokens, effort: payload && payload.effort,
1213
+ mode: payload && payload.mode, parentSignal: signal, depth, rootSessionId, rootOnDelta,
1046
1214
  })
1047
1215
  : await gatedExecuteTool(call, { toolCtx, rootSessionId, rootOnDelta, signal });
1048
1216
  // A subagent's spend rides back on its tool result (see runSubagent).
@@ -1072,7 +1240,7 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
1072
1240
  */
1073
1241
  async function runSubagent(
1074
1242
  { description, subagent_type, prompt: subPrompt } = {},
1075
- { cls, model, maxTokens, mode, parentSignal, depth, rootSessionId, rootOnDelta } = {}
1243
+ { cls, model, statedMaxTokens, effort, mode, parentSignal, depth, rootSessionId, rootOnDelta } = {}
1076
1244
  ) {
1077
1245
  const task = String(subPrompt || description || '').trim();
1078
1246
  if (!task) return { ok: false, error: 'task requires a prompt' };
@@ -1096,8 +1264,17 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
1096
1264
  // silently hanging behind this call's no-op onDelta below.
1097
1265
  const res = await chat(
1098
1266
  {
1099
- class: cls, model, maxTokens, mode, system, prompt: task, sessionId: subSessionId, depth: (depth || 0) + 1,
1267
+ class: cls, model, mode, system, prompt: task, sessionId: subSessionId, depth: (depth || 0) + 1,
1100
1268
  rootSessionId, rootOnDelta,
1269
+ // The parent's budget AUTHORITY is forwarded, not the number it
1270
+ // implies. `maxTokens` is deliberately absent: it is the rung this
1271
+ // turn derived from `effort`, and a re-entry that hands it back gets
1272
+ // read as the caller's own cap (statedCapOf). The rung itself rides
1273
+ // along as `effort`, which is what aegis1 sizes the fan-out and its
1274
+ // ladder from — so a subagent now runs at the effort the user chose
1275
+ // instead of at a number that only meant anything for this model id.
1276
+ statedMaxTokens,
1277
+ effort,
1101
1278
  },
1102
1279
  () => {}
1103
1280
  );
@@ -1136,4 +1313,4 @@ function createLocalEngine({ aegis, settings, ollama, providers, tools, promptBu
1136
1313
  };
1137
1314
  }
1138
1315
 
1139
- module.exports = { CLASSES, createLocalEngine, extractToolCalls, parseArgs };
1316
+ module.exports = { CLASSES, createLocalEngine, extractToolCalls, parseArgs, reasoningBudget };
@@ -0,0 +1,71 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Minimal git worktree introspection: where the repo root is, and what is
5
+ * dirty right now with a content hash per path.
6
+ *
7
+ * Ported from aegiscodex-dev/src/git-scope.js (ESM → CommonJS). Only the two
8
+ * functions `turn-guard.js` needs are carried over — `gitRoot` and
9
+ * `gitStatusSnapshot` (plus their `contentHash` helper). The source file's
10
+ * `foreignChanges` and `scopedCommit` belong to the autonomous queue's
11
+ * commit path, which the plugin does not host, so they are deliberately not
12
+ * vendored: a copy of code nothing calls is a copy that drifts unnoticed.
13
+ *
14
+ * The "dirty before AND byte-identical now" definition lives in
15
+ * `gitStatusSnapshot`'s hashes; `turn-guard.js` is the only consumer.
16
+ */
17
+
18
+ const fs = require('node:fs');
19
+ const path = require('node:path');
20
+ const crypto = require('node:crypto');
21
+ const { spawnSync } = require('node:child_process');
22
+
23
+ /** The repo root for `cwd`, or null if it isn't inside a git work tree. */
24
+ function gitRoot(cwd) {
25
+ const r = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8' });
26
+ return r.status === 0 ? r.stdout.trim() : null;
27
+ }
28
+
29
+ /**
30
+ * Hash a path's worktree content, so "already dirty before the task ran" can
31
+ * be told apart from "this task changed it". `absent` covers deletions;
32
+ * non-files (a submodule, a directory) compare by kind.
33
+ */
34
+ function contentHash(cwd, rel) {
35
+ try {
36
+ const st = fs.lstatSync(path.join(cwd, rel));
37
+ if (!st.isFile()) return st.isDirectory() ? 'nonfile:dir' : 'nonfile:other';
38
+ return crypto.createHash('sha1').update(fs.readFileSync(path.join(cwd, rel))).digest('hex');
39
+ } catch {
40
+ return 'absent';
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Every path git reports as dirty right now, mapped to its content hash.
46
+ * `--no-renames` matters: in `-z` porcelain a rename emits the old name as a
47
+ * second NUL-terminated token, which we would otherwise hash as a change.
48
+ * Untracked files are included, since that is exactly how concurrent work
49
+ * usually arrives. Returns null if `cwd` is not a usable git repo.
50
+ */
51
+ function gitStatusSnapshot(cwd) {
52
+ // Run from the repo root: porcelain reports paths root-relative, so hashing
53
+ // must resolve them against the same directory.
54
+ const root = gitRoot(cwd);
55
+ if (!root) return null;
56
+ const r = spawnSync(
57
+ 'git',
58
+ ['status', '--porcelain=v1', '-z', '--untracked-files=all', '--no-renames'],
59
+ { cwd: root, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 },
60
+ );
61
+ if (r.status !== 0) return null;
62
+ const snap = new Map();
63
+ for (const rec of r.stdout.split('\0')) {
64
+ if (rec.length < 4) continue;
65
+ const p = rec.slice(3);
66
+ snap.set(p, contentHash(root, p));
67
+ }
68
+ return snap;
69
+ }
70
+
71
+ module.exports = { gitRoot, contentHash, gitStatusSnapshot };