aegisone 1.0.34 → 1.0.35

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 -976
  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 -383
  14. package/src/probes.js +1 -159
  15. package/src/release.js +1 -409
  16. package/vendor/cli/package.json +3 -7
  17. package/vendor/cli/scripts/check.mjs +1 -52
  18. package/vendor/cli/scripts/demo.mjs +1 -94
  19. package/vendor/cli/scripts/predist.mjs +1 -75
  20. package/vendor/cli/scripts/runtests.mjs +1 -56
  21. package/vendor/cli/scripts/seal-gate.mjs +1 -74
  22. package/vendor/cli/src/agents.js +1 -139
  23. package/vendor/cli/src/app.js +1 -2957
  24. package/vendor/cli/src/art.js +1 -289
  25. package/vendor/cli/src/chatflow.js +1 -3023
  26. package/vendor/cli/src/checkpoint.js +1 -90
  27. package/vendor/cli/src/clipboard.js +1 -424
  28. package/vendor/cli/src/cloudsync.js +1 -528
  29. package/vendor/cli/src/commands.js +1 -4089
  30. package/vendor/cli/src/config.js +1 -581
  31. package/vendor/cli/src/connect.js +1 -349
  32. package/vendor/cli/src/credentials.js +1 -33
  33. package/vendor/cli/src/deps.js +1 -232
  34. package/vendor/cli/src/devrun.js +1 -187
  35. package/vendor/cli/src/diff.js +1 -333
  36. package/vendor/cli/src/diffview.js +1 -296
  37. package/vendor/cli/src/engine.js +1 -297
  38. package/vendor/cli/src/entitlement.js +1 -355
  39. package/vendor/cli/src/events.js +1 -707
  40. package/vendor/cli/src/export.js +1 -67
  41. package/vendor/cli/src/filepreview.js +1 -153
  42. package/vendor/cli/src/fingerprint.js +1 -592
  43. package/vendor/cli/src/format.js +1 -259
  44. package/vendor/cli/src/fuzzy.js +1 -119
  45. package/vendor/cli/src/history.js +1 -423
  46. package/vendor/cli/src/init.js +1 -175
  47. package/vendor/cli/src/input.js +1 -139
  48. package/vendor/cli/src/keys.js +1 -183
  49. package/vendor/cli/src/markdown.js +1 -306
  50. package/vendor/cli/src/models.js +1 -507
  51. package/vendor/cli/src/naming.js +1 -57
  52. package/vendor/cli/src/overlays.js +1 -462
  53. package/vendor/cli/src/panels.js +1 -1418
  54. package/vendor/cli/src/ping.js +1 -226
  55. package/vendor/cli/src/presence.js +1 -238
  56. package/vendor/cli/src/render.js +1 -516
  57. package/vendor/cli/src/screen.js +1 -518
  58. package/vendor/cli/src/screens.js +1 -896
  59. package/vendor/cli/src/secret.js +1 -59
  60. package/vendor/cli/src/securefs.js +1 -359
  61. package/vendor/cli/src/settings.js +1 -155
  62. package/vendor/cli/src/shared.js +1 -52
  63. package/vendor/cli/src/sharedpaths.js +1 -53
  64. package/vendor/cli/src/signup.js +1 -156
  65. package/vendor/cli/src/summarize.js +1 -95
  66. package/vendor/cli/src/sysdiag.js +1 -585
  67. package/vendor/cli/src/system.js +1 -40
  68. package/vendor/cli/src/theme.js +1 -570
  69. package/vendor/cli/src/title.js +1 -220
  70. package/vendor/cli/src/todos.js +1 -115
  71. package/vendor/cli/src/tokens.js +1 -263
  72. package/vendor/cli/src/topup.js +1 -210
  73. package/vendor/cli/src/update.js +1 -191
  74. package/vendor/cli/vendor/client/aegis.js +1 -2441
  75. package/vendor/cli/vendor/client/attest.js +1 -518
  76. package/vendor/cli/vendor/client/authorship-key.js +1 -410
  77. package/vendor/cli/vendor/client/auto-provision.js +1 -134
  78. package/vendor/cli/vendor/client/brain-catalog.js +1 -268
  79. package/vendor/cli/vendor/client/byok-catalog.js +1 -199
  80. package/vendor/cli/vendor/client/catalog-client.js +1 -487
  81. package/vendor/cli/vendor/client/conversation-export.js +1 -177
  82. package/vendor/cli/vendor/client/credentials.js +1 -494
  83. package/vendor/cli/vendor/client/device-fingerprint.js +1 -141
  84. package/vendor/cli/vendor/client/drive-connect.js +1 -110
  85. package/vendor/cli/vendor/client/drive-upload.js +1 -234
  86. package/vendor/cli/vendor/client/env-file.js +1 -1273
  87. package/vendor/cli/vendor/client/fingerprint.js +1 -1064
  88. package/vendor/cli/vendor/client/foreign-memory.js +1 -669
  89. package/vendor/cli/vendor/client/google-signin.js +1 -133
  90. package/vendor/cli/vendor/client/hooks.js +1 -430
  91. package/vendor/cli/vendor/client/model-discovery.js +1 -373
  92. package/vendor/cli/vendor/client/naming.js +1 -283
  93. package/vendor/cli/vendor/client/platform.js +1 -937
  94. package/vendor/cli/vendor/client/prefs.js +1 -351
  95. package/vendor/cli/vendor/client/presence-constants.js +1 -107
  96. package/vendor/cli/vendor/client/presence.js +1 -438
  97. package/vendor/cli/vendor/client/record-vault.js +3 -1055
  98. package/vendor/cli/vendor/client/session-store.js +1 -575
  99. package/vendor/cli/vendor/client/topup.js +1 -297
  100. package/vendor/cli/vendor/client/touch.js +1 -458
  101. package/vendor/cli/vendor/client/update.js +1 -763
  102. package/vendor/cli/vendor/client/user-models.js +1 -381
  103. package/vendor/cli/vendor/desktop/lib/local/agents.js +1 -105
  104. package/vendor/cli/vendor/desktop/lib/local/attachments.js +1 -276
  105. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1045
  106. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -1028
  107. package/vendor/cli/vendor/desktop/lib/local/context.js +1 -125
  108. package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -3666
  109. package/vendor/cli/vendor/desktop/lib/local/entitlement.js +1 -660
  110. package/vendor/cli/vendor/desktop/lib/local/git-scope.js +1 -228
  111. package/vendor/cli/vendor/desktop/lib/local/local.js +1 -2145
  112. package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -280
  113. package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -560
  114. package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +1 -238
  115. package/vendor/cli/vendor/desktop/lib/local/spill.js +1 -75
  116. package/vendor/cli/vendor/desktop/lib/local/turn-guard.js +1 -300
  117. package/vendor/cli/vendor/desktop/lib/local/worktree-lock.js +1 -235
  118. package/vendor/cli/vendor/desktop/lib/settings.js +1 -890
  119. package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1239
  120. package/vendor/cli/vendor/hosts/install.js +1 -638
  121. package/vendor/cli/vendor/hosts/openai-shim.js +1 -515
  122. package/vendor/cli/vendor/hosts/spec.js +1 -164
  123. package/vendor/cli/vendor/hosts/targets.js +1 -346
  124. package/vendor/cli/vendor/mcp/server.js +1 -221
  125. package/vendor/cli/vendor/mcp/tools.js +1 -408
  126. package/vendor/cli/vendor/one/src/child.js +1 -285
  127. package/vendor/cli/vendor/one/src/permissions.js +1 -383
  128. package/vendor/desktop/bin/aegis.js +1 -32
  129. package/vendor/desktop/lib/account-key.js +1 -56
  130. package/vendor/desktop/lib/auto.js +1 -461
  131. package/vendor/desktop/lib/avatar/companion.js +1 -698
  132. package/vendor/desktop/lib/avatar/cosmetics.js +1 -532
  133. package/vendor/desktop/lib/avatar/events.js +1 -344
  134. package/vendor/desktop/lib/avatar/holder-turn.js +1 -350
  135. package/vendor/desktop/lib/avatar/holders.js +1 -612
  136. package/vendor/desktop/lib/avatar/identity.js +1 -641
  137. package/vendor/desktop/lib/avatar/level.js +1 -368
  138. package/vendor/desktop/lib/avatar/mirror.js +1 -524
  139. package/vendor/desktop/lib/avatar/persona.js +1 -388
  140. package/vendor/desktop/lib/avatar/profile.js +1 -977
  141. package/vendor/desktop/lib/avatar/register.js +1 -307
  142. package/vendor/desktop/lib/avatar/store.js +1 -472
  143. package/vendor/desktop/lib/avatar/tiers.js +1 -38
  144. package/vendor/desktop/lib/avatar/transfer.js +1 -415
  145. package/vendor/desktop/lib/avatar/turn.js +1 -216
  146. package/vendor/desktop/lib/avatar/voice.js +1 -328
  147. package/vendor/desktop/lib/avatar/xp.js +1 -404
  148. package/vendor/desktop/lib/deep-link.js +1 -120
  149. package/vendor/desktop/lib/fingerprint.js +2 -347
  150. package/vendor/desktop/lib/google-connect.js +1 -323
  151. package/vendor/desktop/lib/local/agents.js +1 -105
  152. package/vendor/desktop/lib/local/attachments.js +1 -276
  153. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  154. package/vendor/desktop/lib/local/claude-pro.js +1 -1028
  155. package/vendor/desktop/lib/local/context.js +1 -125
  156. package/vendor/desktop/lib/local/engine.js +1 -3666
  157. package/vendor/desktop/lib/local/entitlement.js +1 -660
  158. package/vendor/desktop/lib/local/git-scope.js +1 -228
  159. package/vendor/desktop/lib/local/local.js +1 -2145
  160. package/vendor/desktop/lib/local/prompt.js +1 -280
  161. package/vendor/desktop/lib/local/queue.js +1 -560
  162. package/vendor/desktop/lib/local/session-rounds.js +1 -238
  163. package/vendor/desktop/lib/local/spill.js +1 -75
  164. package/vendor/desktop/lib/local/telemetry.js +1 -470
  165. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  166. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  167. package/vendor/desktop/lib/provider-key-mirror.js +1 -252
  168. package/vendor/desktop/lib/quick-launcher.js +1 -84
  169. package/vendor/desktop/lib/settings.js +1 -890
  170. package/vendor/desktop/lib/sync/memory-queue.js +1 -60
  171. package/vendor/desktop/lib/sync/persist-gate.js +1 -148
  172. package/vendor/desktop/lib/sync/sessions.js +1 -106
  173. package/vendor/desktop/lib/window-state.js +1 -66
  174. package/vendor/desktop/package.json +2 -4
  175. package/vendor/desktop/preload.js +1 -679
  176. package/vendor/desktop/renderer/app.js +1 -7250
  177. package/vendor/desktop/renderer/avatar/assemble.js +1 -335
  178. package/vendor/desktop/renderer/avatar/avatar.js +1 -380
  179. package/vendor/desktop/renderer/avatar/cards.js +1 -141
  180. package/vendor/desktop/renderer/avatar/hud.js +1 -206
  181. package/vendor/desktop/renderer/avatar/machine.js +1 -213
  182. package/vendor/desktop/renderer/avatar/pane.js +1 -439
  183. package/vendor/desktop/renderer/avatar/parts.js +1 -437
  184. package/vendor/desktop/renderer/budget.js +1 -172
  185. package/vendor/desktop/renderer/companion.js +1 -223
  186. package/vendor/desktop/renderer/diff.js +1 -359
  187. package/vendor/desktop/renderer/diffview.js +1 -336
  188. package/vendor/desktop/renderer/filepreview.js +1 -211
  189. package/vendor/desktop/renderer/fingerprint.js +3 -789
  190. package/vendor/desktop/renderer/markdown.js +1 -168
  191. package/vendor/desktop/renderer/provider-mark.js +1 -311
  192. package/vendor/desktop/renderer/provider-toolbar.js +1 -134
  193. package/vendor/desktop/renderer/providers.js +1 -259
  194. package/vendor/desktop/renderer/quick.js +1 -285
  195. package/vendor/desktop/renderer/stream-policy.js +1 -387
  196. package/vendor/desktop/renderer/transcript-view.js +1 -323
  197. package/vendor/desktop/renderer/usage.js +1 -1239
  198. package/vendor/desktop/vendor/aegis.js +1 -2441
  199. package/vendor/desktop/vendor/attest.js +1 -518
  200. package/vendor/desktop/vendor/authorship-key.js +1 -410
  201. package/vendor/desktop/vendor/auto-provision.js +1 -134
  202. package/vendor/desktop/vendor/brain-catalog.js +1 -268
  203. package/vendor/desktop/vendor/byok-catalog.js +1 -199
  204. package/vendor/desktop/vendor/catalog-client.js +1 -487
  205. package/vendor/desktop/vendor/conversation-export.js +1 -177
  206. package/vendor/desktop/vendor/credentials.js +1 -494
  207. package/vendor/desktop/vendor/device-fingerprint.js +1 -141
  208. package/vendor/desktop/vendor/drive-connect.js +1 -110
  209. package/vendor/desktop/vendor/drive-upload.js +1 -234
  210. package/vendor/desktop/vendor/env-file.js +1 -1273
  211. package/vendor/desktop/vendor/fingerprint.js +1 -1064
  212. package/vendor/desktop/vendor/foreign-memory.js +1 -669
  213. package/vendor/desktop/vendor/google-signin.js +1 -133
  214. package/vendor/desktop/vendor/hooks.js +1 -430
  215. package/vendor/desktop/vendor/model-discovery.js +1 -373
  216. package/vendor/desktop/vendor/naming.js +1 -283
  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 -575
  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 -763
  226. package/vendor/desktop/vendor/user-models.js +1 -381
@@ -1,516 +1,2 @@
1
1
  #!/usr/bin/env node
2
- 'use strict';
3
-
4
- /**
5
- * The OpenAI-compatible shim — AEGIS as a *model provider* for every coding
6
- * program that already lets you type a base URL.
7
- *
8
- * There are two different questions a coding tool can ask an account, and AEGIS
9
- * answers them through two different doors:
10
- *
11
- * - "what can this assistant DO?" → MCP. `./install.js` writes the config and
12
- * the tools in `mcp/tools.js` show up in the tool picker. That covers
13
- * Copilot agent mode, Cursor, Windsurf, Cline, Roo, Zed, Continue, Junie.
14
- *
15
- * - "which MODEL writes the code?" → an OpenAI-compatible endpoint. Most
16
- * editors, and nearly every other client, let you point at a custom
17
- * `base_url` for chat. aegis1 speaks a *different* path
18
- * (`/api/v1/chat/completions`, AEGIS key auth, AEGIS body extensions), so
19
- * no client can point at it directly. This file is the translation:
20
- * loopback-only, `/v1/chat/completions` + `/v1/models`, OpenAI SSE out.
21
- *
22
- * It is a thin proxy on purpose. All transport, SSE reassembly, the stalled
23
- * stream watchdog and the reasoning/tool-call accumulation live in
24
- * `client/aegis.js`, which every other host uses — so a provider that works in
25
- * the desktop app cannot behave differently here. This file owns one thing:
26
- * the OpenAI wire format.
27
- *
28
- * Security posture:
29
- * - binds `127.0.0.1` only, and refuses a non-loopback `--host` unless
30
- * `--allow-remote` is passed explicitly (the endpoint spends the account's
31
- * tokens, so exposing it is a decision, not a default);
32
- * - never logs or echoes the AEGIS key;
33
- * - the key is resolved by the ordinary path (env → 0600 store → legacy
34
- * config.json), so the shim holds no credential of its own.
35
- *
36
- * THE SHARED ENV FILE — and why `run()` below reads it before anything else.
37
- *
38
- * `credentials.resolveApiKey()` reads the *environment*, then its own stores;
39
- * it has never opened `~/.aegiscode/.env` (that is `client/env-file.js`'s job,
40
- * deliberately: one reader, one contract). Every other host in this repo calls
41
- * that reader at start-up — `cli/bin/aegiscode.js` before caps and a session,
42
- * `desktop/main.js` before `createClient`, `mcp/server.js` at load. This file
43
- * did not, so it was the one host where the documented setup
44
- *
45
- * AEGIS_API_KEY=aegis_… # in ~/.aegiscode/.env
46
- *
47
- * silently did nothing: the shim started, the editor got a 401 on the first
48
- * message, and the key instruction printed in this file's own `--help` named a
49
- * file the shim never read. In a shell that had also exported the variable the
50
- * bug was invisible, which is exactly how it survived — a GUI-launched editor
51
- * has no such export, and that is the normal way this shim is used.
52
- *
53
- * So `run()` loads the file, then *checks* the key and refuses to serve without
54
- * one, naming where a key can come from. A shim that starts keyless is worse
55
- * than one that exits: the failure surfaces later, in another program's error
56
- * dialog, as an unexplained 401.
57
- */
58
-
59
- const fs = require('node:fs');
60
- const path = require('node:path');
61
- const http = require('node:http');
62
-
63
- const { createClient } = require('../client/aegis.js');
64
- const credentials = require('../client/credentials.js');
65
-
66
- /**
67
- * The pure model-catalog module, which lives with the CLI (`cli/src/models.js`)
68
- * rather than in `client/`. Two layouts have to work, exactly as `deps.js`
69
- * documents, because this file is staged into `cli/vendor/hosts/` at publish
70
- * time and the CLI's own `src/` moves with it:
71
- *
72
- * in-repo <repo>/hosts/openai-shim.js -> <repo>/cli/src/models.js
73
- * npm <pkg>/vendor/hosts/openai-shim.js -> <pkg>/src/models.js
74
- *
75
- * A single hard-coded `../cli/src/models.js` resolves in the repo and to
76
- * `<pkg>/vendor/cli/src/models.js` once installed — a file no layout ever
77
- * creates, so the shim would die at load with MODULE_NOT_FOUND in exactly the
78
- * configuration it exists to serve. Resolution is by existence, so a source
79
- * checkout and an installed package run the same code.
80
- */
81
- function resolveModelsModule() {
82
- const candidates = [
83
- path.join(__dirname, '..', 'cli', 'src', 'models.js'),
84
- path.join(__dirname, '..', '..', 'src', 'models.js'),
85
- ];
86
- for (const candidate of candidates) {
87
- if (fs.existsSync(candidate)) return candidate;
88
- }
89
- throw new Error(
90
- 'aegis-shim: cannot find models.js. Expected cli/src/models.js beside hosts/ ' +
91
- `(source checkout) or src/models.js in the package root (installed). Looked in: ${candidates.join(', ')}`
92
- );
93
- }
94
-
95
- const { normalizeModelCatalog, pickerEntries } = require(resolveModelsModule());
96
-
97
- const DEFAULT_PORT = 8787;
98
- const DEFAULT_HOST = '127.0.0.1';
99
- const LOOPBACK = new Set(['127.0.0.1', '::1', 'localhost']);
100
-
101
- /**
102
- * Refuse to bind anything but loopback unless the operator asked for it.
103
- *
104
- * Hoisted out of `createShimServer` because `main()` must apply it *first*:
105
- * it is an argument refusal, and a keyless shim still cannot leak anything
106
- * while a public one can. See the call site in `main()` for the ordering bug
107
- * this caused when it lived only inside the server factory.
108
- */
109
- function assertBindAllowed(host, allowRemote) {
110
- if (!LOOPBACK.has(host) && !allowRemote) {
111
- throw new Error(
112
- `refusing to bind ${host}: the shim spends your account's tokens, so it is loopback-only ` +
113
- 'unless you pass --allow-remote'
114
- );
115
- }
116
- }
117
-
118
- /** OpenAI's schema wants `owned_by` and a created timestamp; neither means
119
- * anything for a pooled provider, so both are stable constants. */
120
- const EPOCH = 1735689600; // 2025-01-01T00:00:00Z
121
-
122
- function logLine(stream, msg) {
123
- stream.write(`aegis-shim: ${msg}\n`);
124
- }
125
-
126
- // ---------------------------------------------------------------------------
127
- // Body translation
128
- // ---------------------------------------------------------------------------
129
-
130
- /**
131
- * Fields the pooled endpoint understands and a caller may legitimately send.
132
- * Anything else is dropped rather than forwarded: aegis1 validates its body,
133
- * and passing an unknown key through turns a working client into a 400.
134
- */
135
- function extraFromBody(body) {
136
- const extra = {};
137
- for (const key of ['tools', 'tool_choice', 'temperature', 'top_p', 'stop', 'presence_penalty', 'frequency_penalty']) {
138
- if (body[key] !== undefined) extra[key] = body[key];
139
- }
140
- // `reasoning_effort` is OpenAI's spelling of the AEGIS effort rung; a client
141
- // that offers the knob should get the behaviour it names, not a silent no-op.
142
- const eff = body.reasoning_effort || body.effort;
143
- if (typeof eff === 'string' && ['low', 'medium', 'high'].includes(eff.toLowerCase())) {
144
- extra.effort = eff.toLowerCase();
145
- }
146
- if (body.workers !== undefined) extra.workers = body.workers;
147
- return extra;
148
- }
149
-
150
- function sseHead(res) {
151
- res.writeHead(200, {
152
- 'Content-Type': 'text/event-stream; charset=utf-8',
153
- 'Cache-Control': 'no-cache, no-transform',
154
- Connection: 'keep-alive',
155
- 'X-Accel-Buffering': 'no',
156
- });
157
- }
158
-
159
- function sseSend(res, payload) {
160
- res.write(`data: ${JSON.stringify(payload)}\n\n`);
161
- }
162
-
163
- function chunkFrame(id, model, delta, finishReason) {
164
- return {
165
- id,
166
- object: 'chat.completion.chunk',
167
- created: Math.floor(Date.now() / 1000),
168
- model: model || 'aegis',
169
- choices: [{ index: 0, delta, finish_reason: finishReason || null }],
170
- };
171
- }
172
-
173
- // ---------------------------------------------------------------------------
174
- // Server
175
- // ---------------------------------------------------------------------------
176
-
177
- /**
178
- * @param {object} opts
179
- * @param {object} [opts.client] Injected transport (tests pass a stub).
180
- * @param {number} [opts.port]
181
- * @param {string} [opts.host]
182
- * @param {boolean} [opts.allowRemote]
183
- * @param {boolean} [opts.requireKey] Reject callers that send no bearer token.
184
- * @param {NodeJS.WriteStream} [opts.log]
185
- * @param {Function} [opts.fetchModels] Override catalog fetch (tests).
186
- */
187
- function createShimServer(opts = {}) {
188
- const client = opts.client || createClient(credentials.clientOptions());
189
- const host = opts.host || DEFAULT_HOST;
190
- const port = opts.port === undefined ? DEFAULT_PORT : opts.port;
191
- const out = opts.log || process.stderr;
192
- const requireKey = opts.requireKey !== false;
193
- const fetchModels = opts.fetchModels || (() => client.listModels());
194
-
195
- assertBindAllowed(host, opts.allowRemote);
196
-
197
- // The catalog is cached for a minute: a model picker calls /v1/models on
198
- // every focus, and hitting aegiscloud.org each time is a visible stall in the
199
- // one UI where latency is most obvious.
200
- let catalog = { at: 0, models: [] };
201
- const CATALOG_MS = 60_000;
202
-
203
- async function models() {
204
- if (Date.now() - catalog.at < CATALOG_MS && catalog.models.length) return catalog.models;
205
- const raw = await fetchModels();
206
- catalog = { at: Date.now(), models: pickerEntries(normalizeModelCatalog(raw && raw.models ? raw.models : raw)) };
207
- return catalog.models;
208
- }
209
-
210
- function sendJson(res, status, payload) {
211
- const text = JSON.stringify(payload);
212
- res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': Buffer.byteLength(text) });
213
- res.end(text);
214
- }
215
-
216
- function oaiError(res, status, message, type) {
217
- sendJson(res, status, { error: { message, type: type || 'aegis_error', code: status } });
218
- }
219
-
220
- function authorized(req) {
221
- if (!requireKey) return true;
222
- const header = req.headers.authorization || '';
223
- const m = /^Bearer\s+(.+)$/i.exec(header);
224
- return Boolean(m && m[1].trim());
225
- }
226
-
227
- async function readBody(req) {
228
- const chunks = [];
229
- let size = 0;
230
- for await (const c of req) {
231
- size += c.length;
232
- if (size > 8 * 1024 * 1024) throw new Error('request body too large');
233
- chunks.push(c);
234
- }
235
- const text = Buffer.concat(chunks).toString('utf8');
236
- if (!text.trim()) return {};
237
- return JSON.parse(text);
238
- }
239
-
240
- async function handleModels(res) {
241
- const list = await models();
242
- sendJson(res, 200, {
243
- object: 'list',
244
- data: list.map((m) => ({
245
- id: m.id,
246
- object: 'model',
247
- created: EPOCH,
248
- owned_by: 'aegis',
249
- // Non-standard, harmless, and the reason the picker in Cline/Continue
250
- // does not show five identical rows.
251
- ...(m.label && m.label !== m.id ? { name: m.label } : {}),
252
- })),
253
- });
254
- }
255
-
256
- async function handleChat(req, res) {
257
- let body;
258
- try {
259
- body = await readBody(req);
260
- } catch (err) {
261
- return oaiError(res, 400, `invalid JSON body: ${err.message}`, 'invalid_request_error');
262
- }
263
-
264
- const messages = Array.isArray(body.messages) ? body.messages : null;
265
- if (!messages || !messages.length) {
266
- return oaiError(res, 400, '`messages` is required', 'invalid_request_error');
267
- }
268
-
269
- const stream = body.stream === true;
270
- const id = `chatcmpl-aegis-${Date.now().toString(36)}`;
271
- const model = body.model && body.model !== 'aegis-default' ? String(body.model) : undefined;
272
-
273
- const args = {
274
- messages,
275
- model,
276
- maxTokens: body.max_tokens || body.max_completion_tokens,
277
- extra: extraFromBody(body),
278
- includeUsage: stream,
279
- };
280
-
281
- if (!stream) {
282
- try {
283
- const r = await client.chatCompletion({ ...args, stream: false });
284
- const msg = (r.choices && r.choices[0] && r.choices[0].message) || { content: '' };
285
- return sendJson(res, 200, {
286
- id,
287
- object: 'chat.completion',
288
- created: Math.floor(Date.now() / 1000),
289
- model: r.model || model || 'aegis',
290
- choices: [{ index: 0, message: { role: 'assistant', ...msg }, finish_reason: msg.tool_calls ? 'tool_calls' : 'stop' }],
291
- usage: r.usage || undefined,
292
- });
293
- } catch (err) {
294
- return oaiError(res, err.status && err.status >= 400 && err.status < 600 ? err.status : 502, err.message);
295
- }
296
- }
297
-
298
- sseHead(res);
299
- let closed = false;
300
- req.on('close', () => { closed = true; });
301
- const write = (payload) => { if (!closed) sseSend(res, payload); };
302
-
303
- // First frame carries the role, exactly as OpenAI does — some clients
304
- // (Continue among them) key their stream parser off it.
305
- write(chunkFrame(id, model, { role: 'assistant', content: '' }));
306
-
307
- try {
308
- const r = await client.chatCompletion({
309
- ...args,
310
- stream: true,
311
- onStream: (ev) => {
312
- if (ev.delta) write(chunkFrame(id, model, { content: ev.delta }));
313
- else if (ev.reasoning) write(chunkFrame(id, model, { reasoning_content: ev.reasoning }));
314
- },
315
- onReasoning: (chunk) => write(chunkFrame(id, model, { reasoning_content: chunk })),
316
- });
317
-
318
- const msg = (r.choices && r.choices[0] && r.choices[0].message) || {};
319
- // Tool calls are accumulated inside the transport, not streamed
320
- // fragment-by-fragment, so they arrive as one final frame. That is a
321
- // legal OpenAI chunk (id + index + name + full arguments), and it is the
322
- // only shape the shared transport can prove is complete.
323
- if (Array.isArray(msg.tool_calls) && msg.tool_calls.length) {
324
- write(chunkFrame(id, model, {
325
- tool_calls: msg.tool_calls.map((tc, i) => ({
326
- index: i,
327
- id: tc.id,
328
- type: 'function',
329
- function: { name: tc.function && tc.function.name, arguments: (tc.function && tc.function.arguments) || '' },
330
- })),
331
- }));
332
- }
333
- write(chunkFrame(id, model, {}, msg.tool_calls && msg.tool_calls.length ? 'tool_calls' : 'stop'));
334
- if (r.usage) {
335
- write({ id, object: 'chat.completion.chunk', created: Math.floor(Date.now() / 1000), model: r.model || model || 'aegis', choices: [], usage: r.usage });
336
- }
337
- if (!closed) { res.write('data: [DONE]\n\n'); res.end(); }
338
- } catch (err) {
339
- // Headers are already sent, so the error travels as a terminal SSE frame
340
- // plus a marker the client can surface — an editor that shows a bare
341
- // stalled stream teaches the user nothing.
342
- write({ error: { message: err.message, type: 'aegis_error' } });
343
- if (!closed) { res.write('data: [DONE]\n\n'); res.end(); }
344
- }
345
- }
346
-
347
- const server = http.createServer((req, res) => {
348
- const url = new URL(req.url || '/', `http://${req.headers.host || '127.0.0.1'}`);
349
- const path = url.pathname.replace(/\/+$/, '') || '/';
350
-
351
- if (req.method === 'GET' && (path === '/health' || path === '/')) {
352
- return sendJson(res, 200, { ok: true, service: 'aegis-openai-shim', endpoint: `http://${host}:${port}/v1` });
353
- }
354
- // `/v1` is the OpenAI convention; Cursor and a few others probe `/models`
355
- // without the prefix, and refusing that reads as "the endpoint is wrong".
356
- if (req.method === 'GET' && (path === '/v1/models' || path === '/models')) {
357
- if (!authorized(req)) return oaiError(res, 401, 'missing API key — any non-empty value works locally', 'invalid_request_error');
358
- return handleModels(res).catch((err) => oaiError(res, 502, err.message));
359
- }
360
- if (req.method === 'POST' && (path === '/v1/chat/completions' || path === '/chat/completions')) {
361
- if (!authorized(req)) return oaiError(res, 401, 'missing API key — any non-empty value works locally', 'invalid_request_error');
362
- return handleChat(req, res);
363
- }
364
- // Anthropic-shaped probes from editors that auto-detect the provider.
365
- if (req.method === 'POST' && path === '/v1/messages') {
366
- return oaiError(res, 404, 'this endpoint speaks the OpenAI schema; point the client at /v1 with the OpenAI provider', 'invalid_request_error');
367
- }
368
- return oaiError(res, 404, `no such route: ${req.method} ${path}`, 'invalid_request_error');
369
- });
370
-
371
- server.listen = ((orig) => function listen(...a) {
372
- return orig.apply(server, a);
373
- })(server.listen);
374
-
375
- return {
376
- server,
377
- host,
378
- port,
379
- url: `http://${host}:${port}/v1`,
380
- listen() {
381
- return new Promise((resolve, reject) => {
382
- server.once('error', reject);
383
- server.listen(port, host, () => {
384
- const actual = server.address();
385
- logLine(out, `OpenAI-compatible endpoint on http://${host}:${actual.port}/v1`);
386
- logLine(out, `point any OpenAI-compatible client at that base URL (any API key value)`);
387
- resolve(actual);
388
- });
389
- });
390
- },
391
- close() {
392
- return new Promise((resolve) => server.close(resolve));
393
- },
394
- };
395
- }
396
-
397
- // ---------------------------------------------------------------------------
398
- // CLI
399
- // ---------------------------------------------------------------------------
400
-
401
- function parseArgv(argv) {
402
- const opts = { log: process.stderr };
403
- for (let i = 0; i < argv.length; i++) {
404
- const a = argv[i];
405
- if (a === '--port') opts.port = Number(argv[++i]);
406
- else if (a === '--host') opts.host = argv[++i];
407
- else if (a === '--allow-remote') opts.allowRemote = true;
408
- else if (a === '--no-auth') opts.requireKey = false;
409
- else if (a === '--help' || a === '-h') opts.help = true;
410
- }
411
- return opts;
412
- }
413
-
414
- async function main(argv) {
415
- const opts = parseArgv(argv);
416
- if (opts.help) {
417
- process.stdout.write([
418
- 'aegis openai shim — serve AEGIS as an OpenAI-compatible endpoint',
419
- '',
420
- ' node hosts/openai-shim.js [--port 8787] [--host 127.0.0.1] [--allow-remote] [--no-auth]',
421
- '',
422
- 'Then point a coding tool at it:',
423
- ' base URL http://127.0.0.1:8787/v1',
424
- ' API key anything non-empty (the AEGIS key is read from ~/.aegiscode/.env)',
425
- '',
426
- ].join('\n'));
427
- return 0;
428
- }
429
-
430
- const out = opts.log || process.stderr;
431
-
432
- // ── argument refusal, before the credential precondition ─────────────────
433
- //
434
- // The loopback guard runs FIRST. It is an argument refusal — the operator
435
- // asked for something the shim does not do — and every CLI convention
436
- // validates arguments before resolving credentials. Ordering it the other
437
- // way cost a real regression: `--host 0.0.0.0` without a key answered with
438
- // the no-key line, so the one invocation that would expose the account to
439
- // the network never printed the sentence that explains why it will not.
440
- try {
441
- assertBindAllowed(opts.host || DEFAULT_HOST, opts.allowRemote);
442
- } catch (err) {
443
- logLine(out, err.message);
444
- return 1;
445
- }
446
-
447
- // ── the shared env file, before any credential is resolved ───────────────
448
- //
449
- // Placed after the `--help` early-return so help stays instant, and before
450
- // `createShimServer` — which is where `createClient(credentials.clientOptions())`
451
- // runs and therefore the last point at which process.env can still decide the
452
- // key. An exported `AEGIS_API_KEY` always wins: loadEnvFile() fills only names
453
- // the environment does not already have. Failure is never fatal here — an
454
- // absent file is the pre-existing state — because the check right below turns
455
- // "no key at all" into one sentence instead of a 401 from another program.
456
- // Same call, same contract as cli/bin/aegiscode.js, desktop/main.js and
457
- // mcp/server.js; see this file's header for what its absence cost.
458
- try {
459
- const envFile = require('../client/env-file.js');
460
- const envResult = envFile.loadEnvFile();
461
- if (envResult.loose) {
462
- logLine(
463
- out,
464
- `${envResult.file} is readable by other accounts (mode ${envResult.mode.toString(8)}) — ` +
465
- 'consider `chmod 600` on it'
466
- );
467
- }
468
- } catch (e) {
469
- logLine(out, `could not read the shared env file: ${e && e.message}`);
470
- }
471
-
472
- // Refuse to serve with no account key. The shim cannot answer a single
473
- // request without one, and a keyless endpoint reports that failure to the
474
- // *editor*, hours later, as an opaque 401 — the exact confusion this check
475
- // removes. `--no-auth` is about the caller's bearer token, not this
476
- // credential, so it does not relax this.
477
- const resolved = credentials.resolveApiKey();
478
- if (!resolved.key) {
479
- logLine(
480
- out,
481
- `no AEGIS account key — ${credentials.HOW_TO_SET}, ` +
482
- `or set ${credentials.KEY_ENV} in ~/.aegiscode/.env`
483
- );
484
- return 1;
485
- }
486
- // Where the key came from, never the key itself: "did it pick up my .env or
487
- // the file an older sign-in wrote?" is the question a user actually has, and
488
- // it is unanswerable from a masked key alone.
489
- logLine(out, `AEGIS key: ${credentials.sourceLabel(resolved.source)}`);
490
-
491
- let shim;
492
- try {
493
- shim = createShimServer(opts);
494
- await shim.listen();
495
- } catch (err) {
496
- logLine(process.stderr, err.message);
497
- return 1;
498
- }
499
- const stop = async () => { await shim.close(); process.exit(0); };
500
- process.on('SIGINT', stop);
501
- process.on('SIGTERM', stop);
502
- return null; // runs until signalled
503
- }
504
-
505
- if (require.main === module) {
506
- main(process.argv.slice(2))
507
- .then((code) => {
508
- if (typeof code === 'number') process.exit(code);
509
- })
510
- .catch((err) => {
511
- logLine(process.stderr, err && err.message ? err.message : err);
512
- process.exit(1);
513
- });
514
- }
515
-
516
- module.exports = { createShimServer, extraFromBody, DEFAULT_PORT };
2
+ "use strict";const fs=require("node:fs"),path=require("node:path"),http=require("node:http"),{createClient:createClient}=require("../client/aegis.js"),credentials=require("../client/credentials.js");function resolveModelsModule(){const e=[path.join(__dirname,"..","cli","src","models.js"),path.join(__dirname,"..","..","src","models.js")];for(const t of e)if(fs.existsSync(t))return t;throw new Error(`aegis-shim: cannot find models.js. Expected cli/src/models.js beside hosts/ (source checkout) or src/models.js in the package root (installed). Looked in: ${e.join(", ")}`)}const{normalizeModelCatalog:normalizeModelCatalog,pickerEntries:pickerEntries}=require(resolveModelsModule()),DEFAULT_PORT=8787,DEFAULT_HOST="127.0.0.1",LOOPBACK=new Set(["127.0.0.1","::1","localhost"]);function assertBindAllowed(e,t){if(!LOOPBACK.has(e)&&!t)throw new Error(`refusing to bind ${e}: the shim spends your account's tokens, so it is loopback-only unless you pass --allow-remote`)}const EPOCH=1735689600;function logLine(e,t){e.write(`aegis-shim: ${t}\n`)}function extraFromBody(e){const t={};for(const o of["tools","tool_choice","temperature","top_p","stop","presence_penalty","frequency_penalty"])void 0!==e[o]&&(t[o]=e[o]);const o=e.reasoning_effort||e.effort;return"string"==typeof o&&["low","medium","high"].includes(o.toLowerCase())&&(t.effort=o.toLowerCase()),void 0!==e.workers&&(t.workers=e.workers),t}function sseHead(e){e.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"})}function sseSend(e,t){e.write(`data: ${JSON.stringify(t)}\n\n`)}function chunkFrame(e,t,o,n){return{id:e,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:t||"aegis",choices:[{index:0,delta:o,finish_reason:n||null}]}}function createShimServer(e={}){const t=e.client||createClient(credentials.clientOptions()),o=e.host||DEFAULT_HOST,n=void 0===e.port?DEFAULT_PORT:e.port,s=e.log||process.stderr,r=!1!==e.requireKey,a=e.fetchModels||(()=>t.listModels());assertBindAllowed(o,e.allowRemote);let i={at:0,models:[]};function c(e,t,o){const n=JSON.stringify(o);e.writeHead(t,{"Content-Type":"application/json; charset=utf-8","Content-Length":Buffer.byteLength(n)}),e.end(n)}function l(e,t,o,n){c(e,t,{error:{message:o,type:n||"aegis_error",code:t}})}function d(e){if(!r)return!0;const t=e.headers.authorization||"",o=/^Bearer\s+(.+)$/i.exec(t);return Boolean(o&&o[1].trim())}const m=http.createServer(((e,s)=>{const r=new URL(e.url||"/",`http://${e.headers.host||"127.0.0.1"}`).pathname.replace(/\/+$/,"")||"/";return"GET"!==e.method||"/health"!==r&&"/"!==r?"GET"!==e.method||"/v1/models"!==r&&"/models"!==r?"POST"!==e.method||"/v1/chat/completions"!==r&&"/chat/completions"!==r?"POST"===e.method&&"/v1/messages"===r?l(s,404,"this endpoint speaks the OpenAI schema; point the client at /v1 with the OpenAI provider","invalid_request_error"):l(s,404,`no such route: ${e.method} ${r}`,"invalid_request_error"):d(e)?async function(e,o){let n;try{n=await async function(e){const t=[];let o=0;for await(const n of e){if(o+=n.length,o>8388608)throw new Error("request body too large");t.push(n)}const n=Buffer.concat(t).toString("utf8");return n.trim()?JSON.parse(n):{}}(e)}catch(e){return l(o,400,`invalid JSON body: ${e.message}`,"invalid_request_error")}const s=Array.isArray(n.messages)?n.messages:null;if(!s||!s.length)return l(o,400,"`messages` is required","invalid_request_error");const r=!0===n.stream,a=`chatcmpl-aegis-${Date.now().toString(36)}`,i=n.model&&"aegis-default"!==n.model?String(n.model):void 0,d={messages:s,model:i,maxTokens:n.max_tokens||n.max_completion_tokens,extra:extraFromBody(n),includeUsage:r};if(!r)try{const e=await t.chatCompletion({...d,stream:!1}),n=e.choices&&e.choices[0]&&e.choices[0].message||{content:""};return c(o,200,{id:a,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:e.model||i||"aegis",choices:[{index:0,message:{role:"assistant",...n},finish_reason:n.tool_calls?"tool_calls":"stop"}],usage:e.usage||void 0})}catch(e){return l(o,e.status&&e.status>=400&&e.status<600?e.status:502,e.message)}sseHead(o);let m=!1;e.on("close",(()=>{m=!0}));const u=e=>{m||sseSend(o,e)};u(chunkFrame(a,i,{role:"assistant",content:""}));try{const e=await t.chatCompletion({...d,stream:!0,onStream:e=>{e.delta?u(chunkFrame(a,i,{content:e.delta})):e.reasoning&&u(chunkFrame(a,i,{reasoning_content:e.reasoning}))},onReasoning:e=>u(chunkFrame(a,i,{reasoning_content:e}))}),n=e.choices&&e.choices[0]&&e.choices[0].message||{};Array.isArray(n.tool_calls)&&n.tool_calls.length&&u(chunkFrame(a,i,{tool_calls:n.tool_calls.map(((e,t)=>({index:t,id:e.id,type:"function",function:{name:e.function&&e.function.name,arguments:e.function&&e.function.arguments||""}})))})),u(chunkFrame(a,i,{},n.tool_calls&&n.tool_calls.length?"tool_calls":"stop")),e.usage&&u({id:a,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.model||i||"aegis",choices:[],usage:e.usage}),m||(o.write("data: [DONE]\n\n"),o.end())}catch(e){u({error:{message:e.message,type:"aegis_error"}}),m||(o.write("data: [DONE]\n\n"),o.end())}}(e,s):l(s,401,"missing API key — any non-empty value works locally","invalid_request_error"):d(e)?async function(e){c(e,200,{object:"list",data:(await async function(){if(Date.now()-i.at<6e4&&i.models.length)return i.models;const e=await a();return i={at:Date.now(),models:pickerEntries(normalizeModelCatalog(e&&e.models?e.models:e))},i.models}()).map((e=>({id:e.id,object:"model",created:EPOCH,owned_by:"aegis",...e.label&&e.label!==e.id?{name:e.label}:{}})))})}(s).catch((e=>l(s,502,e.message))):l(s,401,"missing API key — any non-empty value works locally","invalid_request_error"):c(s,200,{ok:!0,service:"aegis-openai-shim",endpoint:`http://${o}:${n}/v1`})}));var u;return m.listen=(u=m.listen,function(...e){return u.apply(m,e)}),{server:m,host:o,port:n,url:`http://${o}:${n}/v1`,listen:()=>new Promise(((e,t)=>{m.once("error",t),m.listen(n,o,(()=>{const t=m.address();logLine(s,`OpenAI-compatible endpoint on http://${o}:${t.port}/v1`),logLine(s,"point any OpenAI-compatible client at that base URL (any API key value)"),e(t)}))})),close:()=>new Promise((e=>m.close(e)))}}function parseArgv(e){const t={log:process.stderr};for(let o=0;o<e.length;o++){const n=e[o];"--port"===n?t.port=Number(e[++o]):"--host"===n?t.host=e[++o]:"--allow-remote"===n?t.allowRemote=!0:"--no-auth"===n?t.requireKey=!1:"--help"!==n&&"-h"!==n||(t.help=!0)}return t}async function main(e){const t=parseArgv(e);if(t.help)return process.stdout.write(["aegis openai shim — serve AEGIS as an OpenAI-compatible endpoint",""," node hosts/openai-shim.js [--port 8787] [--host 127.0.0.1] [--allow-remote] [--no-auth]","","Then point a coding tool at it:"," base URL http://127.0.0.1:8787/v1"," API key anything non-empty (the AEGIS key is read from ~/.aegiscode/.env)",""].join("\n")),0;const o=t.log||process.stderr;try{assertBindAllowed(t.host||DEFAULT_HOST,t.allowRemote)}catch(e){return logLine(o,e.message),1}try{const e=require("../client/env-file.js").loadEnvFile();e.loose&&logLine(o,`${e.file} is readable by other accounts (mode ${e.mode.toString(8)}) — consider \`chmod 600\` on it`)}catch(e){logLine(o,`could not read the shared env file: ${e&&e.message}`)}const n=credentials.resolveApiKey();if(!n.key)return logLine(o,`no AEGIS account key — ${credentials.HOW_TO_SET}, or set ${credentials.KEY_ENV} in ~/.aegiscode/.env`),1;let s;logLine(o,`AEGIS key: ${credentials.sourceLabel(n.source)}`);try{s=createShimServer(t),await s.listen()}catch(e){return logLine(process.stderr,e.message),1}const r=async()=>{await s.close(),process.exit(0)};return process.on("SIGINT",r),process.on("SIGTERM",r),null}require.main===module&&main(process.argv.slice(2)).then((e=>{"number"==typeof e&&process.exit(e)})).catch((e=>{logLine(process.stderr,e&&e.message?e.message:e),process.exit(1)})),module.exports={createShimServer:createShimServer,extraFromBody:extraFromBody,DEFAULT_PORT:DEFAULT_PORT};