aegisone 1.0.41 → 1.0.43
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.
- package/README.md +1 -1
- package/package.json +1 -1
- package/scripts/predist.mjs +1 -1
- package/vendor/cli/package.json +1 -1
- package/vendor/cli/src/chatflow.js +1 -1
- package/vendor/cli/src/commands.js +2 -2
- package/vendor/cli/src/limits.js +1 -1
- package/vendor/cli/src/permissions.js +4 -0
- package/vendor/cli/src/provenance.lock.json +2 -2
- package/vendor/cli/vendor/desktop/lib/local/check-command.js +3 -0
- package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/perm-store.js +7 -2
- package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -1
- package/vendor/cli/vendor/desktop/lib/local/repeat-guard.js +3 -0
- package/vendor/cli/vendor/desktop/lib/local/tools.js +185 -1
- package/vendor/cli/vendor/desktop/lib/local/verify-stop.js +3 -0
- package/vendor/cli/vendor/desktop/main.js +133 -32
- package/vendor/desktop/lib/local/check-command.js +3 -0
- package/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/desktop/lib/local/perm-store.js +7 -2
- package/vendor/desktop/lib/local/prompt.js +1 -1
- package/vendor/desktop/lib/local/repeat-guard.js +3 -0
- package/vendor/desktop/lib/local/tools.js +185 -1
- package/vendor/desktop/lib/local/verify-stop.js +3 -0
- package/vendor/desktop/lib/sync/persist-gate.js +1 -1
- package/vendor/desktop/lib/sync/sessions.js +1 -1
- package/vendor/desktop/main.js +133 -32
- package/vendor/desktop/package.json +3 -2
- package/vendor/desktop/preload.js +1 -1
- package/vendor/desktop/renderer/app.js +3 -3
- package/vendor/desktop/renderer/index.html +43 -15
- package/vendor/desktop/renderer/library.js +3 -0
- package/vendor/desktop/renderer/style.css +149 -0
- package/vendor/desktop/vendor/faces/cli/package.json +1 -1
- package/vendor/desktop/vendor/faces/cli/src/chatflow.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/commands.js +2 -2
- package/vendor/desktop/vendor/faces/cli/src/limits.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/permissions.js +1 -1
- package/vendor/desktop/vendor/faces/cli/src/provenance.lock.json +2 -2
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/check-command.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/engine.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/perm-store.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/prompt.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/repeat-guard.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/tools.js +1 -1
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/verify-stop.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +3 -3
- package/vendor/desktop/vendor/sandbox/provenance.json +7 -7
|
@@ -756,6 +756,7 @@ function watchTopupCredit(aegis, opts) {
|
|
|
756
756
|
*/
|
|
757
757
|
let memoryIndexHandle = null;
|
|
758
758
|
let memoryIndexOff = false;
|
|
759
|
+
let memoryIndexTries = 0;
|
|
759
760
|
function memoryIndex(dir) {
|
|
760
761
|
if (memoryIndexHandle) return memoryIndexHandle;
|
|
761
762
|
if (memoryIndexOff || !dir) return null;
|
|
@@ -763,13 +764,19 @@ function memoryIndex(dir) {
|
|
|
763
764
|
const store = new memoryStore.MemoryStore({ dir });
|
|
764
765
|
const opened = store.open();
|
|
765
766
|
if (!opened.ok) {
|
|
766
|
-
|
|
767
|
+
// `node:sqlite` missing is permanent, so latch on sight. Anything else
|
|
768
|
+
// (EACCES on the dir, EBUSY, a corrupt file) may be transient and must
|
|
769
|
+
// not kill indexing for the whole process — but search runs on every
|
|
770
|
+
// keystroke, so stop attempting a doomed open after a few rather than
|
|
771
|
+
// retrying it per character.
|
|
772
|
+
if (!memoryStore.isAvailable() || ++memoryIndexTries >= 3) memoryIndexOff = true;
|
|
767
773
|
return null;
|
|
768
774
|
}
|
|
775
|
+
memoryIndexTries = 0;
|
|
769
776
|
memoryIndexHandle = store;
|
|
770
777
|
return memoryIndexHandle;
|
|
771
778
|
} catch {
|
|
772
|
-
memoryIndexOff = true;
|
|
779
|
+
if (!memoryStore.isAvailable() || ++memoryIndexTries >= 3) memoryIndexOff = true;
|
|
773
780
|
return null;
|
|
774
781
|
}
|
|
775
782
|
}
|
|
@@ -2711,26 +2718,78 @@ function createSyncDispatch(sessions, dir, aegis, settingsDir, modelDispatch) {
|
|
|
2711
2718
|
auto: () => autoPush.auto(),
|
|
2712
2719
|
memoryPersistState: () => autoPush.gate(),
|
|
2713
2720
|
listSessions: () => ({ sessions: sessions.listSessions(dir) }),
|
|
2714
|
-
// The
|
|
2715
|
-
//
|
|
2716
|
-
// store is a main-process file, and `listSessions()` truncates — it returns
|
|
2717
|
-
// title/messages/updatedAt, so a renderer-side filter would be a second,
|
|
2718
|
-
// weaker copy of the same read. `searchSessions` takes the query and returns
|
|
2719
|
-
// the ranked matches plus WHICH field matched, so the row can say why it is
|
|
2720
|
-
// in the list. An empty query returns the newest N unchanged, so the sheet
|
|
2721
|
-
// opens on something instead of a blank pane.
|
|
2721
|
+
// The ONE search the menu's "Search" (Cmd/Ctrl+K) runs — sessions AND
|
|
2722
|
+
// memory under a single query box.
|
|
2722
2723
|
//
|
|
2723
|
-
//
|
|
2724
|
-
// /
|
|
2725
|
-
//
|
|
2724
|
+
// It used to be two sheets on two accelerators: Cmd/Ctrl+K searched
|
|
2725
|
+
// sessions, Cmd/Ctrl+Shift+K opened the memory inspector. Same verb, two
|
|
2726
|
+
// surfaces, and neither could answer "I know I wrote this down somewhere".
|
|
2727
|
+
// This channel now returns both stores in one payload so the renderer can
|
|
2728
|
+
// paint one list; the inspector keeps its own door in the Memory pane.
|
|
2729
|
+
//
|
|
2730
|
+
// Why the ranking is HERE and not in the renderer: both stores are
|
|
2731
|
+
// main-process files (sessions.json, memory.db), and `listSessions()`
|
|
2732
|
+
// truncates — it returns title/messages/updatedAt — so a renderer-side
|
|
2733
|
+
// filter would be a second, weaker copy of the same read.
|
|
2734
|
+
//
|
|
2735
|
+
// The session ranking is `client/session-search.js`, the same module the
|
|
2736
|
+
// CLI's /resume picker filters with, so the two faces cannot order the same
|
|
2737
|
+
// conversation differently. Memory ranks through `memory-store.js`'s own
|
|
2738
|
+
// `search()`, which is FTS5 when the build has it — its tiers are not
|
|
2739
|
+
// comparable to the session tiers, which is exactly why the sheet draws the
|
|
2740
|
+
// two groups as SECTIONS with a flat cursor order rather than one
|
|
2741
|
+
// cross-type column.
|
|
2742
|
+
//
|
|
2743
|
+
// An empty query returns the newest N of each, so the sheet opens on
|
|
2744
|
+
// something instead of a blank pane.
|
|
2726
2745
|
searchSessions: (payload) => {
|
|
2727
2746
|
const query = payload && typeof payload.query === 'string' ? payload.query : '';
|
|
2728
2747
|
const limit = Number.isInteger(payload && payload.limit) ? payload.limit : 50;
|
|
2748
|
+
const cap = Math.max(1, limit);
|
|
2729
2749
|
const all = sessions.listSessions(dir) || [];
|
|
2730
|
-
const ranked = sessionSearch.rankSessions(query, all).slice(0,
|
|
2750
|
+
const ranked = sessionSearch.rankSessions(query, all).slice(0, cap);
|
|
2751
|
+
// Memory is READ-ONLY here: `search()` is a local index read, never a
|
|
2752
|
+
// cloud round trip, so a keystroke cannot cost the user a metered call.
|
|
2753
|
+
// An unavailable index (no SQLite in this build) is an empty section, not
|
|
2754
|
+
// an error — a search that still works for sessions beats one that fails
|
|
2755
|
+
// because the other store is missing.
|
|
2756
|
+
let memory = [];
|
|
2757
|
+
let memoryTotal = 0;
|
|
2758
|
+
// `ok` | `unavailable` (no SQLite in this build) | `error` (index exists
|
|
2759
|
+
// but could not be read). The renderer must tell these apart: reporting
|
|
2760
|
+
// "0 memories" would claim the store is empty when the truth is that it
|
|
2761
|
+
// was never searched.
|
|
2762
|
+
let memoryStatus = 'ok';
|
|
2763
|
+
try {
|
|
2764
|
+
const index = memoryIndex(dir);
|
|
2765
|
+
if (index) {
|
|
2766
|
+
const found = index.search(query, { limit: cap });
|
|
2767
|
+
if (found && found.ok) {
|
|
2768
|
+
memory = (found.results || []).map((r) => ({
|
|
2769
|
+
id: r.id,
|
|
2770
|
+
content: r.body || '',
|
|
2771
|
+
scope: r.scope || '',
|
|
2772
|
+
tags: Array.isArray(r.tags) ? r.tags : [],
|
|
2773
|
+
updated: r.updated || null,
|
|
2774
|
+
}));
|
|
2775
|
+
memoryTotal = index.count();
|
|
2776
|
+
} else {
|
|
2777
|
+
memoryStatus = 'error';
|
|
2778
|
+
}
|
|
2779
|
+
} else {
|
|
2780
|
+
memoryStatus = memoryStore.isAvailable() && dir ? 'error' : 'unavailable';
|
|
2781
|
+
}
|
|
2782
|
+
} catch {
|
|
2783
|
+
memory = [];
|
|
2784
|
+
memoryTotal = 0;
|
|
2785
|
+
memoryStatus = 'error';
|
|
2786
|
+
}
|
|
2731
2787
|
return {
|
|
2732
2788
|
query,
|
|
2733
2789
|
total: all.length,
|
|
2790
|
+
memoryStatus,
|
|
2791
|
+
memoryTotal,
|
|
2792
|
+
memory,
|
|
2734
2793
|
sessions: ranked.map((s) => ({
|
|
2735
2794
|
id: s && s.id,
|
|
2736
2795
|
title: (s && s.title) || (s && s.id) || 'untitled',
|
|
@@ -2756,6 +2815,20 @@ function createSyncDispatch(sessions, dir, aegis, settingsDir, modelDispatch) {
|
|
|
2756
2815
|
),
|
|
2757
2816
|
delete: (payload) =>
|
|
2758
2817
|
sessions.deleteSession(dir, payload && payload.sessionId),
|
|
2818
|
+
// Rename a thread by hand (the library pane's Rename button).
|
|
2819
|
+
//
|
|
2820
|
+
// `renameSession`, not `setTitle`: lib/sync/sessions.js explains at length
|
|
2821
|
+
// why the shared store's `setTitle` is deliberately NOT re-exported under
|
|
2822
|
+
// that name (client/naming.js duck-checks it to decide whether to spend a
|
|
2823
|
+
// model round). The write it performs is the same one, marked `named` so
|
|
2824
|
+
// no later naming round can overwrite a name the user typed. An empty
|
|
2825
|
+
// title is refused rather than written — blanking a name is not a rename.
|
|
2826
|
+
rename: (payload) =>
|
|
2827
|
+
sessions.renameSession(
|
|
2828
|
+
dir,
|
|
2829
|
+
payload && payload.sessionId,
|
|
2830
|
+
payload && payload.title
|
|
2831
|
+
),
|
|
2759
2832
|
// The naming ladder (client/naming.js), run in the MAIN process.
|
|
2760
2833
|
//
|
|
2761
2834
|
// The window used to name a thread `prompt.slice(0, 60)` — in the renderer,
|
|
@@ -2794,7 +2867,15 @@ function createSyncDispatch(sessions, dir, aegis, settingsDir, modelDispatch) {
|
|
|
2794
2867
|
prompt: text,
|
|
2795
2868
|
system: opts.system,
|
|
2796
2869
|
maxTokens: 64,
|
|
2797
|
-
sessionId
|
|
2870
|
+
// NOT the turn's `sessionId`. The engine keys its cancel registry
|
|
2871
|
+
// by that id (lib/local/engine.js `controllers`), and the desktop
|
|
2872
|
+
// reuses the conversation id for the turn it is streaming — so a
|
|
2873
|
+
// naming round sharing it fought the live turn for the Stop
|
|
2874
|
+
// button. The engine now refuses to lose the turn's controller
|
|
2875
|
+
// either way, but a decoration should not be claiming the turn's
|
|
2876
|
+
// identity in the first place: approvals, round counts and
|
|
2877
|
+
// cancellation all hang off this id, and naming is none of them.
|
|
2878
|
+
sessionId: `${sessionId}:naming`,
|
|
2798
2879
|
// `tools: false` is the engine's own opt-out (a naming round must
|
|
2799
2880
|
// not run the agent loop); nothing else here is a wire field.
|
|
2800
2881
|
tools: false,
|
|
@@ -2805,8 +2886,20 @@ function createSyncDispatch(sessions, dir, aegis, settingsDir, modelDispatch) {
|
|
|
2805
2886
|
return null;
|
|
2806
2887
|
}
|
|
2807
2888
|
};
|
|
2889
|
+
// `sessions.namingStore`, not `sessions`: the binding deliberately does
|
|
2890
|
+
// not carry a bare `setTitle`, because naming.js arms itself on that
|
|
2891
|
+
// name and an incidental re-export would turn a model round per
|
|
2892
|
+
// conversation on invisibly (see lib/sync/sessions.js). Passing the
|
|
2893
|
+
// adapter is what arms it, here, on purpose — this ladder was dead for
|
|
2894
|
+
// as long as the binding was handed over directly.
|
|
2808
2895
|
try {
|
|
2809
|
-
return await namingLib.nameSession(
|
|
2896
|
+
return await namingLib.nameSession(
|
|
2897
|
+
sessions.namingStore,
|
|
2898
|
+
dir,
|
|
2899
|
+
sessionId,
|
|
2900
|
+
prompt,
|
|
2901
|
+
{ callModel }
|
|
2902
|
+
);
|
|
2810
2903
|
} catch {
|
|
2811
2904
|
return null;
|
|
2812
2905
|
}
|
|
@@ -4221,8 +4314,7 @@ function sendDeepLinkToWindow(win, parsed) {
|
|
|
4221
4314
|
|
|
4222
4315
|
/** Application menu: the platform defaults (Edit roles, mac's app/quit
|
|
4223
4316
|
* items) plus the native-shell accelerators this plan adds — New Chat
|
|
4224
|
-
* (Cmd/Ctrl+N), Search
|
|
4225
|
-
* (Cmd/Ctrl+Shift+K), Reload (Cmd/Ctrl+R) and Toggle DevTools
|
|
4317
|
+
* (Cmd/Ctrl+N), Search (Cmd/Ctrl+K), Reload (Cmd/Ctrl+R) and Toggle DevTools
|
|
4226
4318
|
* (Cmd/Ctrl+Shift+I) are plain Electron roles that already carry the right
|
|
4227
4319
|
* accelerator on every platform — plus a manual "Check for Updates…" entry,
|
|
4228
4320
|
* since the automatic checks in createUpdateManager.start() only run on ready
|
|
@@ -4234,8 +4326,9 @@ function sendDeepLinkToWindow(win, parsed) {
|
|
|
4234
4326
|
*
|
|
4235
4327
|
* * Cmd/Ctrl+K opened the MEMORY inspector while the item said "Search…", so
|
|
4236
4328
|
* the label named neither the sheet nor the thing the user wanted. The
|
|
4237
|
-
* chord now goes to
|
|
4238
|
-
*
|
|
4329
|
+
* chord now goes to one search over sessions AND memory (sessions ranked by
|
|
4330
|
+
* client/session-search.js, memory by memory-store.js), and the two are
|
|
4331
|
+
* drawn as sections of a single list rather than as two sheets.
|
|
4239
4332
|
* * There was no licence surface anywhere in the app. `Help` is now on every
|
|
4240
4333
|
* platform and leads with Credits & Licence, which renders
|
|
4241
4334
|
* client/credits.js — the licence, the program notice and every vendored
|
|
@@ -4270,25 +4363,33 @@ function buildAppMenu({ app, Menu, BrowserWindow, updateManager, loggedIn }) {
|
|
|
4270
4363
|
accelerator: 'CmdOrCtrl+N',
|
|
4271
4364
|
click: () => sendToAppWindow(BrowserWindow, MENU_NEW_CHAT_CHANNEL),
|
|
4272
4365
|
};
|
|
4273
|
-
// View > Search
|
|
4366
|
+
// View > Search (Cmd/Ctrl+K).
|
|
4274
4367
|
//
|
|
4275
|
-
//
|
|
4276
|
-
// accelerator, the label and the sheet
|
|
4277
|
-
//
|
|
4278
|
-
//
|
|
4279
|
-
//
|
|
4280
|
-
//
|
|
4368
|
+
// Two corrections live in this item's history. It once said `Search…` and
|
|
4369
|
+
// opened the MEMORY inspector, so the accelerator, the label and the sheet
|
|
4370
|
+
// disagreed. It then said `Search sessions…` and searched only conversations,
|
|
4371
|
+
// while memory kept a parallel sheet on Cmd/Ctrl+Shift+K — one verb, two
|
|
4372
|
+
// surfaces, and no way to answer "I know I wrote this down somewhere".
|
|
4373
|
+
// It is now one sheet over both stores (see `searchSessions` above), so the
|
|
4374
|
+
// label promises exactly what the sheet does and stops naming one store.
|
|
4281
4375
|
const searchItem = {
|
|
4282
|
-
label: 'Search
|
|
4376
|
+
label: 'Search',
|
|
4283
4377
|
accelerator: 'CmdOrCtrl+K',
|
|
4284
4378
|
click: () => sendToAppWindow(BrowserWindow, MENU_SEARCH_CHANNEL),
|
|
4285
4379
|
};
|
|
4286
|
-
//
|
|
4287
|
-
//
|
|
4288
|
-
//
|
|
4380
|
+
// Cmd/Ctrl+Shift+K still opens the same sheet, pre-scoped to memory — the
|
|
4381
|
+
// chord people already learned keeps working, and it lands them in the one
|
|
4382
|
+
// search rather than a second one.
|
|
4383
|
+
//
|
|
4384
|
+
// `visible: false` is deliberate. Electron registers the accelerator of a
|
|
4385
|
+
// hidden item, so the key survives; what goes away is the MENU ROW that
|
|
4386
|
+
// advertised a separate memory search. Removing the item entirely would have
|
|
4387
|
+
// silently killed a chord users have muscle memory for; leaving it visible
|
|
4388
|
+
// would keep advertising the split this change exists to remove.
|
|
4289
4389
|
const searchMemoryItem = {
|
|
4290
|
-
label: 'Search memory
|
|
4390
|
+
label: 'Search memory',
|
|
4291
4391
|
accelerator: 'CmdOrCtrl+Shift+K',
|
|
4392
|
+
visible: false,
|
|
4292
4393
|
click: () => sendToAppWindow(BrowserWindow, MENU_SEARCH_MEMORY_CHANNEL),
|
|
4293
4394
|
};
|
|
4294
4395
|
// Help > Credits & licence — the AGPL licence, the program notice, and every
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
+
"use strict";const fs=require("node:fs"),path=require("node:path");function readJson(t,e){try{return JSON.parse(fs.readFileSync(path.join(e,t),"utf8"))}catch{return null}}function exists(t,e){try{return fs.existsSync(path.join(t,e))}catch{return!1}}function extOf(t){const e=String(t||"").split(/[/\\]/).pop()||"",s=e.lastIndexOf(".");return s<=0?"":e.slice(s).toLowerCase()}const TS_EXT=new Set([".ts",".tsx",".mts",".cts"]),JS_EXT=new Set([".js",".mjs",".cjs",".jsx"]);function safeRelPath(t){const e=String(t||"").replace(/\\/g,"/");return!e||e.length>400||e.startsWith("/")||/^[A-Za-z]:/.test(e)||/[\s;&|`$<>(){}[\]'"!*?~\0]/.test(e)||e.split("/").includes("..")?null:e}function detectCheckCommand(t,e){if(!t)return null;const s=extOf(e),n=safeRelPath(e),c=readJson("package.json",t);if(c&&c.scripts&&"object"==typeof c.scripts)for(const t of["typecheck","type-check","lint","check"])if("string"==typeof c.scripts[t])return{cmd:`npm run ${t}`,why:`package.json defines a "${t}" script`};return TS_EXT.has(s)&&exists(t,"tsconfig.json")?exists(t,path.join("node_modules",".bin","tsc"))||exists(t,path.join("node_modules","typescript"))?{cmd:"npx --no-install tsc --noEmit",why:"this repo has a tsconfig.json and a local TypeScript"}:n?{cmd:`node --check ${n}`,why:"no local TypeScript install, so this is a syntax check only"}:null:".js"!==s&&".mjs"!==s&&".cjs"!==s||!n?JS_EXT.has(s)&&exists(t,"node_modules",".bin","eslint")?{cmd:"npx --no-install eslint .",why:"this repo has a local ESLint"}:".py"===s?n?{cmd:`python -m py_compile ${n}`,why:"a stdlib syntax check — not a type check"}:null:".go"===s?{cmd:"go vet ./...",why:"Go ships its own vet"}:".rs"===s?{cmd:"cargo check",why:"Rust ships its own checker"}:".rb"===s&&n?{cmd:`ruby -c ${n}`,why:"a syntax check"}:null:{cmd:`node --check ${n}`,why:"parses the file without executing it"}}module.exports={detectCheckCommand:detectCheckCommand,safeRelPath:safeRelPath,extOf:extOf};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const{randomUUID:randomUUID}=require("node:crypto"),os=require("node:os"),fs=require("node:fs"),toolsModule=require("./tools.js"),attachmentsModule=require("./attachments.js"),{flattenContent:flattenContent}=attachmentsModule,promptModule=require("./prompt.js"),localTransport=require("./local.js"),{ShellSession:ShellSession}=require("./shell.js"),{planExec:planExec}=require("./exec-plan.js"),claudePro=require("./claude-pro.js"),{agentSystemPrompt:agentSystemPrompt,agentRoleLabel:agentRoleLabel}=require("./agents.js"),{beginTurnGuard:beginTurnGuard,recordWrite:recordWrite,blocksDestructive:blocksDestructive}=require("./turn-guard.js"),{acquireWorktreeLock:acquireWorktreeLock,releaseWorktreeLock:releaseWorktreeLock}=require("./worktree-lock.js"),covenant=require("./covenant.js");let envFile=null;try{envFile=require("../../../client/env-file.js")}catch{try{envFile=require("../../vendor/env-file.js")}catch{envFile=null}}let platformLib=null;try{platformLib=require("../../../client/platform.js")}catch{try{platformLib=require("../../vendor/platform.js")}catch{platformLib=null}}let credentialsLib=null;try{credentialsLib=require("../../../client/credentials.js")}catch{try{credentialsLib=require("../../vendor/credentials.js")}catch{credentialsLib=null}}const PRO_TOOL_MAP=Object.freeze({Write:"writeFile",Edit:"editFile",MultiEdit:"editFile",NotebookEdit:"editFile",Bash:"exec",BashOutput:"exec"}),PRO_PLAN_MODE_SAFE=Object.freeze(new Set(["Read","Glob","Grep"]));function proAskArgs(e,t){const o=e&&"object"==typeof e?e:{};return"exec"===t?"string"==typeof o.command?{command:o.command}:{}:"writeFile"===t?"string"==typeof o.file_path?{file_path:o.file_path,content:o.content}:{}:"editFile"===t?Array.isArray(o.edits)?{file_path:o.file_path,edits:o.edits}:"string"==typeof o.file_path?{file_path:o.file_path,old_string:o.old_string,new_string:o.new_string,replace_all:!0===o.replace_all}:{}:o}function normalizeToolArgs(e,t,o,n){const r=e&&"function"==typeof e.normalizeArgs&&e.normalizeArgs||"function"==typeof toolsModule.normalizeArgs&&toolsModule.normalizeArgs||null;return r?r(t,o,n):{ok:!0,args:o&&"object"==typeof o?o:{},error:null}}function detectVcs(e){if(!e)return null;try{const t=require("node:fs"),o=require("node:path");let n=o.resolve(String(e));for(let e=0;e<8;e+=1){if(t.existsSync(o.join(n,".git")))return"git";const e=o.dirname(n);if(e===n)break;n=e}return""}catch{return null}}function hostEnv(e={},t={},o=null){const n=e||{},r=t||{},s=(e,t)=>null!=r[e]?r[e]:t;let a=n.homedir,i=n.cwd;try{a||(a=os.homedir()),i||(i=process.cwd())}catch{}let l=n.shell,c=n.shellKind;try{if(!l||!c){const e=require("./shell.js").resolveSessionShell();l=l||e.cmd,c=c||e.kind}}catch{}let d=n.desktopdir;try{!d&&platformLib&&(d=platformLib.desktopDir())}catch{}let u=n.dataDir;try{!u&&credentialsLib&&(u=credentialsLib.aegisHome())}catch{}let f=n.locale,p=n.localeName;try{!f&&platformLib&&"function"==typeof platformLib.appLocale&&(f=platformLib.appLocale()),f&&!p&&platformLib&&"function"==typeof platformLib.languageName&&(p=platformLib.languageName(f))}catch{}return{platform:s("platform",n.platform||process.platform),arch:s("arch",n.arch||process.arch),homedir:s("homedir",a),desktopdir:s("desktopdir",d),dataDir:s("dataDir",u),locale:s("locale",f),localeName:s("localeName",p),languages:s("languages",n.languages),cwd:s("cwd",i),vcs:s("vcs",null!=n.vcs?n.vcs:detectVcs(i)),shell:s("shell",l),shellKind:s("shellKind",c),roots:s("roots",n.roots),appVersion:s("appVersion",n.appVersion),model:s("model",o&&o.model)}}function requireSharedBrain(){const e=[()=>require("../../../client/brain-catalog.js"),()=>require("../../vendor/brain-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedByokCatalog(){const e=[()=>require("../../../client/byok-catalog.js"),()=>require("../../vendor/byok-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedUserModels(){const e=[()=>require("../../../client/user-models.js"),()=>require("../../vendor/user-models.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedCatalogClient(){const e=[()=>require("../../../client/catalog-client.js"),()=>require("../../vendor/catalog-client.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelDiscovery(){const e=[()=>require("../../../client/model-discovery.js"),()=>require("../../vendor/model-discovery.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}const WORKTREE_LOCK_WAIT_MS=1500,MAX_SUBAGENT_DEPTH=4,CLASSES=[{class:"aegis",label:"Aegis Cloud",kind:"cloud"},{class:"byok",label:"Bring your own key",kind:"cloud"},{class:"local",label:"Local model",kind:"local"},{class:"pro",label:"Claude Code Pro",kind:"subscription"}],BYOK_NAMESPACE_PREFIX="byok:";function byokNamespace(e){return`${BYOK_NAMESPACE_PREFIX}${e}`}function splitByokModel(e){const t="string"==typeof e?e:"",o=t.indexOf(":");return o<0?{provider:"",model:t}:{provider:t.slice(0,o),model:t.slice(o+1)}}function providerKeyRecord(e){const t={key:"",env:"",rejected:null};if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return t;try{const o=envFile.providerKeyFromEnv(e)||t;return{key:"string"==typeof o.key?o.key:"",env:"string"==typeof o.env?o.env:"",rejected:"string"==typeof o.rejected&&o.rejected?o.rejected:null}}catch{return t}}function providerKeyFromEnv(e){if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return"";try{return envFile.providerKeyFromEnv(e).key||""}catch{return""}}const DEEPSEEK_REASONING_MODEL_RE=/^deepseek-(v4(\.\d+)?-(flash|pro)|flash|pro|reasoner)$/,EFFORT_TOKEN_BUDGET={low:8192,medium:16384,high:32768,max:32768},DEEPSEEK_EFFORT={low:"low",medium:"high",high:"high"},DEEPSEEK_EFFORT_EXTRA={max:"max"},EFFORT_IDENTITY={low:"low",medium:"medium",high:"high"},EFFORT_INERT_RE=/non-reasoning/i,EFFORT_DIALECTS=[{provider:"deepseek",re:DEEPSEEK_REASONING_MODEL_RE,field:"effort",map:DEEPSEEK_EFFORT,extra:DEEPSEEK_EFFORT_EXTRA},{provider:"openai",re:/^(gpt-5|o[0-9])/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"groq",re:/^(openai\/gpt-oss|qwen\/qwen3)/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"xai",re:/^grok-(4\.[5-9]|[5-9])/,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"google",re:/^gemini-(2\.5|3|[4-9])/,field:"reasoning_effort",map:{...EFFORT_IDENTITY,medium:"high"}}],AUTONOMOUS_IDLE_TIMEOUT_MS=9e5;function reasoningBudget(e,t,o){const n=Number(t);return Number.isFinite(n)&&n>0?n:DEEPSEEK_REASONING_MODEL_RE.test(String(e||""))?EFFORT_TOKEN_BUDGET["low"===o||"medium"===o||"max"===o?o:"high"]:void 0}function nativeEffort(e,t,o){const n=String(t||"");if(EFFORT_INERT_RE.test(n))return;if(null===o)return;const r="low"===o||"medium"===o?o:"max"===o?"max":"high";for(const t of EFFORT_DIALECTS)if(t.provider===e&&t.re.test(n)){const e=Object.prototype.hasOwnProperty.call(t.map,r)?t.map[r]:t.extra&&Object.prototype.hasOwnProperty.call(t.extra,r)?t.extra[r]:void 0;if(void 0===e)return;return{field:t.field,level:e}}}function normalizeCatalog(e){return Array.isArray(e)?e.map((e=>"string"==typeof e?{id:e}:e)).filter((e=>e&&e.id)):[]}const{offerableCatalog:offerableCatalog}=requireSharedBrain(),{withByokAdditions:withByokAdditions,canonicalModelId:canonicalModelId,nexusFallbackModel:nexusFallbackModel}=requireSharedByokCatalog(),{withUserModels:withUserModels,unmatchedUserProviders:unmatchedUserProviders,load:loadUserModels,addUserModel:addUserModel,removeUserModel:removeUserModel}=requireSharedUserModels(),{withCatalog:withCatalog}=requireSharedCatalogClient(),{discoverModels:discoverVendorModels,canDiscover:canDiscoverVendorModels,endpointFor:vendorEndpointFor,discoverableProviders:discoverableProviders}=requireSharedModelDiscovery();function parseArgs(e){if(null==e)return{};if("object"==typeof e)return e;try{const t=JSON.parse(String(e));return t&&"object"==typeof t?t:{}}catch{return{}}}function extractToolCalls(e){if(!e)return[];if(Array.isArray(e.toolCalls)&&e.toolCalls.length)return e.toolCalls.map((e=>({id:e.id||"",name:e.name||"",args:parseArgs(e.args)}))).filter((e=>e.name));const t=e.choices&&e.choices[0]&&e.choices[0].message,o=t&&t.tool_calls||[];return Array.isArray(o)?o.map((e=>{const t=e&&e.function||{};return{id:e&&e.id||"",name:t.name||e&&e.name||"",args:parseArgs(t.arguments)}})).filter((e=>e.name)):[]}function proTurnPrompt(e){const t=Array.isArray(e.prompt)?flattenContent(e.prompt):e.prompt;if("string"==typeof t&&t.trim())return t;const o=Array.isArray(e.messages)?e.messages:[];for(let e=o.length-1;e>=0;e-=1){const t=o[e];if(!t||"user"!==t.role)continue;const n=flattenContent(t.content);if(n.trim())return n}return t}function assistantText(e){const t=e&&e.choices&&e.choices[0]&&e.choices[0].message;return t&&"string"==typeof t.content&&t.content||""}function finishReasonOf(e){const t=e&&e.choices&&e.choices[0];return t&&t.finish_reason||e&&e.stop_reason||""}function isTruncated(e){const t=finishReasonOf(e);return"length"===t||"max_tokens"===t}function reasoningTextOf(e){if(!e)return"";const t=e.choices&&e.choices[0],o=t&&t.message||{};if(Array.isArray(o.content)){const e=o.content.filter((e=>e&&("thinking"===e.type||"reasoning"===e.type))).map((e=>e.thinking||e.text||"")).join("");if(e)return e}const n=o.content&&"object"==typeof o.content?o.content.reasoning_content:"",r=[o.reasoning_content,o.reasoning,t&&t.reasoning_content,e.reasoning_content,e.reasoning,n];for(const e of r)if("string"==typeof e&&e)return e;return""}function reasoningTokensOf(e){if(!e)return 0;const t=e.choices&&e.choices[0],o=t&&t.message||{},n=e.usage||{},r=n.completion_tokens_details||n.output_tokens_details||{},s=[o.thinking_tokens,o.reasoning_tokens,t&&t.thinking_tokens,e.thinking_tokens,r.reasoning_tokens,r.thinking_tokens];for(const e of s)if("number"==typeof e&&Number.isFinite(e)&&e>0)return e;return 0}function reasonedButSilent(e){return!assistantText(e)&&(""!==reasoningTextOf(e)||reasoningTokensOf(e)>0)}const REASONING_RETRY_FLOOR=32768;function retryBudgetFor(e,t){const o=doubledBudget(e.maxTokens);return t&&ladderRung(e.maxTokens)?Math.max(o,REASONING_RETRY_FLOOR):o}function ladderRung(e){const t=Number(e);return Number.isFinite(t)&&Object.values(EFFORT_TOKEN_BUDGET).includes(t)}function doubledBudget(e){const t=Number(e)||0;return t>0?2*t:8192}function statedCapOf(e){const t=e=>{const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0};return e&&Object.prototype.hasOwnProperty.call(e,"statedMaxTokens")?t(e.statedMaxTokens):t(e&&e.maxTokens)}const EMPTY_TURN_NUDGE="Your previous reply came back empty — it contained no answer and no tool call. Write your answer now, using only the information already gathered above. No tools are available in this reply, so do not call any: respond in plain prose or markdown.",THOUGHT_ONLY_NUDGE="Your previous round was spent entirely on hidden reasoning and produced no visible reply. Answer the user directly and briefly now. Do not reason, explain, or think first — write only the answer, no tools.",FINAL_ANSWER_NUDGE="Write your answer now, in plain prose, using only what is already in this conversation. If your information is incomplete, say what you have and what is missing — an incomplete answer is the expected outcome here and is better than none. No tools, no preface.",RECOVERY_ROUNDS=2,UNMUTATED_TURN_NUDGE="You ended the turn without changing any file, but this request asked for a change. The tools are still available in this reply: make the edit now with editFile or writeFile. If you already know what to change, change it — describing the fix is not the fix. If you genuinely cannot, say precisely what blocks you.",MUTATION_INTENT_RE=new RegExp("\\b(?:fix|implement|add|create|write|refactor|rename|remove|delete|replace|update|patch|migrate|convert|make\\s+(?:it|them|this|that|the|sure)|change|correct|resolve|repair|address|apply|introduce|support|wire\\s+up)\\b","i");function wantsMutation(e,t,o){if(t)return!1;if(!(o>0))return!1;const n=String(e||"");return!!n.trim()&&!/\?\s*$/.test(n.trim())&&MUTATION_INTENT_RE.test(n)}function emptyTurnError({cls:e,model:t,finishReason:o,reasoningChars:n,reasoningTokens:r,effort:s,recoveryRounds:a}){const i=Number(a)||0,l=Number(r)||0,c=new Error(`The model returned no answer after ${e}/${t} was asked to summarise its results`+(i?`, and ${i} extra recovery call${1===i?"":"s"} with a larger budget and a changed ask came back empty too`:"")+` (stop reason: ${o||"none"}`+(s?`, effort: ${s}`:"")+(n?`, hidden reasoning: ${n} chars and no visible text`:l>0?`, ~${l} thinking tokens billed and no visible text`:"")+"). "+(n||l>0?"Every one of those calls spent its output on hidden reasoning instead of writing a word, so this is the model rather than the budget: pick a model that answers without a thinking pass, or ask for a smaller piece of work.":"No visible text came back from any of those calls. Send the request again, in smaller pieces, or from a different model."));return c.status=502,c}function createLocalEngine({aegis:e,settings:t,tools:o,promptBuilder:n,recallProvider:r,env:s,getConfirmMode:a,getPermissionMode:i,sandbox:l,localTransport:c=localTransport,fetchImpl:d,gitScope:u,permissionRules:f}){const p=new Map,m=o||toolsModule,h=n&&n.buildSystemPrompt||promptModule.buildSystemPrompt,g=f&&"function"==typeof f.rulesVerdict?f.rulesVerdict:null,y=f&&"function"==typeof f.alwaysAllow?f.alwaysAllow:null,k=f&&"function"==typeof f.subjectFor?f.subjectFor:null,v=require("./session-rounds.js"),b=()=>{if("function"==typeof a)return!1!==a();if(t&&"function"==typeof t.getConfirmMode){const e=t.getConfirmMode();return void 0===e||Boolean(e)}return!0},w=()=>"function"==typeof i?"plan"===i():!(!t||"function"!=typeof t.getPermissionMode)&&"plan"===t.getPermissionMode();function E(e,t){return`${e} was not executed — this session is in plan mode (read-only). Plan mode may read files, search, run read-only shell commands and deploy subagents to research, but may not create, edit or delete files, run a mutating command, or install packages`+(t?` (this command: ${t})`:"")+". Do NOT retry it or attempt the same effect by another route. Finish your research and present a plan in plain text; the user exits plan mode (`/permissions mode off`) before any edit can run."}const _=new Map,T=new Map,S=new Map,x=200,A=new Map,M=require("./pro-sessions.js"),O=new Map,N=new Map;function F(e,t){if("function"!=typeof k)return e;let o="";try{o=String(k(e,t||{})||"")}catch{o=""}return`${e}\0${o}`}function R(e,t,o){_.has(e)||_.set(e,new Set),_.get(e).add(F(t,o))}function D(e,t){const o=T.get(e);return Boolean(o&&o.has(t))}function U(e,t){T.has(e)||T.set(e,new Set),T.get(e).add(t)}function I(e){if(!e)return null;try{return{existed:!0,content:fs.readFileSync(e,"utf8")}}catch(e){return e&&"ENOENT"===e.code?{existed:!1,content:null}:null}}function L(e){return`${e} was not executed — the user denied this tool for this conversation. Do NOT retry it and do NOT attempt the same effect by another route (another command, a writeFile instead of an edit, a subagent). Stop calling tools and reply in plain text: say what you were trying to do, what you need, and that the user can re-enable ${e} to let it proceed.`}function C(e,t,o,n){return new Promise((r=>{if(o&&o.aborted)return void r("cancel");const s=randomUUID();let a=!1;const i=()=>l("cancel"),l=e=>{a||(a=!0,O.delete(s),o&&o.removeEventListener("abort",i),r(e))};o&&o.addEventListener("abort",i,{once:!0}),O.set(s,{resolve:l}),"function"==typeof t?t({delta:"",approval:{id:s,sessionId:e,tool:n.tool,args:n.args,diff:n.diff||null,canPersist:"function"==typeof y}}):l("cancel")}))}function P(e,t,o,n){return new Promise((r=>{if(o&&o.aborted)return void r(!1);const s=randomUUID();let a=!1;const i=()=>l(!1),l=e=>{a||(a=!0,N.delete(s),o&&o.removeEventListener("abort",i),r(e))};o&&o.addEventListener("abort",i,{once:!0}),N.set(s,{resolve:l}),"function"==typeof t?t({delta:"",rounds:{id:s,sessionId:e,spent:n.spent,extensions:n.extensions,max:n.max,size:n.size}}):l(!1)}))}async function $(e,t,o,n,r){const s=normalizeToolArgs(m,e,t,o||{});if(!s.ok)return{ok:!1,error:s.error};t=s.args;const a=o&&o.guard;if(a&&"exec"===e){const e=blocksDestructive(a,t&&t.command);if(!e.ok)return{ok:!1,error:e.reason}}const i=covenant.preActionAssert({tool:e,args:t||{}});if(!i.allowed){const o=covenant.bindRefusal({tool:e,args:t||{}},i);return{ok:!1,error:`refused by the ÆGIS covenant — ${i.clause} (${i.label}): ${i.reason}`,covenant:o}}const l="writeFile"===e||"editFile"===e,c=l?I(t&&t.file_path):null,d=await m.executeTool(e,t,o);if(a&&l&&d&&!1!==d.ok&&recordWrite(a,t&&t.file_path),l&&c&&d&&!1!==d.ok){const o=I(t&&t.file_path);o&&function(e,t){if(!e)return;S.has(e)||S.set(e,[]);const o=S.get(e);o.push(t),o.length>x&&o.shift()}(n,{id:r||randomUUID(),tool:e,path:t&&t.file_path,before:c,after:o,at:Date.now()})}return d}function j(e,t){if(!e||"object"!=typeof e)return{ok:!0,content:`${t}\n${null==e?"":e}`};if(!1===e.ok||!0===e.isError){const o=e.error||e.content||"";return{...e,error:`${t}\n${o}`,content:`${t}\n${o}`}}const o=null!=e.content?e.content:null!=e.output?e.output:"";return{...e,content:`${t}\n${o}`}}async function B(e,{toolCtx:t,rootSessionId:o,rootOnDelta:n,signal:r}){const{name:s}=e,a=normalizeToolArgs(m,s,e.args,t||{});if(!a.ok)return{ok:!1,error:a.error};const i=a.args;if(!m.MUTATING_TOOLS.has(s))return $(s,i,t,o,e.id);if(w()){if("exec"===s){const n=planExec(i&&i.command,{baseCwd:t&&t.cwd||void 0});return n.oneShot?$(s,i,t,o,e.id):{ok:!1,error:E(s,n.reason)}}return{ok:!1,error:E(s)}}if(!b())return $(s,i,t,o,e.id);if(function(e,t,o){const n=_.get(e);return Boolean(n&&n.has(F(t,o)))}(o,s,i))return $(s,i,t,o,e.id);if("function"==typeof g){let n;try{n=g(s,i)}catch(e){n={verdict:null,source:"error",error:e&&e.message||String(e)}}if(n&&"deny"===n.verdict)return U(o,s),{ok:!1,error:L(s),permissionRule:n.rule||null};if(n&&"allow"===n.verdict)return $(s,i,t,o,e.id)}if(D(o,s))return{ok:!1,error:L(s)};let l=null;if(("writeFile"===s||"editFile"===s)&&(l=m.previewMutation(s,i,t||{}),!l.ok))return{ok:!1,error:l.error};const c=await C(o,n,r,{tool:s,args:i,diff:l&&l.diff});if("deny"===c)return U(o,s),{ok:!1,error:L(s)};if("session"!==c&&"once"!==c&&"always"!==c)return{ok:!1,error:`${s} was not executed — the request was cancelled.`};let d=null;if("always"===c){let e=null;if("function"==typeof y)try{e=y(s,i)}catch(t){e={ok:!1,reason:t&&t.message||String(t)}}else e={ok:!1,reason:"no durable store is wired on this host"};d=e&&e.ok?`[permission_rule] stored ${e.rule} — this command will not ask again`:`[permission_rule] nothing was stored — ${e&&e.reason||"unknown reason"}; this call was allowed once only`}if("session"===c&&R(o,s,i),l){const e=m.applyChecked(s,i,l,t||{});return e&&!1!==e.ok&&t&&t.guard&&recordWrite(t.guard,i&&i.file_path),d?j(e,d):e}const u=await $(s,i,t,o,e.id);return d?j(u,d):u}function q(e){return hostEnv(s||{},e&&e.env||{},e)}function K(e){const t=[],o=e=>String(e||"").replace(/[\\/]+$/,""),n=o(e),r=e=>{const r=o(e);r&&r!==n&&!t.includes(r)&&t.push(r)};let s=u;if(void 0===s)try{s=require("./git-scope.js")}catch{s=null}try{s&&"function"==typeof s.gitRoot&&r(s.gitRoot(e))}catch{}try{credentialsLib&&"function"==typeof credentialsLib.aegisHome&&r(credentialsLib.aegisHome())}catch{}return t}async function G(t,o){if("aegis"===t){const t=!o.singlePass&&(!!o.autonomous||void 0);return e.chatCompletion({prompt:o.prompt,system:o.system,messages:o.messages,model:o.model,mode:o.mode,maxTokens:o.statedMaxTokens,stream:!1!==o.stream,includeUsage:!0,onStream:o.onDelta,onReasoning:o.onReasoning,idleTimeoutMs:o.idleTimeoutMs,signal:o.signal,extra:{aegis_recall:!0,...o.recallDeep?{aegis_recall_deep:!0}:{},session:o.sessionId,...void 0===t?{}:{brain:t},...!1===t?{mode:"brain"}:{},...o.effort?{effort:o.effort}:{},...!0===t&&o.workers?{workers:o.workers}:{},...o.tools.length?{tools:o.tools}:{},...o.toolChoice?{tool_choice:o.toolChoice}:{}},agentKey:o.tools.length&&(process.env.AEGIS_AGENT_KEY||"").trim()||void 0})}if("byok"===t){const{provider:t,model:n}=splitByokModel(o.model),r=canonicalModelId(t,n),s=nativeEffort(t,r,o.effort);try{return await e.byokChatCompletion({provider:t,model:r,providerKey:o.apiKey,baseURL:o.cfg&&o.cfg.baseURL,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,tools:o.tools,toolChoice:o.toolChoice,effort:s&&"effort"===s.field?s.level:void 0,reasoningEffort:s&&"reasoning_effort"===s.field?s.level:void 0,stream:!0,onStream:o.onDelta,signal:o.signal})}catch(e){if(e&&402===e.status){const e=new Error("byok: this account has no AEGIS balance left, and the BYOK handling fee is billed there — your provider key is still valid, this is not a key problem. Top up the account, then try again (or /class aegis to use the pooled lane).");throw e.status=402,e}throw e}}if("local"===t){const e=o.cfg&&o.cfg.baseURL||c.DEFAULT_BASE,t=t=>c.chat({baseURL:e,model:o.model,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,signal:o.signal,onDelta:o.onDelta,...t&&o.tools.length?{tools:o.tools,toolChoice:o.toolChoice}:{}});try{return await t(!0)}catch(e){if(o.tools.length&&e&&400===e.status)return t(!1);throw e}}if("pro"===t){const e=o.sessionKey||o.rootSessionId||o.sessionId;let t=null;if(e&&(t=A.get(e)||null,!t)){try{t=M.get(e,s)||null}catch{}t&&A.set(e,t)}const n=K(o.cwd),r=e=>claudePro.runClaudePro({prompt:proTurnPrompt(o),model:o.model&&"default"!==o.model?o.model:void 0,system:o.system,cwd:o.cwd,addDir:n,resumeSessionId:e||void 0,gate:b(),onAsk:async e=>{if(!e||!e.requestId)return"deny";const t=o.rootSessionId,n=o.rootOnDelta,r=PRO_TOOL_MAP[String(e.toolName||"")]||null,s=r||String(e.toolName||"unknown"),a=proAskArgs(e.input||{},s),i=covenant.preActionAssert({tool:s,args:a});if(!i.allowed)return n&&n({delta:"",note:`aegis: refused by the ÆGIS covenant — ${i.clause} (${i.label}): ${i.reason}`}),"deny";if(w()){if("exec"===s){const e=planExec(a&&a.command,{baseCwd:o.cwd||void 0});return e.oneShot?"once":(n&&n({delta:"",note:E(s,e.reason)}),"deny")}if(r&&m.MUTATING_TOOLS.has(s))return n&&n({delta:"",note:E(s)}),"deny";if(!r&&!PRO_PLAN_MODE_SAFE.has(s))return n&&n({delta:"",note:E(s)}),"deny"}if(!b())return"once";if("function"==typeof g){let e;try{e=g(s,a)}catch{e=null}if(e&&"deny"===e.verdict)return n&&n({delta:"",note:L(s)}),"deny";if(e&&"allow"===e.verdict)return"once"}if(D(t,s))return n&&n({delta:"",note:L(s)}),"deny";const l=await C(t,n,o.signal,{tool:s,args:a,diff:null});if("deny"===l)return U(t,s),"deny";if("session"!==l&&"once"!==l&&"always"!==l)return"deny";if("session"===l&&R(t,s,a),"always"===l&&"function"==typeof y)try{y(s,a)}catch{}return l},signal:o.signal,onDelta:o.onDelta,onSpawn:(e,t)=>{o.onDelta&&t&&o.onDelta({delta:"",note:claudePro.childLine(t)})}});let a=await r(t);if(a&&a.resumeStale){A.delete(e);try{M.del(e,s)}catch{}o.onDelta&&o.onDelta({delta:"",note:"aegis: the remembered Claude session no longer exists on this machine — continuing as a new conversation (earlier turns are not in its context)"}),a=await r(null)}if(e&&a&&a.sessionId&&!a.error){A.set(e,a.sessionId);try{M.set(e,a.sessionId,s)}catch{}}return a}throw new Error(`dispatch: unknown model class ${JSON.stringify(t)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)}async function Y(o,n){const r=o&&o.class,s=o&&o.model,a=reasoningBudget("byok"===r?splitByokModel(s).model:s,o&&o.maxTokens,o&&o.effort),i=statedCapOf(o),d="aegis"===r&&Boolean(o&&o.autonomous),u=Boolean(o&&o.roundsAsk),f=o&&o.sessionId||randomUUID(),g=Number.isInteger(o&&o.depth)?o.depth:0,y=o&&o.rootSessionId||f,k=o&&o.rootOnDelta||n,b="function"==typeof n?e=>e&&n({reasoning:e}):void 0,w=new AbortController;p.set(f,w);const E=w.signal,_=!(o&&!1===o.tools),T=_?m.toolsFor({includeSubagent:g<4}):[],S=o&&o.toolChoice||null,x=o&&o.system||h(q(o)),A=Array.isArray(o&&o.messages)?o.messages.filter(Boolean).slice():[];let M=A.length,O=o&&o.prompt||"";const N=String(O||""),F=Array.isArray(o&&o.attachments)?o.attachments.filter((e=>e&&"object"==typeof e)).slice(0,attachmentsModule.MAX_ATTACHMENTS):[];let R=F.length?attachmentsModule.buildContent(O,F):O,D=null;const U=q(o),I=((e,t)=>{if(null==l)return null;const o="function"==typeof l.policy?l.policy():l.policy;if(!o)return null;const n=require("./sandbox.js"),r=e&&e.cwd||process.cwd(),s=n.normalize(o,r);if("off"===s.mode)return null;let a=[];try{let e=null;try{e=require("node:os").homedir()}catch{e=null}a=n.autoGrants(r,{home:e,addDirs:(()=>{try{return K(r)}catch{return[]}})()})}catch{a=[]}if(a.length){const e=new Set;for(const t of s.fileSystem.entries)t&&t.path&&"path"===t.path.type&&t.path.path&&e.add(`${t.access}:${t.path.path}`);for(const t of a){const o=`${t.access}:${t.path.path}`;e.has(o)||(e.add(o),s.fileSystem.entries.push(t))}}return"local"===t&&"restricted"===s.network&&(s.network="open",s.networkExempt="local"),{policy:s,state:l.state||n.detect({appDir:l.appDir}),workspace:r,appDir:l.appDir,strict:!0===l.strict}})(U,r),L=U.cwd,C={getShell:()=>D||(D=new ShellSession({cwd:U.cwd,sandbox:I})),signal:E,cwd:L,desktopdir:U.desktopdir,sandbox:I};try{const l="byok"===r?splitByokModel(s):null;let p=null;const h="byok"===r?t.get(byokNamespace(l.provider))||{}:"local"===r&&t.get("local")||{},w="byok"===r?t.rawKey(byokNamespace(l.provider)):null,D="byok"!==r?null:w||providerKeyFromEnv(l.provider);if(!("byok"!==r||l.provider&&l.model)){const e=new Error('byok: model must be "<provider>:<model>" (pick one from /models) — got '+JSON.stringify(s||""));throw e.status=400,e}if("byok"===r&&!D){const t="anthropic"===l.provider?claudePro.claudeProStatus({env:process.env}):null,o=providerKeyRecord(l.provider).rejected,n=nexusFallbackModel({provider:l.provider,providerKey:D,providerKeyRefused:o,aegisKey:D?"":e.apiKey});if(!n){const e=new Error(o?`${o}. That is why this turn has no ${l.provider} key: an env value that short is a paste that lost its payload, not a credential. Fix ${o.split(" ")[0]} in ~/.aegiscode/.env (or the shell that exported it) — or skip keys entirely: /byok-key ${l.provider} <key> to set one here.`:t&&t.loggedIn?`No Anthropic API key on this machine — an "anthropic:…" id is served by your own console key, which a Claude subscription is not. Use the subscription instead: /class pro (it spends your Claude Code ${t.subscription||"Pro"} plan through the claude CLI) — or add a real console key: /byok-key anthropic <key>.`:`No key for "${l.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, no setup) — or add this provider's own key: /byok-key ${l.provider} <key>.`);throw e.status=400,e}p={from:l.provider,model:n}}if("byok"===r&&!e.apiKey){const e=new Error("No AEGIS key connected yet. Easiest fix: /class aegis (skips BYOK entirely) — or add your AEGIS key with /login, then try again.");throw e.status=401,e}if("local"===r){const e=c.remoteRefusal(h.baseURL||c.DEFAULT_BASE);if(e)throw e}if("byok"===r&&"custom"===l.provider&&!(h.baseURL||"").trim()){const e=new Error('No endpoint saved for the "custom" provider — its key is on this machine but the address it dials is not, and no default exists for a vendor AEGIS does not know. Fix: /model-add custom <https-base-url> <api-key> <model-id> (writes both halves), or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const U=p?"aegis":r,I={cls:U,model:p?p.model:s,mode:o&&o.mode,maxTokens:a,statedMaxTokens:i,autonomous:d,sessionId:f,signal:E,onDelta:n,cfg:h,apiKey:D,toolChoice:S,pooledFrom:p?p.from:void 0,cwd:L,rootSessionId:y,sessionKey:o&&o.sessionKey||void 0,rootOnDelta:k,effort:o&&o.effort,workers:o&&o.workers,recallDeep:o&&!0===o.recallDeep,singlePass:o&&!0===o.singlePass,onReasoning:b,idleTimeoutMs:d?9e5:void 0,stream:!o||!1!==o.stream};let $=!1,j=!1;const q=d?"AEGIS_AUTONOMOUS_MAX_ROUNDS":"AEGIS_CHAT_MAX_ROUNDS",K=(()=>{const e=Number.parseInt(process.env[q]||"",10);return Number.isFinite(e)&&e>0?e:0})(),Y=K||(d?40:24);let z=v.keyFor(o,A),H=v.take(z);if(!H&&!v.isStatedKey(o)){const e=v.adopt();e&&(H=e.entry,z=e.key)}if(H){const e=v.resumePreamble(H);0===A.length?Array.isArray(H.messages)&&H.messages.length&&A.push(...H.messages):Array.isArray(H.added)&&H.added.length&&A.push(...H.added),O?(O=`${e}\n\n${O}`,R=F.length?attachmentsModule.buildContent(O,F):O):(A.push({role:"user",content:e}),R=""),k&&k({delta:`\n\n[resuming work this session left unfinished at ${H.rounds} tool rounds`+(H.interruptions>1?` (cut off ${H.interruptions}×)`:"")+"…]\n"})}let V=K||Y+(H?v.bonus(Y):0),X=0;const J=Y,Q=8;let Z=0;const ee={calls:0},te=["input_tokens","output_tokens","prompt_tokens","completion_tokens","total_tokens","cache_read_input_tokens","cache_creation_input_tokens","prompt_cache_hit_tokens","prompt_cache_miss_tokens","reasoning_tokens","thinking_tokens"],oe=e=>{const t=e&&e.usage;if(t&&"object"==typeof t){ee.calls+=1;for(const e of te)"number"==typeof t[e]&&Number.isFinite(t[e])&&(ee[e]=(ee[e]||0)+t[e]);if("number"!=typeof t.total_tokens){const e=(t.prompt_tokens??t.input_tokens??0)+(t.completion_tokens??t.output_tokens??0);e&&(ee.total_tokens=(ee.total_tokens||0)+e)}}},ne=e=>{if(!e||"object"!=typeof e)return e;const t=p?{...e,pooled_from:p.from,pooled_model:p.model,pooled_notice:requireSharedByokCatalog().nexusFallbackNotice({pooled_from:p.from,pooled_model:p.model})}:e;return ee.calls?{...t,usage:{...ee}}:t},re=()=>{if(""===R)return;const e=A[A.length-1],t=e&&"user"===e.role?flattenContent(e.content):null;e&&"user"===e.role&&t===flattenContent(R)||A.push({role:"user",content:R}),O="",R=""};M=A.length;const se=m&&m.MUTATING_TOOLS||new Set;let ae=0,ie=0,le=!1;for(;;){if(X>=V){if(u&&Z<Q&&!E.aborted&&await P(y,k,E,{spent:V,extensions:Z+1,max:Q,size:J})){Z+=1;const e=V;V+=J,A.push({role:"user",content:`You have used all ${e} tool rounds allowed for this turn; ${J} more have been granted (do not restart). Continue the task from exactly where you stopped — do not re-plan, do not repeat work already done, and finish with an answer.`});continue}const e=u?"":`, or raise ${q} for a longer single turn`,t=`[stopped at ${V} tool rounds`+(ee.total_tokens?`, ${ee.total_tokens.toLocaleString()} tokens`:"")+". This session holds the work: your next message here resumes it automatically"+` (with a continuation preamble)${e}.]`,o=v.record(z,{rounds:X,tokens:ee.total_tokens||0,note:t,chain:H?H.interruptions:0,messages:A,added:A.slice(M)});return k&&k({delta:`\n\n${t}`}),ne({model:I.model,choices:[{message:{content:t},finish_reason:"length"}],stoppedOnRounds:!0,heldForSession:!0,heldRounds:o.rounds,sessionInterruptions:o.interruptions,resumedFrom:z})}X+=1;const e={...I,system:x,messages:A,prompt:R,tools:T,recallDeep:I.recallDeep&&1===X};let t;if(t=await G(U,e),oe(t),E.aborted)return ne(t);if(!$&&!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){$=!0;const o=reasonedButSilent(t);if(t=await G(U,{...e,singlePass:!0,recallDeep:!1,effort:o?"high":e.effort,maxTokens:retryBudgetFor(e,o),statedMaxTokens:e.statedMaxTokens?doubledBudget(e.statedMaxTokens):void 0}),oe(t),E.aborted)return ne(t)}const a=T.length?extractToolCalls(t):[];if(!a.length){if(assistantText(t)||j||!_){if(!le&&_&&wantsMutation(N,ie>0,ae)){le=!0,re(),A.push({role:"assistant",content:assistantText(t)}),A.push({role:"user",content:UNMUTATED_TURN_NUDGE}),k&&k({delta:""});continue}return ne(t)}j=!0,re(),A.push({role:"user",content:reasonedButSilent(t)?THOUGHT_ONLY_NUDGE:EMPTY_TURN_NUDGE});const o={...e,singlePass:!0,recallDeep:!1,messages:A,prompt:"",tools:[]};t=await G(U,o);let n=o.maxTokens,a=o.effort;if(oe(t),E.aborted)return ne(t);if(!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){const e=reasonedButSilent(t);if(n=retryBudgetFor(o,e),a=e?"high":o.effort,t=await G(U,{...o,effort:a,maxTokens:n,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),E.aborted)return ne(t)}const i=(()=>{const e=Number(n)||0;if(!e)return n;const t={maxTokens:n};return o.statedMaxTokens&&(t.statedMaxTokens=o.statedMaxTokens),Math.max(e,retryBudgetFor(t,!0))})();let l=0;for(;!assistantText(t)&&l<2&&!E.aborted;){const e=reasonedButSilent(t);if(l+=1,A.push({role:"user",content:e?1===l?THOUGHT_ONLY_NUDGE:FINAL_ANSWER_NUDGE:EMPTY_TURN_NUDGE}),e&&(a="high"),n=i,t=await G(U,{...o,messages:A,effort:a,maxTokens:n,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),E.aborted)return ne(t)}if(!assistantText(t))throw emptyTurnError({cls:r,model:s,effort:a,recoveryRounds:l,finishReason:finishReasonOf(t),reasoningChars:reasoningTextOf(t).length,reasoningTokens:reasoningTokensOf(t)});return ne(t)}re(),A.push({role:"assistant",content:assistantText(t),tool_calls:a.map((e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}})))});const l=new WeakMap,c=e=>{if("exec"!==e.name)return null;if(l.has(e))return l.get(e);const t=planExec(e.args&&e.args.command,{baseCwd:L});return l.set(e,t),t},d=e=>{if(!se.has(e.name))return!0;const t=c(e);return Boolean(t&&t.oneShot)},f=[];for(const e of a){const t=f[f.length-1];d(e)&&t&&t.parallel?t.calls.push(e):f.push({parallel:d(e),calls:[e]})}const p=async e=>{n&&n({delta:"",tool:{name:e.name,args:e.args,id:e.id,cwd:L,phase:"run"}});const t=c(e),a=t&&t.oneShot?{...C,oneShotExec:!0,cwd:t.cwd||C.cwd}:C,l=e.name===m.SUBAGENT_TOOL?await W(e.args,{cls:r,model:s,statedMaxTokens:i,effort:o&&o.effort,mode:o&&o.mode,parentSignal:E,depth:g,rootSessionId:y,rootOnDelta:k}):await B(e,{toolCtx:a,rootSessionId:y,rootOnDelta:k,signal:E});return l&&l.usage&&oe({usage:l.usage}),n&&n({delta:"",tool:{name:e.name,args:e.args,ok:l.ok,id:e.id,cwd:L,phase:"done"}}),l};for(const e of f){const t=e.parallel&&e.calls.length>1?await Promise.all(e.calls.map((e=>p(e)))):[await p(e.calls[0])];e.calls.forEach(((e,o)=>{const n=t[o];se.has(e.name)&&(ae+=1,n&&n.ok&&(ie+=1)),A.push({role:"tool",tool_call_id:e.id,name:e.name,content:m.toolResultText(n)})}))}}}catch(e){throw E.aborted&&e&&"object"==typeof e&&(e.aegisCancelled=!0),e}finally{D&&D.dispose(),p.delete(f)}}async function W({description:e,subagent_type:t,prompt:o}={},{cls:n,model:r,statedMaxTokens:s,effort:a,mode:i,parentSignal:l,depth:c,rootSessionId:d,rootOnDelta:u}={}){const f=String(o||e||"").trim();if(!f)return{ok:!1,error:"task requires a prompt"};const p=t&&"general"!==t?agentRoleLabel(t):"general",m=agentSystemPrompt(t),h=randomUUID();let g;if(l){if(l.aborted)return{ok:!1,error:"aborted"};g=()=>z(h),l.addEventListener("abort",g,{once:!0})}try{const e=await Y({class:n,model:r,mode:i,system:m,prompt:f,sessionId:h,depth:(c||0)+1,rootSessionId:d,rootOnDelta:u,statedMaxTokens:s,effort:a},(()=>{})),t=assistantText(e),o=e&&e.usage?{usage:e.usage}:{};return t?{ok:!0,output:t,...o}:{ok:!1,error:`subagent (${p}) produced no output`,...o}}catch(e){return{ok:!1,error:`subagent (${p}) failed: ${e&&e.message?e.message:e}`}}finally{l&&g&&l.removeEventListener("abort",g)}}function z(e){const t=p.get(e);return t&&t.abort(),{ok:Boolean(t)}}return{CLASSES:CLASSES,listClasses:async function(){return CLASSES.map((o=>{if("aegis"===o.class)return{...o,configured:Boolean(e.apiKey)};if("byok"===o.class){const e=(t.list()||[]).some((e=>!(!e||"string"!=typeof e.provider||!e.provider.startsWith("byok:"))&&(!!e.configured||Boolean(providerKeyFromEnv(e.provider.slice(BYOK_NAMESPACE_PREFIX.length))))));return{...o,configured:e}}if("local"===o.class)return{...o,configured:!0};if("pro"===o.class){const e=claudePro.claudeProStatus({env:process.env}),t=claudePro.seamAvailable();return{...o,configured:e.loggedIn,status:e,seam:t}}return{...o,configured:!1}}))},listModels:async function(o){if("aegis"===o){if(!e.apiKey)return{class:o,models:[],needsKey:!0};const t=await e.listModels();return{class:o,models:offerableCatalog(normalizeCatalog(t&&t.models))}}if("byok"===o){let n=[],r=null,s=!1,a=null;try{const t=await e.byokProviders();n=withUserModels(withCatalog(withByokAdditions(t&&t.providers||[]))),r=t&&t.fee||null}catch(e){n=[],s=!0,a=e&&e.message||String(e)}const i=[];for(const e of n){if(!e||!e.id)continue;const o=t.get(byokNamespace(e.id))||{},n=providerKeyRecord(e.id),r=n.key||"",s=Array.isArray(e.models)?e.models:[];for(const t of s){const s="string"==typeof t?t:t&&t.id;s&&i.push({id:`${e.id}:${s}`,label:`${e.label||e.id} — ${s}`,provider:e.id,configured:Boolean(o.configured||r),keyRejected:n.rejected||null})}}return{class:o,models:i,providers:n,needsProviderKey:i.length>0&&!i.some((e=>e.configured)),needsAegisKey:!e.apiKey,fee:r,providersFailed:s,providersError:a,unmatchedProviders:unmatchedUserProviders(n)}}if("local"===o){const e=(t.get("local")||{}).baseURL||c.DEFAULT_BASE,n=await c.probe(e);if(!n.running)return{class:o,models:[],baseURL:n.baseURL,needsDaemon:!0};let r=[],s=!0;try{r=await c.listTags(e)}catch{s=!1}return{class:o,models:r,baseURL:n.baseURL,listed:s}}if("pro"===o){const e=claudePro.claudeProStatus({env:process.env});return{class:o,models:claudePro.PRO_MODELS.map((t=>({id:t.id,label:t.label,note:t.note,configured:e.loggedIn}))),needsProviderKey:!1,needsAegisKey:!1,subscription:e.subscription,loggedIn:e.loggedIn,credentialFile:e.file,shadowed:e.shadowed||null,seam:claudePro.seamAvailable()}}throw new Error(`listModels: unknown model class ${JSON.stringify(o)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)},chat:Y,cancel:z,respondApproval:function(e,t){const o=O.get(e);return o?(O.delete(e),o.resolve("session"===t||"once"===t||"always"===t?t:"deny"),{ok:!0}):{ok:!1}},respondRoundsAsk:function(e,t){const o=N.get(e);return o?(N.delete(e),o.resolve(!0===t||"continue"===t),{ok:!0}):{ok:!1}},clearSessionApprovals:function(e){_.delete(e),T.delete(e),S.delete(e),A.delete(e);try{M.del(e,s)}catch{}return{ok:!0}},listUndoable:function(e){return(S.get(e)||[]).map((e=>({id:e.id,tool:e.tool,path:e.path,at:e.at}))).reverse()},undoMutation:function(e,t){const o=S.get(e)||[],n=t?o.findIndex((e=>e.id===t)):o.length-1;if(-1===n)return{ok:!1,error:t?`no undo record "${t}" for this conversation`:"nothing to undo in this conversation"};const r=o[n],s=I(r.path);if(!s||s.existed!==r.after.existed||s.content!==r.after.content)return{ok:!1,error:`${r.path} has changed since ${r.tool} ran — undo refused rather than overwriting work this session did not do. Resolve it by hand, or undo a different entry.`};try{r.before.existed?fs.writeFileSync(r.path,r.before.content,"utf8"):fs.unlinkSync(r.path)}catch(e){return{ok:!1,error:`undo failed: ${e&&e.message||e}`}}return o.splice(n,1),{ok:!0,path:r.path,restored:r.before.existed?"content":"deleted"}},settings:t,unloadLocalModels:function(){return c.unloadAll()},userModels:()=>loadUserModels(),addUserModel:(e,t)=>addUserModel(e,t),removeUserModel:(e,t)=>removeUserModel(e,t),discoverModels:async e=>{const o=String(null==e?"":e).trim().toLowerCase(),n=function(e){const o=String(null==e?"":e).trim().toLowerCase();if(!o)return"";try{if(t&&"function"==typeof t.rawKey){const e=t.rawKey(byokNamespace(o));if("string"==typeof e&&e.trim())return e.trim()}}catch{}return providerKeyFromEnv(o)}(o),r=await discoverVendorModels(o,{key:n,fetchImpl:d});if(!r||!r.ok)return r;const s=[];try{const e=loadUserModels().map;for(const t of Array.isArray(e[o])?e[o]:[])s.push(t)}catch{}return{...r,declared:s,endpoint:(vendorEndpointFor(o)||{}).url||""}},addUserModels:(e,t)=>{const o=Array.isArray(t)?t:[],n={provider:e,added:0,already:[],failed:[],capped:0,file:""};for(const t of o)try{const o=addUserModel(e,t);n.file=o.file||n.file,o.added?n.added+=1:n.already.push(o.model)}catch(e){const r=e&&e.message||String(e);if(/the cap/.test(r)){n.capped=o.length-n.added-n.already.length-n.failed.length;break}n.failed.push({id:String(t),reason:r})}return n},canDiscoverModels:e=>canDiscoverVendorModels(e),discoverableProviders:()=>discoverableProviders()}}module.exports={CLASSES:CLASSES,createLocalEngine:createLocalEngine,extractToolCalls:extractToolCalls,parseArgs:parseArgs,reasoningBudget:reasoningBudget,nativeEffort:nativeEffort,hostEnv:hostEnv};
|
|
3
|
+
"use strict";const{randomUUID:randomUUID}=require("node:crypto"),os=require("node:os"),fs=require("node:fs"),toolsModule=require("./tools.js"),attachmentsModule=require("./attachments.js"),{flattenContent:flattenContent}=attachmentsModule,promptModule=require("./prompt.js"),localTransport=require("./local.js"),{ShellSession:ShellSession}=require("./shell.js"),{planExec:planExec}=require("./exec-plan.js"),claudePro=require("./claude-pro.js"),{agentSystemPrompt:agentSystemPrompt,agentRoleLabel:agentRoleLabel}=require("./agents.js"),{beginTurnGuard:beginTurnGuard,recordWrite:recordWrite,blocksDestructive:blocksDestructive}=require("./turn-guard.js"),repeatGuard=require("./repeat-guard.js"),verifyGuard=require("./verify-stop.js"),{acquireWorktreeLock:acquireWorktreeLock,releaseWorktreeLock:releaseWorktreeLock}=require("./worktree-lock.js"),covenant=require("./covenant.js");let envFile=null;try{envFile=require("../../../client/env-file.js")}catch{try{envFile=require("../../vendor/env-file.js")}catch{envFile=null}}let platformLib=null;try{platformLib=require("../../../client/platform.js")}catch{try{platformLib=require("../../vendor/platform.js")}catch{platformLib=null}}let credentialsLib=null;try{credentialsLib=require("../../../client/credentials.js")}catch{try{credentialsLib=require("../../vendor/credentials.js")}catch{credentialsLib=null}}const PRO_TOOL_MAP=Object.freeze({Write:"writeFile",Edit:"editFile",MultiEdit:"editFile",NotebookEdit:"editFile",Bash:"exec",BashOutput:"exec"}),PRO_PLAN_MODE_SAFE=Object.freeze(new Set(["Read","Glob","Grep"]));function proAskArgs(e,t){const o=e&&"object"==typeof e?e:{};return"exec"===t?"string"==typeof o.command?{command:o.command}:{}:"writeFile"===t?"string"==typeof o.file_path?{file_path:o.file_path,content:o.content}:{}:"editFile"===t?Array.isArray(o.edits)?{file_path:o.file_path,edits:o.edits}:"string"==typeof o.file_path?{file_path:o.file_path,old_string:o.old_string,new_string:o.new_string,replace_all:!0===o.replace_all}:{}:o}function normalizeToolArgs(e,t,o,r){const n=e&&"function"==typeof e.normalizeArgs&&e.normalizeArgs||"function"==typeof toolsModule.normalizeArgs&&toolsModule.normalizeArgs||null;return n?n(t,o,r):{ok:!0,args:o&&"object"==typeof o?o:{},error:null}}function detectVcs(e){if(!e)return null;try{const t=require("node:fs"),o=require("node:path");let r=o.resolve(String(e));for(let e=0;e<8;e+=1){if(t.existsSync(o.join(r,".git")))return"git";const e=o.dirname(r);if(e===r)break;r=e}return""}catch{return null}}function hostEnv(e={},t={},o=null){const r=e||{},n=t||{},s=(e,t)=>null!=n[e]?n[e]:t;let a=r.homedir,i=r.cwd;try{a||(a=os.homedir()),i||(i=process.cwd())}catch{}let l=r.shell,c=r.shellKind;try{if(!l||!c){const e=require("./shell.js").resolveSessionShell();l=l||e.cmd,c=c||e.kind}}catch{}let d=r.desktopdir;try{!d&&platformLib&&(d=platformLib.desktopDir())}catch{}let u=r.dataDir;try{!u&&credentialsLib&&(u=credentialsLib.aegisHome())}catch{}let f=r.locale,p=r.localeName;try{!f&&platformLib&&"function"==typeof platformLib.appLocale&&(f=platformLib.appLocale()),f&&!p&&platformLib&&"function"==typeof platformLib.languageName&&(p=platformLib.languageName(f))}catch{}return{platform:s("platform",r.platform||process.platform),arch:s("arch",r.arch||process.arch),homedir:s("homedir",a),desktopdir:s("desktopdir",d),dataDir:s("dataDir",u),locale:s("locale",f),localeName:s("localeName",p),languages:s("languages",r.languages),cwd:s("cwd",i),vcs:s("vcs",null!=r.vcs?r.vcs:detectVcs(i)),shell:s("shell",l),shellKind:s("shellKind",c),roots:s("roots",r.roots),appVersion:s("appVersion",r.appVersion),model:s("model",o&&o.model)}}function requireSharedBrain(){const e=[()=>require("../../../client/brain-catalog.js"),()=>require("../../vendor/brain-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedByokCatalog(){const e=[()=>require("../../../client/byok-catalog.js"),()=>require("../../vendor/byok-catalog.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedUserModels(){const e=[()=>require("../../../client/user-models.js"),()=>require("../../vendor/user-models.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedCatalogClient(){const e=[()=>require("../../../client/catalog-client.js"),()=>require("../../vendor/catalog-client.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}function requireSharedModelDiscovery(){const e=[()=>require("../../../client/model-discovery.js"),()=>require("../../vendor/model-discovery.js")];let t=null;for(const o of e)try{return o()}catch(e){t=e}throw t}const WORKTREE_LOCK_WAIT_MS=1500,MAX_SUBAGENT_DEPTH=4,CLASSES=[{class:"aegis",label:"Aegis Cloud",kind:"cloud"},{class:"byok",label:"Bring your own key",kind:"cloud"},{class:"local",label:"Local model",kind:"local"},{class:"pro",label:"Claude Code Pro",kind:"subscription"}],BYOK_NAMESPACE_PREFIX="byok:";function byokNamespace(e){return`${BYOK_NAMESPACE_PREFIX}${e}`}function splitByokModel(e){const t="string"==typeof e?e:"",o=t.indexOf(":");return o<0?{provider:"",model:t}:{provider:t.slice(0,o),model:t.slice(o+1)}}function providerKeyRecord(e){const t={key:"",env:"",rejected:null};if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return t;try{const o=envFile.providerKeyFromEnv(e)||t;return{key:"string"==typeof o.key?o.key:"",env:"string"==typeof o.env?o.env:"",rejected:"string"==typeof o.rejected&&o.rejected?o.rejected:null}}catch{return t}}function providerKeyFromEnv(e){if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return"";try{return envFile.providerKeyFromEnv(e).key||""}catch{return""}}const DEEPSEEK_REASONING_MODEL_RE=/^deepseek-(v4(\.\d+)?-(flash|pro)|flash|pro|reasoner)$/,EFFORT_TOKEN_BUDGET={low:8192,medium:16384,high:32768,max:32768},DEEPSEEK_EFFORT={low:"low",medium:"high",high:"high"},DEEPSEEK_EFFORT_EXTRA={max:"max"},EFFORT_IDENTITY={low:"low",medium:"medium",high:"high"},EFFORT_INERT_RE=/non-reasoning/i,EFFORT_DIALECTS=[{provider:"deepseek",re:DEEPSEEK_REASONING_MODEL_RE,field:"effort",map:DEEPSEEK_EFFORT,extra:DEEPSEEK_EFFORT_EXTRA},{provider:"openai",re:/^(gpt-5|o[0-9])/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"groq",re:/^(openai\/gpt-oss|qwen\/qwen3)/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"xai",re:/^grok-(4\.[5-9]|[5-9])/,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"google",re:/^gemini-(2\.5|3|[4-9])/,field:"reasoning_effort",map:{...EFFORT_IDENTITY,medium:"high"}}],AUTONOMOUS_IDLE_TIMEOUT_MS=9e5;function reasoningBudget(e,t,o){const r=Number(t);return Number.isFinite(r)&&r>0?r:DEEPSEEK_REASONING_MODEL_RE.test(String(e||""))?EFFORT_TOKEN_BUDGET["low"===o||"medium"===o||"max"===o?o:"high"]:void 0}function nativeEffort(e,t,o){const r=String(t||"");if(EFFORT_INERT_RE.test(r))return;if(null===o)return;const n="low"===o||"medium"===o?o:"max"===o?"max":"high";for(const t of EFFORT_DIALECTS)if(t.provider===e&&t.re.test(r)){const e=Object.prototype.hasOwnProperty.call(t.map,n)?t.map[n]:t.extra&&Object.prototype.hasOwnProperty.call(t.extra,n)?t.extra[n]:void 0;if(void 0===e)return;return{field:t.field,level:e}}}function normalizeCatalog(e){return Array.isArray(e)?e.map((e=>"string"==typeof e?{id:e}:e)).filter((e=>e&&e.id)):[]}const{offerableCatalog:offerableCatalog}=requireSharedBrain(),{withByokAdditions:withByokAdditions,canonicalModelId:canonicalModelId,nexusFallbackModel:nexusFallbackModel}=requireSharedByokCatalog(),{withUserModels:withUserModels,unmatchedUserProviders:unmatchedUserProviders,load:loadUserModels,addUserModel:addUserModel,removeUserModel:removeUserModel}=requireSharedUserModels(),{withCatalog:withCatalog}=requireSharedCatalogClient(),{discoverModels:discoverVendorModels,canDiscover:canDiscoverVendorModels,endpointFor:vendorEndpointFor,discoverableProviders:discoverableProviders}=requireSharedModelDiscovery();function parseArgs(e){if(null==e)return{};if("object"==typeof e)return e;try{const t=JSON.parse(String(e));return t&&"object"==typeof t?t:{}}catch{return{}}}function extractToolCalls(e){if(!e)return[];if(Array.isArray(e.toolCalls)&&e.toolCalls.length)return e.toolCalls.map((e=>({id:e.id||"",name:e.name||"",args:parseArgs(e.args)}))).filter((e=>e.name));const t=e.choices&&e.choices[0]&&e.choices[0].message,o=t&&t.tool_calls||[];return Array.isArray(o)?o.map((e=>{const t=e&&e.function||{};return{id:e&&e.id||"",name:t.name||e&&e.name||"",args:parseArgs(t.arguments)}})).filter((e=>e.name)):[]}function proTurnPrompt(e){const t=Array.isArray(e.prompt)?flattenContent(e.prompt):e.prompt;if("string"==typeof t&&t.trim())return t;const o=Array.isArray(e.messages)?e.messages:[];for(let e=o.length-1;e>=0;e-=1){const t=o[e];if(!t||"user"!==t.role)continue;const r=flattenContent(t.content);if(r.trim())return r}return t}function assistantText(e){const t=e&&e.choices&&e.choices[0]&&e.choices[0].message;return t&&"string"==typeof t.content&&t.content||""}function finishReasonOf(e){const t=e&&e.choices&&e.choices[0];return t&&t.finish_reason||e&&e.stop_reason||""}function isTruncated(e){const t=finishReasonOf(e);return"length"===t||"max_tokens"===t}function reasoningTextOf(e){if(!e)return"";const t=e.choices&&e.choices[0],o=t&&t.message||{};if(Array.isArray(o.content)){const e=o.content.filter((e=>e&&("thinking"===e.type||"reasoning"===e.type))).map((e=>e.thinking||e.text||"")).join("");if(e)return e}const r=o.content&&"object"==typeof o.content?o.content.reasoning_content:"",n=[o.reasoning_content,o.reasoning,t&&t.reasoning_content,e.reasoning_content,e.reasoning,r];for(const e of n)if("string"==typeof e&&e)return e;return""}function reasoningTokensOf(e){if(!e)return 0;const t=e.choices&&e.choices[0],o=t&&t.message||{},r=e.usage||{},n=r.completion_tokens_details||r.output_tokens_details||{},s=[o.thinking_tokens,o.reasoning_tokens,t&&t.thinking_tokens,e.thinking_tokens,n.reasoning_tokens,n.thinking_tokens];for(const e of s)if("number"==typeof e&&Number.isFinite(e)&&e>0)return e;return 0}function reasonedButSilent(e){return!assistantText(e)&&(""!==reasoningTextOf(e)||reasoningTokensOf(e)>0)}const REASONING_RETRY_FLOOR=32768;function retryBudgetFor(e,t){const o=doubledBudget(e.maxTokens);return t&&ladderRung(e.maxTokens)?Math.max(o,REASONING_RETRY_FLOOR):o}function ladderRung(e){const t=Number(e);return Number.isFinite(t)&&Object.values(EFFORT_TOKEN_BUDGET).includes(t)}function doubledBudget(e){const t=Number(e)||0;return t>0?2*t:8192}function statedCapOf(e){const t=e=>{const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0};return e&&Object.prototype.hasOwnProperty.call(e,"statedMaxTokens")?t(e.statedMaxTokens):t(e&&e.maxTokens)}const EMPTY_TURN_NUDGE="Your previous reply came back empty — it contained no answer and no tool call. Write your answer now, using only the information already gathered above. No tools are available in this reply, so do not call any: respond in plain prose or markdown.",THOUGHT_ONLY_NUDGE="Your previous round was spent entirely on hidden reasoning and produced no visible reply. Answer the user directly and briefly now. Do not reason, explain, or think first — write only the answer, no tools.",FINAL_ANSWER_NUDGE="Write your answer now, in plain prose, using only what is already in this conversation. If your information is incomplete, say what you have and what is missing — an incomplete answer is the expected outcome here and is better than none. No tools, no preface.",RECOVERY_ROUNDS=2,UNMUTATED_TURN_NUDGE="You ended the turn without changing any file, but this request asked for a change. The tools are still available in this reply: make the edit now with editFile or writeFile. If you already know what to change, change it — describing the fix is not the fix. If you genuinely cannot, say precisely what blocks you.",MUTATION_INTENT_RE=new RegExp("\\b(?:fix|implement|add|create|write|refactor|rename|remove|delete|replace|update|patch|migrate|convert|make\\s+(?:it|them|this|that|the|sure)|change|correct|resolve|repair|address|apply|introduce|support|wire\\s+up)\\b","i");function wantsMutation(e,t,o){if(t)return!1;if(!(o>0))return!1;const r=String(e||"");return!!r.trim()&&!/\?\s*$/.test(r.trim())&&MUTATION_INTENT_RE.test(r)}function emptyTurnError({cls:e,model:t,finishReason:o,reasoningChars:r,reasoningTokens:n,effort:s,recoveryRounds:a}){const i=Number(a)||0,l=Number(n)||0,c=new Error(`The model returned no answer after ${e}/${t} was asked to summarise its results`+(i?`, and ${i} extra recovery call${1===i?"":"s"} with a larger budget and a changed ask came back empty too`:"")+` (stop reason: ${o||"none"}`+(s?`, effort: ${s}`:"")+(r?`, hidden reasoning: ${r} chars and no visible text`:l>0?`, ~${l} thinking tokens billed and no visible text`:"")+"). "+(r||l>0?"Every one of those calls spent its output on hidden reasoning instead of writing a word, so this is the model rather than the budget: pick a model that answers without a thinking pass, or ask for a smaller piece of work.":"No visible text came back from any of those calls. Send the request again, in smaller pieces, or from a different model."));return c.status=502,c}function createLocalEngine({aegis:e,settings:t,tools:o,promptBuilder:r,recallProvider:n,env:s,getConfirmMode:a,getPermissionMode:i,sandbox:l,localTransport:c=localTransport,fetchImpl:d,gitScope:u,permissionRules:f}){const p=new Map,m=o||toolsModule,h=r&&r.buildSystemPrompt||promptModule.buildSystemPrompt,g=f&&"function"==typeof f.rulesVerdict?f.rulesVerdict:null,y=f&&"function"==typeof f.alwaysAllow?f.alwaysAllow:null,k=f&&"function"==typeof f.subjectFor?f.subjectFor:null,v=require("./session-rounds.js"),b=()=>{if("function"==typeof a)return!1!==a();if(t&&"function"==typeof t.getConfirmMode){const e=t.getConfirmMode();return void 0===e||Boolean(e)}return!0},w=()=>"function"==typeof i?"plan"===i():!(!t||"function"!=typeof t.getPermissionMode)&&"plan"===t.getPermissionMode();function E(e,t){return`${e} was not executed — this session is in plan mode (read-only). Plan mode may read files, search, run read-only shell commands and deploy subagents to research, but may not create, edit or delete files, run a mutating command, or install packages`+(t?` (this command: ${t})`:"")+". Do NOT retry it or attempt the same effect by another route. Finish your research and present a plan in plain text; the user exits plan mode (`/permissions mode off`) before any edit can run."}const _=new Map,T=new Map,S=new Map,x=200,A=new Map,M=require("./pro-sessions.js"),O=new Map,N=new Map;function F(e,t){if("function"!=typeof k)return e;let o="";try{o=String(k(e,t||{})||"")}catch{o=""}return`${e}\0${o}`}function R(e,t,o){_.has(e)||_.set(e,new Set),_.get(e).add(F(t,o))}function D(e,t){const o=T.get(e);return Boolean(o&&o.has(t))}function U(e,t){T.has(e)||T.set(e,new Set),T.get(e).add(t)}function I(e){if(!e)return null;try{return{existed:!0,content:fs.readFileSync(e,"utf8")}}catch(e){return e&&"ENOENT"===e.code?{existed:!1,content:null}:null}}function L(e){return`${e} was not executed — the user denied this tool for this conversation. Do NOT retry it and do NOT attempt the same effect by another route (another command, a writeFile instead of an edit, a subagent). Stop calling tools and reply in plain text: say what you were trying to do, what you need, and that the user can re-enable ${e} to let it proceed.`}function C(e,t,o,r){return new Promise((n=>{if(o&&o.aborted)return void n("cancel");const s=randomUUID();let a=!1;const i=()=>l("cancel"),l=e=>{a||(a=!0,O.delete(s),o&&o.removeEventListener("abort",i),n(e))};o&&o.addEventListener("abort",i,{once:!0}),O.set(s,{resolve:l}),"function"==typeof t?t({delta:"",approval:{id:s,sessionId:e,tool:r.tool,args:r.args,diff:r.diff||null,canPersist:"function"==typeof y}}):l("cancel")}))}function P(e,t,o,r){return new Promise((n=>{if(o&&o.aborted)return void n(!1);const s=randomUUID();let a=!1;const i=()=>l(!1),l=e=>{a||(a=!0,N.delete(s),o&&o.removeEventListener("abort",i),n(e))};o&&o.addEventListener("abort",i,{once:!0}),N.set(s,{resolve:l}),"function"==typeof t?t({delta:"",rounds:{id:s,sessionId:e,spent:r.spent,extensions:r.extensions,max:r.max,size:r.size}}):l(!1)}))}async function $(e,t,o,r,n){const s=normalizeToolArgs(m,e,t,o||{});if(!s.ok)return{ok:!1,error:s.error};t=s.args;const a=o&&o.guard;if(a&&"exec"===e){const e=blocksDestructive(a,t&&t.command);if(!e.ok)return{ok:!1,error:e.reason}}const i=o&&o.repeat,l=i?repeatGuard.check(i,e,t):null;if(l&&"refuse"===l.action)return{ok:!1,error:l.error};const c=covenant.preActionAssert({tool:e,args:t||{}});if(!c.allowed){const o=covenant.bindRefusal({tool:e,args:t||{}},c);return{ok:!1,error:`refused by the ÆGIS covenant — ${c.clause} (${c.label}): ${c.reason}`,covenant:o}}const d="writeFile"===e||"editFile"===e,u=d?I(t&&t.file_path):null,f=await m.executeTool(e,t,o);a&&d&&f&&!1!==f.ok&&recordWrite(a,t&&t.file_path),i&&d&&f&&!1!==f.ok&&repeatGuard.recordWrite(i,t&&t.file_path);const p=o&&o.verify;if(p&&(verifyGuard.EXEC_TOOLS.has(e)&&f&&!1!==f.ok?verifyGuard.recordExec(p):d&&f&&!1!==f.ok&&verifyGuard.recordMutation(p,t&&t.file_path)),d&&u&&f&&!1!==f.ok){const o=I(t&&t.file_path);o&&function(e,t){if(!e)return;S.has(e)||S.set(e,[]);const o=S.get(e);o.push(t),o.length>x&&o.shift()}(r,{id:n||randomUUID(),tool:e,path:t&&t.file_path,before:u,after:o,at:Date.now()})}return l&&l.note?j(f,l.note):f}function j(e,t){if(!e||"object"!=typeof e)return{ok:!0,content:`${t}\n${null==e?"":e}`};if(!1===e.ok||!0===e.isError){const o=e.error||e.content||"";return{...e,error:`${t}\n${o}`,content:`${t}\n${o}`}}const o=null!=e.content?e.content:null!=e.output?e.output:"";return{...e,content:`${t}\n${o}`}}async function q(e,{toolCtx:t,rootSessionId:o,rootOnDelta:r,signal:n}){const{name:s}=e,a=normalizeToolArgs(m,s,e.args,t||{});if(!a.ok)return{ok:!1,error:a.error};const i=a.args;if(!m.MUTATING_TOOLS.has(s))return $(s,i,t,o,e.id);if(w()){if("exec"===s){const r=planExec(i&&i.command,{baseCwd:t&&t.cwd||void 0});return r.oneShot?$(s,i,t,o,e.id):{ok:!1,error:E(s,r.reason)}}return{ok:!1,error:E(s)}}if(!b())return $(s,i,t,o,e.id);if(function(e,t,o){const r=_.get(e);return Boolean(r&&r.has(F(t,o)))}(o,s,i))return $(s,i,t,o,e.id);if("function"==typeof g){let r;try{r=g(s,i)}catch(e){r={verdict:null,source:"error",error:e&&e.message||String(e)}}if(r&&"deny"===r.verdict)return U(o,s),{ok:!1,error:L(s),permissionRule:r.rule||null};if(r&&"allow"===r.verdict)return $(s,i,t,o,e.id)}if(D(o,s))return{ok:!1,error:L(s)};let l=null;if(("writeFile"===s||"editFile"===s)&&(l=m.previewMutation(s,i,t||{}),!l.ok))return{ok:!1,error:l.error};const c=await C(o,r,n,{tool:s,args:i,diff:l&&l.diff});if("deny"===c)return U(o,s),{ok:!1,error:L(s)};if("session"!==c&&"once"!==c&&"always"!==c)return{ok:!1,error:`${s} was not executed — the request was cancelled.`};let d=null;if("always"===c){let e=null;if("function"==typeof y)try{e=y(s,i)}catch(t){e={ok:!1,reason:t&&t.message||String(t)}}else e={ok:!1,reason:"no durable store is wired on this host"};d=e&&e.ok?`[permission_rule] stored ${e.rule} — this command will not ask again`:`[permission_rule] nothing was stored — ${e&&e.reason||"unknown reason"}; this call was allowed once only`}if("session"===c&&R(o,s,i),l){const e=m.applyChecked(s,i,l,t||{});return e&&!1!==e.ok&&t&&t.guard&&recordWrite(t.guard,i&&i.file_path),d?j(e,d):e}const u=await $(s,i,t,o,e.id);return d?j(u,d):u}function B(e){return hostEnv(s||{},e&&e.env||{},e)}function K(e){const t=[],o=e=>String(e||"").replace(/[\\/]+$/,""),r=o(e),n=e=>{const n=o(e);n&&n!==r&&!t.includes(n)&&t.push(n)};let s=u;if(void 0===s)try{s=require("./git-scope.js")}catch{s=null}try{s&&"function"==typeof s.gitRoot&&n(s.gitRoot(e))}catch{}try{credentialsLib&&"function"==typeof credentialsLib.aegisHome&&n(credentialsLib.aegisHome())}catch{}return t}async function G(t,o){if("aegis"===t){const t=!o.singlePass&&(!!o.autonomous||void 0);return e.chatCompletion({prompt:o.prompt,system:o.system,messages:o.messages,model:o.model,mode:o.mode,maxTokens:o.statedMaxTokens,stream:!1!==o.stream,includeUsage:!0,onStream:o.onDelta,onReasoning:o.onReasoning,idleTimeoutMs:o.idleTimeoutMs,signal:o.signal,extra:{aegis_recall:!0,...o.recallDeep?{aegis_recall_deep:!0}:{},session:o.sessionId,...void 0===t?{}:{brain:t},...!1===t?{mode:"brain"}:{},...o.effort?{effort:o.effort}:{},...!0===t&&o.workers?{workers:o.workers}:{},...o.tools.length?{tools:o.tools}:{},...o.toolChoice?{tool_choice:o.toolChoice}:{}},agentKey:o.tools.length&&(process.env.AEGIS_AGENT_KEY||"").trim()||void 0})}if("byok"===t){const{provider:t,model:r}=splitByokModel(o.model),n=canonicalModelId(t,r),s=nativeEffort(t,n,o.effort);try{return await e.byokChatCompletion({provider:t,model:n,providerKey:o.apiKey,baseURL:o.cfg&&o.cfg.baseURL,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,tools:o.tools,toolChoice:o.toolChoice,effort:s&&"effort"===s.field?s.level:void 0,reasoningEffort:s&&"reasoning_effort"===s.field?s.level:void 0,stream:!0,onStream:o.onDelta,signal:o.signal})}catch(e){if(e&&402===e.status){const e=new Error("byok: this account has no AEGIS balance left, and the BYOK handling fee is billed there — your provider key is still valid, this is not a key problem. Top up the account, then try again (or /class aegis to use the pooled lane).");throw e.status=402,e}throw e}}if("local"===t){const e=o.cfg&&o.cfg.baseURL||c.DEFAULT_BASE,t=t=>c.chat({baseURL:e,model:o.model,prompt:o.prompt,system:o.system,messages:o.messages,maxTokens:o.maxTokens,signal:o.signal,onDelta:o.onDelta,...t&&o.tools.length?{tools:o.tools,toolChoice:o.toolChoice}:{}});try{return await t(!0)}catch(e){if(o.tools.length&&e&&400===e.status)return t(!1);throw e}}if("pro"===t){const e=o.sessionKey||o.rootSessionId||o.sessionId;let t=null;if(e&&(t=A.get(e)||null,!t)){try{t=M.get(e,s)||null}catch{}t&&A.set(e,t)}const r=K(o.cwd),n=e=>claudePro.runClaudePro({prompt:proTurnPrompt(o),model:o.model&&"default"!==o.model?o.model:void 0,system:o.system,cwd:o.cwd,addDir:r,resumeSessionId:e||void 0,gate:b(),onAsk:async e=>{if(!e||!e.requestId)return"deny";const t=o.rootSessionId,r=o.rootOnDelta,n=PRO_TOOL_MAP[String(e.toolName||"")]||null,s=n||String(e.toolName||"unknown"),a=proAskArgs(e.input||{},s),i=covenant.preActionAssert({tool:s,args:a});if(!i.allowed)return r&&r({delta:"",note:`aegis: refused by the ÆGIS covenant — ${i.clause} (${i.label}): ${i.reason}`}),"deny";if(w()){if("exec"===s){const e=planExec(a&&a.command,{baseCwd:o.cwd||void 0});return e.oneShot?"once":(r&&r({delta:"",note:E(s,e.reason)}),"deny")}if(n&&m.MUTATING_TOOLS.has(s))return r&&r({delta:"",note:E(s)}),"deny";if(!n&&!PRO_PLAN_MODE_SAFE.has(s))return r&&r({delta:"",note:E(s)}),"deny"}if(!b())return"once";if("function"==typeof g){let e;try{e=g(s,a)}catch{e=null}if(e&&"deny"===e.verdict)return r&&r({delta:"",note:L(s)}),"deny";if(e&&"allow"===e.verdict)return"once"}if(D(t,s))return r&&r({delta:"",note:L(s)}),"deny";const l=await C(t,r,o.signal,{tool:s,args:a,diff:null});if("deny"===l)return U(t,s),"deny";if("session"!==l&&"once"!==l&&"always"!==l)return"deny";if("session"===l&&R(t,s,a),"always"===l&&"function"==typeof y)try{y(s,a)}catch{}return l},signal:o.signal,onDelta:o.onDelta,onSpawn:(e,t)=>{o.onDelta&&t&&o.onDelta({delta:"",note:claudePro.childLine(t)})}});let a=await n(t);if(a&&a.resumeStale){A.delete(e);try{M.del(e,s)}catch{}o.onDelta&&o.onDelta({delta:"",note:"aegis: the remembered Claude session no longer exists on this machine — continuing as a new conversation (earlier turns are not in its context)"}),a=await n(null)}if(e&&a&&a.sessionId&&!a.error){A.set(e,a.sessionId);try{M.set(e,a.sessionId,s)}catch{}}return a}throw new Error(`dispatch: unknown model class ${JSON.stringify(t)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)}async function Y(o,r){const n=o&&o.class,s=o&&o.model,a=reasoningBudget("byok"===n?splitByokModel(s).model:s,o&&o.maxTokens,o&&o.effort),i=statedCapOf(o),d="aegis"===n&&Boolean(o&&o.autonomous),u=Boolean(o&&o.roundsAsk),f=o&&o.sessionId||randomUUID(),g=Number.isInteger(o&&o.depth)?o.depth:0,y=o&&o.rootSessionId||f,k=o&&o.rootOnDelta||r,b="function"==typeof r?e=>e&&r({reasoning:e}):void 0,w=new AbortController,E=p.get(f)||null;p.set(f,w);const _=w.signal,T=!(o&&!1===o.tools),S=T?m.toolsFor({includeSubagent:g<4}):[],x=o&&o.toolChoice||null,A=o&&o.system||h(B(o)),M=Array.isArray(o&&o.messages)?o.messages.filter(Boolean).slice():[];let O=M.length,N=o&&o.prompt||"";const F=String(N||""),R=Array.isArray(o&&o.attachments)?o.attachments.filter((e=>e&&"object"==typeof e)).slice(0,attachmentsModule.MAX_ATTACHMENTS):[];let D=R.length?attachmentsModule.buildContent(N,R):N,U=null;const I=B(o),L=((e,t)=>{if(null==l)return null;const o="function"==typeof l.policy?l.policy():l.policy;if(!o)return null;const r=require("./sandbox.js"),n=e&&e.cwd||process.cwd(),s=r.normalize(o,n);if("off"===s.mode)return null;let a=[];try{let e=null;try{e=require("node:os").homedir()}catch{e=null}a=r.autoGrants(n,{home:e,addDirs:(()=>{try{return K(n)}catch{return[]}})()})}catch{a=[]}if(a.length){const e=new Set;for(const t of s.fileSystem.entries)t&&t.path&&"path"===t.path.type&&t.path.path&&e.add(`${t.access}:${t.path.path}`);for(const t of a){const o=`${t.access}:${t.path.path}`;e.has(o)||(e.add(o),s.fileSystem.entries.push(t))}}return"local"===t&&"restricted"===s.network&&(s.network="open",s.networkExempt="local"),{policy:s,state:l.state||r.detect({appDir:l.appDir}),workspace:n,appDir:l.appDir,strict:!0===l.strict}})(I,n),C=I.cwd,$={getShell:()=>U||(U=new ShellSession({cwd:I.cwd,sandbox:L})),signal:_,cwd:C,desktopdir:I.desktopdir,sandbox:L,repeat:repeatGuard.beginRepeatGuard({cwd:C}),verify:verifyGuard.beginVerifyGuard({cwd:C}),guard:beginTurnGuard(C)};try{const l="byok"===n?splitByokModel(s):null;let p=null;const h="byok"===n?t.get(byokNamespace(l.provider))||{}:"local"===n&&t.get("local")||{},w="byok"===n?t.rawKey(byokNamespace(l.provider)):null,E="byok"!==n?null:w||providerKeyFromEnv(l.provider);if(!("byok"!==n||l.provider&&l.model)){const e=new Error('byok: model must be "<provider>:<model>" (pick one from /models) — got '+JSON.stringify(s||""));throw e.status=400,e}if("byok"===n&&!E){const t="anthropic"===l.provider?claudePro.claudeProStatus({env:process.env}):null,o=providerKeyRecord(l.provider).rejected,r=nexusFallbackModel({provider:l.provider,providerKey:E,providerKeyRefused:o,aegisKey:E?"":e.apiKey});if(!r){const e=new Error(o?`${o}. That is why this turn has no ${l.provider} key: an env value that short is a paste that lost its payload, not a credential. Fix ${o.split(" ")[0]} in ~/.aegiscode/.env (or the shell that exported it) — or skip keys entirely: /byok-key ${l.provider} <key> to set one here.`:t&&t.loggedIn?`No Anthropic API key on this machine — an "anthropic:…" id is served by your own console key, which a Claude subscription is not. Use the subscription instead: /class pro (it spends your Claude Code ${t.subscription||"Pro"} plan through the claude CLI) — or add a real console key: /byok-key anthropic <key>.`:`No key for "${l.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, no setup) — or add this provider's own key: /byok-key ${l.provider} <key>.`);throw e.status=400,e}p={from:l.provider,model:r}}if("byok"===n&&!e.apiKey){const e=new Error("No AEGIS key connected yet. Easiest fix: /class aegis (skips BYOK entirely) — or add your AEGIS key with /login, then try again.");throw e.status=401,e}if("local"===n){const e=c.remoteRefusal(h.baseURL||c.DEFAULT_BASE);if(e)throw e}if("byok"===n&&"custom"===l.provider&&!(h.baseURL||"").trim()){const e=new Error('No endpoint saved for the "custom" provider — its key is on this machine but the address it dials is not, and no default exists for a vendor AEGIS does not know. Fix: /model-add custom <https-base-url> <api-key> <model-id> (writes both halves), or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const U=p?"aegis":n,I={cls:U,model:p?p.model:s,mode:o&&o.mode,maxTokens:a,statedMaxTokens:i,autonomous:d,sessionId:f,signal:_,onDelta:r,cfg:h,apiKey:E,toolChoice:x,pooledFrom:p?p.from:void 0,cwd:C,rootSessionId:y,sessionKey:o&&o.sessionKey||void 0,rootOnDelta:k,effort:o&&o.effort,workers:o&&o.workers,recallDeep:o&&!0===o.recallDeep,singlePass:o&&!0===o.singlePass,onReasoning:b,idleTimeoutMs:d?9e5:void 0,stream:!o||!1!==o.stream};let L=!1,j=!1;const B=d?"AEGIS_AUTONOMOUS_MAX_ROUNDS":"AEGIS_CHAT_MAX_ROUNDS",K=(()=>{const e=Number.parseInt(process.env[B]||"",10);return Number.isFinite(e)&&e>0?e:0})(),Y=K||(d?40:24);let z=v.keyFor(o,M),V=v.take(z);if(!V&&!v.isStatedKey(o)){const e=v.adopt();e&&(V=e.entry,z=e.key)}if(V){const e=v.resumePreamble(V);0===M.length?Array.isArray(V.messages)&&V.messages.length&&M.push(...V.messages):Array.isArray(V.added)&&V.added.length&&M.push(...V.added),N?(N=`${e}\n\n${N}`,D=R.length?attachmentsModule.buildContent(N,R):N):(M.push({role:"user",content:e}),D=""),k&&k({delta:`\n\n[resuming work this session left unfinished at ${V.rounds} tool rounds`+(V.interruptions>1?` (cut off ${V.interruptions}×)`:"")+"…]\n"})}let H=K||Y+(V?v.bonus(Y):0),X=0;const J=Y,Q=8;let Z=0;const ee={calls:0},te=["input_tokens","output_tokens","prompt_tokens","completion_tokens","total_tokens","cache_read_input_tokens","cache_creation_input_tokens","prompt_cache_hit_tokens","prompt_cache_miss_tokens","reasoning_tokens","thinking_tokens"],oe=e=>{const t=e&&e.usage;if(t&&"object"==typeof t){ee.calls+=1;for(const e of te)"number"==typeof t[e]&&Number.isFinite(t[e])&&(ee[e]=(ee[e]||0)+t[e]);if("number"!=typeof t.total_tokens){const e=(t.prompt_tokens??t.input_tokens??0)+(t.completion_tokens??t.output_tokens??0);e&&(ee.total_tokens=(ee.total_tokens||0)+e)}}},re=e=>{if(!e||"object"!=typeof e)return e;const t=p?{...e,pooled_from:p.from,pooled_model:p.model,pooled_notice:requireSharedByokCatalog().nexusFallbackNotice({pooled_from:p.from,pooled_model:p.model})}:e;return ee.calls?{...t,usage:{...ee}}:t},ne=()=>{if(""===D)return;const e=M[M.length-1],t=e&&"user"===e.role?flattenContent(e.content):null;e&&"user"===e.role&&t===flattenContent(D)||M.push({role:"user",content:D}),N="",D=""};O=M.length;const se=m&&m.MUTATING_TOOLS||new Set;let ae=0,ie=0,le=!1,ce=!1;for(;;){if(X>=H){if(u&&Z<Q&&!_.aborted&&await P(y,k,_,{spent:H,extensions:Z+1,max:Q,size:J})){Z+=1;const e=H;H+=J,M.push({role:"user",content:`You have used all ${e} tool rounds allowed for this turn; ${J} more have been granted (do not restart). Continue the task from exactly where you stopped — do not re-plan, do not repeat work already done, and finish with an answer.`});continue}const e=u?"":`, or raise ${B} for a longer single turn`,t=`[stopped at ${H} tool rounds`+(ee.total_tokens?`, ${ee.total_tokens.toLocaleString()} tokens`:"")+". This session holds the work: your next message here resumes it automatically"+` (with a continuation preamble)${e}.]`,o=v.record(z,{rounds:X,tokens:ee.total_tokens||0,note:t,chain:V?V.interruptions:0,messages:M,added:M.slice(O)});return k&&k({delta:`\n\n${t}`}),re({model:I.model,choices:[{message:{content:t},finish_reason:"length"}],stoppedOnRounds:!0,heldForSession:!0,heldRounds:o.rounds,sessionInterruptions:o.interruptions,resumedFrom:z})}X+=1;const e={...I,system:A,messages:M,prompt:D,tools:S,recallDeep:I.recallDeep&&1===X};let t;if(t=await G(U,e),oe(t),_.aborted)return re(t);if(!L&&!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){L=!0;const o=reasonedButSilent(t);if(t=await G(U,{...e,singlePass:!0,recallDeep:!1,effort:o?"high":e.effort,maxTokens:retryBudgetFor(e,o),statedMaxTokens:e.statedMaxTokens?doubledBudget(e.statedMaxTokens):void 0}),oe(t),_.aborted)return re(t)}const a=S.length?extractToolCalls(t):[];if(!a.length){if(assistantText(t)||j||!T){if(!le&&T&&wantsMutation(F,ie>0,ae)){le=!0,ne(),M.push({role:"assistant",content:assistantText(t)}),M.push({role:"user",content:UNMUTATED_TURN_NUDGE}),k&&k({delta:""});continue}if($.verify&&!ce){const e=verifyGuard.shouldNudge($.verify);if(e.nudge){ce=!0,ne(),M.push({role:"assistant",content:assistantText(t)}),M.push({role:"user",content:e.text}),k&&k({delta:""});continue}}return re(t)}j=!0,ne(),M.push({role:"user",content:reasonedButSilent(t)?THOUGHT_ONLY_NUDGE:EMPTY_TURN_NUDGE});const o={...e,singlePass:!0,recallDeep:!1,messages:M,prompt:"",tools:[]};t=await G(U,o);let r=o.maxTokens,a=o.effort;if(oe(t),_.aborted)return re(t);if(!assistantText(t)&&(isTruncated(t)||reasonedButSilent(t))){const e=reasonedButSilent(t);if(r=retryBudgetFor(o,e),a=e?"high":o.effort,t=await G(U,{...o,effort:a,maxTokens:r,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),_.aborted)return re(t)}const i=(()=>{const e=Number(r)||0;if(!e)return r;const t={maxTokens:r};return o.statedMaxTokens&&(t.statedMaxTokens=o.statedMaxTokens),Math.max(e,retryBudgetFor(t,!0))})();let l=0;for(;!assistantText(t)&&l<2&&!_.aborted;){const e=reasonedButSilent(t);if(l+=1,M.push({role:"user",content:e?1===l?THOUGHT_ONLY_NUDGE:FINAL_ANSWER_NUDGE:EMPTY_TURN_NUDGE}),e&&(a="high"),r=i,t=await G(U,{...o,messages:M,effort:a,maxTokens:r,statedMaxTokens:o.statedMaxTokens?doubledBudget(o.statedMaxTokens):void 0}),oe(t),_.aborted)return re(t)}if(!assistantText(t))throw emptyTurnError({cls:n,model:s,effort:a,recoveryRounds:l,finishReason:finishReasonOf(t),reasoningChars:reasoningTextOf(t).length,reasoningTokens:reasoningTokensOf(t)});return re(t)}ne(),M.push({role:"assistant",content:assistantText(t),tool_calls:a.map((e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}})))});const l=new WeakMap,c=e=>{if("exec"!==e.name)return null;if(l.has(e))return l.get(e);const t=planExec(e.args&&e.args.command,{baseCwd:C});return l.set(e,t),t},d=e=>{if(!se.has(e.name))return!0;const t=c(e);return Boolean(t&&t.oneShot)},f=[];for(const e of a){const t=f[f.length-1];d(e)&&t&&t.parallel?t.calls.push(e):f.push({parallel:d(e),calls:[e]})}const p=async e=>{r&&r({delta:"",tool:{name:e.name,args:e.args,id:e.id,cwd:C,phase:"run"}});const t=c(e),a=t&&t.oneShot?{...$,oneShotExec:!0,cwd:t.cwd||$.cwd}:$,l=e.name===m.SUBAGENT_TOOL?await W(e.args,{cls:n,model:s,statedMaxTokens:i,effort:o&&o.effort,mode:o&&o.mode,parentSignal:_,depth:g,rootSessionId:y,rootOnDelta:k}):await q(e,{toolCtx:a,rootSessionId:y,rootOnDelta:k,signal:_});return l&&l.usage&&oe({usage:l.usage}),r&&r({delta:"",tool:{name:e.name,args:e.args,ok:l.ok,id:e.id,cwd:C,phase:"done"}}),l};for(const e of f){const t=e.parallel&&e.calls.length>1?await Promise.all(e.calls.map((e=>p(e)))):[await p(e.calls[0])];e.calls.forEach(((e,o)=>{const r=t[o];se.has(e.name)&&(ae+=1,r&&r.ok&&(ie+=1)),M.push({role:"tool",tool_call_id:e.id,name:e.name,content:m.toolResultText(r)})}))}}}catch(e){throw _.aborted&&e&&"object"==typeof e&&(e.aegisCancelled=!0),e}finally{U&&U.dispose(),p.get(f)===w&&(E&&!E.signal.aborted?p.set(f,E):p.delete(f))}}async function W({description:e,subagent_type:t,prompt:o}={},{cls:r,model:n,statedMaxTokens:s,effort:a,mode:i,parentSignal:l,depth:c,rootSessionId:d,rootOnDelta:u}={}){const f=String(o||e||"").trim();if(!f)return{ok:!1,error:"task requires a prompt"};const p=t&&"general"!==t?agentRoleLabel(t):"general",m=agentSystemPrompt(t),h=randomUUID();let g;if(l){if(l.aborted)return{ok:!1,error:"aborted"};g=()=>z(h),l.addEventListener("abort",g,{once:!0})}try{const e=await Y({class:r,model:n,mode:i,system:m,prompt:f,sessionId:h,depth:(c||0)+1,rootSessionId:d,rootOnDelta:u,statedMaxTokens:s,effort:a},(()=>{})),t=assistantText(e),o=e&&e.usage?{usage:e.usage}:{};return t?{ok:!0,output:t,...o}:{ok:!1,error:`subagent (${p}) produced no output`,...o}}catch(e){return{ok:!1,error:`subagent (${p}) failed: ${e&&e.message?e.message:e}`}}finally{l&&g&&l.removeEventListener("abort",g)}}function z(e){const t=p.get(e);return t&&t.abort(),{ok:Boolean(t)}}return{CLASSES:CLASSES,listClasses:async function(){return CLASSES.map((o=>{if("aegis"===o.class)return{...o,configured:Boolean(e.apiKey)};if("byok"===o.class){const e=(t.list()||[]).some((e=>!(!e||"string"!=typeof e.provider||!e.provider.startsWith("byok:"))&&(!!e.configured||Boolean(providerKeyFromEnv(e.provider.slice(BYOK_NAMESPACE_PREFIX.length))))));return{...o,configured:e}}if("local"===o.class)return{...o,configured:!0};if("pro"===o.class){const e=claudePro.claudeProStatus({env:process.env}),t=claudePro.seamAvailable();return{...o,configured:e.loggedIn,status:e,seam:t}}return{...o,configured:!1}}))},listModels:async function(o){if("aegis"===o){if(!e.apiKey)return{class:o,models:[],needsKey:!0};const t=await e.listModels();return{class:o,models:offerableCatalog(normalizeCatalog(t&&t.models))}}if("byok"===o){let r=[],n=null,s=!1,a=null;try{const t=await e.byokProviders();r=withUserModels(withCatalog(withByokAdditions(t&&t.providers||[]))),n=t&&t.fee||null}catch(e){r=[],s=!0,a=e&&e.message||String(e)}const i=[];for(const e of r){if(!e||!e.id)continue;const o=t.get(byokNamespace(e.id))||{},r=providerKeyRecord(e.id),n=r.key||"",s=Array.isArray(e.models)?e.models:[];for(const t of s){const s="string"==typeof t?t:t&&t.id;s&&i.push({id:`${e.id}:${s}`,label:`${e.label||e.id} — ${s}`,provider:e.id,configured:Boolean(o.configured||n),keyRejected:r.rejected||null})}}return{class:o,models:i,providers:r,needsProviderKey:i.length>0&&!i.some((e=>e.configured)),needsAegisKey:!e.apiKey,fee:n,providersFailed:s,providersError:a,unmatchedProviders:unmatchedUserProviders(r)}}if("local"===o){const e=(t.get("local")||{}).baseURL||c.DEFAULT_BASE,r=await c.probe(e);if(!r.running)return{class:o,models:[],baseURL:r.baseURL,needsDaemon:!0};let n=[],s=!0;try{n=await c.listTags(e)}catch{s=!1}return{class:o,models:n,baseURL:r.baseURL,listed:s}}if("pro"===o){const e=claudePro.claudeProStatus({env:process.env});return{class:o,models:claudePro.PRO_MODELS.map((t=>({id:t.id,label:t.label,note:t.note,configured:e.loggedIn}))),needsProviderKey:!1,needsAegisKey:!1,subscription:e.subscription,loggedIn:e.loggedIn,credentialFile:e.file,shadowed:e.shadowed||null,seam:claudePro.seamAvailable()}}throw new Error(`listModels: unknown model class ${JSON.stringify(o)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)},chat:Y,cancel:z,respondApproval:function(e,t){const o=O.get(e);return o?(O.delete(e),o.resolve("session"===t||"once"===t||"always"===t?t:"deny"),{ok:!0}):{ok:!1}},respondRoundsAsk:function(e,t){const o=N.get(e);return o?(N.delete(e),o.resolve(!0===t||"continue"===t),{ok:!0}):{ok:!1}},clearSessionApprovals:function(e){_.delete(e),T.delete(e),S.delete(e),A.delete(e);try{M.del(e,s)}catch{}return{ok:!0}},listUndoable:function(e){return(S.get(e)||[]).map((e=>({id:e.id,tool:e.tool,path:e.path,at:e.at}))).reverse()},undoMutation:function(e,t){const o=S.get(e)||[],r=t?o.findIndex((e=>e.id===t)):o.length-1;if(-1===r)return{ok:!1,error:t?`no undo record "${t}" for this conversation`:"nothing to undo in this conversation"};const n=o[r],s=I(n.path);if(!s||s.existed!==n.after.existed||s.content!==n.after.content)return{ok:!1,error:`${n.path} has changed since ${n.tool} ran — undo refused rather than overwriting work this session did not do. Resolve it by hand, or undo a different entry.`};try{n.before.existed?fs.writeFileSync(n.path,n.before.content,"utf8"):fs.unlinkSync(n.path)}catch(e){return{ok:!1,error:`undo failed: ${e&&e.message||e}`}}return o.splice(r,1),{ok:!0,path:n.path,restored:n.before.existed?"content":"deleted"}},settings:t,unloadLocalModels:function(){return c.unloadAll()},userModels:()=>loadUserModels(),addUserModel:(e,t)=>addUserModel(e,t),removeUserModel:(e,t)=>removeUserModel(e,t),discoverModels:async e=>{const o=String(null==e?"":e).trim().toLowerCase(),r=function(e){const o=String(null==e?"":e).trim().toLowerCase();if(!o)return"";try{if(t&&"function"==typeof t.rawKey){const e=t.rawKey(byokNamespace(o));if("string"==typeof e&&e.trim())return e.trim()}}catch{}return providerKeyFromEnv(o)}(o),n=await discoverVendorModels(o,{key:r,fetchImpl:d});if(!n||!n.ok)return n;const s=[];try{const e=loadUserModels().map;for(const t of Array.isArray(e[o])?e[o]:[])s.push(t)}catch{}return{...n,declared:s,endpoint:(vendorEndpointFor(o)||{}).url||""}},addUserModels:(e,t)=>{const o=Array.isArray(t)?t:[],r={provider:e,added:0,already:[],failed:[],capped:0,file:""};for(const t of o)try{const o=addUserModel(e,t);r.file=o.file||r.file,o.added?r.added+=1:r.already.push(o.model)}catch(e){const n=e&&e.message||String(e);if(/the cap/.test(n)){r.capped=o.length-r.added-r.already.length-r.failed.length;break}r.failed.push({id:String(t),reason:n})}return r},canDiscoverModels:e=>canDiscoverVendorModels(e),discoverableProviders:()=>discoverableProviders()}}module.exports={CLASSES:CLASSES,createLocalEngine:createLocalEngine,extractToolCalls:extractToolCalls,parseArgs:parseArgs,reasoningBudget:reasoningBudget,nativeEffort:nativeEffort,hostEnv:hostEnv};
|
|
@@ -134,7 +134,7 @@ const UNITS = Object.freeze([
|
|
|
134
134
|
* (`tools/desktop-seal.mjs` in the source tree, `tools/obfuscate-faces.mjs`
|
|
135
135
|
* after obfuscation), never by hand.
|
|
136
136
|
*/
|
|
137
|
-
const SEALED = '
|
|
137
|
+
const SEALED = '2cc769c4c18eaba250015d15c7064f24076d14e0ff390e337abda71a23a4b34f';
|
|
138
138
|
|
|
139
139
|
/**
|
|
140
140
|
* Ask the question. Never throws — a check that can break the program it is
|
|
@@ -199,9 +199,14 @@ function validateRule(rule, opts = {}) {
|
|
|
199
199
|
// Removing the ability to express it would push users to `/confirm off`,
|
|
200
200
|
// which is the same state with no visible rule at all.
|
|
201
201
|
if (pattern === undefined || pattern === '') {
|
|
202
|
+
// The multi-`cd` rail only exists for the shell tool; naming it in a
|
|
203
|
+
// warning about `websearch` or `read` would be a sentence about nothing.
|
|
204
|
+
const rail = canonTool(tool) === 'shell'
|
|
205
|
+
? ', including commands that change directory more than once'
|
|
206
|
+
: '';
|
|
202
207
|
return {
|
|
203
208
|
ok: true,
|
|
204
|
-
warning: `a bare ${tool}() rule matches every ${tool} call
|
|
209
|
+
warning: `a bare ${tool}() rule matches every ${tool} call${rail}`,
|
|
205
210
|
};
|
|
206
211
|
}
|
|
207
212
|
return { ok: true };
|
|
@@ -209,7 +214,7 @@ function validateRule(rule, opts = {}) {
|
|
|
209
214
|
|
|
210
215
|
/** The capabilities `cli/src/permissions.js`'s TOOL_ALIAS folds onto. A rule
|
|
211
216
|
* naming anything else is inert, which `validateRule` refuses. */
|
|
212
|
-
const KNOWN_TOOLS = new Set(['shell', 'read', 'write', 'edit', 'list', 'glob', 'grep', 'task']);
|
|
217
|
+
const KNOWN_TOOLS = new Set(['shell', 'read', 'write', 'edit', 'list', 'glob', 'grep', 'websearch', 'task']);
|
|
213
218
|
|
|
214
219
|
/** The file shape, with `explicitAsk` deliberately absent — see listRules. */
|
|
215
220
|
function toFileShape(rules) {
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
2
|
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
-
"use strict";const MAIN_CHAT_PROMPT='You are Aegiscodex, a terminal coding assistant working in the user\'s repository: read and reason about code, write and edit files, run shell commands, investigate bugs. Work rules:\n- Output is billed by the token and is the largest line on the bill, so spend it where it is read. Before a tool call, one short sentence on what you are about to find out. Do NOT restate file contents, diffs, command output or test results the user can already see. Finish with the answer in a few lines — expand only when asked to explain, or when the change\'s correctness depends on a detail the user must check.\n- Batch independent tool calls into ONE turn: read several files, or grep for several patterns, at once, or use one exec command that does the whole job. Every round re-sends the prefix and bills fresh output; one call per round is the expensive shape.\n- Edit in one call, not one hunk per round: editFile takes an `edits` array, so every hunk you already know about for one file goes in a single call. A fix you can see is a fix you can also write without asking the tool anything in between.\n- Run the thing you changed before you call it done. A patch you never executed is a hypothesis; when the repo has a test or repro command, run it (or the narrowest slice of it) and report what it printed. If you cannot run it, say which command you would have run. - Use tools silently. A one-line reason is enough; do not narrate your plan as a story. - Never claim what a tool found or what a command returned before the tool actually runs. Report only the results you really received. - Before starting a fix or feature, check whether they have asked for it before and whether it was delivered: recalled memory, `queue.jsonl`, `PLAN.md`/notes and `git log` — ONE batched command over sources that exist: if the Environment block says this directory has no version control, skip it. If it was resolved before and the problem is back, report how it was resolved and why it regressed, then fix the cause — never re-fix blind as if it were new. If it was never met, say so plainly before starting. - Match the response to the request. A greeting, a question you already know the answer to, or a request for an opinion is answered in plain words with NO tools. Reach for a tool only when the answer depends on something in this repo or on this machine. "hey" is not a task.\n- WHEN THE USER HAS ASKED FOR WORK: act, don\'t just inspect. After at most 2 rounds of reading or exploration, start making changes with writeFile or editFile. Reconnaissance is not progress — implement, then verify. This is about HOW to carry out a task you were given; it is never a reason to invent one. Never write or modify a file the user did not ask you to touch.\n- Zero tolerance for stalling: once the cause is identified and only the edit remains, make it in the same turn. Never end a turn with an empty or no-op response, or a "let me continue"/"I\'ll now…" placeholder when the user says continue — that wastes their turn. This has been flagged as non-compliance before; treat it as a hard rule. - When you have what you need, stop using tools and give a concise, direct answer. Never end a turn with an intention like "Let me check…" — that is not an answer. - When a focused multi-step sub-task can be delegated, use the task tool to spawn a specialist subagent rather than doing it inline. - If the user references a workflow you don\'t recognize, inspect the repo/scripts for that mechanism before acting.',TOOL_LINE="Tools: readFile, writeFile, editFile, listDir, glob, grep, exec, task. Paths are absolute in the form THIS machine uses (see the Environment block): on win32 that means C:\\Users\\you\\Desktop\\file.txt, not /home/you/Desktop/file.txt or /tmp/file.txt. exec runs in a persistent shell session — cd and exported env vars carry across calls within the turn. task spawns a specialist subagent (its own tool loop, same model).";function languageLine(e){if("string"==typeof e)return e.trim();if(!e||"object"!=typeof e)return"";if("string"==typeof e.value&&e.value.trim())return e.value.trim();const t="string"==typeof e.name?e.name.trim():"",n="string"==typeof e.code?e.code.trim():"string"==typeof e.key?e.key.trim():"";return t&&n?`${t} (${n})`:t||n}function environmentPreamble(e={}){const{platform:t,arch:n,homedir:o,desktopdir:
|
|
3
|
+
"use strict";const MAIN_CHAT_PROMPT='You are Aegiscodex, a terminal coding assistant working in the user\'s repository: read and reason about code, write and edit files, run shell commands, investigate bugs. Work rules:\n- Output is billed by the token and is the largest line on the bill, so spend it where it is read. Before a tool call, one short sentence on what you are about to find out. Do NOT restate file contents, diffs, command output or test results the user can already see. Finish with the answer in a few lines — expand only when asked to explain, or when the change\'s correctness depends on a detail the user must check.\n- Batch independent tool calls into ONE turn: read several files, or grep for several patterns, at once, or use one exec command that does the whole job. Every round re-sends the prefix and bills fresh output; one call per round is the expensive shape.\n- Edit in one call, not one hunk per round: editFile takes an `edits` array, so every hunk you already know about for one file goes in a single call. A fix you can see is a fix you can also write without asking the tool anything in between.\n- Run the thing you changed before you call it done. A patch you never executed is a hypothesis; when the repo has a test or repro command, run it (or the narrowest slice of it) and report what it printed. If you cannot run it, say which command you would have run. - Use tools silently. A one-line reason is enough; do not narrate your plan as a story. - Never claim what a tool found or what a command returned before the tool actually runs. Report only the results you really received. - Before starting a fix or feature, check whether they have asked for it before and whether it was delivered: recalled memory, `queue.jsonl`, `PLAN.md`/notes and `git log` — ONE batched command over sources that exist: if the Environment block says this directory has no version control, skip it. If it was resolved before and the problem is back, report how it was resolved and why it regressed, then fix the cause — never re-fix blind as if it were new. If it was never met, say so plainly before starting. - Match the response to the request. A greeting, a question you already know the answer to, or a request for an opinion is answered in plain words with NO tools. Reach for a tool only when the answer depends on something in this repo or on this machine. "hey" is not a task.\n- WHEN THE USER HAS ASKED FOR WORK: act, don\'t just inspect. After at most 2 rounds of reading or exploration, start making changes with writeFile or editFile. Reconnaissance is not progress — implement, then verify. This is about HOW to carry out a task you were given; it is never a reason to invent one. Never write or modify a file the user did not ask you to touch.\n- Zero tolerance for stalling: once the cause is identified and only the edit remains, make it in the same turn. Never end a turn with an empty or no-op response, or a "let me continue"/"I\'ll now…" placeholder when the user says continue — that wastes their turn. This has been flagged as non-compliance before; treat it as a hard rule. - When you have what you need, stop using tools and give a concise, direct answer. Never end a turn with an intention like "Let me check…" — that is not an answer. - When a focused multi-step sub-task can be delegated, use the task tool to spawn a specialist subagent rather than doing it inline. - If the user references a workflow you don\'t recognize, inspect the repo/scripts for that mechanism before acting.',TOOL_LINE="Tools: readFile, writeFile, editFile, listDir, glob, grep, exec, websearch, task. Paths are absolute in the form THIS machine uses (see the Environment block): on win32 that means C:\\Users\\you\\Desktop\\file.txt, not /home/you/Desktop/file.txt or /tmp/file.txt. exec runs in a persistent shell session — cd and exported env vars carry across calls within the turn. websearch reaches the web for facts this repo cannot answer. task spawns a specialist subagent (its own tool loop, same model).";function languageLine(e){if("string"==typeof e)return e.trim();if(!e||"object"!=typeof e)return"";if("string"==typeof e.value&&e.value.trim())return e.value.trim();const t="string"==typeof e.name?e.name.trim():"",n="string"==typeof e.code?e.code.trim():"string"==typeof e.key?e.key.trim():"";return t&&n?`${t} (${n})`:t||n}function environmentPreamble(e={}){const{platform:t,arch:n,homedir:o,desktopdir:r,dataDir:s,locale:a,localeName:i,languages:h,cwd:l,vcs:c,shell:d,shellKind:u,roots:p,appVersion:m,model:f}=e||{},y=[];if(t&&y.push(`platform: ${t}${n?` (${n})`:""}`),a){const e=String(a).split("-")[0].toLowerCase(),t=i?` (${i})`:"";y.push("en"===e?`locale: ${a}${t}`:`locale: ${a}${t} — the user's own machine and account run in this language, so expect requests written in it and answer in the language the user writes to you in. Use this to resolve an otherwise ambiguous request (a bare path, a pasted error, a one-word command) — never to override a request written in another language.`)}const w=(Array.isArray(h)?h:[]).map((e=>languageLine(e))).filter(Boolean);w.length&&y.push(`recorded language evidence from the user's own saved writing: ${w.join("; ")} — the language of the request in front of you always wins; this is evidence, not an instruction to switch`),o&&y.push(`home directory: ${o}`),r&&y.push(`desktop directory: ${r} — use this exact path when the user says "my desktop"; do NOT build it yourself from the home directory`),s&&y.push(`AEGIS data directory: ${s} — the store itself (config, sessions, credentials, queue). Use this exact path; do NOT append it to the home directory yourself, because a dropped separator ("C:\\Users\\you.aegiscode") names a path that does not exist and looks like an empty directory rather than a mistake`),l&&y.push(`working directory: ${l}`),"git"===c?y.push("version control: this directory IS inside a git work tree, so `git log`, `git diff` and `git status` are usable for checking what was already done"):""===c&&y.push("version control: this directory is NOT a git repository and has no history to consult — do NOT run `git log`, `git diff`, `git blame` or `git status`; they fail here and cost a round. Read the files that exist instead"),d&&y.push(`exec shell: ${d}${u?` (${u})`:""}`),f&&y.push(`model: ${f}`),m&&y.push(`AEGIS Desktop ${m}`);const g=Array.isArray(p)?p.filter(Boolean):[],b=[];y.length&&b.push(y.join("\n")),g.length&&b.push(`repo roots:\n${g.map((e=>` - ${e}`)).join("\n")}`);const v=commandDialectLine(t,u);return v&&b.push(v),b.length?`# Environment\n${b.join("\n")}`:""}function commandDialectLine(e,t){return e?"win32"===e?`This is Windows: exec runs ${"powershell"===t?"PowerShell":"a Windows shell"}, so use Windows-native commands — Get-ChildItem/dir, Get-Content/type, Select-String/findstr, where, New-Item -ItemType Directory — NOT ls, cat, grep, mkdir -p, touch or rm -rf, which do not exist here. Separate paths with \\, and never assume /tmp, /usr or /home exist.`:"darwin"===e?"This is macOS: exec runs a POSIX shell and the standard Unix commands are available, but the userland is BSD, not GNU — sed -i needs an argument (sed -i ''), and readlink -f, date -d and sed -r are absent. Prefer portable forms, or python3.":"This is a POSIX host: the standard Unix commands are available in exec.":""}const PROJECT_DOC_NAMES=["AEGIS.md","AGENTS.md","CLAUDE.md"],PROJECT_DOC_MAX_CHARS=8e3;function readProjectDoc(e,t={}){if(!e)return"";let n=t.fs,o=t.path;try{n||(n=require("node:fs")),o||(o=require("node:path"))}catch(e){return""}for(const t of PROJECT_DOC_NAMES){let r;try{const s=o.join(e,t),a=n.statSync(s);if(!a||!a.isFile())continue;r=n.readFileSync(s,"utf8")}catch(e){continue}if("string"!=typeof r)continue;const s=r.trim();if(s)return`# Project instructions (${t})\nThese are this repository's own rules. They outrank the generic work rules above wherever the two disagree, and they are the source for build/test/lint commands — prefer them over re-deriving commands by exploring.\n\n`+(s.length>PROJECT_DOC_MAX_CHARS?s.slice(0,PROJECT_DOC_MAX_CHARS)+`\n\n[${t} truncated at ${PROJECT_DOC_MAX_CHARS} characters — read the file for the rest]`:s)}return""}function buildSystemPrompt(e={}){const t=[MAIN_CHAT_PROMPT,TOOL_LINE],n="string"==typeof e.projectDoc&&e.projectDoc.trim()?e.projectDoc.trim():readProjectDoc(e.cwd||process.cwd());n&&t.push(n);const o=environmentPreamble(e);return o&&t.push(o),t.join("\n\n")}module.exports={MAIN_CHAT_PROMPT:MAIN_CHAT_PROMPT,TOOL_LINE:TOOL_LINE,PROJECT_DOC_NAMES:PROJECT_DOC_NAMES,PROJECT_DOC_MAX_CHARS:PROJECT_DOC_MAX_CHARS,environmentPreamble:environmentPreamble,commandDialectLine:commandDialectLine,readProjectDoc:readProjectDoc,buildSystemPrompt:buildSystemPrompt};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
+
"use strict";const path=require("node:path"),WARN_AT=2,REFUSE_AT=5,MODES=new Set(["off","dark","enforce"]),READ_TOOLS=new Set(["readFile"]);function resolveMode(e){const t=String((e||process.env||{}).AEGIS_REPEAT_GUARD||"").trim().toLowerCase();return MODES.has(t)?t:"dark"}function stableJson(e){return null===e||"object"!=typeof e?JSON.stringify(e):Array.isArray(e)?`[${e.map(stableJson).join(",")}]`:`{${Object.keys(e).filter((t=>void 0!==e[t])).sort().map((t=>`${JSON.stringify(t)}:${stableJson(e[t])}`)).join(",")}}`}function callKey(e,t){let a;try{a=stableJson(t&&"object"==typeof t?t:{})}catch{a=`~unserialisable:${Math.random()}`}return`${e}\0${a}`}function beginRepeatGuard(e){const t=resolveMode(e&&e.env);return{mode:t,active:"off"!==t,cwd:e&&e.cwd||null,counts:new Map,paths:new Map,written:new Set,readKeys:new Map,warned:new Set,refusals:0,warnings:0}}function pathKey(e,t){let a=String(e||"");return a?(!t||a.startsWith("~")||path.isAbsolute(a)||(a=path.resolve(t,a)),a.split("\\").join("/").replace(/^\.\//,"")):""}function recordWrite(e,t){if(!e||!e.active)return;const a=pathKey(t,e.cwd);if(!a)return;e.written.add(a);const n=e.readKeys.get(a);if(n){for(const t of n)e.counts.delete(t),e.paths.delete(t),e.warned.delete(t);n.clear()}}function check(e,t,a){if(!e||!e.active)return{action:"allow"};let n=!1;if(READ_TOOLS.has(t)){const t=pathKey(a&&a.file_path,e.cwd);t&&e.written.has(t)&&(e.written.delete(t),n=!0)}const r=callKey(t,a),s=(e.counts.get(r)||0)+1;if(e.counts.set(r,s),1===s&&e.paths.set(r,summarize(t,a)),READ_TOOLS.has(t)){const t=pathKey(a&&a.file_path,e.cwd);t&&(e.readKeys.has(t)||e.readKeys.set(t,new Set),e.readKeys.get(t).add(r))}if(n)return{action:"allow"};if(s<2)return{action:"allow"};const o=e.paths.get(r)||t;return s>=5?(5===s&&(e.refusals+=1),"enforce"===e.mode?{action:"refuse",error:`refused: this is the ${ordinal(s)} identical call to \`${o}\` this turn, so the result is already in the conversation above and running it again cannot change it. Do not repeat it and do not retry it with a cosmetic variation. Either use what the earlier result already told you, or take a different action (read a different path, change the command, or write the fix). If you are genuinely blocked, stop calling tools and say what blocks you.`}:{action:"allow"}):"enforce"!==e.mode||e.warned.has(r)?{action:"allow"}:(e.warned.add(r),e.warnings+=1,{action:"allow",note:`note: you have now called \`${o}\` ${s} times this turn with identical arguments. Its result is already above — read it again before repeating the call.`})}function summarize(e,t){const a=t&&"object"==typeof t?t:{},n=a.file_path||a.path||a.command||a.pattern||a.query;return"string"==typeof n&&n?`${e} ${n.length>80?`${n.slice(0,77)}…`:n}`:e}function ordinal(e){const t=["th","st","nd","rd"],a=e%100;return t[(a-20)%10]||t[a]||t[0]}function stats(e){if(!e)return{distinct:0,warnings:0,refusals:0,maxRepeat:0,repeats:[]};let t=0;const a=[];for(const[n,r]of e.counts)r>t&&(t=r),r>=2&&a.push({call:e.paths.get(n)||"",times:r});return a.sort(((e,t)=>t.times-e.times)),{distinct:e.counts.size,warnings:e.warnings,refusals:e.refusals,maxRepeat:t,repeats:a.slice(0,5)}}module.exports={WARN_AT:2,REFUSE_AT:5,beginRepeatGuard:beginRepeatGuard,recordWrite:recordWrite,check:check,stats:stats,callKey:callKey,stableJson:stableJson,resolveMode:resolveMode};
|