aegisone 1.0.21 → 1.0.23

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 -2
  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 -2
  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 -3008
  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 -3987
  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 -2054
  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 -85
  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 -125
  95. package/vendor/cli/vendor/client/hooks.js +1 -430
  96. package/vendor/cli/vendor/client/model-discovery.js +1 -330
  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 -3228
  112. package/vendor/cli/vendor/desktop/lib/local/entitlement.js +1 -654
  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 -169
  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 -3228
  160. package/vendor/desktop/lib/local/entitlement.js +1 -654
  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 -4390
  179. package/vendor/desktop/package.json +3 -5
  180. package/vendor/desktop/preload.js +1 -628
  181. package/vendor/desktop/renderer/app.js +1 -6560
  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 -720
  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 -2054
  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 -85
  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 -125
  215. package/vendor/desktop/vendor/hooks.js +1 -430
  216. package/vendor/desktop/vendor/model-discovery.js +1 -330
  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,298 +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
- * The edit block's paint layer: a one-line summary row plus, when the block is
10
- * open, the diff itself in Monokai Extended colors.
11
- *
12
- * Two shapes, driven by one boolean (`open`):
13
- *
14
- * collapsed ● editFile
15
- * ⎿ Update(src/diff.js) +12 -3 · click to view diff
16
- *
17
- * open ● editFile
18
- * ⎿ Update(src/diff.js) +12 -3 · click to collapse
19
- * 12 const a = 1;
20
- * 13 - const b = 2;
21
- * 13 + const b = 3;
22
- *
23
- * Small diffs open themselves (AUTO_OPEN_ROWS) so the common one-line edit is
24
- * readable with no gesture at all — and that is not a nicety on this host: the
25
- * CLI writes finished turns once to scrollback (screen.js's design note), so
26
- * an edit the user has to ask for twice is an edit they will not read. Anything
27
- * bigger starts collapsed so a 300-line rewrite cannot bury the transcript.
28
- *
29
- * Width safety is a hard requirement here, not a preference: `cli-render.test.mjs`
30
- * pins that no emitted row exceeds the terminal width, because one row that
31
- * wraps corrupts the cursor arithmetic of every row after it. Every row this
32
- * module returns is therefore built from `clip()`-measured plain text and
33
- * closed with RESET, so an add/del background can never bleed into the next
34
- * line of scrollback.
35
- */
36
-
37
- const { DIM, RESET, GLYPH, themeOf, diffOf } = require('./theme.js');
38
- const { w, clip } = require('./screen.js');
39
-
40
- /** Diff body rows at or below this size open without a gesture. */
41
- const AUTO_OPEN_ROWS = 30;
42
- /** Rows painted inside one open block before the "… more diff lines" footer. */
43
- const MAX_BLOCK_ROWS = 200;
44
-
45
- /** " ⎿ " is five cells, so block rows indent under the summary's text. */
46
- const INDENT = ' ';
47
-
48
- const KEYWORDS = new Set([
49
- 'const', 'let', 'var', 'function', 'return', 'if', 'else', 'for', 'while', 'do', 'switch',
50
- 'case', 'break', 'continue', 'import', 'export', 'from', 'default', 'class', 'extends',
51
- 'new', 'try', 'catch', 'finally', 'throw', 'async', 'await', 'yield', 'static', 'typeof',
52
- 'instanceof', 'in', 'of', 'delete', 'this', 'super', 'null', 'undefined', 'true', 'false',
53
- 'def', 'elif', 'lambda', 'pass', 'raise', 'with', 'as', 'not', 'and', 'or', 'is', 'None',
54
- 'True', 'False', 'self', 'fn', 'mut', 'pub', 'impl', 'struct', 'enum', 'trait', 'match',
55
- 'package', 'func', 'defer', 'chan', 'nil', 'echo', 'local', 'then', 'fi', 'esac',
56
- ]);
57
-
58
- /**
59
- * Split one line of code into colored tokens. Deliberately line-local and cheap
60
- * — it runs on every changed row of every block — so it colors comments,
61
- * strings, numbers, keywords and called functions and leaves the rest plain,
62
- * which is all the tinted diff rows need to read as code.
63
- *
64
- * @param {string} text
65
- * @param {object} [d] Diff palette (defaults to the dark one).
66
- * @returns {Array<{t: string, c: string}>} tokens; `c` is a foreground color.
67
- */
68
- function highlightLine(text, d) {
69
- const D = d || diffOf(null);
70
- const out = [];
71
- const src = String(text == null ? '' : text);
72
- const re = /(\/\/[^\n]*|#[^\n]*|\/\*[\s\S]*?\*\/)|('(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"|`(?:\\.|[^`\\])*`)|(0[xX][0-9a-fA-F]+|\d+(?:\.\d+)?)|([A-Za-z_$][A-Za-z0-9_$]*)/g;
73
- const push = (t, c) => { if (t) out.push({ t, c }); };
74
- let last = 0;
75
- let m;
76
- while ((m = re.exec(src))) {
77
- if (m.index > last) push(src.slice(last, m.index), D.codeFg);
78
- if (m[1]) push(m[1], D.comment);
79
- else if (m[2]) push(m[2], D.str);
80
- else if (m[3]) push(m[3], D.num);
81
- else {
82
- const word = m[4];
83
- const isCall = /^\s*\(/.test(src.slice(m.index + word.length));
84
- push(word, KEYWORDS.has(word) ? D.kw : isCall ? D.fn : D.codeFg);
85
- }
86
- last = m.index + m[0].length;
87
- }
88
- if (last < src.length) push(src.slice(last), D.codeFg);
89
- return out;
90
- }
91
-
92
- /**
93
- * Pair a run of removed rows with the added run that follows it and mark the
94
- * slice that actually differs, so the changed word renders in the bright
95
- * variant of the diff color. Equal run lengths only, and only when the shared
96
- * prefix+suffix dominates the line — otherwise the mark would land on
97
- * unrelated text. Mutates rows in place, adding `hi = {start, end}` in
98
- * code-point offsets.
99
- */
100
- function markIntraLine(rows) {
101
- for (let i = 0; i < rows.length; i++) {
102
- if (rows[i].sign !== '-') continue;
103
- let d = i;
104
- while (d < rows.length && rows[d].sign === '-') d++;
105
- let a = d;
106
- while (a < rows.length && rows[a].sign === '+') a++;
107
- const delCount = d - i;
108
- const addCount = a - d;
109
- if (delCount && delCount === addCount) {
110
- for (let k = 0; k < delCount; k++) {
111
- const pair = intraLine(rows[i + k].text, rows[d + k].text);
112
- if (!pair) continue;
113
- rows[i + k].hi = { start: pair.delStart, end: pair.delEnd, side: 'del' };
114
- rows[d + k].hi = { start: pair.addStart, end: pair.addEnd, side: 'add' };
115
- }
116
- }
117
- i = a - 1;
118
- }
119
- return rows;
120
- }
121
-
122
- function intraLine(delText, addText) {
123
- const d = [...String(delText == null ? '' : delText)];
124
- const a = [...String(addText == null ? '' : addText)];
125
- let pre = 0;
126
- while (pre < d.length && pre < a.length && d[pre] === a[pre]) pre++;
127
- let post = 0;
128
- while (post < d.length - pre && post < a.length - pre && d[d.length - 1 - post] === a[a.length - 1 - post]) post++;
129
- const shared = pre + post;
130
- const longest = Math.max(d.length, a.length) || 1;
131
- if (shared < longest * 0.4) return null;
132
- return {
133
- delStart: pre,
134
- delEnd: d.length - post,
135
- addStart: pre,
136
- addEnd: a.length - post,
137
- };
138
- }
139
-
140
- /**
141
- * Should this preview start open? Small diffs (the routine edit) do, so the
142
- * change is readable immediately; a big one stays a one-line summary.
143
- */
144
- function defaultOpen(preview) {
145
- if (!preview || !preview.rows) return false;
146
- return preview.rows.length <= AUTO_OPEN_ROWS;
147
- }
148
-
149
- /**
150
- * The summary row: ` ⎿ Update(src/diff.js) +12 -3 · click to view diff`.
151
- *
152
- * @param {object} preview From diff.js's editPreview().
153
- * @param {object} ctx App context (selects the light/dark diff palette).
154
- * @param {{open?: boolean}} [opts] Whether the block is expanded — flips the
155
- * hint to "click to collapse", the way the click gesture will read next.
156
- */
157
- function diffSummaryRow(preview, ctx, opts = {}) {
158
- const t = themeOf(ctx);
159
- const D = diffOf(ctx);
160
- const bits = [` ${t.gray}${GLYPH.hook} ${RESET}`];
161
- bits.push(`${t.lavender}${preview.kind}(${preview.short})${RESET}`);
162
- if (preview.adds) bits.push(`${D.addFg} +${preview.adds}${RESET}`);
163
- if (preview.dels) bits.push(`${D.delFg} -${preview.dels}${RESET}`);
164
- if (!preview.adds && !preview.dels) bits.push(`${t.gray} no line changes${RESET}`);
165
- if (preview.misses) bits.push(`${t.gold} ${preview.misses} edit(s) not applied${RESET}`);
166
- // The affordance, and the only thing that tells the reader this row is
167
- // clickable — chatflow's clickHits map keys the row painted here. It also
168
- // mirrors aegiscodex-dev's diffSummaryRow(), which emits the same hint, so
169
- // the two hosts advertise the same gesture in the same words.
170
- bits.push(`${DIM} · ${opts.open ? 'click to collapse' : 'click to view diff'}${RESET}`);
171
- return bits.join('');
172
- }
173
-
174
- /**
175
- * Everything the transcript paints for one edit block: the summary row, plus
176
- * the colored diff body when open.
177
- *
178
- * @param {object} preview From diff.js's editPreview().
179
- * @param {object} ctx App context (selects the light/dark diff palette).
180
- * @param {number} cols Terminal width — the add/del backgrounds run the full
181
- * width, which is what makes the rows read as one block rather than as loose
182
- * colored text.
183
- * @param {{open?: boolean}} [opts]
184
- * @returns {string[]} ANSI rows, each at most `cols` cells wide and RESET-closed.
185
- */
186
- function renderDiffBlock(preview, ctx, cols, opts = {}) {
187
- const width = Math.max(8, Number(cols) || 80);
188
- const D = diffOf(ctx);
189
- const t = themeOf(ctx);
190
- const out = [clipRow(diffSummaryRow(preview, ctx, { open: opts.open }), width)];
191
- if (!opts.open || !preview || !preview.rows || !preview.rows.length) return out;
192
-
193
- const rows = markIntraLine(preview.rows.slice(0, MAX_BLOCK_ROWS).map((r) => Object.assign({}, r)));
194
- let maxNo = 1;
195
- for (const r of rows) if (r.no && r.no > maxNo) maxNo = r.no;
196
- const gutterW = Math.max(2, String(maxNo).length);
197
- // INDENT + gutter + one separating space + the sign and its space.
198
- const codeWidth = Math.max(4, width - (INDENT.length + gutterW + 3));
199
-
200
- for (const r of rows) {
201
- if (r.marker) {
202
- out.push(clipRow(`${DIM}${INDENT}… ${r.note == null ? '' : r.note}${RESET}`, width));
203
- continue;
204
- }
205
- const side = r.sign === '-' ? 'del' : r.sign === '+' ? 'add' : 'ctx';
206
- const bg = side === 'del' ? D.delBg : side === 'add' ? D.addBg : '';
207
- const hiBg = side === 'del' ? D.delHiBg : D.addHiBg;
208
- const hiFg = side === 'del' ? D.delHiFg : D.addHiFg;
209
- const fg = side === 'del' ? D.delFg : side === 'add' ? D.addFg : DIM;
210
-
211
- const lead = `${bg}${D.gutter}${INDENT}${String(r.no == null ? '' : r.no).padStart(gutterW)} ${RESET}`;
212
- const sign = `${bg}${fg}${r.sign === ' ' ? ' ' : r.sign} ${RESET}`;
213
- // Clip the CODE, never the finished row: clipping the painted string would
214
- // count escape bytes as cells and could also cut mid-sequence, leaving the
215
- // terminal in the add/del background for the rest of the scrollback.
216
- const body = codeRow(clip(String(r.text == null ? '' : r.text), codeWidth), bg, hiBg, hiFg, D, r.hi);
217
- const used = w(`${INDENT}${String(r.no == null ? '' : r.no).padStart(gutterW)} `) + 2 + w(clip(String(r.text == null ? '' : r.text), codeWidth));
218
- const fill = bg && used < width ? `${bg}${' '.repeat(width - used)}${RESET}` : '';
219
- out.push(lead + sign + body + fill + RESET);
220
- }
221
-
222
- const hidden = preview.rows.length - MAX_BLOCK_ROWS;
223
- if (hidden > 0) out.push(clipRow(`${DIM}${INDENT}… ${hidden} more diff lines${RESET}`, width));
224
- if (preview.truncated) {
225
- out.push(clipRow(`${DIM}${INDENT}… diff truncated (file too large to compare in full)${RESET}`, width));
226
- }
227
- return out;
228
- }
229
-
230
- /** Colored code tokens for one diff row, with the changed slice highlighted. */
231
- function codeRow(text, bg, hiBg, hiFg, D, hi) {
232
- const out = [];
233
- let idx = 0;
234
- for (const tk of highlightLine(text, D)) {
235
- const chars = [...tk.t];
236
- const start = idx;
237
- const end = idx + chars.length;
238
- idx = end;
239
- if (!hi || end <= hi.start || start >= hi.end) {
240
- out.push(`${bg}${tk.c}${tk.t}`);
241
- continue;
242
- }
243
- const a = Math.max(hi.start, start) - start;
244
- const b = Math.min(hi.end, end) - start;
245
- if (a > 0) out.push(`${bg}${tk.c}${chars.slice(0, a).join('')}`);
246
- if (b > a) out.push(`${hiBg}${hiFg}${chars.slice(a, b).join('')}`);
247
- if (b < chars.length) out.push(`${bg}${tk.c}${chars.slice(b).join('')}`);
248
- }
249
- return out.join('');
250
- }
251
-
252
- /** Clip a painted row to `width` cells, measuring only its visible text. */
253
- function clipRow(row, width) {
254
- if (w(row) <= width) return row;
255
- // Rebuild from the plain text so the escapes stay paired with the cells that
256
- // survive the cut; the last segment ends with RESET below.
257
- return clipVisible(row, width) + RESET;
258
- }
259
-
260
- /**
261
- * Truncate a painted row to `width` visible cells, keeping the escape
262
- * sequences it passes and never splitting one. Reuse the per-character width
263
- * rule that `w()`/`clip()` use so a CJK or emoji cell can't be cut in half.
264
- */
265
- function clipVisible(row, width) {
266
- let used = 0;
267
- let out = '';
268
- let i = 0;
269
- const s = String(row);
270
- while (i < s.length) {
271
- if (s[i] === '\x1b' && s[i + 1] === '[') {
272
- const close = s.indexOf('m', i);
273
- if (close === -1) break;
274
- out += s.slice(i, close + 1);
275
- i = close + 1;
276
- continue;
277
- }
278
- const cp = s.codePointAt(i);
279
- const ch = String.fromCodePoint(cp);
280
- i += ch.length;
281
- const cw = w(ch);
282
- if (used + cw > width) break;
283
- out += ch;
284
- used += cw;
285
- }
286
- return out;
287
- }
288
-
289
- module.exports = {
290
- AUTO_OPEN_ROWS,
291
- MAX_BLOCK_ROWS,
292
- INDENT,
293
- defaultOpen,
294
- highlightLine,
295
- markIntraLine,
296
- diffSummaryRow,
297
- renderDiffBlock,
298
- };
3
+ "use strict";const{DIM:DIM,RESET:RESET,GLYPH:GLYPH,themeOf:themeOf,diffOf:diffOf}=require("./theme.js"),{w:w,clip:clip}=require("./screen.js"),AUTO_OPEN_ROWS=30,MAX_BLOCK_ROWS=200,INDENT=" ",KEYWORDS=new Set(["const","let","var","function","return","if","else","for","while","do","switch","case","break","continue","import","export","from","default","class","extends","new","try","catch","finally","throw","async","await","yield","static","typeof","instanceof","in","of","delete","this","super","null","undefined","true","false","def","elif","lambda","pass","raise","with","as","not","and","or","is","None","True","False","self","fn","mut","pub","impl","struct","enum","trait","match","package","func","defer","chan","nil","echo","local","then","fi","esac"]);function highlightLine(e,n){const t=n||diffOf(null),i=[],l=String(null==e?"":e),o=/(\/\/[^\n]*|#[^\n]*|\/\*[\s\S]*?\*\/)|('(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"|`(?:\\.|[^`\\])*`)|(0[xX][0-9a-fA-F]+|\d+(?:\.\d+)?)|([A-Za-z_$][A-Za-z0-9_$]*)/g,s=(e,n)=>{e&&i.push({t:e,c:n})};let r,d=0;for(;r=o.exec(l);){if(r.index>d&&s(l.slice(d,r.index),t.codeFg),r[1])s(r[1],t.comment);else if(r[2])s(r[2],t.str);else if(r[3])s(r[3],t.num);else{const e=r[4],n=/^\s*\(/.test(l.slice(r.index+e.length));s(e,KEYWORDS.has(e)?t.kw:n?t.fn:t.codeFg)}d=r.index+r[0].length}return d<l.length&&s(l.slice(d),t.codeFg),i}function markIntraLine(e){for(let n=0;n<e.length;n++){if("-"!==e[n].sign)continue;let t=n;for(;t<e.length&&"-"===e[t].sign;)t++;let i=t;for(;i<e.length&&"+"===e[i].sign;)i++;const l=t-n;if(l&&l===i-t)for(let i=0;i<l;i++){const l=intraLine(e[n+i].text,e[t+i].text);l&&(e[n+i].hi={start:l.delStart,end:l.delEnd,side:"del"},e[t+i].hi={start:l.addStart,end:l.addEnd,side:"add"})}n=i-1}return e}function intraLine(e,n){const t=[...String(null==e?"":e)],i=[...String(null==n?"":n)];let l=0;for(;l<t.length&&l<i.length&&t[l]===i[l];)l++;let o=0;for(;o<t.length-l&&o<i.length-l&&t[t.length-1-o]===i[i.length-1-o];)o++;return l+o<.4*(Math.max(t.length,i.length)||1)?null:{delStart:l,delEnd:t.length-o,addStart:l,addEnd:i.length-o}}function defaultOpen(e){return!(!e||!e.rows)&&e.rows.length<=30}function diffSummaryRow(e,n,t={}){const i=themeOf(n),l=diffOf(n),o=[` ${i.gray}${GLYPH.hook} ${RESET}`];return o.push(`${i.lavender}${e.kind}(${e.short})${RESET}`),e.adds&&o.push(`${l.addFg} +${e.adds}${RESET}`),e.dels&&o.push(`${l.delFg} -${e.dels}${RESET}`),e.adds||e.dels||o.push(`${i.gray} no line changes${RESET}`),e.misses&&o.push(`${i.gold} ${e.misses} edit(s) not applied${RESET}`),o.push(`${DIM} · ${t.open?"click to collapse":"click to view diff"}${RESET}`),o.join("")}function renderDiffBlock(e,n,t,i={}){const l=Math.max(8,Number(t)||80),o=diffOf(n),s=(themeOf(n),[clipRow(diffSummaryRow(e,n,{open:i.open}),l)]);if(!(i.open&&e&&e.rows&&e.rows.length))return s;const r=markIntraLine(e.rows.slice(0,200).map((e=>Object.assign({},e))));let d=1;for(const e of r)e.no&&e.no>d&&(d=e.no);const a=Math.max(2,String(d).length),c=Math.max(4,l-(5+a+3));for(const e of r){if(e.marker){s.push(clipRow(`${DIM}${INDENT}… ${null==e.note?"":e.note}${RESET}`,l));continue}const n="-"===e.sign?"del":"+"===e.sign?"add":"ctx",t="del"===n?o.delBg:"add"===n?o.addBg:"",i="del"===n?o.delHiBg:o.addHiBg,r="del"===n?o.delHiFg:o.addHiFg,d="del"===n?o.delFg:"add"===n?o.addFg:DIM,f=`${t}${o.gutter}${INDENT}${String(null==e.no?"":e.no).padStart(a)} ${RESET}`,h=`${t}${d}${" "===e.sign?" ":e.sign} ${RESET}`,u=codeRow(clip(String(null==e.text?"":e.text),c),t,i,r,o,e.hi),g=w(`${INDENT}${String(null==e.no?"":e.no).padStart(a)} `)+2+w(clip(String(null==e.text?"":e.text),c)),$=t&&g<l?`${t}${" ".repeat(l-g)}${RESET}`:"";s.push(f+h+u+$+RESET)}const f=e.rows.length-200;return f>0&&s.push(clipRow(`${DIM}${INDENT}… ${f} more diff lines${RESET}`,l)),e.truncated&&s.push(clipRow(`${DIM}${INDENT}… diff truncated (file too large to compare in full)${RESET}`,l)),s}function codeRow(e,n,t,i,l,o){const s=[];let r=0;for(const d of highlightLine(e,l)){const e=[...d.t],l=r,a=r+e.length;if(r=a,!o||a<=o.start||l>=o.end){s.push(`${n}${d.c}${d.t}`);continue}const c=Math.max(o.start,l)-l,f=Math.min(o.end,a)-l;c>0&&s.push(`${n}${d.c}${e.slice(0,c).join("")}`),f>c&&s.push(`${t}${i}${e.slice(c,f).join("")}`),f<e.length&&s.push(`${n}${d.c}${e.slice(f).join("")}`)}return s.join("")}function clipRow(e,n){return w(e)<=n?e:clipVisible(e,n)+RESET}function clipVisible(e,n){let t=0,i="",l=0;const o=String(e);for(;l<o.length;){if(""===o[l]&&"["===o[l+1]){const e=o.indexOf("m",l);if(-1===e)break;i+=o.slice(l,e+1),l=e+1;continue}const e=o.codePointAt(l),s=String.fromCodePoint(e);l+=s.length;const r=w(s);if(t+r>n)break;i+=s,t+=r}return i}module.exports={AUTO_OPEN_ROWS:30,MAX_BLOCK_ROWS:200,INDENT:INDENT,defaultOpen:defaultOpen,highlightLine:highlightLine,markIntraLine:markIntraLine,diffSummaryRow:diffSummaryRow,renderDiffBlock:renderDiffBlock};
@@ -1,299 +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
- * Wires the CLI into the same agent-loop engine the desktop app already ships
10
- * (desktop/lib/local/engine.js): persistent-shell exec, readFile/writeFile/
11
- * editFile/listDir/glob/grep, and Task subagents.
12
- *
13
- * ── the two classes this host runs ──────────────────────────────────────────
14
- *
15
- * aegis the pooled route. The account's AEGIS key authenticates the call and
16
- * pays for it; the pool picks the provider.
17
- * byok "bring your own key". The user's *provider* key authenticates the
18
- * upstream call, the account's AEGIS key rides along as X-AEGIS-Key,
19
- * and the request goes through the stateless relay
20
- * (POST /api/v1/byok/chat/completions, client/aegis.js
21
- * byokChatCompletion). The relay charges AEGIS's handling fee on the
22
- * turn, which is exactly what makes BYOK billable traffic instead of a
23
- * free ride — and why the key must never be handed to a direct provider
24
- * call from here.
25
- * pro the user's own Claude Code Pro/Max subscription, spent by spawning
26
- * the `claude` CLI. Unchanged from the tunnel repo's claude-pro.js: no
27
- * relay, no AEGIS key, no vendor key, and therefore nothing to bill.
28
- *
29
- * Ollama stays a stub that throws if the engine ever calls it: it needs an
30
- * endpoint surface this host does not offer, and a stub is proof that a code
31
- * path meant for another host never silently runs here.
32
- *
33
- * ── the key store ───────────────────────────────────────────────────────────
34
- *
35
- * The 'byok' class reads one row per provider (`byok:<provider>` —
36
- * desktop/lib/settings.js, the same rows the desktop's Provider settings write)
37
- * for the provider key. The CLI creates that store itself, without Electron's
38
- * safeStorage: base64 at rest, file mode 0600, in the CLI's data dir
39
- * ($AEGISCODE_HOME or ~/.aegiscode). No server-side BYOK mechanism is involved
40
- * here — that one (/byok-set, services/byok_service.py) stores the key on the
41
- * AEGIS account and is folded into the pooled route, an unbilled path by
42
- * design; the two must not be confused.
43
- */
44
-
45
- const os = require('node:os');
46
- const { createLocalEngine, createSettingsStore } = require('./deps.js');
47
- const { credentials } = require('./shared.js');
48
- const VERSION = require('../package.json').version;
49
-
50
- /**
51
- * The classes this host can actually run (see the docstring above).
52
- * aegis — the pooled route (account key pays, pool picks the provider; bills).
53
- * byok — the BYOK relay (your provider key, AEGIS bills a handling fee).
54
- * local — a model on hardware you own, over loopback. Bills nobody because
55
- * there is no vendor; refused outright if the base URL is not local
56
- * (desktop/lib/local/local.js remoteRefusal, fail-closed).
57
- * pro — your own Claude Code Pro/Max subscription, spent by spawning the
58
- * `claude` CLI (desktop/lib/local/claude-pro.js). Bills nobody:
59
- * no relay is involved and no AEGIS endpoint is called.
60
- */
61
- const HOST_CLASSES = Object.freeze(['aegis', 'byok', 'local', 'pro']);
62
-
63
- /**
64
- * The classes this host will actually OFFER, given the `proEnabled` gate.
65
- *
66
- * `pro` is in HOST_CLASSES because this host can run it; it is NOT offered
67
- * unless the user opted in with `/class pro on` (config.js `proEnabled`,
68
- * default false). Every surface that lists, validates or auto-selects a class
69
- * goes through this list, so the gate cannot be honoured by `/class` while the
70
- * `/model` picker and the anthropic→pro override still route turns onto a
71
- * subscription the user never enabled.
72
- *
73
- * @param {boolean|{proEnabled?: boolean}} [want] `true`, or a config object.
74
- * @returns {ReadonlyArray<string>}
75
- */
76
- function offeredClasses(want) {
77
- const on = want === true || (want && want.proEnabled === true);
78
- return on ? HOST_CLASSES : HOST_CLASSES.filter((c) => c !== 'pro');
79
- }
80
-
81
- /** Whether the `pro` class may be selected on this host. */
82
- function proEnabled(cfg) {
83
- return cfg === true || (!!cfg && cfg.proEnabled === true);
84
- }
85
-
86
- /** The class a turn runs on when nothing else is said. */
87
- const DEFAULT_CLASS = 'aegis';
88
-
89
- /** One-line labels for /class, the status line and the model picker. */
90
- const CLASS_LABELS = Object.freeze({
91
- aegis: 'AEGIS Cloud (pooled)',
92
- byok: 'Bring your own key (relayed, billed)',
93
- local: 'Local model (your own machine, free)',
94
- pro: 'Claude Code Pro (your own subscription)',
95
- });
96
-
97
- /**
98
- * @param {object} client A client from client/aegis.js (createClient()).
99
- * @param {() => boolean} getConfirmMode Whether mutating tools (exec,
100
- * writeFile, editFile) require approval before running. Read per call, so
101
- * toggling it (/permissions, /automode) takes effect on the next tool round.
102
- * @param {() => string} getClass Which class the next turn runs on — read per
103
- * call for the same reason getConfirmMode is: /class must take effect on the
104
- * very next turn, not on the next launch.
105
- * @param {() => boolean} [getProEnabled] Whether the `pro` class is enabled for
106
- * this install (config.js `proEnabled`, `/class pro on`). Read per call, like
107
- * getClass, so turning it off takes effect on the very next turn rather than
108
- * on the next launch — a stale `pro` session state must not survive it.
109
- * @param {object} [settings] The provider-config store. Injected by tests
110
- * (and by app.js, so one store serves both the engine and the commands);
111
- * otherwise created against the CLI's data dir.
112
- * @returns {{chat: Function, cancel: Function, respondApproval: Function,
113
- * respondRoundsAsk: Function, clearSessionApprovals: Function, listClasses: Function,
114
- * listModels: Function, classLabel: Function, getClass: Function, setClass: Function,
115
- * unloadLocalModels: () => Promise<void>, settings: object}}
116
- */
117
- function createEngine({ client, getConfirmMode, getClass, getProEnabled, settings: injectedSettings } = {}) {
118
- const settings = injectedSettings || createSettingsStore({ dir: credentials.aegisHome() });
119
-
120
- const local = createLocalEngine({
121
- aegis: client,
122
- settings,
123
- // No `ollama` or `providers` injection: both were stubs for a transport
124
- // this host never runs. The local class is served by the engine's own
125
- // `localTransport`, which defaults to ./local.js — vendored alongside this
126
- // engine by cli/scripts/predist.mjs — so a local model on the user's own
127
- // machine works here with no extra wiring. `byok` never touches a local
128
- // transport at all: it is relayed through AEGIS.
129
- env: {
130
- platform: process.platform,
131
- arch: process.arch,
132
- homedir: os.homedir(),
133
- cwd: process.cwd(),
134
- appVersion: `aegiscode v${VERSION}`,
135
- },
136
- getConfirmMode,
137
- });
138
-
139
- /** The classes this host offers right now — `pro` only once enabled. */
140
- function liveClasses() {
141
- const on = typeof getProEnabled === 'function' ? !!getProEnabled() : false;
142
- return offeredClasses(on);
143
- }
144
-
145
- /** The live class, clamped to what this host can run AND offers. */
146
- function currentClass() {
147
- const asked = typeof getClass === 'function' ? getClass() : null;
148
- const allowed = liveClasses();
149
- return allowed.includes(asked) ? asked : DEFAULT_CLASS;
150
- }
151
-
152
- function chat(payload, onDelta) {
153
- // `class` is stamped here rather than sent by every caller, so the class a
154
- // turn runs on has exactly one source of truth (the live session state) and
155
- // a caller cannot accidentally pin a stale one.
156
- //
157
- // …WHEN THERE IS A LIVE SESSION TO STAMP FROM. `getClass` is the
158
- // interactive surface's `/class` state; a payload that NAMES a class is
159
- // stating its own, and the only such caller is the autonomous queue, whose
160
- // tasks each carry the class they were queued on (autonomous.js runTask).
161
- // The drain builds this engine through buildEngine() below, which supplies
162
- // no `getClass` at all — deliberately, because a drain has no interactive
163
- // session to read.
164
- //
165
- // Reading `currentClass()` unconditionally was therefore not a clamp but an
166
- // OVERWRITE: every queued task went out as `class: 'aegis'` regardless of
167
- // what it was queued as, so a byok or local task (feature from 9eeef09) was
168
- // billed to the pooled route it did not ask for, on a model id the pool
169
- // does not serve. Verified against this tree: a payload `{class:'pro'}` was
170
- // observed arriving at the shared engine as `{class:'aegis'}`.
171
- //
172
- // Precedence is unchanged for the interactive path, which always supplies
173
- // `getClass`: a live class wins over anything a payload carries, so a stale
174
- // value still cannot pin a turn. Only an ABSENT live class lets the
175
- // payload's own class through, and then only one this host can run.
176
- const live = typeof getClass === 'function' ? getClass() : null;
177
- const stated = payload && payload.class;
178
- // The offered set, not HOST_CLASSES: a `pro` turn must not run through the
179
- // subscription unless it was explicitly enabled, and that holds for a
180
- // payload that names its own class too (the queue stamps the class a task
181
- // was queued on, which may predate the gate).
182
- const allowed = liveClasses();
183
- const cls = allowed.includes(live)
184
- ? live
185
- : allowed.includes(stated)
186
- ? stated
187
- : DEFAULT_CLASS;
188
- return local.chat({ ...payload, class: cls }, onDelta);
189
- }
190
-
191
- return {
192
- chat,
193
- cancel: local.cancel,
194
- respondApproval: local.respondApproval,
195
- respondRoundsAsk: local.respondRoundsAsk,
196
- clearSessionApprovals: local.clearSessionApprovals,
197
- // "Closing this host closes the model", the rule the desktop has enforced
198
- // on its quit path (`main.js` before-quit -> engine.unloadLocalModels ->
199
- // local.js unloadAll) since the lane shipped — and the one the CLI was
200
- // missing entirely. Without this passthrough a local turn left the weights
201
- // resident on the user's own hardware for the full length of the pin
202
- // (local.js DEFAULT_WARM_SECS = 1800, i.e. 30 minutes) after the process
203
- // was gone: the local lane exists to bill nothing because the compute is
204
- // already paid for, and a model nobody is using anymore is the one cost it
205
- // was supposed never to have.
206
- //
207
- // Wrapped rather than forwarded bare because this host is also built
208
- // against a VENDORED copy of the shared engine (cli/scripts/predist.mjs
209
- // stages desktop/lib/local/* into cli/vendor), so an install staged from a
210
- // tree that predates `unloadLocalModels` must degrade to a no-op instead of
211
- // throwing on the exit path — a teardown that crashes is worse than a
212
- // residency window that lapses on its own.
213
- unloadLocalModels: () =>
214
- typeof local.unloadLocalModels === 'function'
215
- ? local.unloadLocalModels()
216
- : Promise.resolve(),
217
- // The engine's own class table, narrowed to the ones this host runs — so a
218
- // UI built from listClasses() can never offer a class that would throw.
219
- // Async, like the local engine's: listClasses() probes Ollama (a live
220
- // HTTP round-trip) before it can answer, so returning the raw promise made
221
- // `/class` throw "filter is not a function". The caller awaits it.
222
- // The offered set, not HOST_CLASSES: `/class`, `/models` and the pickers are
223
- // built from this, so a disabled `pro` cannot be listed or entered.
224
- listClasses: async () => {
225
- const allowed = liveClasses();
226
- return (await local.listClasses()).filter((c) => allowed.includes(c.class));
227
- },
228
- listModels: (cls) => local.listModels(cls || currentClass()),
229
- // The user's own model declarations (`$AEGISCODE_HOME/models.json`), read
230
- // through the shared store (`client/user-models.js`) this host's engine
231
- // already applies to every `listModels('byok')` call. Exposed on the
232
- // surface because a caller outside the engine needs to know WHEN that list
233
- // changed: the picker's cache (`app.js` byokCache) is keyed on this file's
234
- // content as well as on time, since a declaration written by the desktop's
235
- // Custom provider card, by `/model-add` in another terminal, or by the
236
- // user's editor cannot notify this process. Degrades to an empty map on a
237
- // vendored tree that predates the reader (`local.userModels`), so a cache
238
- // key can never throw on the path that paints a picker.
239
- userModels: () =>
240
- typeof local.userModels === 'function'
241
- ? local.userModels()
242
- : { dir: '', file: '', map: {}, invalid: [] },
243
- classLabel: (cls) => CLASS_LABELS[cls] || CLASS_LABELS[DEFAULT_CLASS],
244
- getClass: currentClass,
245
- /** The classes selectable right now (see offeredClasses) — for surfaces
246
- * that validate a class without instantiating a turn. */
247
- offeredClasses: () => liveClasses(),
248
- settings,
249
- };
250
- }
251
-
252
- /**
253
- * The settings row one BYOK provider's key lives in. Exported (rather than
254
- * spelled out again in commands.js) because it is the SAME key the shared
255
- * engine reads when it resolves the relay's provider credential — and the same
256
- * row the desktop's Provider settings write. Two spellings would mean a key
257
- * saved by `/byok-key openai` never reaching the call that needs it.
258
- */
259
- function byokNamespace(provider) {
260
- return `byok:${provider}`;
261
- }
262
-
263
- /**
264
- * The effort rung a turn travels with: always 'low' | 'medium' | 'high'.
265
- *
266
- * This host has exactly three levels and every one of them must reach the wire,
267
- * so the normalisation lives here — on the path from session state to request —
268
- * rather than in the renderers. An absent, empty, `null` or retired `auto`
269
- * value resolves to `high`, the rung the desktop's select defaults to and the
270
- * one the shared engine applies to an unstated effort (desktop/lib/local/
271
- * engine.js reasoningBudget/nativeEffort both floor to high).
272
- *
273
- * WHY THIS IS NOT OPTIONAL: the pooled dispatch in the shared engine states the
274
- * rung conditionally (`...(opts.effort ? { effort: opts.effort } : {})`), and
275
- * the BYOK dispatch translates it (nativeEffort). A falsy value therefore is
276
- * not "the default" — it is "state no opinion", and the server then sizes the
277
- * turn itself. `auto` was the CLI's DEFAULT, so the default turn was the one
278
- * turn that sent nothing: /effort changed the status line and nothing else.
279
- *
280
- * Mirrors effortRung() in desktop/renderer/budget.js (and the `=== 'low' ||
281
- * === 'medium' ? : 'high'` floor in the shared engine). Carried rather than
282
- * shared because the CLI must not require the renderer bundle — the same reason
283
- * cli/src/tokens.js re-exports the shared usage folds instead of reaching into
284
- * desktop/.
285
- */
286
- function effortRung(effort) {
287
- return effort === 'low' || effort === 'medium' ? effort : 'high';
288
- }
289
-
290
- module.exports = {
291
- createEngine,
292
- HOST_CLASSES,
293
- DEFAULT_CLASS,
294
- CLASS_LABELS,
295
- offeredClasses,
296
- proEnabled,
297
- byokNamespace,
298
- effortRung,
299
- };
3
+ "use strict";const os=require("node:os"),{createLocalEngine:createLocalEngine,createSettingsStore:createSettingsStore}=require("./deps.js"),{credentials:credentials}=require("./shared.js"),VERSION=require("../package.json").version,HOST_CLASSES=Object.freeze(["aegis","byok","local","pro"]);function offeredClasses(e){return!0===e||e&&!0===e.proEnabled?HOST_CLASSES:HOST_CLASSES.filter((e=>"pro"!==e))}function proEnabled(e){return!0===e||!!e&&!0===e.proEnabled}const DEFAULT_CLASS="aegis",CLASS_LABELS=Object.freeze({aegis:"AEGIS Cloud (pooled)",byok:"Bring your own key (relayed, billed)",local:"Local model (your own machine, free)",pro:"Claude Code Pro (your own subscription)"});function createEngine({client:e,getConfirmMode:s,getClass:o,getProEnabled:n,settings:r}={}){const a=r||createSettingsStore({dir:credentials.aegisHome()}),t=createLocalEngine({aegis:e,settings:a,env:{platform:process.platform,arch:process.arch,homedir:os.homedir(),cwd:process.cwd(),appVersion:`aegiscode v${VERSION}`},getConfirmMode:s});function l(){return offeredClasses("function"==typeof n&&!!n())}function i(){const e="function"==typeof o?o():null;return l().includes(e)?e:"aegis"}return{chat:function(e,s){const n="function"==typeof o?o():null,r=e&&e.class,a=l(),i=a.includes(n)?n:a.includes(r)?r:"aegis";return t.chat({...e,class:i},s)},cancel:t.cancel,respondApproval:t.respondApproval,respondRoundsAsk:t.respondRoundsAsk,clearSessionApprovals:t.clearSessionApprovals,unloadLocalModels:()=>"function"==typeof t.unloadLocalModels?t.unloadLocalModels():Promise.resolve(),listClasses:async()=>{const e=l();return(await t.listClasses()).filter((s=>e.includes(s.class)))},listModels:e=>t.listModels(e||i()),userModels:()=>"function"==typeof t.userModels?t.userModels():{dir:"",file:"",map:{},invalid:[]},classLabel:e=>CLASS_LABELS[e]||CLASS_LABELS.aegis,getClass:i,offeredClasses:()=>l(),settings:a}}function byokNamespace(e){return`byok:${e}`}function effortRung(e){return"low"===e||"medium"===e?e:"high"}module.exports={createEngine:createEngine,HOST_CLASSES:HOST_CLASSES,DEFAULT_CLASS:"aegis",CLASS_LABELS:CLASS_LABELS,offeredClasses:offeredClasses,proEnabled:proEnabled,byokNamespace:byokNamespace,effortRung:effortRung};