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/history.js CHANGED
@@ -1,3 +1,425 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{aegisDir:aegisDir}=require("./config.js"),{ensurePrivateDir:ensurePrivateDir,writePrivateFile:writePrivateFile}=require("./securefs.js"),{sessionStore:sessionStore}=require("./shared.js"),{cwdName:cwdName}=require("./format.js"),{estimateTokens:estimateTokens}=require("./tokens.js"),HISTORY_LIMIT=500,SOURCE="aegiscode-cli";function historyPath(){return path.join(aegisDir(),"history.jsonl")}function ensureHistoryDir(){ensurePrivateDir(path.dirname(historyPath()))}function appendHistory({sessionId:e,prompt:t,reply:s,status:r,usage:i,title:n,model:o,provider:a}){try{const c={ts:(new Date).toISOString(),sessionId:e,cwd:process.cwd(),prompt:t,reply:s,status:r,tokens:i?{input:i.input||0,output:i.output||0,cacheRead:i.cacheRead||0,cacheWrite:i.cacheWrite||0,real:!0}:{input:estimateTokens(t),output:estimateTokens(s||""),real:!1}};i&&"number"==typeof i.costUsd&&(c.costUsd=i.costUsd);const d=String(n||"").trim();d&&(c.title=d);const u="string"==typeof o?o.trim():"";u&&(c.model=u);const l="string"==typeof a?a.trim():"";return l&&(c.provider=l),appendHistoryEntries([c])}catch(e){return process.env.AEGIS_HIST_DEBUG&&console.error("[history] write failed:",e),0}}function appendHistoryEntries(e){const t=(Array.isArray(e)?e:[]).filter(Boolean);if(!t.length)return 0;try{ensureHistoryDir();const e=historyPath(),s=[...fs.existsSync(e)?fs.readFileSync(e,"utf8").split("\n").filter(Boolean):[],...t.map((e=>JSON.stringify(e)))],r=s.slice(Math.max(0,s.length-HISTORY_LIMIT));return writePrivateFile(e,r.join("\n")+"\n"),mirrorToSharedStore(t),t.length}catch(e){return process.env.AEGIS_HIST_DEBUG&&console.error("[history] write failed:",e),0}}function mirrorToSharedStore(e){for(const t of e)try{sessionStore.recordExchange(aegisDir(),{sessionId:t.sessionId,prompt:t.prompt,reply:t.reply,status:t.status,cwd:t.cwd,ts:t.ts,tokens:t.tokens,costUsd:t.costUsd,model:t.model,provider:t.provider,origin:SOURCE})}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[history] mirror failed:",e)}}function readEntries(){try{return fs.readFileSync(historyPath(),"utf8").split("\n").map((e=>e.trim())).filter(Boolean).map((e=>{try{return JSON.parse(e)}catch{return null}})).filter(Boolean)}catch{return[]}}function readHistoryEntries(){return readEntries()}function readOwnSessions(e=8){const t=readEntries(),s=new Map;for(const e of t){const t=s.get(e.sessionId);t?(!t.title&&e.title||!t.title==!e.title&&String(e.ts)>String(t.ts))&&s.set(e.sessionId,e):s.set(e.sessionId,e)}return[...s.values()].sort(((e,t)=>e.ts<t.ts?1:-1)).slice(0,e).map((e=>({id:e.sessionId,cwd:cwdName(e.cwd),summary:(e.title||e.prompt||"").slice(0,60),time:e.ts,own:!0})))}function readSessionTranscript(e){const t=readEntries().filter((t=>t.sessionId===e)).flatMap((e=>[{role:"user",text:e.prompt},{role:"assistant",text:e.reply||"(no response)"}]));if(t.length)return t;try{return sessionStore.readTranscript(aegisDir(),e)}catch{return[]}}function readSharedStoreSessions(e=8){try{return sessionStore.listSummaries(aegisDir(),e)}catch{return[]}}function sessionHistoryEntries(e){return readEntries().filter((t=>t.sessionId===e))}function setSessionTitle(e,t){const s=String(t||"").trim();if(!s)return 0;try{sessionStore.setTitle(aegisDir(),e,s)}catch{}try{const t=historyPath();if(!fs.existsSync(t))return 0;let r=0;const i=fs.readFileSync(t,"utf8").split("\n").map((e=>e.trim())).filter(Boolean).map((t=>{try{const i=JSON.parse(t);return i.sessionId!==e||i.title===s?t:(i.title=s,r++,JSON.stringify(i))}catch{return t}}));return r?(writePrivateFile(t,i.join("\n")+"\n"),r):0}catch(e){return process.env.AEGIS_HIST_DEBUG&&console.error("[history] title write failed:",e),0}}function readSessionTitle(e){const t=readEntries().find((t=>t.sessionId===e&&t.title));return t?String(t.title):""}function pruneSessionHistory(e){try{const t=historyPath();if(!fs.existsSync(t))return;const s=fs.readFileSync(t,"utf8").split("\n").map((e=>e.trim())).filter(Boolean).filter((t=>{try{return JSON.parse(t).sessionId!==e}catch{return!0}}));writePrivateFile(t,s.length?s.join("\n")+"\n":"")}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[history] prune failed:",e)}}function aggregateSessionUsage(e){const t=sessionHistoryEntries(e),s={input:0,output:0,cacheRead:0,cacheWrite:0};let r=t.length>0,i=0;for(const e of t){const t=e.tokens||{};t.real||(r=!1),s.input+=t.input||0,s.output+=t.output||0,s.cacheRead+=t.cacheRead||0,s.cacheWrite+=t.cacheWrite||0,"number"==typeof e.costUsd&&(i+=e.costUsd)}return{entries:t.length,usage:s,real:r,costUsd:i}}function readResumeList(e=8,t=5,s=8){const r=readOwnSessions(t),i=new Set(r.map((e=>e.id))),n=readSharedStoreSessions(t).filter((e=>!i.has(e.id)&&(i.add(e.id),!0))),o=[],a=`${os.homedir()}/.claude/history.jsonl`;try{const e=fs.readFileSync(a,"utf8").trim().split("\n").reverse().slice(0,s);for(const t of e)try{const e=JSON.parse(t),s=e.extra&&JSON.parse(e.extra);if(s&&s.sessionId&&!i.has(s.sessionId)){i.add(s.sessionId);const t=cwdName(e.cwd),r=(e.summary||"").slice(0,60);o.push({id:s.sessionId,cwd:t,summary:r,time:e.timestamp,own:!1})}}catch{}}catch{}return[...r,...n,...o].sort(((e,t)=>String(e.time||"")<String(t.time||"")?1:-1)).slice(0,e)}module.exports={HISTORY_LIMIT:HISTORY_LIMIT,SOURCE:SOURCE,historyPath:historyPath,ensureHistoryDir:ensureHistoryDir,appendHistory:appendHistory,appendHistoryEntries:appendHistoryEntries,readHistoryEntries:readHistoryEntries,readOwnSessions:readOwnSessions,readSessionTranscript:readSessionTranscript,readSharedStoreSessions:readSharedStoreSessions,sessionHistoryEntries:sessionHistoryEntries,pruneSessionHistory:pruneSessionHistory,aggregateSessionUsage:aggregateSessionUsage,readResumeList:readResumeList,setSessionTitle:setSessionTitle,readSessionTitle:readSessionTitle};
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
+ * Session persistence — one JSON line per exchange in ~/.aegiscode/history.jsonl
10
+ * (or $AEGISCODE_HOME). Keeps the file bounded (oldest entries dropped past
11
+ * HISTORY_LIMIT lines).
12
+ *
13
+ * history.jsonl is this host's *ledger*: one record per exchange, carrying the
14
+ * token/cost numbers `/cost` aggregates. It stays the CLI's own format.
15
+ *
16
+ * What changed with the shared store (`client/session-store.js`) is that every
17
+ * recorded exchange is ALSO mirrored into `<dir>/sessions.json`, the store the
18
+ * desktop app and the MCP plugin read. That file is what makes a terminal turn
19
+ * show up in the GUI's session list — and, in the other direction, what lets
20
+ * `/resume` open a session that was typed in the desktop, without cloud sync
21
+ * and without a key. `readResumeList` merges both sources by id, so no session
22
+ * is listed twice.
23
+ *
24
+ * Ported from the upstream engine reference (ESM → CommonJS). The data dir now
25
+ * comes from config.js's shared `aegisDir()` helper.
26
+ */
27
+
28
+ const fs = require('node:fs');
29
+ const os = require('node:os');
30
+ const path = require('node:path');
31
+ const { aegisDir } = require('./config.js');
32
+ const { ensurePrivateDir, writePrivateFile } = require('./securefs.js');
33
+ const { sessionStore } = require('./shared.js');
34
+ const { cwdName } = require('./format.js');
35
+ const { estimateTokens } = require('./tokens.js');
36
+
37
+ const HISTORY_LIMIT = 500;
38
+ /** Which host wrote a mirrored record, so either side can tell them apart. */
39
+ const SOURCE = 'aegiscode-cli';
40
+
41
+ function historyPath() {
42
+ return path.join(aegisDir(), 'history.jsonl');
43
+ }
44
+
45
+ function ensureHistoryDir() {
46
+ ensurePrivateDir(path.dirname(historyPath()));
47
+ }
48
+
49
+ /**
50
+ * Record one exchange. `reply` is stored in full so /resume can restore the
51
+ * transcript exactly. Token accounting:
52
+ * live — `usage` carries the real numbers from the provider stream-json
53
+ * (input/output/cacheRead/cacheWrite + costUsd), stored verbatim;
54
+ * demo — estimated from text length (~4 chars/token), labeled real:false.
55
+ * /cost aggregates these records, so compacted-away exchanges still count.
56
+ *
57
+ * `title` is the conversation's own name (naming.js). It is written on every
58
+ * record for the session so `/resume` shows what the session is ABOUT — it used
59
+ * to show `prompt.slice(0, 60)`, the raw first message, which is a prompt and
60
+ * not a name ("heey").
61
+ *
62
+ * `model` and `provider` are what this turn actually RAN ON. They matter beyond
63
+ * bookkeeping: the record's AI axis reads `model` off these rows (`MODEL_KEYS` in
64
+ * client/attest.js), so a ledger that never wrote one minted every sealed record
65
+ * with `aiModel: null` — the "which mind answered" half of the fingerprint was
66
+ * structurally unimplemented for real conversations, not merely unpopulated.
67
+ * Written only when known: an absent field means "this turn did not say", which
68
+ * is the same distinction the record itself draws, so old rows keep their shape
69
+ * and a turn with no model is not stamped with a guessed one.
70
+ */
71
+ function appendHistory({ sessionId, prompt, reply, status, usage, title, model, provider }) {
72
+ try {
73
+ const entry = {
74
+ ts: new Date().toISOString(),
75
+ sessionId,
76
+ cwd: process.cwd(),
77
+ prompt,
78
+ reply,
79
+ status, // 'done' | 'stopped' | 'error'
80
+ tokens: usage
81
+ ? {
82
+ input: usage.input || 0,
83
+ output: usage.output || 0,
84
+ cacheRead: usage.cacheRead || 0,
85
+ cacheWrite: usage.cacheWrite || 0,
86
+ real: true,
87
+ }
88
+ : { input: estimateTokens(prompt), output: estimateTokens(reply || ''), real: false },
89
+ };
90
+ if (usage && typeof usage.costUsd === 'number') entry.costUsd = usage.costUsd;
91
+ const clean = String(title || '').trim();
92
+ if (clean) entry.title = clean;
93
+ // Provenance, when the turn knows it. `model` is the id the provider
94
+ // answered on; `provider` is the vendor the id names. Both are normalised
95
+ // to a trimmed string so a null/''/undefined can never be written as a
96
+ // value that the AI axis would then attest as a model.
97
+ const modelId = typeof model === 'string' ? model.trim() : '';
98
+ if (modelId) entry.model = modelId;
99
+ const vendor = typeof provider === 'string' ? provider.trim() : '';
100
+ if (vendor) entry.provider = vendor;
101
+ return appendHistoryEntries([entry]);
102
+ } catch (e) {
103
+ // Persistence is best-effort; never crash the session over it.
104
+ if (process.env.AEGIS_HIST_DEBUG) console.error('[history] write failed:', e);
105
+ return 0;
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Append a batch of already-shaped entries in ONE read/trim/write pass.
111
+ *
112
+ * `appendHistory` re-reads and rewrites the whole file per exchange, which is
113
+ * fine for one turn at a time but quadratic for a caller with a list of them —
114
+ * importing 50 pulled sessions would rewrite the file 50 times, each pass
115
+ * re-parsing everything the previous pass just wrote. The single writer (and
116
+ * therefore the single place the file format is defined) stays here.
117
+ *
118
+ * @returns {number} entries written
119
+ */
120
+ function appendHistoryEntries(entries) {
121
+ const list = (Array.isArray(entries) ? entries : []).filter(Boolean);
122
+ if (!list.length) return 0;
123
+ try {
124
+ ensureHistoryDir();
125
+ const p = historyPath();
126
+ const prev = fs.existsSync(p) ? fs.readFileSync(p, 'utf8').split('\n').filter(Boolean) : [];
127
+ const lines = [...prev, ...list.map((e) => JSON.stringify(e))];
128
+ const trimmed = lines.slice(Math.max(0, lines.length - HISTORY_LIMIT));
129
+ // 0600: this file is every prompt and reply the session has ever had.
130
+ writePrivateFile(p, trimmed.join('\n') + '\n');
131
+ mirrorToSharedStore(list);
132
+ return list.length;
133
+ } catch (e) {
134
+ // Persistence is best-effort; never crash the session over it.
135
+ if (process.env.AEGIS_HIST_DEBUG) console.error('[history] write failed:', e);
136
+ return 0;
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Mirror freshly-recorded exchanges into the shared session store, so the
142
+ * desktop and the MCP plugin can see this host's sessions.
143
+ *
144
+ * Only *writes* mirror — a read of history.jsonl never re-imports itself, which
145
+ * is what would otherwise duplicate every exchange on every launch. A mirror
146
+ * failure must never cost the user the history line it accompanies, so this is
147
+ * called after the ledger write and swallows its own errors.
148
+ */
149
+ function mirrorToSharedStore(entries) {
150
+ for (const e of entries) {
151
+ try {
152
+ sessionStore.recordExchange(aegisDir(), {
153
+ sessionId: e.sessionId,
154
+ prompt: e.prompt,
155
+ reply: e.reply,
156
+ status: e.status,
157
+ cwd: e.cwd,
158
+ ts: e.ts,
159
+ tokens: e.tokens,
160
+ costUsd: e.costUsd,
161
+ // Carried, not dropped: the desktop lists these sessions and mints from
162
+ // this store too, so a model recorded only in history.jsonl would be
163
+ // invisible to every surface that reads the shared store.
164
+ model: e.model,
165
+ provider: e.provider,
166
+ origin: SOURCE,
167
+ });
168
+ } catch (err) {
169
+ if (process.env.AEGIS_HIST_DEBUG) console.error('[history] mirror failed:', err);
170
+ }
171
+ }
172
+ }
173
+
174
+ function readEntries() {
175
+ try {
176
+ const raw = fs.readFileSync(historyPath(), 'utf8');
177
+ return raw
178
+ .split('\n')
179
+ .map((l) => l.trim())
180
+ .filter(Boolean)
181
+ .map((l) => { try { return JSON.parse(l); } catch { return null; } })
182
+ .filter(Boolean);
183
+ } catch {
184
+ return [];
185
+ }
186
+ }
187
+
188
+ /** Every history record, oldest first. Public name for other modules. */
189
+ function readHistoryEntries() {
190
+ return readEntries();
191
+ }
192
+
193
+ /** Newest-first list of own sessions, one per distinct sessionId. */
194
+ function readOwnSessions(limit = 8) {
195
+ const entries = readEntries();
196
+ const byId = new Map();
197
+ for (const e of entries) {
198
+ const cur = byId.get(e.sessionId);
199
+ if (!cur) {
200
+ byId.set(e.sessionId, e);
201
+ continue;
202
+ }
203
+ // Prefer a record that carries the conversation's name — naming lands one
204
+ // model round after the first exchange is persisted, so the newest record
205
+ // is not necessarily the titled one. Failing that, the newest wins.
206
+ if (!cur.title && e.title) byId.set(e.sessionId, e);
207
+ else if (!cur.title === !e.title && String(e.ts) > String(cur.ts)) byId.set(e.sessionId, e);
208
+ }
209
+ const items = [...byId.values()]
210
+ .sort((a, b) => (a.ts < b.ts ? 1 : -1))
211
+ .slice(0, limit)
212
+ .map((e) => ({
213
+ id: e.sessionId,
214
+ cwd: cwdName(e.cwd),
215
+ // The conversation's own name when it has one (naming.js), else the old
216
+ // raw-prompt fallback so a session recorded before naming existed is
217
+ // still identifiable.
218
+ summary: (e.title || e.prompt || '').slice(0, 60),
219
+ time: e.ts,
220
+ own: true,
221
+ }));
222
+ return items;
223
+ }
224
+
225
+ /**
226
+ * Rebuild the transcript (user/assistant pairs) of a session, oldest first.
227
+ *
228
+ * history.jsonl wins when it has records for the id (this host's own ledger,
229
+ * complete with the exchanges the shared store may have trimmed). Otherwise the
230
+ * session came from another host — a desktop thread — and the shared store is
231
+ * the only place its messages exist, so /resume can open it too.
232
+ */
233
+ function readSessionTranscript(sessionId) {
234
+ const own = readEntries()
235
+ .filter((e) => e.sessionId === sessionId)
236
+ .flatMap((e) => [
237
+ { role: 'user', text: e.prompt },
238
+ { role: 'assistant', text: e.reply || '(no response)' },
239
+ ]);
240
+ if (own.length) return own;
241
+ try {
242
+ return sessionStore.readTranscript(aegisDir(), sessionId);
243
+ } catch {
244
+ return [];
245
+ }
246
+ }
247
+
248
+ /** Sessions in the shared store written by another host (the desktop app). */
249
+ function readSharedStoreSessions(limit = 8) {
250
+ try {
251
+ return sessionStore.listSummaries(aegisDir(), limit);
252
+ } catch {
253
+ return [];
254
+ }
255
+ }
256
+
257
+ /** All history records for one session, oldest first (power /cost). */
258
+ function sessionHistoryEntries(sessionId) {
259
+ return readEntries().filter((e) => e.sessionId === sessionId);
260
+ }
261
+
262
+ /**
263
+ * Stamp a conversation's name onto every record this session already has.
264
+ *
265
+ * Naming is one model round, run off the critical path, so it usually lands
266
+ * *after* the first exchange was written to history.jsonl. Without this the
267
+ * resume list would show the raw first prompt for the rest of the session's
268
+ * life, because readOwnSessions() would find no `title` anywhere.
269
+ *
270
+ * Best-effort, like every other writer here: a failed rewrite costs a name in a
271
+ * picker, never a turn. Records are rewritten to the same 0600 file via
272
+ * securefs, and only the session's own lines are touched.
273
+ */
274
+ function setSessionTitle(sessionId, title) {
275
+ const clean = String(title || '').trim();
276
+ if (!clean) return 0;
277
+ // The shared store is the other surface a name is read from: the desktop app
278
+ // and the MCP plugin list sessions from `sessions.json`, so a name that lived
279
+ // only in history.jsonl would name the session in `/resume` and leave it
280
+ // unnamed in the GUI. Stamped first and unconditionally — the store may hold
281
+ // this session even when the ledger does not. Best-effort, like everything
282
+ // else here.
283
+ try {
284
+ sessionStore.setTitle(aegisDir(), sessionId, clean);
285
+ } catch {
286
+ /* the store is optional; the ledger below is the CLI's own */
287
+ }
288
+ try {
289
+ const p = historyPath();
290
+ if (!fs.existsSync(p)) return 0;
291
+ let touched = 0;
292
+ const out = fs
293
+ .readFileSync(p, 'utf8')
294
+ .split('\n')
295
+ .map((l) => l.trim())
296
+ .filter(Boolean)
297
+ .map((l) => {
298
+ try {
299
+ const j = JSON.parse(l);
300
+ if (j.sessionId !== sessionId || j.title === clean) return l;
301
+ j.title = clean;
302
+ touched++;
303
+ return JSON.stringify(j);
304
+ } catch {
305
+ return l;
306
+ }
307
+ });
308
+ if (!touched) return 0;
309
+ writePrivateFile(p, out.join('\n') + '\n');
310
+ return touched;
311
+ } catch (e) {
312
+ if (process.env.AEGIS_HIST_DEBUG) console.error('[history] title write failed:', e);
313
+ return 0;
314
+ }
315
+ }
316
+
317
+ /** The conversation's name, if any record for it carries one. */
318
+ function readSessionTitle(sessionId) {
319
+ const hit = readEntries().find((e) => e.sessionId === sessionId && e.title);
320
+ return hit ? String(hit.title) : '';
321
+ }
322
+
323
+ /**
324
+ * Drop every history record for a session. /clear
325
+ * calls this so /cost stops summing old rows — the sessionId stays stable, so
326
+ * rewind checkpoints and the transcript lineage are unaffected.
327
+ */
328
+ function pruneSessionHistory(sessionId) {
329
+ try {
330
+ const p = historyPath();
331
+ if (!fs.existsSync(p)) return;
332
+ const kept = fs
333
+ .readFileSync(p, 'utf8')
334
+ .split('\n')
335
+ .map((l) => l.trim())
336
+ .filter(Boolean)
337
+ .filter((l) => {
338
+ try { return JSON.parse(l).sessionId !== sessionId; } catch { return true; }
339
+ });
340
+ writePrivateFile(p, kept.length ? kept.join('\n') + '\n' : '');
341
+ } catch (e) {
342
+ if (process.env.AEGIS_HIST_DEBUG) console.error('[history] prune failed:', e);
343
+ }
344
+ }
345
+
346
+ /**
347
+ * Sum a session's token records across history.jsonl. Compacted-away exchanges
348
+ * still count because /compact writes a summary exchange, it never deletes the
349
+ * file. `real` is true only when every record carries live CLI usage numbers.
350
+ */
351
+ function aggregateSessionUsage(sessionId) {
352
+ const entries = sessionHistoryEntries(sessionId);
353
+ const usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
354
+ let real = entries.length > 0;
355
+ let costUsd = 0;
356
+ for (const e of entries) {
357
+ const t = e.tokens || {};
358
+ if (!t.real) real = false;
359
+ usage.input += t.input || 0;
360
+ usage.output += t.output || 0;
361
+ usage.cacheRead += t.cacheRead || 0;
362
+ usage.cacheWrite += t.cacheWrite || 0;
363
+ if (typeof e.costUsd === 'number') costUsd += e.costUsd;
364
+ }
365
+ return { entries: entries.length, usage, real, costUsd };
366
+ }
367
+
368
+ /**
369
+ * Sessions for the /resume overlay: own Aegiscode sessions, sessions written
370
+ * into the shared store by another host (the desktop app), and real Claude Code
371
+ * sessions from ~/.claude/history.jsonl — newest first, deduplicated by id.
372
+ *
373
+ * The dedup matters: an own session is mirrored into the shared store, so
374
+ * without it every terminal session would be listed twice, once from each
375
+ * source.
376
+ */
377
+ function readResumeList(limit = 8, ownLimit = 5, claudeLimit = 8) {
378
+ const items = readOwnSessions(ownLimit);
379
+ const seen = new Set(items.map((i) => i.id));
380
+ const sharedItems = readSharedStoreSessions(ownLimit).filter((i) => {
381
+ if (seen.has(i.id)) return false;
382
+ seen.add(i.id);
383
+ return true;
384
+ });
385
+ const claudeItems = [];
386
+ const histPath = `${os.homedir()}/.claude/history.jsonl`;
387
+ try {
388
+ const raw = fs.readFileSync(histPath, 'utf8');
389
+ const lines = raw.trim().split('\n').reverse().slice(0, claudeLimit);
390
+ for (const l of lines) {
391
+ try {
392
+ const j = JSON.parse(l);
393
+ const meta = j.extra && JSON.parse(j.extra);
394
+ if (meta && meta.sessionId && !seen.has(meta.sessionId)) {
395
+ seen.add(meta.sessionId);
396
+ const c = cwdName(j.cwd);
397
+ const t = (j.summary || '').slice(0, 60);
398
+ claudeItems.push({ id: meta.sessionId, cwd: c, summary: t, time: j.timestamp, own: false });
399
+ }
400
+ } catch {}
401
+ }
402
+ } catch {}
403
+ return [...items, ...sharedItems, ...claudeItems]
404
+ .sort((a, b) => (String(a.time || '') < String(b.time || '') ? 1 : -1))
405
+ .slice(0, limit);
406
+ }
407
+
408
+ module.exports = {
409
+ HISTORY_LIMIT,
410
+ SOURCE,
411
+ historyPath,
412
+ ensureHistoryDir,
413
+ appendHistory,
414
+ appendHistoryEntries,
415
+ readHistoryEntries,
416
+ readOwnSessions,
417
+ readSessionTranscript,
418
+ readSharedStoreSessions,
419
+ sessionHistoryEntries,
420
+ pruneSessionHistory,
421
+ aggregateSessionUsage,
422
+ readResumeList,
423
+ setSessionTitle,
424
+ readSessionTitle,
425
+ };
package/src/init.js CHANGED
@@ -1,3 +1,177 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const fs=require("node:fs"),path=require("node:path"),{execSync:execSync}=require("node:child_process"),{pathName:pathName}=require("./format.js");function readJson(e,t){try{return JSON.parse(fs.readFileSync(path.join(t,e),"utf8"))}catch{return null}}function hasFile(e,...t){return t.some((t=>fs.existsSync(path.join(e,t))))}function gitName(e){try{const t=execSync("git config --get remote.origin.url",{encoding:"utf8",cwd:e,stdio:["ignore","pipe","ignore"]}).trim(),s=pathName(t).replace(/\.git$/,"");if(s)return s}catch{}try{return pathName(e)||"this project"}catch{return"this project"}}function sniffProject(e=process.cwd()){const t=readJson("package.json",e),s={name:t&&t.name?t.name:gitName(e),lang:"unknown",build:null,test:null,lint:null,dev:null,structure:[],toolchain:[]};if(t){s.lang="JavaScript/TypeScript (Node.js)",s.toolchain.push("Node.js");const e=t.scripts||{};e.build&&(s.build="npm run build"),e.test&&(s.test="npm test"),e.lint&&(s.lint="npm run lint"),(e.dev||e.start||e.watch)&&(s.dev=e.dev?"npm run dev":"npm start"),t.packageManager&&s.toolchain.push(t.packageManager)}else hasFile(e,"go.mod")?(s.lang="Go",s.toolchain.push("Go"),s.build="go build ./...",s.test="go test ./...",s.lint="golangci-lint run",s.dev="go run ."):hasFile(e,"Cargo.toml")?(s.lang="Rust",s.toolchain.push("Cargo"),s.build="cargo build",s.test="cargo test",s.lint="cargo clippy -- -D warnings",s.dev="cargo run"):hasFile(e,"pyproject.toml","setup.py","requirements.txt")?(s.lang="Python",s.toolchain.push("Python"),s.test=hasFile(e,"pytest.ini","tox.ini")?"pytest":"python -m pytest",s.lint="ruff check ."):hasFile(e,"Makefile")?(s.lang="C/C++ or make-driven",s.toolchain.push("make"),s.build="make",s.test="make test",s.dev="make run"):hasFile(e,"pom.xml","build.gradle")?(s.lang="Java",s.toolchain.push("Maven/Gradle"),s.build=hasFile(e,"pom.xml")?"mvn package":"gradle build",s.test=hasFile(e,"pom.xml")?"mvn test":"gradle test"):hasFile(e,"Gemfile")?(s.lang="Ruby",s.toolchain.push("Ruby"),s.test="bundle exec rspec",s.build="bundle exec rake build"):hasFile(e,"composer.json")?(s.lang="PHP",s.toolchain.push("Composer"),s.test="composer test"):hasFile(e,".csproj")&&(s.lang="C#/.NET",s.toolchain.push(".NET"),s.build="dotnet build",s.test="dotnet test");for(const t of["src","lib","app","tests","test","spec","docs","scripts"])fs.existsSync(path.join(e,t))&&s.structure.push(t);for(const t of["eslint.config.js",".eslintrc",".prettierrc","biome.json","tsconfig.json",".github/workflows"])fs.existsSync(path.join(e,t))&&s.toolchain.push(t.split("/")[0]);return s}function buildAegisMd(e){const t=e,s=[];if(s.push("# AEGIS.md"),s.push(""),s.push("Generated by AEGIS Code /init — edit freely. This file teaches AI agents how to work in this repo."),s.push(""),s.push("## Project"),s.push(""),s.push(`- Project: ${t.name}`),s.push(`- Language: ${t.lang}`),t.toolchain.length&&s.push(`- Toolchain: ${[...new Set(t.toolchain)].join(", ")}`),s.push(""),s.push("## Commands"),s.push(""),s.push("Run these to build, test, and lint:"),s.push("```bash"),t.build&&s.push(t.build+" # build"),t.test&&s.push(t.test+" # test"),t.lint&&s.push(t.lint+" # lint"),t.dev&&s.push(t.dev+" # dev server"),s.push("```"),s.push(""),t.structure.length){s.push("## Project structure"),s.push("");for(const e of t.structure)s.push(`- \`${e}/\` — ${"src"===e||"lib"===e?"source code":"tests"===e||"test"===e||"spec"===e?"tests":e}`);s.push("")}return s.push("## Coding conventions"),s.push(""),s.push("- Keep changes minimal and focused; match the surrounding style."),s.push("- Before editing a file, read it; verify with the test command above."),s.push("- Prefer the project's own scripts over ad-hoc shell commands."),s.push(""),s.join("\n")}module.exports={sniffProject:sniffProject,buildAegisMd:buildAegisMd,buildClaudeMd:buildAegisMd};
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
+ * /init support: sniff a project (language, build/test/lint commands, layout)
10
+ * and generate an AEGIS.md with real project instructions. Never overwrites an
11
+ * existing file — the handler reports and leaves the file alone.
12
+ *
13
+ * Ported from the upstream engine reference (ESM → CommonJS). The reference wrote
14
+ * a CLAUDE.md; this build writes AEGIS.md and the generated document is headed
15
+ * "# AEGIS.md" and references "AEGIS Code". The `buildClaudeMd` export is kept
16
+ * as an alias of `buildAegisMd` so callers ported from the reference still
17
+ * resolve.
18
+ */
19
+
20
+ const fs = require('node:fs');
21
+ const path = require('node:path');
22
+ const { execSync } = require('node:child_process');
23
+ const { pathName } = require('./format.js');
24
+
25
+ function readJson(p, cwd) {
26
+ try { return JSON.parse(fs.readFileSync(path.join(cwd, p), 'utf8')); } catch { return null; }
27
+ }
28
+
29
+ function hasFile(cwd, ...names) {
30
+ return names.some((n) => fs.existsSync(path.join(cwd, n)));
31
+ }
32
+
33
+ function gitName(cwd) {
34
+ try {
35
+ const remote = execSync('git config --get remote.origin.url', { encoding: 'utf8', cwd, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
36
+ // A remote is normally a posix URL, but a Windows checkout can record a
37
+ // drive path (`C:\src\foo`), and pathName reads both — it strips the same
38
+ // trailing `.git` either way.
39
+ const base = pathName(remote).replace(/\.git$/, '');
40
+ if (base) return base;
41
+ } catch {}
42
+ try {
43
+ // The project's own name is the leaf of its path — through the shared rule,
44
+ // so a Windows checkout (`C:\src\proj`) names "proj" like every other host
45
+ // instead of the whole path (see format.js).
46
+ const dir = pathName(cwd);
47
+ return dir || 'this project';
48
+ } catch { return 'this project'; }
49
+ }
50
+
51
+ /** Describe a project enough to write a useful AEGIS.md. */
52
+ function sniffProject(cwd = process.cwd()) {
53
+ const pkg = readJson('package.json', cwd);
54
+ const out = {
55
+ name: pkg && pkg.name ? pkg.name : gitName(cwd),
56
+ lang: 'unknown',
57
+ build: null,
58
+ test: null,
59
+ lint: null,
60
+ dev: null,
61
+ structure: [],
62
+ toolchain: [],
63
+ };
64
+
65
+ if (pkg) {
66
+ out.lang = 'JavaScript/TypeScript (Node.js)';
67
+ out.toolchain.push('Node.js');
68
+ const scripts = pkg.scripts || {};
69
+ if (scripts.build) out.build = `npm run build`;
70
+ if (scripts.test) out.test = `npm test`;
71
+ if (scripts.lint) out.lint = `npm run lint`;
72
+ if (scripts.dev || scripts.start || scripts.watch) out.dev = scripts.dev ? `npm run dev` : `npm start`;
73
+ if (pkg.packageManager) out.toolchain.push(pkg.packageManager);
74
+ } else if (hasFile(cwd, 'go.mod')) {
75
+ out.lang = 'Go';
76
+ out.toolchain.push('Go');
77
+ out.build = 'go build ./...';
78
+ out.test = 'go test ./...';
79
+ out.lint = 'golangci-lint run' ;
80
+ out.dev = 'go run .';
81
+ } else if (hasFile(cwd, 'Cargo.toml')) {
82
+ out.lang = 'Rust';
83
+ out.toolchain.push('Cargo');
84
+ out.build = 'cargo build';
85
+ out.test = 'cargo test';
86
+ out.lint = 'cargo clippy -- -D warnings';
87
+ out.dev = 'cargo run';
88
+ } else if (hasFile(cwd, 'pyproject.toml', 'setup.py', 'requirements.txt')) {
89
+ out.lang = 'Python';
90
+ out.toolchain.push('Python');
91
+ out.test = hasFile(cwd, 'pytest.ini', 'tox.ini') ? 'pytest' : 'python -m pytest';
92
+ out.lint = 'ruff check .';
93
+ } else if (hasFile(cwd, 'Makefile')) {
94
+ out.lang = 'C/C++ or make-driven';
95
+ out.toolchain.push('make');
96
+ out.build = 'make';
97
+ out.test = 'make test';
98
+ out.dev = 'make run';
99
+ } else if (hasFile(cwd, 'pom.xml', 'build.gradle')) {
100
+ out.lang = 'Java';
101
+ out.toolchain.push('Maven/Gradle');
102
+ out.build = hasFile(cwd, 'pom.xml') ? 'mvn package' : 'gradle build';
103
+ out.test = hasFile(cwd, 'pom.xml') ? 'mvn test' : 'gradle test';
104
+ } else if (hasFile(cwd, 'Gemfile')) {
105
+ out.lang = 'Ruby';
106
+ out.toolchain.push('Ruby');
107
+ out.test = 'bundle exec rspec';
108
+ out.build = 'bundle exec rake build';
109
+ } else if (hasFile(cwd, 'composer.json')) {
110
+ out.lang = 'PHP';
111
+ out.toolchain.push('Composer');
112
+ out.test = 'composer test';
113
+ } else if (hasFile(cwd, '.csproj')) {
114
+ out.lang = 'C#/.NET';
115
+ out.toolchain.push('.NET');
116
+ out.build = 'dotnet build';
117
+ out.test = 'dotnet test';
118
+ }
119
+
120
+ // Layout conventions.
121
+ for (const d of ['src', 'lib', 'app', 'tests', 'test', 'spec', 'docs', 'scripts']) {
122
+ if (fs.existsSync(path.join(cwd, d))) out.structure.push(d);
123
+ }
124
+ for (const f of ['eslint.config.js', '.eslintrc', '.prettierrc', 'biome.json', 'tsconfig.json', '.github/workflows']) {
125
+ // The FIRST segment of a repo-relative probe path. This one stays a literal
126
+ // split: `f` is written two lines up in repo-relative form, so its `/` is
127
+ // not a host separator. A path that arrived from the OS needs pathName().
128
+ if (fs.existsSync(path.join(cwd, f))) out.toolchain.push(f.split('/')[0]);
129
+ }
130
+
131
+ return out;
132
+ }
133
+
134
+ /** Render an AEGIS.md from a sniff result. */
135
+ function buildAegisMd(sniff) {
136
+ const s = sniff;
137
+ const lines = [];
138
+ lines.push(`# AEGIS.md`);
139
+ lines.push('');
140
+ lines.push(`Generated by AEGIS Code /init — edit freely. This file teaches AI agents how to work in this repo.`);
141
+ lines.push('');
142
+ lines.push('## Project');
143
+ lines.push('');
144
+ lines.push(`- Project: ${s.name}`);
145
+ lines.push(`- Language: ${s.lang}`);
146
+ if (s.toolchain.length) lines.push(`- Toolchain: ${[...new Set(s.toolchain)].join(', ')}`);
147
+ lines.push('');
148
+ lines.push('## Commands');
149
+ lines.push('');
150
+ lines.push('Run these to build, test, and lint:');
151
+ lines.push('```bash');
152
+ if (s.build) lines.push(s.build + ' # build');
153
+ if (s.test) lines.push(s.test + ' # test');
154
+ if (s.lint) lines.push(s.lint + ' # lint');
155
+ if (s.dev) lines.push(s.dev + ' # dev server');
156
+ lines.push('```');
157
+ lines.push('');
158
+ if (s.structure.length) {
159
+ lines.push('## Project structure');
160
+ lines.push('');
161
+ for (const d of s.structure) lines.push(`- \`${d}/\` — ${d === 'src' || d === 'lib' ? 'source code' : d === 'tests' || d === 'test' || d === 'spec' ? 'tests' : d}`);
162
+ lines.push('');
163
+ }
164
+ lines.push('## Coding conventions');
165
+ lines.push('');
166
+ lines.push('- Keep changes minimal and focused; match the surrounding style.');
167
+ lines.push('- Before editing a file, read it; verify with the test command above.');
168
+ lines.push('- Prefer the project\'s own scripts over ad-hoc shell commands.');
169
+ lines.push('');
170
+ return lines.join('\n');
171
+ }
172
+
173
+ module.exports = {
174
+ sniffProject,
175
+ buildAegisMd,
176
+ buildClaudeMd: buildAegisMd, // reference name kept for compatibility
177
+ };