aegiscode 7.0.24 → 7.0.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/package.json +7 -3
  2. package/scripts/check.mjs +52 -1
  3. package/scripts/demo.mjs +94 -1
  4. package/scripts/predist.mjs +75 -1
  5. package/scripts/runtests.mjs +56 -1
  6. package/scripts/seal-gate.mjs +74 -1
  7. package/src/agents.js +139 -1
  8. package/src/app.js +2957 -1
  9. package/src/art.js +289 -1
  10. package/src/chatflow.js +3023 -1
  11. package/src/checkpoint.js +90 -1
  12. package/src/clipboard.js +424 -1
  13. package/src/cloudsync.js +528 -1
  14. package/src/commands.js +4089 -1
  15. package/src/config.js +581 -1
  16. package/src/connect.js +349 -1
  17. package/src/credentials.js +33 -1
  18. package/src/deps.js +232 -1
  19. package/src/devrun.js +187 -1
  20. package/src/diff.js +333 -1
  21. package/src/diffview.js +296 -1
  22. package/src/engine.js +297 -1
  23. package/src/entitlement.js +355 -1
  24. package/src/events.js +707 -1
  25. package/src/export.js +67 -1
  26. package/src/filepreview.js +153 -1
  27. package/src/fingerprint.js +592 -1
  28. package/src/format.js +259 -1
  29. package/src/fuzzy.js +119 -1
  30. package/src/history.js +423 -1
  31. package/src/init.js +175 -1
  32. package/src/input.js +139 -1
  33. package/src/keys.js +183 -1
  34. package/src/markdown.js +306 -1
  35. package/src/models.js +507 -1
  36. package/src/naming.js +57 -1
  37. package/src/overlays.js +462 -1
  38. package/src/panels.js +1418 -1
  39. package/src/ping.js +226 -1
  40. package/src/presence.js +238 -1
  41. package/src/render.js +516 -1
  42. package/src/screen.js +518 -1
  43. package/src/screens.js +896 -1
  44. package/src/secret.js +59 -1
  45. package/src/securefs.js +359 -1
  46. package/src/settings.js +155 -1
  47. package/src/shared.js +52 -1
  48. package/src/sharedpaths.js +53 -1
  49. package/src/signup.js +156 -1
  50. package/src/summarize.js +95 -1
  51. package/src/sysdiag.js +585 -1
  52. package/src/system.js +40 -1
  53. package/src/theme.js +570 -1
  54. package/src/title.js +220 -1
  55. package/src/todos.js +115 -1
  56. package/src/tokens.js +263 -1
  57. package/src/topup.js +210 -1
  58. package/src/update.js +191 -1
  59. package/vendor/client/aegis.js +2441 -1
  60. package/vendor/client/attest.js +518 -1
  61. package/vendor/client/authorship-key.js +410 -1
  62. package/vendor/client/auto-provision.js +134 -1
  63. package/vendor/client/brain-catalog.js +268 -1
  64. package/vendor/client/byok-catalog.js +199 -1
  65. package/vendor/client/catalog-client.js +487 -1
  66. package/vendor/client/conversation-export.js +177 -1
  67. package/vendor/client/credentials.js +494 -1
  68. package/vendor/client/device-fingerprint.js +141 -1
  69. package/vendor/client/drive-connect.js +110 -1
  70. package/vendor/client/drive-upload.js +234 -1
  71. package/vendor/client/env-file.js +1273 -1
  72. package/vendor/client/fingerprint.js +1064 -1
  73. package/vendor/client/foreign-memory.js +669 -1
  74. package/vendor/client/google-signin.js +133 -1
  75. package/vendor/client/hooks.js +430 -1
  76. package/vendor/client/model-discovery.js +373 -1
  77. package/vendor/client/naming.js +283 -1
  78. package/vendor/client/platform.js +937 -1
  79. package/vendor/client/prefs.js +351 -1
  80. package/vendor/client/presence-constants.js +107 -1
  81. package/vendor/client/presence.js +438 -1
  82. package/vendor/client/record-vault.js +1055 -3
  83. package/vendor/client/session-store.js +575 -1
  84. package/vendor/client/topup.js +297 -1
  85. package/vendor/client/touch.js +458 -1
  86. package/vendor/client/update.js +763 -1
  87. package/vendor/client/user-models.js +381 -1
  88. package/vendor/desktop/lib/local/agents.js +105 -1
  89. package/vendor/desktop/lib/local/attachments.js +276 -1
  90. package/vendor/desktop/lib/local/autonomous.js +1045 -1
  91. package/vendor/desktop/lib/local/claude-pro.js +1028 -1
  92. package/vendor/desktop/lib/local/context.js +125 -1
  93. package/vendor/desktop/lib/local/engine.js +3666 -1
  94. package/vendor/desktop/lib/local/entitlement.js +660 -1
  95. package/vendor/desktop/lib/local/git-scope.js +228 -1
  96. package/vendor/desktop/lib/local/local.js +2145 -1
  97. package/vendor/desktop/lib/local/prompt.js +280 -1
  98. package/vendor/desktop/lib/local/queue.js +560 -1
  99. package/vendor/desktop/lib/local/session-rounds.js +238 -1
  100. package/vendor/desktop/lib/local/spill.js +75 -1
  101. package/vendor/desktop/lib/local/turn-guard.js +300 -1
  102. package/vendor/desktop/lib/local/worktree-lock.js +235 -1
  103. package/vendor/desktop/lib/settings.js +890 -1
  104. package/vendor/desktop/renderer/usage.js +1239 -1
  105. package/vendor/hosts/install.js +638 -1
  106. package/vendor/hosts/openai-shim.js +515 -1
  107. package/vendor/hosts/spec.js +164 -1
  108. package/vendor/hosts/targets.js +346 -1
  109. package/vendor/mcp/server.js +221 -1
  110. package/vendor/mcp/tools.js +408 -1
  111. package/vendor/one/src/child.js +285 -1
  112. package/vendor/one/src/permissions.js +383 -1
  113. package/SOURCE-OFFER.txt +0 -9
@@ -1,3 +1,383 @@
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 fs=require("node:fs"),path=require("node:path"),credentials=require("./credentials.js"),USER_MODELS_FILE="models.json",FILE_MODE=384,MAX_MODELS_PER_PROVIDER=32,MAX_PROVIDERS=64,PROVIDER_RE=/^[a-z0-9][a-z0-9._-]{0,63}$/,MODEL_RE=/^[A-Za-z0-9][A-Za-z0-9._/-]{0,95}$/;function userModelsDir(e){return e&&e.dir||credentials.aegisHome(e&&e.env)}function userModelsPath(e){return path.join(userModelsDir(e),USER_MODELS_FILE)}function badValue(e,r,o){return new Error(`aegiscode: ${e} ${JSON.stringify(String(r))} is not usable — ${o}`)}function sanitizeProvider(e){const r=String(null==e?"":e).trim().toLowerCase();if(!r)throw badValue("provider",e,"the provider id is empty");if(!PROVIDER_RE.test(r))throw badValue("provider",e,"a provider id is lowercase letters, digits, dot, dash or underscore (the id `/byok` prints)");return r}function sanitizeModel(e){const r=String(null==e?"":e).trim();if(!r)throw badValue("model id",e,"the model id is empty");if(/:/.test(r))throw badValue("model id",e,"'provider:model' is how a picked model is addressed, so a model id cannot contain a colon");if(!MODEL_RE.test(r))throw badValue("model id",e,"a model id has no spaces — it is the string sent to the vendor (e.g. deepseek-v4.2-preview, claude-opus-9-1)");return r}function isPlainObject(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function load(e){const r=userModelsPath(e),o=[];let s;try{s=JSON.parse(fs.readFileSync(r,"utf8"))}catch(s){return s&&"ENOENT"===s.code||o.push({provider:null,model:null,reason:`unreadable: ${s&&s.message||s}`}),{dir:userModelsDir(e),file:r,map:{},invalid:o}}const i={};if(!isPlainObject(s))return o.push({provider:null,model:null,reason:"the file must be an object of provider → [model ids]"}),{dir:userModelsDir(e),file:r,map:i,invalid:o};for(const[e,r]of Object.entries(s)){if("version"===e||"$schema"===e)continue;let s;try{s=sanitizeProvider(e)}catch(r){o.push({provider:e,model:null,reason:r.message});continue}const t=Array.isArray(r)?r:[r],d=new Set,n=[];for(const e of t){let r;try{r=sanitizeModel(e)}catch(r){o.push({provider:s,model:e,reason:r.message});continue}d.has(r)||(d.add(r),n.push(r))}n.length&&(i[s]=n)}return{dir:userModelsDir(e),file:r,map:i,invalid:o}}function readUserModels(e){return load(e).map}function userModelIdsFor(e,r){let o;try{o=sanitizeProvider(e)}catch{return[]}const s=readUserModels(r);return Array.isArray(s[o])?s[o].slice():[]}function writeMap(e,r){const o=userModelsPath(r);fs.mkdirSync(path.dirname(o),{recursive:!0});const s=`${o}.tmp-${process.pid}`;fs.writeFileSync(s,JSON.stringify(e,null,2)+"\n",{mode:FILE_MODE}),fs.renameSync(s,o);try{fs.chmodSync(o,FILE_MODE)}catch{}return e}function addUserModel(e,r,o){const s=sanitizeProvider(e),i=sanitizeModel(r),t=readUserModels(o),d=Array.isArray(t[s])?t[s].slice():[];if(d.includes(i))return{file:userModelsPath(o),provider:s,model:i,added:!1,models:d};if(d.length>=32)throw new Error(`aegiscode: ${s} already carries ${d.length} user models (the cap) — remove one with /model-rm before adding another.`);if(!t[s]&&Object.keys(t).length>=64)throw new Error(`aegiscode: ${Object.keys(t).length} providers already carry user models (the cap).`);const n=[...d,i];return writeMap({...t,[s]:n},o),{file:userModelsPath(o),provider:s,model:i,added:!0,models:n}}function removeUserModel(e,r,o){const s=sanitizeProvider(e),i=sanitizeModel(r),t=readUserModels(o),d=Array.isArray(t[s])?t[s].slice():[];if(!d.includes(i))return{file:userModelsPath(o),provider:s,model:i,removed:!1,models:d};const n=d.filter((e=>e!==i)),a={...t};return n.length?a[s]=n:delete a[s],writeMap(a,o),{file:userModelsPath(o),provider:s,model:i,removed:!0,models:n}}function modelIdsOf(e){return(Array.isArray(e&&e.models)?e.models:[]).map((e=>"string"==typeof e?e:e&&e.id)).map((e=>"string"==typeof e?e.trim():"")).filter(Boolean)}function providerArray(e){return Array.isArray(e)?e:Array.isArray(e&&e.providers)?e.providers:null}function withUserModels(e,r){const o=providerArray(e);if(!o)return[];const s=void 0===r?readUserModels():isPlainObject(r)?r:{},i=[];for(const e of o){if(!e||"object"!=typeof e)continue;const r="string"==typeof e.id?e.id.trim():"",o=r&&Array.isArray(s[r])?s[r]:null;if(!o||!o.length){i.push(e);continue}const t=new Set(modelIdsOf(e)),d=o.map((e=>String(e).trim())).filter((e=>e&&!t.has(e)));if(!d.length){i.push(e);continue}const n=Array.isArray(e.models)?e.models:[];i.push({...e,models:[...n,...d]})}return i}function unmatchedUserProviders(e,r){const o=providerArray(e)||[],s=void 0===r?readUserModels():isPlainObject(r)?r:{},i=new Set(o.map((e=>e&&"string"==typeof e.id?e.id.trim():"")).filter(Boolean));return Object.keys(s).filter((e=>!i.has(e)))}module.exports={USER_MODELS_FILE:USER_MODELS_FILE,MAX_MODELS_PER_PROVIDER:32,userModelsDir:userModelsDir,userModelsPath:userModelsPath,sanitizeProvider:sanitizeProvider,sanitizeModel:sanitizeModel,load:load,readUserModels:readUserModels,userModelIdsFor:userModelIdsFor,addUserModel:addUserModel,removeUserModel:removeUserModel,withUserModels:withUserModels,unmatchedUserProviders:unmatchedUserProviders};
3
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
+ // Conveying a modified copy, or running one as a network service, owes the
5
+ // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
+ 'use strict';
7
+
8
+ /**
9
+ * user-models.js — the models the USER declares, in one file every host reads.
10
+ *
11
+ * ── the problem this module removes ────────────────────────────────────────
12
+ *
13
+ * `client/byok-catalog.js` is the list of vendor ids the server's catalog does
14
+ * not name but the relay forwards. It is a *shipping* artifact: every entry is
15
+ * a code change, a review, a release, and a desktop rebuild — and the file's own
16
+ * doc says so ("the durable fix for any of them is the server's MODEL_CATALOG").
17
+ * That is the right shape for the ids AEGIS should be offering everybody. It is
18
+ * the wrong shape for an id one user can call today: a freshly shipped model, a
19
+ * fine-tune, a preview id behind their own vendor key, a Together/Groq/OpenRouter
20
+ * route the relay forwards and the catalog simply has not caught up with.
21
+ *
22
+ * The BYOK relay is a stateless pass-through (`services/byok_service.py`): the
23
+ * caller's own vendor key authenticates upstream and AEGIS forwards the model
24
+ * string it was handed. So for a provider the account holds a key for, an id the
25
+ * VENDOR serves is callable whether or not this repo has ever heard of it. The
26
+ * only thing missing was a way for the user to say so without waiting for us.
27
+ *
28
+ * ── what a user does now ───────────────────────────────────────────────────
29
+ *
30
+ * CLI `/model-add <provider> [api-key] <model-id>` (and `/model-rm …`)
31
+ * Desktop Settings → "Add a model" → provider + id
32
+ * Either hand-edit `$AEGISCODE_HOME/models.json` (default `~/.aegiscode`)
33
+ *
34
+ * All three end up in the same file, and the file is the whole state:
35
+ * `{ "deepseek": ["deepseek-v4.2-preview"], "anthropic": ["claude-opus-9-1"] }`.
36
+ * Because the CLI and the desktop both read it at the moment they build the
37
+ * picker, a model added in the terminal is in the window's list on its next
38
+ * refresh, with no restart and no release. That is the whole point of putting
39
+ * it in the shared data dir rather than in each host's own config.
40
+ *
41
+ * ── the rules this module keeps (the same ones byok-catalog.js keeps) ──────
42
+ *
43
+ * - NEVER invent a provider. User models are applied only to a provider row
44
+ * the server's catalog already lists. A row this file fabricated would
45
+ * invite a key for a slug the relay may not accept, and the failure would
46
+ * land on the user's first turn — so a declaration naming an unknown
47
+ * provider is preserved in the file and REPORTED (`unmatchedUserProviders`),
48
+ * never rendered as a picker row.
49
+ * - ONE spelling per route. Declarations are de-duplicated on add and again
50
+ * when they are applied, so the same id added twice — or added while the
51
+ * server has started listing it itself — paints one row, not two.
52
+ * - Idempotent and non-mutating. `withUserModels` returns a NEW array, shares
53
+ * the provider objects that gained nothing, and appends after the server's
54
+ * own models so the server's `default_model` keeps its first position (the
55
+ * default is what a bare provider id runs).
56
+ * - Validated, not trusted. A model id is a string the relay forwards to a
57
+ * vendor: a typo does not error here, it 404s upstream on the user's first
58
+ * turn. So ids and provider slugs are shape-checked on write (and re-checked
59
+ * on read, because the file is hand-editable), and a bad row is dropped with
60
+ * a reason rather than silently stored.
61
+ * - Never secret. Only provider slugs and model ids belong here — the file is
62
+ * written 0600 anyway, next to the credential store, because provider/model
63
+ * choice is not the kind of thing another local account should be able to
64
+ * rewrite.
65
+ */
66
+
67
+ const fs = require('node:fs');
68
+ const path = require('node:path');
69
+
70
+ const credentials = require('./credentials.js');
71
+
72
+ /** The file the CLI, the desktop and the MCP host all read. */
73
+ const USER_MODELS_FILE = 'models.json';
74
+ const FILE_MODE = 0o600;
75
+ /** A ceiling, not a policy: enough for a real vendor lineup, small enough that
76
+ * a runaway script cannot turn the picker into a wall of rows. */
77
+ const MAX_MODELS_PER_PROVIDER = 32;
78
+ const MAX_PROVIDERS = 64;
79
+
80
+ /**
81
+ * The provider slug shape the relay addresses (`deepseek`, `together-ai`,
82
+ * `openai-gpt4o-mini`). Lowercase on purpose: `/byok-key OpenAI` resolves to
83
+ * `openai` through the server's catalog, and two spellings of one provider id
84
+ * is exactly how a stored user model comes to never match the row it was meant
85
+ * for.
86
+ */
87
+ const PROVIDER_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;
88
+ /**
89
+ * The model id shape. Deliberately permissive across vendors (dots for Claude,
90
+ * dashes for DeepSeek, slashes for the org-prefixed routes OpenRouter and
91
+ * Together use) and deliberately exclusive of two things: whitespace, because a
92
+ * model id with a space in it is a paste accident, and `:`, because
93
+ * `provider:model` is the id the picker and the engine already speak — a model
94
+ * id containing a colon would make that split ambiguous.
95
+ */
96
+ const MODEL_RE = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,95}$/;
97
+
98
+ /** The data dir (`$AEGISCODE_HOME` or `~/.aegiscode`), from the ONE definition. */
99
+ function userModelsDir(opts) {
100
+ return (opts && opts.dir) || credentials.aegisHome(opts && opts.env);
101
+ }
102
+
103
+ /** The absolute path of the shared user-model file. */
104
+ function userModelsPath(opts) {
105
+ return path.join(userModelsDir(opts), USER_MODELS_FILE);
106
+ }
107
+
108
+ /** Throw a message that says what to type instead. */
109
+ function badValue(what, raw, why) {
110
+ return new Error(
111
+ `aegiscode: ${what} ${JSON.stringify(String(raw))} is not usable — ${why}`
112
+ );
113
+ }
114
+
115
+ /** One provider slug, validated. Accepts the server's own spelling idempotently. */
116
+ function sanitizeProvider(raw) {
117
+ const s = String(raw == null ? '' : raw).trim().toLowerCase();
118
+ if (!s) throw badValue('provider', raw, 'the provider id is empty');
119
+ if (!PROVIDER_RE.test(s)) {
120
+ throw badValue(
121
+ 'provider',
122
+ raw,
123
+ 'a provider id is lowercase letters, digits, dot, dash or underscore ' +
124
+ '(the id `/byok` prints)'
125
+ );
126
+ }
127
+ return s;
128
+ }
129
+
130
+ /** One model id, validated. Ids are compared verbatim — never case-folded. */
131
+ function sanitizeModel(raw) {
132
+ const s = String(raw == null ? '' : raw).trim();
133
+ if (!s) throw badValue('model id', raw, 'the model id is empty');
134
+ if (/:/.test(s)) {
135
+ throw badValue(
136
+ 'model id',
137
+ raw,
138
+ "'provider:model' is how a picked model is addressed, so a model id cannot contain a colon"
139
+ );
140
+ }
141
+ if (!MODEL_RE.test(s)) {
142
+ throw badValue(
143
+ 'model id',
144
+ raw,
145
+ 'a model id has no spaces — it is the string sent to the vendor ' +
146
+ '(e.g. deepseek-v4.2-preview, claude-opus-9-1)'
147
+ );
148
+ }
149
+ return s;
150
+ }
151
+
152
+ /** True when `value` is a plain object (never an array, never null). */
153
+ function isPlainObject(value) {
154
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
155
+ }
156
+
157
+ /**
158
+ * Read the file and return BOTH the usable map and what was dropped.
159
+ *
160
+ * Never throws: a corrupt, unreadable or hand-mangled file reads as "no user
161
+ * models", because a declaration store must not be able to take the model
162
+ * picker down. But it does not lie about it either — `invalid` carries one
163
+ * `{ provider, model, reason }` per row that was skipped, which is what the
164
+ * hosts surface so a hand-edited typo is visible instead of looking like "the
165
+ * feature did nothing".
166
+ */
167
+ function load(opts) {
168
+ const file = userModelsPath(opts);
169
+ const invalid = [];
170
+ let raw;
171
+ try {
172
+ raw = JSON.parse(fs.readFileSync(file, 'utf8'));
173
+ } catch (err) {
174
+ // ENOENT is the normal state of a fresh install, not a problem to report.
175
+ if (err && err.code === 'ENOENT') return { dir: userModelsDir(opts), file, map: {}, invalid };
176
+ invalid.push({ provider: null, model: null, reason: `unreadable: ${(err && err.message) || err}` });
177
+ return { dir: userModelsDir(opts), file, map: {}, invalid };
178
+ }
179
+ const map = {};
180
+ if (!isPlainObject(raw)) {
181
+ invalid.push({ provider: null, model: null, reason: 'the file must be an object of provider → [model ids]' });
182
+ return { dir: userModelsDir(opts), file, map, invalid };
183
+ }
184
+ for (const [providerRaw, modelsRaw] of Object.entries(raw)) {
185
+ if (providerRaw === 'version' || providerRaw === '$schema') continue;
186
+ let provider;
187
+ try {
188
+ provider = sanitizeProvider(providerRaw);
189
+ } catch (err) {
190
+ invalid.push({ provider: providerRaw, model: null, reason: err.message });
191
+ continue;
192
+ }
193
+ const list = Array.isArray(modelsRaw) ? modelsRaw : [modelsRaw];
194
+ const seen = new Set();
195
+ const keep = [];
196
+ for (const m of list) {
197
+ let model;
198
+ try {
199
+ model = sanitizeModel(m);
200
+ } catch (err) {
201
+ invalid.push({ provider, model: m, reason: err.message });
202
+ continue;
203
+ }
204
+ if (seen.has(model)) continue; // one spelling per route, in the file too
205
+ seen.add(model);
206
+ keep.push(model);
207
+ }
208
+ if (keep.length) map[provider] = keep;
209
+ }
210
+ return { dir: userModelsDir(opts), file, map, invalid };
211
+ }
212
+
213
+ /** Just the usable provider → [ids] map (`load()` without the report). */
214
+ function readUserModels(opts) {
215
+ return load(opts).map;
216
+ }
217
+
218
+ /** The ids declared for one provider (an empty array when there are none). */
219
+ function userModelIdsFor(provider, opts) {
220
+ let id;
221
+ try {
222
+ id = sanitizeProvider(provider);
223
+ } catch {
224
+ return [];
225
+ }
226
+ const map = readUserModels(opts);
227
+ return Array.isArray(map[id]) ? map[id].slice() : [];
228
+ }
229
+
230
+ /** Write the map atomically, 0600, pretty-printed so it stays hand-editable. */
231
+ function writeMap(map, opts) {
232
+ const file = userModelsPath(opts);
233
+ fs.mkdirSync(path.dirname(file), { recursive: true });
234
+ const tmp = `${file}.tmp-${process.pid}`;
235
+ fs.writeFileSync(tmp, JSON.stringify(map, null, 2) + '\n', { mode: FILE_MODE });
236
+ fs.renameSync(tmp, file);
237
+ try {
238
+ fs.chmodSync(file, FILE_MODE);
239
+ } catch {
240
+ /* Windows: POSIX modes are a no-op and ACLs are the OS's business */
241
+ }
242
+ return map;
243
+ }
244
+
245
+ /**
246
+ * Declare one model id for one provider.
247
+ *
248
+ * Returns `{ file, provider, model, added, models }` — `added: false` when the
249
+ * id was already declared, so the caller can say "already there" instead of
250
+ * claiming a change it did not make. Rejects a provider or id that fails the
251
+ * shape checks above, and refuses to grow a single provider past the ceiling.
252
+ */
253
+ function addUserModel(provider, model, opts) {
254
+ const id = sanitizeProvider(provider);
255
+ const modelId = sanitizeModel(model);
256
+ const map = readUserModels(opts);
257
+ const have = Array.isArray(map[id]) ? map[id].slice() : [];
258
+ if (have.includes(modelId)) {
259
+ return { file: userModelsPath(opts), provider: id, model: modelId, added: false, models: have };
260
+ }
261
+ if (have.length >= MAX_MODELS_PER_PROVIDER) {
262
+ throw new Error(
263
+ `aegiscode: ${id} already carries ${have.length} user models (the cap) — ` +
264
+ 'remove one with /model-rm before adding another.'
265
+ );
266
+ }
267
+ if (!map[id] && Object.keys(map).length >= MAX_PROVIDERS) {
268
+ throw new Error(
269
+ `aegiscode: ${Object.keys(map).length} providers already carry user models (the cap).`
270
+ );
271
+ }
272
+ const models = [...have, modelId];
273
+ const next = { ...map, [id]: models };
274
+ writeMap(next, opts);
275
+ return { file: userModelsPath(opts), provider: id, model: modelId, added: true, models };
276
+ }
277
+
278
+ /**
279
+ * Retire one declaration. Returns `{ …, removed }`; `removed: false` means it
280
+ * was not declared, which is a report and not an error (the file is shared, so
281
+ * another host may have removed it a moment ago).
282
+ */
283
+ function removeUserModel(provider, model, opts) {
284
+ const id = sanitizeProvider(provider);
285
+ const modelId = sanitizeModel(model);
286
+ const map = readUserModels(opts);
287
+ const have = Array.isArray(map[id]) ? map[id].slice() : [];
288
+ if (!have.includes(modelId)) {
289
+ return { file: userModelsPath(opts), provider: id, model: modelId, removed: false, models: have };
290
+ }
291
+ const models = have.filter((m) => m !== modelId);
292
+ const next = { ...map };
293
+ if (models.length) next[id] = models;
294
+ else delete next[id];
295
+ writeMap(next, opts);
296
+ return { file: userModelsPath(opts), provider: id, model: modelId, removed: true, models };
297
+ }
298
+
299
+ /** The model ids an entry names, tolerating the server's two shapes. */
300
+ function modelIdsOf(provider) {
301
+ return (Array.isArray(provider && provider.models) ? provider.models : [])
302
+ .map((m) => (typeof m === 'string' ? m : m && m.id))
303
+ .map((m) => (typeof m === 'string' ? m.trim() : ''))
304
+ .filter(Boolean);
305
+ }
306
+
307
+ /** The provider array out of either shape the server sends (or `[]`). */
308
+ function providerArray(providers) {
309
+ if (Array.isArray(providers)) return providers;
310
+ if (Array.isArray(providers && providers.providers)) return providers.providers;
311
+ return null;
312
+ }
313
+
314
+ /**
315
+ * The server's BYOK catalog with the USER's declared models applied.
316
+ *
317
+ * @param {Array<object>|object} providers the payload (array, or `{providers}`)
318
+ * @param {object} [extra] an explicit provider → [ids] map. Omitted by every
319
+ * host (they want the file); passing it is what makes this function pure and
320
+ * therefore testable without touching a real data dir.
321
+ * @returns {Array<object>} a NEW array. Providers that gained nothing come back
322
+ * as the SAME objects, an unknown provider is never fabricated, and an
323
+ * empty/absent payload returns `[]` rather than a list invented from the file.
324
+ */
325
+ function withUserModels(providers, extra) {
326
+ const raw = providerArray(providers);
327
+ if (!raw) return [];
328
+ const map = extra === undefined ? readUserModels() : isPlainObject(extra) ? extra : {};
329
+ const out = [];
330
+ for (const p of raw) {
331
+ if (!p || typeof p !== 'object') continue;
332
+ const id = typeof p.id === 'string' ? p.id.trim() : '';
333
+ const declared = id && Array.isArray(map[id]) ? map[id] : null;
334
+ if (!declared || !declared.length) {
335
+ out.push(p);
336
+ continue;
337
+ }
338
+ const have = new Set(modelIdsOf(p));
339
+ const missing = declared
340
+ .map((m) => String(m).trim())
341
+ .filter((m) => m && !have.has(m));
342
+ // Nothing to add — hand back the SAME object, so a complete payload is
343
+ // byte-identical after this pass and a caller cannot tell it ran.
344
+ if (!missing.length) {
345
+ out.push(p);
346
+ continue;
347
+ }
348
+ const models = Array.isArray(p.models) ? p.models : [];
349
+ out.push({ ...p, models: [...models, ...missing] });
350
+ }
351
+ return out;
352
+ }
353
+
354
+ /**
355
+ * Declared providers the payload does NOT list — the honest half of the rules
356
+ * above. A host reports these ("no provider row for `foo` — the relay takes
357
+ * keys for: …") instead of either hiding the declaration or showing a row that
358
+ * would 401 on its first turn.
359
+ */
360
+ function unmatchedUserProviders(providers, extra) {
361
+ const raw = providerArray(providers) || [];
362
+ const map = extra === undefined ? readUserModels() : isPlainObject(extra) ? extra : {};
363
+ const known = new Set(
364
+ raw.map((p) => (p && typeof p.id === 'string' ? p.id.trim() : '')).filter(Boolean)
365
+ );
366
+ return Object.keys(map).filter((id) => !known.has(id));
367
+ }
368
+
369
+ module.exports = {
370
+ USER_MODELS_FILE,
371
+ MAX_MODELS_PER_PROVIDER,
372
+ userModelsDir,
373
+ userModelsPath,
374
+ sanitizeProvider,
375
+ sanitizeModel,
376
+ load,
377
+ readUserModels,
378
+ userModelIdsFor,
379
+ addUserModel,
380
+ removeUserModel,
381
+ withUserModels,
382
+ unmatchedUserProviders,
383
+ };
@@ -1,3 +1,107 @@
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 AGENT_PRESETS={synthesizer:"You are a senior technical lead. Given analysis from multiple specialist agents, synthesize their findings into a clear, actionable summary.\nStructure your response as: key findings, recommended approach, top action items.\nBe direct, concrete, and avoid repeating everything the agents said.\nFocus on delivering a decision-ready synthesis.",architect:"You are a System Architect. Design the new application architecture.\nDefine: project structure, tech stack, directory layout, key modules, data flow, API design.\nConsider: scalability, maintainability, testing strategy, deployment.\nOutput a concrete file tree and architecture decisions log. Be specific.",scaffolder:"You are a Project Scaffolder. Build the complete application from scratch.\n\nYOUR JOB IS TO CREATE ALL PROJECT FILES - not just describe them.\n\nUse writeFile to create: package.json, tsconfig.json, source files, configs, tests.\nGenerate COMPLETE, WORKING code - not stubs or placeholders.\nSet up build scripts, lint config, and any necessary tooling.\n\nAfter creating files, use exec to run: npm/pnpm install, then build/compile.\nFix any errors until the project builds successfully.\n\nBe thorough - a real, runnable project is the goal.",planner:"You are a Refactoring Planner. Given the analyzer findings, create a step-by-step plan.\nEach step: file path, what to change, why, risk level (LOW/MEDIUM/HIGH).\nInclude before/after snippets. Order by impact. Be concrete.",implementer:"You are an Implementation Engineer. Execute the refactoring plan.\nUse editFile and writeFile to make actual code changes.\nAfter each change, use readFile to verify correctness. Keep existing code style.\nRun build commands with exec to ensure nothing is broken.",reviewer:"You are a Code Reviewer. Review the approach and code.\nCheck: logic errors, type safety, error handling, performance, security.\nBe critical but constructive. Report specific issues with file paths.",debugger:"You are a Debugging Specialist. Analyze potential issues and edge cases.\nIdentify: failure modes, error handling gaps, testing considerations.\nThink about what could go wrong and how to prevent it.",scanner:"You are a Security Vulnerability Scanner.\nScan for: hardcoded API keys/secrets, SQL injection, XSS, unsafe eval/exec, path traversal.\nUse grep with targeted patterns. Report every finding with: file path, severity (CRITICAL/HIGH/MEDIUM/LOW), line number.",analyzer:"You are a Code Analyzer. Find refactoring opportunities.\nLook for: duplicated code, long functions (>20 lines), complex conditionals, unused imports,\ncircular dependencies, inconsistent patterns. Report with file paths and line numbers."},GENERAL_AGENT_PROMPT="You are a capable autonomous coding subagent. Complete the assigned task end to end using the available tools (exec, readFile, writeFile, editFile, listDir, glob, grep). Work in the current repository, verify your work, and finish with a concise report of what you did and what you found. You cannot ask follow-up questions — make reasonable assumptions and proceed. When a large sub-task is better handled by a focused specialist, delegate it with the task tool.";function agentRoleLabel(e){return{synthesizer:"Technical Lead",architect:"System Architect",scaffolder:"Project Scaffolder",planner:"Refactoring Planner",implementer:"Implementation Engineer",reviewer:"Code Reviewer",debugger:"Debugging Specialist",scanner:"Vulnerability Scanner",analyzer:"Code Analyzer",general:"General"}[e]||e}function agentRoles(){return Object.keys(AGENT_PRESETS)}function agentSystemPrompt(e){return AGENT_PRESETS[e]||GENERAL_AGENT_PROMPT}module.exports={AGENT_PRESETS:AGENT_PRESETS,GENERAL_AGENT_PROMPT:GENERAL_AGENT_PROMPT,agentRoleLabel:agentRoleLabel,agentRoles:agentRoles,agentSystemPrompt:agentSystemPrompt};
3
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
+ // Conveying a modified copy, or running one as a network service, owes the
5
+ // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
+ 'use strict';
7
+
8
+ /**
9
+ * agents.js — subagent prompt presets for the desktop `task` tool, ported
10
+ * from the upstream engine reference (same roles, same synthesis presets).
11
+ * A preset is a system prompt: `task` runs it through the normal engine.chat
12
+ * loop as a nested turn (its own tool rounds, same model class), not a
13
+ * separate runtime, so the presets are pure prompt composition.
14
+ *
15
+ * Text is adapted to the desktop's own tool vocabulary (readFile/writeFile/
16
+ * editFile/listDir/glob/grep/exec/task — see tools.js) so a subagent's
17
+ * instructions never name a tool the desktop doesn't actually advertise.
18
+ */
19
+
20
+ /** Role → system prompt. */
21
+ const AGENT_PRESETS = {
22
+ synthesizer: `You are a senior technical lead. Given analysis from multiple specialist agents, synthesize their findings into a clear, actionable summary.
23
+ Structure your response as: key findings, recommended approach, top action items.
24
+ Be direct, concrete, and avoid repeating everything the agents said.
25
+ Focus on delivering a decision-ready synthesis.`,
26
+
27
+ architect: `You are a System Architect. Design the new application architecture.
28
+ Define: project structure, tech stack, directory layout, key modules, data flow, API design.
29
+ Consider: scalability, maintainability, testing strategy, deployment.
30
+ Output a concrete file tree and architecture decisions log. Be specific.`,
31
+
32
+ scaffolder: `You are a Project Scaffolder. Build the complete application from scratch.
33
+
34
+ YOUR JOB IS TO CREATE ALL PROJECT FILES - not just describe them.
35
+
36
+ Use writeFile to create: package.json, tsconfig.json, source files, configs, tests.
37
+ Generate COMPLETE, WORKING code - not stubs or placeholders.
38
+ Set up build scripts, lint config, and any necessary tooling.
39
+
40
+ After creating files, use exec to run: npm/pnpm install, then build/compile.
41
+ Fix any errors until the project builds successfully.
42
+
43
+ Be thorough - a real, runnable project is the goal.`,
44
+
45
+ planner: `You are a Refactoring Planner. Given the analyzer findings, create a step-by-step plan.
46
+ Each step: file path, what to change, why, risk level (LOW/MEDIUM/HIGH).
47
+ Include before/after snippets. Order by impact. Be concrete.`,
48
+
49
+ implementer: `You are an Implementation Engineer. Execute the refactoring plan.
50
+ Use editFile and writeFile to make actual code changes.
51
+ After each change, use readFile to verify correctness. Keep existing code style.
52
+ Run build commands with exec to ensure nothing is broken.`,
53
+
54
+ reviewer: `You are a Code Reviewer. Review the approach and code.
55
+ Check: logic errors, type safety, error handling, performance, security.
56
+ Be critical but constructive. Report specific issues with file paths.`,
57
+
58
+ debugger: `You are a Debugging Specialist. Analyze potential issues and edge cases.
59
+ Identify: failure modes, error handling gaps, testing considerations.
60
+ Think about what could go wrong and how to prevent it.`,
61
+
62
+ scanner: `You are a Security Vulnerability Scanner.
63
+ Scan for: hardcoded API keys/secrets, SQL injection, XSS, unsafe eval/exec, path traversal.
64
+ Use grep with targeted patterns. Report every finding with: file path, severity (CRITICAL/HIGH/MEDIUM/LOW), line number.`,
65
+
66
+ analyzer: `You are a Code Analyzer. Find refactoring opportunities.
67
+ Look for: duplicated code, long functions (>20 lines), complex conditionals, unused imports,
68
+ circular dependencies, inconsistent patterns. Report with file paths and line numbers.`,
69
+ };
70
+
71
+ /** System prompt for a `general` (or unrecognized) subagent type. */
72
+ const GENERAL_AGENT_PROMPT =
73
+ 'You are a capable autonomous coding subagent. Complete the assigned task end to end using ' +
74
+ 'the available tools (exec, readFile, writeFile, editFile, listDir, glob, grep). Work in the ' +
75
+ 'current repository, verify your work, and finish with a concise report of what you did and ' +
76
+ 'what you found. You cannot ask follow-up questions — make reasonable assumptions and proceed. ' +
77
+ 'When a large sub-task is better handled by a focused specialist, delegate it with the task tool.';
78
+
79
+ /** Human-readable role label for a preset id (falls back to the id). */
80
+ function agentRoleLabel(role) {
81
+ const labels = {
82
+ synthesizer: 'Technical Lead', architect: 'System Architect',
83
+ scaffolder: 'Project Scaffolder', planner: 'Refactoring Planner',
84
+ implementer: 'Implementation Engineer', reviewer: 'Code Reviewer',
85
+ debugger: 'Debugging Specialist', scanner: 'Vulnerability Scanner',
86
+ analyzer: 'Code Analyzer', general: 'General',
87
+ };
88
+ return labels[role] || role;
89
+ }
90
+
91
+ /** Every preset id, in palette order (excludes the 'general' fallback). */
92
+ function agentRoles() {
93
+ return Object.keys(AGENT_PRESETS);
94
+ }
95
+
96
+ /** Resolve a subagent_type to its system prompt (unknown/absent → general). */
97
+ function agentSystemPrompt(role) {
98
+ return AGENT_PRESETS[role] || GENERAL_AGENT_PROMPT;
99
+ }
100
+
101
+ module.exports = {
102
+ AGENT_PRESETS,
103
+ GENERAL_AGENT_PROMPT,
104
+ agentRoleLabel,
105
+ agentRoles,
106
+ agentSystemPrompt,
107
+ };