aegiscode 7.0.24 → 7.0.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/package.json +7 -3
  2. package/scripts/check.mjs +52 -1
  3. package/scripts/demo.mjs +94 -1
  4. package/scripts/predist.mjs +75 -1
  5. package/scripts/runtests.mjs +56 -1
  6. package/scripts/seal-gate.mjs +74 -1
  7. package/src/agents.js +139 -1
  8. package/src/app.js +2957 -1
  9. package/src/art.js +289 -1
  10. package/src/chatflow.js +3023 -1
  11. package/src/checkpoint.js +90 -1
  12. package/src/clipboard.js +424 -1
  13. package/src/cloudsync.js +528 -1
  14. package/src/commands.js +4089 -1
  15. package/src/config.js +581 -1
  16. package/src/connect.js +349 -1
  17. package/src/credentials.js +33 -1
  18. package/src/deps.js +232 -1
  19. package/src/devrun.js +187 -1
  20. package/src/diff.js +333 -1
  21. package/src/diffview.js +296 -1
  22. package/src/engine.js +297 -1
  23. package/src/entitlement.js +355 -1
  24. package/src/events.js +707 -1
  25. package/src/export.js +67 -1
  26. package/src/filepreview.js +153 -1
  27. package/src/fingerprint.js +592 -1
  28. package/src/format.js +259 -1
  29. package/src/fuzzy.js +119 -1
  30. package/src/history.js +423 -1
  31. package/src/init.js +175 -1
  32. package/src/input.js +139 -1
  33. package/src/keys.js +183 -1
  34. package/src/markdown.js +306 -1
  35. package/src/models.js +507 -1
  36. package/src/naming.js +57 -1
  37. package/src/overlays.js +462 -1
  38. package/src/panels.js +1418 -1
  39. package/src/ping.js +226 -1
  40. package/src/presence.js +238 -1
  41. package/src/render.js +516 -1
  42. package/src/screen.js +518 -1
  43. package/src/screens.js +896 -1
  44. package/src/secret.js +59 -1
  45. package/src/securefs.js +359 -1
  46. package/src/settings.js +155 -1
  47. package/src/shared.js +52 -1
  48. package/src/sharedpaths.js +53 -1
  49. package/src/signup.js +156 -1
  50. package/src/summarize.js +95 -1
  51. package/src/sysdiag.js +585 -1
  52. package/src/system.js +40 -1
  53. package/src/theme.js +570 -1
  54. package/src/title.js +220 -1
  55. package/src/todos.js +115 -1
  56. package/src/tokens.js +263 -1
  57. package/src/topup.js +210 -1
  58. package/src/update.js +191 -1
  59. package/vendor/client/aegis.js +2441 -1
  60. package/vendor/client/attest.js +518 -1
  61. package/vendor/client/authorship-key.js +410 -1
  62. package/vendor/client/auto-provision.js +134 -1
  63. package/vendor/client/brain-catalog.js +268 -1
  64. package/vendor/client/byok-catalog.js +199 -1
  65. package/vendor/client/catalog-client.js +487 -1
  66. package/vendor/client/conversation-export.js +177 -1
  67. package/vendor/client/credentials.js +494 -1
  68. package/vendor/client/device-fingerprint.js +141 -1
  69. package/vendor/client/drive-connect.js +110 -1
  70. package/vendor/client/drive-upload.js +234 -1
  71. package/vendor/client/env-file.js +1273 -1
  72. package/vendor/client/fingerprint.js +1064 -1
  73. package/vendor/client/foreign-memory.js +669 -1
  74. package/vendor/client/google-signin.js +133 -1
  75. package/vendor/client/hooks.js +430 -1
  76. package/vendor/client/model-discovery.js +373 -1
  77. package/vendor/client/naming.js +283 -1
  78. package/vendor/client/platform.js +937 -1
  79. package/vendor/client/prefs.js +351 -1
  80. package/vendor/client/presence-constants.js +107 -1
  81. package/vendor/client/presence.js +438 -1
  82. package/vendor/client/record-vault.js +1055 -3
  83. package/vendor/client/session-store.js +575 -1
  84. package/vendor/client/topup.js +297 -1
  85. package/vendor/client/touch.js +458 -1
  86. package/vendor/client/update.js +763 -1
  87. package/vendor/client/user-models.js +381 -1
  88. package/vendor/desktop/lib/local/agents.js +105 -1
  89. package/vendor/desktop/lib/local/attachments.js +276 -1
  90. package/vendor/desktop/lib/local/autonomous.js +1045 -1
  91. package/vendor/desktop/lib/local/claude-pro.js +1028 -1
  92. package/vendor/desktop/lib/local/context.js +125 -1
  93. package/vendor/desktop/lib/local/engine.js +3666 -1
  94. package/vendor/desktop/lib/local/entitlement.js +660 -1
  95. package/vendor/desktop/lib/local/git-scope.js +228 -1
  96. package/vendor/desktop/lib/local/local.js +2145 -1
  97. package/vendor/desktop/lib/local/prompt.js +280 -1
  98. package/vendor/desktop/lib/local/queue.js +560 -1
  99. package/vendor/desktop/lib/local/session-rounds.js +238 -1
  100. package/vendor/desktop/lib/local/spill.js +75 -1
  101. package/vendor/desktop/lib/local/turn-guard.js +300 -1
  102. package/vendor/desktop/lib/local/worktree-lock.js +235 -1
  103. package/vendor/desktop/lib/settings.js +890 -1
  104. package/vendor/desktop/renderer/usage.js +1239 -1
  105. package/vendor/hosts/install.js +638 -1
  106. package/vendor/hosts/openai-shim.js +515 -1
  107. package/vendor/hosts/spec.js +164 -1
  108. package/vendor/hosts/targets.js +346 -1
  109. package/vendor/mcp/server.js +221 -1
  110. package/vendor/mcp/tools.js +408 -1
  111. package/vendor/one/src/child.js +285 -1
  112. package/vendor/one/src/permissions.js +383 -1
  113. package/SOURCE-OFFER.txt +0 -9
package/src/diffview.js CHANGED
@@ -1,3 +1,298 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const{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};
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
+ };
package/src/engine.js CHANGED
@@ -1,3 +1,299 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const 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||"max"===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};
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 === 'max' ? 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
+ };