aegisone 1.0.22 → 1.0.24

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 (226) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +1 -1
  3. package/SOURCE-OFFER.txt +9 -0
  4. package/bin/aegis.js +1 -322
  5. package/package.json +4 -5
  6. package/scripts/bump.mjs +1 -211
  7. package/scripts/bundle.js +1 -129
  8. package/scripts/predist.mjs +1 -939
  9. package/src/child.js +1 -285
  10. package/src/dispatch.js +1 -269
  11. package/src/doctor.js +1 -639
  12. package/src/host.js +1 -111
  13. package/src/permissions.js +1 -369
  14. package/src/probes.js +1 -159
  15. package/src/release.js +1 -409
  16. package/vendor/cli/bin/aegiscode.js +2 -914
  17. package/vendor/cli/package.json +3 -7
  18. package/vendor/cli/scripts/check.mjs +1 -52
  19. package/vendor/cli/scripts/demo.mjs +1 -94
  20. package/vendor/cli/scripts/predist.mjs +1 -75
  21. package/vendor/cli/scripts/runtests.mjs +1 -56
  22. package/vendor/cli/scripts/seal-gate.mjs +1 -74
  23. package/vendor/cli/src/agents.js +1 -139
  24. package/vendor/cli/src/app.js +1 -2932
  25. package/vendor/cli/src/art.js +1 -289
  26. package/vendor/cli/src/autonomous.js +1 -515
  27. package/vendor/cli/src/caps.js +1 -879
  28. package/vendor/cli/src/chatflow.js +1 -3020
  29. package/vendor/cli/src/checkpoint.js +1 -90
  30. package/vendor/cli/src/clipboard.js +1 -424
  31. package/vendor/cli/src/cloudsync.js +1 -528
  32. package/vendor/cli/src/commands.js +1 -4003
  33. package/vendor/cli/src/config.js +1 -581
  34. package/vendor/cli/src/connect.js +1 -349
  35. package/vendor/cli/src/credentials.js +1 -33
  36. package/vendor/cli/src/deps.js +1 -232
  37. package/vendor/cli/src/devrun.js +1 -187
  38. package/vendor/cli/src/diff.js +1 -333
  39. package/vendor/cli/src/diffview.js +1 -296
  40. package/vendor/cli/src/engine.js +1 -297
  41. package/vendor/cli/src/entitlement.js +1 -355
  42. package/vendor/cli/src/events.js +1 -707
  43. package/vendor/cli/src/export.js +1 -67
  44. package/vendor/cli/src/fingerprint.js +1 -592
  45. package/vendor/cli/src/format.js +1 -259
  46. package/vendor/cli/src/fuzzy.js +1 -119
  47. package/vendor/cli/src/gate.js +1 -55
  48. package/vendor/cli/src/history.js +1 -401
  49. package/vendor/cli/src/init.js +1 -175
  50. package/vendor/cli/src/input.js +1 -139
  51. package/vendor/cli/src/keys.js +1 -183
  52. package/vendor/cli/src/limits.js +1 -190
  53. package/vendor/cli/src/markdown.js +1 -306
  54. package/vendor/cli/src/mcp.js +1 -694
  55. package/vendor/cli/src/models.js +1 -487
  56. package/vendor/cli/src/naming.js +1 -229
  57. package/vendor/cli/src/overlays.js +1 -461
  58. package/vendor/cli/src/panels.js +1 -1418
  59. package/vendor/cli/src/permissions.js +1 -290
  60. package/vendor/cli/src/ping.js +1 -226
  61. package/vendor/cli/src/presence.js +1 -238
  62. package/vendor/cli/src/provenance.js +2 -182
  63. package/vendor/cli/src/render.js +1 -515
  64. package/vendor/cli/src/screen.js +1 -518
  65. package/vendor/cli/src/screens.js +1 -896
  66. package/vendor/cli/src/secret.js +1 -59
  67. package/vendor/cli/src/securefs.js +1 -359
  68. package/vendor/cli/src/settings.js +1 -155
  69. package/vendor/cli/src/shared.js +1 -52
  70. package/vendor/cli/src/sharedpaths.js +1 -53
  71. package/vendor/cli/src/signup.js +1 -156
  72. package/vendor/cli/src/summarize.js +1 -95
  73. package/vendor/cli/src/sysdiag.js +1 -585
  74. package/vendor/cli/src/system.js +1 -40
  75. package/vendor/cli/src/theme.js +1 -570
  76. package/vendor/cli/src/title.js +1 -220
  77. package/vendor/cli/src/todos.js +1 -115
  78. package/vendor/cli/src/tokens.js +1 -263
  79. package/vendor/cli/src/topup.js +1 -210
  80. package/vendor/cli/src/update.js +1 -181
  81. package/vendor/cli/vendor/client/aegis.js +1 -2179
  82. package/vendor/cli/vendor/client/attest.js +1 -442
  83. package/vendor/cli/vendor/client/authorship-key.js +1 -410
  84. package/vendor/cli/vendor/client/auto-provision.js +1 -134
  85. package/vendor/cli/vendor/client/brain-catalog.js +1 -268
  86. package/vendor/cli/vendor/client/byok-catalog.js +1 -230
  87. package/vendor/cli/vendor/client/credentials.js +1 -494
  88. package/vendor/cli/vendor/client/device-fingerprint.js +1 -141
  89. package/vendor/cli/vendor/client/drive-connect.js +1 -110
  90. package/vendor/cli/vendor/client/drive-upload.js +1 -174
  91. package/vendor/cli/vendor/client/env-file.js +1 -1273
  92. package/vendor/cli/vendor/client/fingerprint.js +1 -1064
  93. package/vendor/cli/vendor/client/foreign-memory.js +1 -669
  94. package/vendor/cli/vendor/client/google-signin.js +1 -133
  95. package/vendor/cli/vendor/client/hooks.js +1 -430
  96. package/vendor/cli/vendor/client/model-discovery.js +1 -373
  97. package/vendor/cli/vendor/client/platform.js +1 -937
  98. package/vendor/cli/vendor/client/prefs.js +1 -351
  99. package/vendor/cli/vendor/client/presence-constants.js +1 -107
  100. package/vendor/cli/vendor/client/presence.js +1 -438
  101. package/vendor/cli/vendor/client/record-vault.js +3 -1055
  102. package/vendor/cli/vendor/client/session-store.js +1 -548
  103. package/vendor/cli/vendor/client/topup.js +1 -297
  104. package/vendor/cli/vendor/client/touch.js +1 -458
  105. package/vendor/cli/vendor/client/update.js +1 -704
  106. package/vendor/cli/vendor/client/user-models.js +1 -381
  107. package/vendor/cli/vendor/desktop/lib/local/agents.js +1 -105
  108. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1045
  109. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -993
  110. package/vendor/cli/vendor/desktop/lib/local/context.js +1 -95
  111. package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -3301
  112. package/vendor/cli/vendor/desktop/lib/local/entitlement.js +1 -660
  113. package/vendor/cli/vendor/desktop/lib/local/git-scope.js +1 -228
  114. package/vendor/cli/vendor/desktop/lib/local/local.js +1 -2135
  115. package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -275
  116. package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -560
  117. package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +1 -208
  118. package/vendor/cli/vendor/desktop/lib/local/shell.js +1 -680
  119. package/vendor/cli/vendor/desktop/lib/local/tools.js +1 -1238
  120. package/vendor/cli/vendor/desktop/lib/local/turn-guard.js +1 -300
  121. package/vendor/cli/vendor/desktop/lib/local/worktree-lock.js +1 -235
  122. package/vendor/cli/vendor/desktop/lib/settings.js +1 -890
  123. package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1239
  124. package/vendor/cli/vendor/hosts/install.js +1 -638
  125. package/vendor/cli/vendor/hosts/openai-shim.js +1 -515
  126. package/vendor/cli/vendor/hosts/spec.js +1 -164
  127. package/vendor/cli/vendor/hosts/targets.js +1 -346
  128. package/vendor/cli/vendor/mcp/server.js +1 -221
  129. package/vendor/cli/vendor/mcp/tools.js +1 -408
  130. package/vendor/cli/vendor/one/src/child.js +1 -285
  131. package/vendor/cli/vendor/one/src/permissions.js +1 -369
  132. package/vendor/desktop/bin/aegis.js +1 -32
  133. package/vendor/desktop/lib/account-key.js +1 -56
  134. package/vendor/desktop/lib/auto.js +1 -430
  135. package/vendor/desktop/lib/avatar/companion.js +1 -698
  136. package/vendor/desktop/lib/avatar/cosmetics.js +1 -532
  137. package/vendor/desktop/lib/avatar/events.js +1 -344
  138. package/vendor/desktop/lib/avatar/holder-turn.js +1 -350
  139. package/vendor/desktop/lib/avatar/holders.js +1 -612
  140. package/vendor/desktop/lib/avatar/identity.js +1 -641
  141. package/vendor/desktop/lib/avatar/level.js +1 -368
  142. package/vendor/desktop/lib/avatar/mirror.js +1 -524
  143. package/vendor/desktop/lib/avatar/persona.js +1 -388
  144. package/vendor/desktop/lib/avatar/profile.js +1 -977
  145. package/vendor/desktop/lib/avatar/register.js +1 -307
  146. package/vendor/desktop/lib/avatar/store.js +1 -472
  147. package/vendor/desktop/lib/avatar/tiers.js +1 -38
  148. package/vendor/desktop/lib/avatar/transfer.js +1 -415
  149. package/vendor/desktop/lib/avatar/turn.js +1 -216
  150. package/vendor/desktop/lib/avatar/voice.js +1 -328
  151. package/vendor/desktop/lib/avatar/xp.js +1 -404
  152. package/vendor/desktop/lib/deep-link.js +1 -120
  153. package/vendor/desktop/lib/fingerprint.js +2 -347
  154. package/vendor/desktop/lib/google-connect.js +1 -227
  155. package/vendor/desktop/lib/local/agents.js +1 -105
  156. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  157. package/vendor/desktop/lib/local/claude-pro.js +1 -993
  158. package/vendor/desktop/lib/local/context.js +1 -95
  159. package/vendor/desktop/lib/local/engine.js +1 -3301
  160. package/vendor/desktop/lib/local/entitlement.js +1 -660
  161. package/vendor/desktop/lib/local/git-scope.js +1 -228
  162. package/vendor/desktop/lib/local/local.js +1 -2135
  163. package/vendor/desktop/lib/local/prompt.js +1 -275
  164. package/vendor/desktop/lib/local/queue.js +1 -560
  165. package/vendor/desktop/lib/local/session-rounds.js +1 -208
  166. package/vendor/desktop/lib/local/shell.js +1 -680
  167. package/vendor/desktop/lib/local/telemetry.js +1 -470
  168. package/vendor/desktop/lib/local/tools.js +1 -1238
  169. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  170. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  171. package/vendor/desktop/lib/provider-key-mirror.js +1 -252
  172. package/vendor/desktop/lib/quick-launcher.js +1 -84
  173. package/vendor/desktop/lib/settings.js +1 -890
  174. package/vendor/desktop/lib/sync/memory-queue.js +1 -60
  175. package/vendor/desktop/lib/sync/persist-gate.js +1 -148
  176. package/vendor/desktop/lib/sync/sessions.js +1 -106
  177. package/vendor/desktop/lib/window-state.js +1 -66
  178. package/vendor/desktop/main.js +1 -4529
  179. package/vendor/desktop/package.json +3 -5
  180. package/vendor/desktop/preload.js +1 -636
  181. package/vendor/desktop/renderer/app.js +1 -6660
  182. package/vendor/desktop/renderer/avatar/assemble.js +1 -335
  183. package/vendor/desktop/renderer/avatar/avatar.js +1 -380
  184. package/vendor/desktop/renderer/avatar/cards.js +1 -141
  185. package/vendor/desktop/renderer/avatar/hud.js +1 -206
  186. package/vendor/desktop/renderer/avatar/machine.js +1 -213
  187. package/vendor/desktop/renderer/avatar/pane.js +1 -439
  188. package/vendor/desktop/renderer/avatar/parts.js +1 -437
  189. package/vendor/desktop/renderer/budget.js +1 -168
  190. package/vendor/desktop/renderer/companion.js +1 -223
  191. package/vendor/desktop/renderer/diff.js +1 -359
  192. package/vendor/desktop/renderer/diffview.js +1 -336
  193. package/vendor/desktop/renderer/fingerprint.js +3 -736
  194. package/vendor/desktop/renderer/markdown.js +1 -168
  195. package/vendor/desktop/renderer/provider-toolbar.js +1 -134
  196. package/vendor/desktop/renderer/providers.js +1 -259
  197. package/vendor/desktop/renderer/quick.js +1 -191
  198. package/vendor/desktop/renderer/stream-policy.js +1 -306
  199. package/vendor/desktop/renderer/transcript-view.js +1 -323
  200. package/vendor/desktop/renderer/usage.js +1 -1239
  201. package/vendor/desktop/vendor/aegis.js +1 -2179
  202. package/vendor/desktop/vendor/attest.js +1 -442
  203. package/vendor/desktop/vendor/authorship-key.js +1 -410
  204. package/vendor/desktop/vendor/auto-provision.js +1 -134
  205. package/vendor/desktop/vendor/brain-catalog.js +1 -268
  206. package/vendor/desktop/vendor/byok-catalog.js +1 -230
  207. package/vendor/desktop/vendor/credentials.js +1 -494
  208. package/vendor/desktop/vendor/device-fingerprint.js +1 -141
  209. package/vendor/desktop/vendor/drive-connect.js +1 -110
  210. package/vendor/desktop/vendor/drive-upload.js +1 -174
  211. package/vendor/desktop/vendor/env-file.js +1 -1273
  212. package/vendor/desktop/vendor/fingerprint.js +1 -1064
  213. package/vendor/desktop/vendor/foreign-memory.js +1 -669
  214. package/vendor/desktop/vendor/google-signin.js +1 -133
  215. package/vendor/desktop/vendor/hooks.js +1 -430
  216. package/vendor/desktop/vendor/model-discovery.js +1 -373
  217. package/vendor/desktop/vendor/platform.js +1 -937
  218. package/vendor/desktop/vendor/prefs.js +1 -351
  219. package/vendor/desktop/vendor/presence-constants.js +1 -107
  220. package/vendor/desktop/vendor/presence.js +1 -438
  221. package/vendor/desktop/vendor/record-vault.js +3 -1055
  222. package/vendor/desktop/vendor/session-store.js +1 -548
  223. package/vendor/desktop/vendor/topup.js +1 -297
  224. package/vendor/desktop/vendor/touch.js +1 -458
  225. package/vendor/desktop/vendor/update.js +1 -704
  226. package/vendor/desktop/vendor/user-models.js +1 -381
@@ -1,224 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
4
- // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
5
- // Conveying a modified copy, or running one as a network service, owes the
6
- // corresponding source under this licence (§5/§13) — see LICENSING.md.
7
- /**
8
- * AEGIS MCP server — exposes aegiscloud capabilities to any Claude Code user.
9
- *
10
- * Zero dependencies: raw JSON-RPC 2.0 over stdio (newline-delimited), Node's
11
- * global fetch. Runs from a bare `node server.js` — no npm install required.
12
- *
13
- * This is a thin HOST: all transport lives in ../client/aegis.js and the tool
14
- * registry lives in ./tools.js. This file only speaks MCP JSON-RPC.
15
- */
16
-
17
- 'use strict';
18
-
19
- const { createClient } = require('../client/aegis.js');
20
- const credentials = require('../client/credentials.js');
21
- const { autoProvisionApiKey } = require('../client/auto-provision.js');
22
- const { createTools } = require('./tools.js');
23
-
24
- // `~/.aegiscode/.env` read into process.env once, before anything resolves a
25
- // credential. Without this the one-instruction setup ("put your key in
26
- // ~/.aegiscode/.env") would be true in the CLI and the desktop and false here,
27
- // because this host resolves a key from the environment or the 0600 store and
28
- // nothing filled the environment from the file. A variable already exported in
29
- // the environment Claude Code was launched from always wins. Failure is never
30
- // fatal: an absent file is the pre-existing state, not an error.
31
- try {
32
- const loaded = require('../client/env-file.js').loadEnvFile();
33
- if (loaded.loose) {
34
- process.stderr.write(
35
- `aegis: ${loaded.file} is readable by other accounts (mode ` +
36
- `${loaded.mode.toString(8)}) — consider \`chmod 600\` on it.\n`
37
- );
38
- }
39
- } catch { /* an absent or unreadable file is not a startup error */ }
40
-
41
- // The account credential is resolved the same way in all four hosts: the
42
- // environment first, then the 0600 store the terminal host writes with
43
- // `aegiscode login` (or /key), then a legacy config.json. This host used to
44
- // read `AEGIS_API_KEY` from the environment alone, so a user who signed in from
45
- // the CLI still met "No AEGIS_API_KEY is set" here — the credential existed,
46
- // this process just would not look at it.
47
- //
48
- // `client/` is inside the tree the plugin ships (mcp/ + client/), so this needs
49
- // no dependency on the CLI package to work when installed.
50
- const aegis = createClient(credentials.clientOptions());
51
- // The tool registry lives in ./tools.js, shared with the terminal host
52
- // (cli/) so the two hosts cannot drift apart. This file owns the JSON-RPC
53
- // plumbing and nothing else.
54
- const { TOOLS, toolList } = createTools(aegis);
55
- const API_BASE = aegis.apiBase;
56
- const SERVER_NAME = 'aegis';
57
- // Keep in sync with .claude-plugin/plugin.json "version".
58
- const SERVER_VERSION = '0.4.0';
59
-
60
- /** The one instruction that actually resolves a missing key. */
61
- function missingKeyText() {
62
- const { path } = credentials.keyStatus();
63
- return [
64
- 'No AEGIS API key is configured for this session.',
65
- '',
66
- 'Set one with any of:',
67
- ' • `aegiscode login` in a terminal (saves it to ' + path + ', mode 0600)',
68
- ' • export AEGIS_API_KEY=… in the environment Claude Code was launched from',
69
- ' • put `AEGIS_API_KEY=…` in ~/.aegiscode/.env (read at startup, every host)',
70
- '',
71
- 'Then restart Claude Code. Get a key at https://aegiscloud.org.',
72
- ].join('\n');
73
- }
74
-
75
- // A tool call with no key configured anywhere gets ONE auto-provision attempt
76
- // per process, not one per call: `register-device` is rate-limited server-side
77
- // at 5/hour/IP, and a session that fires several tool calls before the user
78
- // notices the failure message must not burn through that budget on retries
79
- // that would fail the same way. Success or failure, this only ever runs once.
80
- // The provisioning itself (endpoint, fingerprint, timeout) is shared with the
81
- // desktop app and the CLI — see client/auto-provision.js.
82
- let provisionAttempted = false;
83
- async function ensureApiKey() {
84
- if (aegis.apiKey || provisionAttempted) return;
85
- provisionAttempted = true;
86
- const result = await autoProvisionApiKey(aegis, credentials, { app: 'mcp' });
87
- if (result.error) {
88
- process.stderr.write(`aegis: device auto-registration failed (${result.error.message}) — falling back to manual setup.\n`);
89
- return;
90
- }
91
- if (!result.key) {
92
- process.stderr.write('aegis: device auto-registration returned no usable key — falling back to manual setup.\n');
93
- return;
94
- }
95
- // The key comes with aegis1's one-time 30-day welcome-trial `unlimited`
96
- // entitlement (token-bank credit + a `subscriptions` row, granted in the
97
- // same register-device request — see registerDevice()'s doc in
98
- // client/aegis.js), so the very next call works pooled. Once that allowance
99
- // is spent or the trial lapses, the balance gate applies again.
100
- process.stderr.write(
101
- 'aegis: no API key was configured — auto-provisioned a free AEGIS account' +
102
- (result.ok ? ` (key saved to ${credentials.keyStatus().path}).\n` : ' (could not save it — see above).\n') +
103
- `Fund it at ${aegis.promptUrl('topup', 'device_autoprovision')} or set your own BYOK key with aegis_byok_set.\n`
104
- );
105
- }
106
-
107
- // ---------------------------------------------------------------------------
108
- // JSON-RPC / MCP plumbing
109
- // ---------------------------------------------------------------------------
110
-
111
- function send(msg) {
112
- process.stdout.write(JSON.stringify(msg) + '\n');
113
- }
114
-
115
- function reply(id, result) {
116
- send({ jsonrpc: '2.0', id, result });
117
- }
118
-
119
- function replyError(id, code, message) {
120
- send({ jsonrpc: '2.0', id, error: { code, message } });
121
- }
122
-
123
- // Track in-flight handlers so we don't exit while a fetch is pending.
124
- let pending = 0;
125
- let stdinClosed = false;
126
- function maybeExit() {
127
- if (stdinClosed && pending === 0) process.exit(0);
128
- }
129
-
130
- async function handleMessage(msg) {
131
- const { id, method, params } = msg;
132
- const isNotification = id === undefined || id === null;
133
-
134
- try {
135
- switch (method) {
136
- case 'initialize':
137
- reply(id, {
138
- protocolVersion: (params && params.protocolVersion) || '2024-11-05',
139
- capabilities: { tools: {} },
140
- serverInfo: { name: SERVER_NAME, version: SERVER_VERSION },
141
- });
142
- return;
143
-
144
- case 'notifications/initialized':
145
- case 'notifications/cancelled':
146
- return; // no response for notifications
147
-
148
- case 'ping':
149
- if (!isNotification) reply(id, {});
150
- return;
151
-
152
- case 'tools/list':
153
- reply(id, { tools: toolList() });
154
- return;
155
-
156
- case 'tools/call': {
157
- const name = params && params.name;
158
- const tool = TOOLS[name];
159
- if (!tool) {
160
- reply(id, {
161
- content: [{ type: 'text', text: `Unknown tool: ${name}` }],
162
- isError: true,
163
- });
164
- return;
165
- }
166
- if (!aegis.apiKey) await ensureApiKey();
167
- if (!aegis.apiKey) {
168
- reply(id, {
169
- content: [{ type: 'text', text: missingKeyText() }],
170
- isError: true,
171
- });
172
- return;
173
- }
174
- try {
175
- const text = await tool.run((params && params.arguments) || {});
176
- reply(id, { content: [{ type: 'text', text }], isError: false });
177
- } catch (err) {
178
- reply(id, {
179
- content: [{ type: 'text', text: `AEGIS error: ${err.message}` }],
180
- isError: true,
181
- });
182
- }
183
- return;
184
- }
185
-
186
- default:
187
- if (!isNotification) replyError(id, -32601, `Method not found: ${method}`);
188
- return;
189
- }
190
- } catch (err) {
191
- if (!isNotification) replyError(id, -32603, err.message);
192
- }
193
- }
194
-
195
- // ---------------------------------------------------------------------------
196
- // stdin loop — newline-delimited JSON-RPC
197
- // ---------------------------------------------------------------------------
198
-
199
- let buffer = '';
200
- process.stdin.setEncoding('utf8');
201
- process.stdin.on('data', (chunk) => {
202
- buffer += chunk;
203
- let nl;
204
- while ((nl = buffer.indexOf('\n')) !== -1) {
205
- const line = buffer.slice(0, nl).trim();
206
- buffer = buffer.slice(nl + 1);
207
- if (!line) continue;
208
- let msg;
209
- try {
210
- msg = JSON.parse(line);
211
- } catch {
212
- continue; // skip malformed lines
213
- }
214
- pending++;
215
- Promise.resolve(handleMessage(msg)).finally(() => {
216
- pending--;
217
- maybeExit();
218
- });
219
- }
220
- });
221
- process.stdin.on('end', () => {
222
- stdinClosed = true;
223
- maybeExit();
224
- });
4
+ "use strict";const{createClient:createClient}=require("../client/aegis.js"),credentials=require("../client/credentials.js"),{autoProvisionApiKey:autoProvisionApiKey}=require("../client/auto-provision.js"),{createTools:createTools}=require("./tools.js");try{const e=require("../client/env-file.js").loadEnvFile();e.loose&&process.stderr.write(`aegis: ${e.file} is readable by other accounts (mode ${e.mode.toString(8)}) — consider \`chmod 600\` on it.\n`)}catch{}const aegis=createClient(credentials.clientOptions()),{TOOLS:TOOLS,toolList:toolList}=createTools(aegis),API_BASE=aegis.apiBase,SERVER_NAME="aegis",SERVER_VERSION="0.4.0";function missingKeyText(){const{path:e}=credentials.keyStatus();return["No AEGIS API key is configured for this session.","","Set one with any of:"," • `aegiscode login` in a terminal (saves it to "+e+", mode 0600)"," • export AEGIS_API_KEY=… in the environment Claude Code was launched from"," • put `AEGIS_API_KEY=…` in ~/.aegiscode/.env (read at startup, every host)","","Then restart Claude Code. Get a key at https://aegiscloud.org."].join("\n")}let provisionAttempted=!1;async function ensureApiKey(){if(aegis.apiKey||provisionAttempted)return;provisionAttempted=!0;const e=await autoProvisionApiKey(aegis,credentials,{app:"mcp"});e.error?process.stderr.write(`aegis: device auto-registration failed (${e.error.message}) — falling back to manual setup.\n`):e.key?process.stderr.write("aegis: no API key was configured — auto-provisioned a free AEGIS account"+(e.ok?` (key saved to ${credentials.keyStatus().path}).\n`:" (could not save it — see above).\n")+`Fund it at ${aegis.promptUrl("topup","device_autoprovision")} or set your own BYOK key with aegis_byok_set.\n`):process.stderr.write("aegis: device auto-registration returned no usable key — falling back to manual setup.\n")}function send(e){process.stdout.write(JSON.stringify(e)+"\n")}function reply(e,t){send({jsonrpc:"2.0",id:e,result:t})}function replyError(e,t,i){send({jsonrpc:"2.0",id:e,error:{code:t,message:i}})}let pending=0,stdinClosed=!1;function maybeExit(){stdinClosed&&0===pending&&process.exit(0)}async function handleMessage(e){const{id:t,method:i,params:o}=e,r=null==t;try{switch(i){case"initialize":return void reply(t,{protocolVersion:o&&o.protocolVersion||"2024-11-05",capabilities:{tools:{}},serverInfo:{name:"aegis",version:"0.4.0"}});case"notifications/initialized":case"notifications/cancelled":return;case"ping":return void(r||reply(t,{}));case"tools/list":return void reply(t,{tools:toolList()});case"tools/call":{const i=o&&o.name,r=TOOLS[i];if(!r)return void reply(t,{content:[{type:"text",text:`Unknown tool: ${i}`}],isError:!0});if(aegis.apiKey||await ensureApiKey(),!aegis.apiKey)return void reply(t,{content:[{type:"text",text:missingKeyText()}],isError:!0});try{reply(t,{content:[{type:"text",text:await r.run(o&&o.arguments||{})}],isError:!1})}catch(e){reply(t,{content:[{type:"text",text:`AEGIS error: ${e.message}`}],isError:!0})}return}default:return void(r||replyError(t,-32601,`Method not found: ${i}`))}}catch(e){r||replyError(t,-32603,e.message)}}let buffer="";process.stdin.setEncoding("utf8"),process.stdin.on("data",(e=>{let t;for(buffer+=e;-1!==(t=buffer.indexOf("\n"));){const e=buffer.slice(0,t).trim();if(buffer=buffer.slice(t+1),!e)continue;let i;try{i=JSON.parse(e)}catch{continue}pending++,Promise.resolve(handleMessage(i)).finally((()=>{pending--,maybeExit()}))}})),process.stdin.on("end",(()=>{stdinClosed=!0,maybeExit()}));
@@ -1,410 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
- // Conveying a modified copy, or running one as a network service, owes the
5
- // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
- 'use strict';
7
-
8
- /**
9
- * AEGIS tool registry — the one definition of what the AEGIS surface can do.
10
- *
11
- * Both hosts build from this file: `mcp/server.js` (the MCP host) and `cli/`
12
- * (the terminal host). A capability can therefore never exist in one host and
13
- * be silently missing from the other, and the JSON schemas the model sees are
14
- * literally the same objects the CLI's /commands dispatch against.
15
- *
16
- * This module is pure: names, schemas, and the text each tool returns. It holds
17
- * no JSON-RPC, no ANSI, and no terminal state. The transport is injected rather
18
- * than created here, so each host passes its own configured client — and a test
19
- * can pass a stub.
20
- *
21
- * The tool bodies are indented one level deeper than they were when they lived
22
- * in mcp/server.js; the shift is whitespace only (no template literal in the
23
- * block spans a line).
24
- */
25
-
26
- const foreignMemory = require('../client/foreign-memory.js');
27
-
28
- /**
29
- * Build the registry against a client instance.
30
- *
31
- * @param {object} client A client from client/aegis.js (or a stub with the same
32
- * method surface). Required — a host owns its own key handling, so this
33
- * module never reads the environment itself.
34
- * @returns {{TOOLS: object, toolList: () => Array<{name: string, description: string, inputSchema: object}>}}
35
- */
36
- function createTools(client) {
37
- if (!client || typeof client !== 'object') {
38
- throw new TypeError('createTools(client): a client instance is required');
39
- }
40
-
41
- // The moved bodies call through this name, so the registry cannot reach any
42
- // other module state.
43
- const aegis = client;
44
-
45
- // Attribution for money prompts. A stub client (tests pass one) may not carry
46
- // `promptUrl`, and a throw here would kill the tool body mid-message — so the
47
- // guard degrades to an untagged link rather than to no link at all.
48
- const promptUrl = (page, campaign) =>
49
- typeof aegis.promptUrl === 'function'
50
- ? aegis.promptUrl(page, campaign)
51
- : `https://aegiscloud.org/go/${page}`;
52
-
53
- const TOOLS = {
54
- aegis_status: {
55
- description:
56
- "Check the current AEGIS account: validates the API key and reports the plan, email, and whether cloud memory is enabled. Call this first to confirm setup.",
57
- inputSchema: { type: 'object', properties: {}, additionalProperties: false },
58
- async run() {
59
- const info = await aegis.verifyApiKey();
60
- const lines = [
61
- `Key valid: ${info.valid ? 'yes' : 'no'}`,
62
- `Plan: ${info.plan || 'unknown'}`,
63
- info.email ? `Account: ${info.email}` : null,
64
- `Memory: ${info.memory_token ? 'enabled (cloud sync available)' : 'not enabled'}`,
65
- `API base: ${aegis.apiBase}`,
66
- ].filter(Boolean);
67
- return lines.join('\n');
68
- },
69
- },
70
-
71
- aegis_ask: {
72
- description:
73
- "Send a prompt to AEGIS pooled inference, billed against the account's token bank. List models with aegis_list_models and pass any id as `model`; omit `model` to let the server pick its default. `mode` is a legacy server-side shorthand and is never required.",
74
- inputSchema: {
75
- type: 'object',
76
- properties: {
77
- prompt: { type: 'string', description: 'The user prompt / question.' },
78
- model: {
79
- type: 'string',
80
- description:
81
- 'Pin any model id from aegis_list_models — or omit for the server default.',
82
- },
83
- mode: {
84
- type: 'string',
85
- description:
86
- "Legacy server-side shorthand (e.g. 'fast', 'smart', 'neo'). Optional — never defaulted client-side.",
87
- },
88
- system: { type: 'string', description: 'Optional system instruction.' },
89
- max_tokens: {
90
- type: 'integer',
91
- description:
92
- 'Max output tokens. The server enforces the true ceiling; omit for the server default.',
93
- minimum: 1,
94
- maximum: 64000,
95
- },
96
- },
97
- required: ['prompt'],
98
- additionalProperties: false,
99
- },
100
- async run(args) {
101
- // Use the OpenAI-compatible endpoint (stream:false): it returns structured
102
- // JSON errors (e.g. 402 insufficient_quota) instead of the opaque 502 that
103
- // /api/v1/complete emits. An exact `model` id pins that provider directly;
104
- // omitting `model` lets the server route to its default.
105
- const data = await aegis.chatCompletion({
106
- prompt: args.prompt,
107
- system: args.system,
108
- model: args.model,
109
- mode: args.mode,
110
- maxTokens: args.max_tokens,
111
- });
112
- const choice = (data.choices && data.choices[0]) || {};
113
- const text = (choice.message && choice.message.content) || '(empty response)';
114
- const meta = [
115
- data.model ? `model: ${data.model}` : null,
116
- data.usage ? `tokens: ${data.usage.total_tokens}` : null,
117
- ]
118
- .filter(Boolean)
119
- .join(' · ');
120
- return `${text}\n\n— ${meta}`;
121
- },
122
- },
123
-
124
- aegis_list_models: {
125
- description:
126
- "List the exact models available to pin with aegis_ask's `model` argument — the server's model list is the truth, and omitting `model` uses the server default.",
127
- inputSchema: { type: 'object', properties: {}, additionalProperties: false },
128
- async run() {
129
- const data = await aegis.listModels();
130
- const models = data.models || [];
131
- if (!models.length) return 'No pinnable models are currently configured on AEGIS.';
132
- return [
133
- 'Pass one of these as aegis_ask\'s `model` argument:',
134
- '',
135
- ...models.map((m) => ` ${m.id} (${(m.capabilities || []).join(', ')})`),
136
- ].join('\n');
137
- },
138
- },
139
-
140
- aegis_balance: {
141
- description:
142
- "Check the AEGIS token bank balance and recent spend. Call this before aegis_ask if you're unsure whether the account has funds, or to see what recent calls cost.",
143
- inputSchema: { type: 'object', properties: {}, additionalProperties: false },
144
- async run() {
145
- const data = await aegis.tokenBankBalance();
146
- const lines = [`Balance: €${Number(data.balance_eur || 0).toFixed(2)}`];
147
- const ledger = (data.ledger || []).slice(0, 5);
148
- if (ledger.length) {
149
- lines.push('', 'Recent activity:');
150
- for (const l of ledger) {
151
- // The balance endpoint returns `amount_eur`, signed from the user's
152
- // side: negative = spent on a call, positive = top-up/rebate. This
153
- // used to read `charged_micros`, which the endpoint does not return
154
- // at all — every row rendered as "-€0.0000" no matter how many
155
- // tokens the call consumed. Only fall back to the raw micros column
156
- // (opposite sign) if a future server drops amount_eur.
157
- const eur = l.amount_eur != null
158
- ? Number(l.amount_eur)
159
- : -Number(l.charged_micros || 0) / 1_000_000;
160
- // Sub-cent calls are the norm here, so keep 4dp below a cent and
161
- // fall back to 2dp for cash-sized rows.
162
- const abs = Math.abs(eur);
163
- const amount = `${eur < 0 ? '-' : '+'}€${abs < 0.01 ? abs.toFixed(4) : abs.toFixed(2)}`;
164
- const kind = l.kind === 'topup' ? 'top-up' : (l.kind || '');
165
- const model = l.model_key || kind || '';
166
- const tokens = (l.tokens_in || l.tokens_out)
167
- ? ` ${l.tokens_in || 0}/${l.tokens_out || 0} tokens`
168
- : '';
169
- lines.push(` ${l.created_at || ''} ${model}${tokens} ${amount}`);
170
- }
171
- } else {
172
- lines.push('No spend yet.');
173
- }
174
- if ((data.balance_eur || 0) <= 0) {
175
- lines.push(
176
- '',
177
- `Balance is empty — top up at ${promptUrl('topup', 'topup_bank')}, or set your own ` +
178
- 'provider key with aegis_byok_set to use aegis_ask for free at cost.'
179
- );
180
- }
181
- return lines.join('\n');
182
- },
183
- },
184
-
185
- aegis_byok_providers: {
186
- description:
187
- "List every provider that accepts a Bring-Your-Own-Key on AEGIS: the exact provider id to pass to aegis_byok_set, the models each one unlocks, where to create the key, and the prefix a valid key starts with. Call this before aegis_byok_set so the user knows which key to go get rather than guessing a provider id.",
188
- inputSchema: { type: 'object', properties: {}, additionalProperties: false },
189
- async run() {
190
- const data = await aegis.byokProviders();
191
- const providers = data.providers || [];
192
- if (!providers.length) return 'AEGIS is not advertising any BYOK providers right now.';
193
- const lines = ["Set one with aegis_byok_set — pass the id exactly as shown:"];
194
- for (const p of providers) {
195
- // Bare ids, not objects — the same mismatch that made the CLI render
196
- // an empty model line for every provider.
197
- const models = (p.models || [])
198
- .map((m) => (typeof m === 'string' ? m : m && m.id))
199
- .filter(Boolean);
200
- const state = p.configured ? ` ✓ set${p.masked ? ` (${p.masked})` : ''}` : '';
201
- lines.push('');
202
- lines.push(` ${p.id}${state}`);
203
- if (p.label) lines.push(` ${p.label}`);
204
- if (models.length) lines.push(` models: ${models.join(', ')}`);
205
- if (p.key_prefix) lines.push(` key starts with: ${p.key_prefix}`);
206
- if (p.key_url) lines.push(` get a key: ${p.key_url}`);
207
- }
208
- return lines.join('\n');
209
- },
210
- },
211
-
212
- aegis_byok_status: {
213
- description:
214
- "List which providers have a Bring-Your-Own-Key configured on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …). A configured BYOK key is used automatically by aegis_ask instead of the pooled balance for that provider, so calls no longer cost AEGIS token-bank funds.",
215
- inputSchema: { type: 'object', properties: {}, additionalProperties: false },
216
- async run() {
217
- const data = await aegis.byokStatus();
218
- const entries = Object.entries(data || {});
219
- if (!entries.length) return 'No BYOK providers are configured. Run aegis_byok_providers to see what you can set.';
220
- // The status endpoint historically answered with a bare provider->info
221
- // map. Once a catalog is available the same keys are rendered with the
222
- // operator's own label, so a message never depends on the reader
223
- // knowing that "together" is a company.
224
- let labels = {};
225
- try {
226
- const cat = await aegis.byokProviders();
227
- for (const p of cat.providers || []) labels[p.id] = p.label || '';
228
- } catch {
229
- // Catalog is a nicety here, never a reason to fail a status call.
230
- }
231
- const rows = entries.map(([provider, info]) => {
232
- const set = info && info.set;
233
- const label = labels[provider] ? ` ${labels[provider]}` : '';
234
- return ` ${provider}${label}: ${set ? `set (${info.masked})` : 'not set'}`;
235
- });
236
- return `BYOK keys:\n${rows.join('\n')}`;
237
- },
238
- },
239
-
240
- aegis_byok_set: {
241
- description:
242
- "Set or remove a Bring-Your-Own-Key API key for a provider on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …; the server validates what it supports). Once set, aegis_ask uses that key directly for that provider instead of the pooled AEGIS balance — unlimited use at the user's own cost. Omit api_key to remove a previously set key.",
243
- inputSchema: {
244
- type: 'object',
245
- properties: {
246
- provider: {
247
- type: 'string',
248
- description:
249
- "Which provider this key is for (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …).",
250
- },
251
- api_key: { type: 'string', description: "The provider's own API key. Omit to delete the stored key instead." },
252
- },
253
- required: ['provider'],
254
- additionalProperties: false,
255
- },
256
- async run(args) {
257
- const data = await aegis.byokSet(args.provider, args.api_key);
258
- return data.message || (args.api_key ? `${args.provider} key saved.` : `${args.provider} key removed.`);
259
- },
260
- },
261
-
262
- aegis_memory_search: {
263
- description:
264
- "Search the user's AEGIS cloud memory (persists across machines and sessions). Returns the most relevant stored entries for a query.",
265
- inputSchema: {
266
- type: 'object',
267
- properties: {
268
- query: { type: 'string', description: 'Search text. Empty returns most recent.' },
269
- limit: { type: 'integer', description: 'Max entries (1-50). Default 5.', minimum: 1, maximum: 50 },
270
- },
271
- required: ['query'],
272
- additionalProperties: false,
273
- },
274
- async run(args) {
275
- const data = await aegis.memorySearch(args.query, args.limit || 5);
276
- const entries = data.entries || [];
277
- if (!entries.length) return `No memory entries matched "${args.query}".`;
278
- return entries
279
- .map((e, i) => {
280
- const when = e.timestamp || e.createdAt || '';
281
- const tags = (e.tags && e.tags.length) ? ` [${e.tags.join(', ')}]` : '';
282
- return `${i + 1}. ${e.content}${tags}${when ? `\n (${when})` : ''}`;
283
- })
284
- .join('\n');
285
- },
286
- },
287
-
288
- aegis_memory_save: {
289
- description:
290
- "Save a note to the user's AEGIS cloud memory so it persists across machines and future sessions. Use for durable facts, decisions, or preferences the user asks you to remember.",
291
- inputSchema: {
292
- type: 'object',
293
- properties: {
294
- content: { type: 'string', description: 'The fact/note to store.' },
295
- tags: { type: 'array', items: { type: 'string' }, description: 'Optional tags.' },
296
- importance: { type: 'integer', description: 'Optional 1-10 salience. Default 5.', minimum: 1, maximum: 10 },
297
- session: { type: 'string', description: 'Optional session/label to group under.' },
298
- },
299
- required: ['content'],
300
- additionalProperties: false,
301
- },
302
- async run(args) {
303
- const entry = {
304
- id: aegis.randomUUID(),
305
- content: args.content,
306
- role: 'assistant',
307
- source: 'claude-code',
308
- session: args.session || 'claude-code',
309
- tags: args.tags || [],
310
- importance: typeof args.importance === 'number' ? args.importance : 5,
311
- timestamp: new Date().toISOString(),
312
- };
313
- const data = await aegis.memorySave(entry);
314
- return `Saved ${data.saved || 1} memory entry (id ${entry.id}).`;
315
- },
316
- },
317
-
318
- aegis_memory_import: {
319
- description:
320
- "Import memory and past conversation context from OTHER AI coding tools installed on this machine (Claude Code, Codex, Cursor, Gemini CLI, Continue, Goose, opencode, Windsurf, Zed, and a local AEGIS engine) into the user's AEGIS cloud memory. Scans read-only; nothing in the other tools' directories is modified. Defaults to a DRY RUN that only reports what it found — pass confirm:true to actually save. Entries are content-addressed, so re-running never duplicates.",
321
- inputSchema: {
322
- type: 'object',
323
- properties: {
324
- confirm: {
325
- type: 'boolean',
326
- description: 'false (default) = report only. true = actually write the entries to AEGIS memory.',
327
- },
328
- sources: {
329
- type: 'array',
330
- items: { type: 'string' },
331
- description:
332
- 'Optional subset of source ids to import (e.g. ["claude-code"]). Omit for every source found on this machine.',
333
- },
334
- limit: { type: 'integer', description: 'Max entries to import (1-5000). Default 1000.', minimum: 1, maximum: 5000 },
335
- },
336
- additionalProperties: false,
337
- },
338
- async run(args) {
339
- const limit = args.limit || 1000;
340
- const report = foreignMemory.scan({ sources: args.sources, limit });
341
- const summary = foreignMemory.describe(report);
342
-
343
- if (!report.entries.length) {
344
- return `${summary}\n\nNothing to import.`;
345
- }
346
-
347
- if (!args.confirm) {
348
- return [
349
- summary,
350
- '',
351
- `Dry run — ${report.totals.entries} entries would be saved to AEGIS memory under ${report.totals.sourcesWithEntries} session(s) (${report.totals.skipped} skipped as too short/noise).`,
352
- 'Call this tool again with confirm:true to save them.',
353
- ].join('\n');
354
- }
355
-
356
- let saved = 0;
357
- const failures = [];
358
- for (const batch of foreignMemory.chunk(report.entries, 200)) {
359
- try {
360
- const data = await aegis.memorySaveBatch(batch);
361
- saved += (data && data.saved) || batch.length;
362
- } catch (err) {
363
- // A 402 here means the free-tier session cap; surface it verbatim
364
- // rather than pretending part of the import worked.
365
- failures.push(err.message);
366
- break;
367
- }
368
- }
369
-
370
- if (failures.length) {
371
- return `${summary}\n\nSaved ${saved} of ${report.totals.entries} entries, then stopped: ${failures[0]}`;
372
- }
373
- return `${summary}\n\nSaved ${saved} entries to AEGIS memory. They are searchable now with aegis_memory_search.`;
374
- },
375
- },
376
-
377
- aegis_memory_list: {
378
- description:
379
- "List the most recent entries in the user's AEGIS cloud memory. Useful to review what AEGIS already remembers.",
380
- inputSchema: {
381
- type: 'object',
382
- properties: {
383
- limit: { type: 'integer', description: 'Max entries (1-50). Default 10.', minimum: 1, maximum: 50 },
384
- },
385
- additionalProperties: false,
386
- },
387
- async run(args) {
388
- const data = await aegis.memoryList(args.limit || 10);
389
- const entries = data.entries || [];
390
- if (!entries.length) return 'AEGIS cloud memory is empty.';
391
- const body = entries.map((e, i) => `${i + 1}. ${e.content}`).join('\n');
392
- return `Recent ${entries.length} entries:\n${body}`;
393
- },
394
- },
395
- };
396
-
397
-
398
- /** The MCP `tools/list` payload — and the CLI's command index. */
399
- function toolList() {
400
- return Object.entries(TOOLS).map(([name, t]) => ({
401
- name,
402
- description: t.description,
403
- inputSchema: t.inputSchema,
404
- }));
405
- }
406
-
407
- return { TOOLS, toolList };
408
- }
409
-
410
- module.exports = { createTools };
3
+ "use strict";const foreignMemory=require("../client/foreign-memory.js");function createTools(e){if(!e||"object"!=typeof e)throw new TypeError("createTools(client): a client instance is required");const t=e,o={aegis_status:{description:"Check the current AEGIS account: validates the API key and reports the plan, email, and whether cloud memory is enabled. Call this first to confirm setup.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await t.verifyApiKey();return["Key valid: "+(e.valid?"yes":"no"),`Plan: ${e.plan||"unknown"}`,e.email?`Account: ${e.email}`:null,"Memory: "+(e.memory_token?"enabled (cloud sync available)":"not enabled"),`API base: ${t.apiBase}`].filter(Boolean).join("\n")}},aegis_ask:{description:"Send a prompt to AEGIS pooled inference, billed against the account's token bank. List models with aegis_list_models and pass any id as `model`; omit `model` to let the server pick its default. `mode` is a legacy server-side shorthand and is never required.",inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The user prompt / question."},model:{type:"string",description:"Pin any model id from aegis_list_models — or omit for the server default."},mode:{type:"string",description:"Legacy server-side shorthand (e.g. 'fast', 'smart', 'neo'). Optional — never defaulted client-side."},system:{type:"string",description:"Optional system instruction."},max_tokens:{type:"integer",description:"Max output tokens. The server enforces the true ceiling; omit for the server default.",minimum:1,maximum:64e3}},required:["prompt"],additionalProperties:!1},async run(e){const o=await t.chatCompletion({prompt:e.prompt,system:e.system,model:e.model,mode:e.mode,maxTokens:e.max_tokens}),s=o.choices&&o.choices[0]||{};return`${s.message&&s.message.content||"(empty response)"}\n\n— ${[o.model?`model: ${o.model}`:null,o.usage?`tokens: ${o.usage.total_tokens}`:null].filter(Boolean).join(" · ")}`}},aegis_list_models:{description:"List the exact models available to pin with aegis_ask's `model` argument — the server's model list is the truth, and omitting `model` uses the server default.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=(await t.listModels()).models||[];return e.length?["Pass one of these as aegis_ask's `model` argument:","",...e.map((e=>` ${e.id} (${(e.capabilities||[]).join(", ")})`))].join("\n"):"No pinnable models are currently configured on AEGIS."}},aegis_balance:{description:"Check the AEGIS token bank balance and recent spend. Call this before aegis_ask if you're unsure whether the account has funds, or to see what recent calls cost.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await t.tokenBankBalance(),o=[`Balance: €${Number(e.balance_eur||0).toFixed(2)}`],s=(e.ledger||[]).slice(0,5);if(s.length){o.push("","Recent activity:");for(const e of s){const t=null!=e.amount_eur?Number(e.amount_eur):-Number(e.charged_micros||0)/1e6,s=Math.abs(t),r=`${t<0?"-":"+"}€${s<.01?s.toFixed(4):s.toFixed(2)}`,i="topup"===e.kind?"top-up":e.kind||"",n=e.model_key||i||"",a=e.tokens_in||e.tokens_out?` ${e.tokens_in||0}/${e.tokens_out||0} tokens`:"";o.push(` ${e.created_at||""} ${n}${a} ${r}`)}}else o.push("No spend yet.");var r;return(e.balance_eur||0)<=0&&o.push("",`Balance is empty — top up at ${r="topup","function"==typeof t.promptUrl?t.promptUrl(r,"topup_bank"):`https://aegiscloud.org/go/${r}`}, or set your own provider key with aegis_byok_set to use aegis_ask for free at cost.`),o.join("\n")}},aegis_byok_providers:{description:"List every provider that accepts a Bring-Your-Own-Key on AEGIS: the exact provider id to pass to aegis_byok_set, the models each one unlocks, where to create the key, and the prefix a valid key starts with. Call this before aegis_byok_set so the user knows which key to go get rather than guessing a provider id.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=(await t.byokProviders()).providers||[];if(!e.length)return"AEGIS is not advertising any BYOK providers right now.";const o=["Set one with aegis_byok_set — pass the id exactly as shown:"];for(const t of e){const e=(t.models||[]).map((e=>"string"==typeof e?e:e&&e.id)).filter(Boolean),s=t.configured?" ✓ set"+(t.masked?` (${t.masked})`:""):"";o.push(""),o.push(` ${t.id}${s}`),t.label&&o.push(` ${t.label}`),e.length&&o.push(` models: ${e.join(", ")}`),t.key_prefix&&o.push(` key starts with: ${t.key_prefix}`),t.key_url&&o.push(` get a key: ${t.key_url}`)}return o.join("\n")}},aegis_byok_status:{description:"List which providers have a Bring-Your-Own-Key configured on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …). A configured BYOK key is used automatically by aegis_ask instead of the pooled balance for that provider, so calls no longer cost AEGIS token-bank funds.",inputSchema:{type:"object",properties:{},additionalProperties:!1},async run(){const e=await t.byokStatus(),o=Object.entries(e||{});if(!o.length)return"No BYOK providers are configured. Run aegis_byok_providers to see what you can set.";let s={};try{const e=await t.byokProviders();for(const t of e.providers||[])s[t.id]=t.label||""}catch{}return`BYOK keys:\n${o.map((([e,t])=>{const o=t&&t.set;return` ${e}${s[e]?` ${s[e]}`:""}: ${o?`set (${t.masked})`:"not set"}`})).join("\n")}`}},aegis_byok_set:{description:"Set or remove a Bring-Your-Own-Key API key for a provider on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …; the server validates what it supports). Once set, aegis_ask uses that key directly for that provider instead of the pooled AEGIS balance — unlimited use at the user's own cost. Omit api_key to remove a previously set key.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Which provider this key is for (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …)."},api_key:{type:"string",description:"The provider's own API key. Omit to delete the stored key instead."}},required:["provider"],additionalProperties:!1},run:async e=>(await t.byokSet(e.provider,e.api_key)).message||(e.api_key?`${e.provider} key saved.`:`${e.provider} key removed.`)},aegis_memory_search:{description:"Search the user's AEGIS cloud memory (persists across machines and sessions). Returns the most relevant stored entries for a query.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search text. Empty returns most recent."},limit:{type:"integer",description:"Max entries (1-50). Default 5.",minimum:1,maximum:50}},required:["query"],additionalProperties:!1},async run(e){const o=(await t.memorySearch(e.query,e.limit||5)).entries||[];return o.length?o.map(((e,t)=>{const o=e.timestamp||e.createdAt||"",s=e.tags&&e.tags.length?` [${e.tags.join(", ")}]`:"";return`${t+1}. ${e.content}${s}${o?`\n (${o})`:""}`})).join("\n"):`No memory entries matched "${e.query}".`}},aegis_memory_save:{description:"Save a note to the user's AEGIS cloud memory so it persists across machines and future sessions. Use for durable facts, decisions, or preferences the user asks you to remember.",inputSchema:{type:"object",properties:{content:{type:"string",description:"The fact/note to store."},tags:{type:"array",items:{type:"string"},description:"Optional tags."},importance:{type:"integer",description:"Optional 1-10 salience. Default 5.",minimum:1,maximum:10},session:{type:"string",description:"Optional session/label to group under."}},required:["content"],additionalProperties:!1},async run(e){const o={id:t.randomUUID(),content:e.content,role:"assistant",source:"claude-code",session:e.session||"claude-code",tags:e.tags||[],importance:"number"==typeof e.importance?e.importance:5,timestamp:(new Date).toISOString()};return`Saved ${(await t.memorySave(o)).saved||1} memory entry (id ${o.id}).`}},aegis_memory_import:{description:"Import memory and past conversation context from OTHER AI coding tools installed on this machine (Claude Code, Codex, Cursor, Gemini CLI, Continue, Goose, opencode, Windsurf, Zed, and a local AEGIS engine) into the user's AEGIS cloud memory. Scans read-only; nothing in the other tools' directories is modified. Defaults to a DRY RUN that only reports what it found — pass confirm:true to actually save. Entries are content-addressed, so re-running never duplicates.",inputSchema:{type:"object",properties:{confirm:{type:"boolean",description:"false (default) = report only. true = actually write the entries to AEGIS memory."},sources:{type:"array",items:{type:"string"},description:'Optional subset of source ids to import (e.g. ["claude-code"]). Omit for every source found on this machine.'},limit:{type:"integer",description:"Max entries to import (1-5000). Default 1000.",minimum:1,maximum:5e3}},additionalProperties:!1},async run(e){const o=e.limit||1e3,s=foreignMemory.scan({sources:e.sources,limit:o}),r=foreignMemory.describe(s);if(!s.entries.length)return`${r}\n\nNothing to import.`;if(!e.confirm)return[r,"",`Dry run — ${s.totals.entries} entries would be saved to AEGIS memory under ${s.totals.sourcesWithEntries} session(s) (${s.totals.skipped} skipped as too short/noise).`,"Call this tool again with confirm:true to save them."].join("\n");let i=0;const n=[];for(const o of foreignMemory.chunk(s.entries,200))try{const e=await t.memorySaveBatch(o);i+=e&&e.saved||o.length}catch(e){n.push(e.message);break}return n.length?`${r}\n\nSaved ${i} of ${s.totals.entries} entries, then stopped: ${n[0]}`:`${r}\n\nSaved ${i} entries to AEGIS memory. They are searchable now with aegis_memory_search.`}},aegis_memory_list:{description:"List the most recent entries in the user's AEGIS cloud memory. Useful to review what AEGIS already remembers.",inputSchema:{type:"object",properties:{limit:{type:"integer",description:"Max entries (1-50). Default 10.",minimum:1,maximum:50}},additionalProperties:!1},async run(e){const o=(await t.memoryList(e.limit||10)).entries||[];if(!o.length)return"AEGIS cloud memory is empty.";const s=o.map(((e,t)=>`${t+1}. ${e.content}`)).join("\n");return`Recent ${o.length} entries:\n${s}`}}};return{TOOLS:o,toolList:function(){return Object.entries(o).map((([e,t])=>({name:e,description:t.description,inputSchema:t.inputSchema})))}}}module.exports={createTools:createTools};