aegiscode 7.0.14 → 7.0.15

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 (109) hide show
  1. package/SOURCE-OFFER.txt +9 -0
  2. package/package.json +3 -2
  3. package/scripts/check.mjs +1 -52
  4. package/scripts/demo.mjs +1 -94
  5. package/scripts/predist.mjs +1 -75
  6. package/scripts/runtests.mjs +1 -56
  7. package/scripts/seal-gate.mjs +1 -74
  8. package/src/agents.js +1 -139
  9. package/src/app.js +1 -2932
  10. package/src/art.js +1 -289
  11. package/src/chatflow.js +1 -3020
  12. package/src/checkpoint.js +1 -90
  13. package/src/clipboard.js +1 -424
  14. package/src/cloudsync.js +1 -528
  15. package/src/commands.js +1 -4003
  16. package/src/config.js +1 -581
  17. package/src/connect.js +1 -349
  18. package/src/credentials.js +1 -33
  19. package/src/deps.js +1 -232
  20. package/src/devrun.js +1 -187
  21. package/src/diff.js +1 -333
  22. package/src/diffview.js +1 -296
  23. package/src/engine.js +1 -297
  24. package/src/entitlement.js +1 -355
  25. package/src/events.js +1 -707
  26. package/src/export.js +1 -67
  27. package/src/fingerprint.js +1 -592
  28. package/src/format.js +1 -259
  29. package/src/fuzzy.js +1 -119
  30. package/src/history.js +1 -401
  31. package/src/init.js +1 -175
  32. package/src/input.js +1 -139
  33. package/src/keys.js +1 -183
  34. package/src/markdown.js +1 -306
  35. package/src/models.js +1 -487
  36. package/src/naming.js +1 -229
  37. package/src/overlays.js +1 -461
  38. package/src/panels.js +1 -1418
  39. package/src/ping.js +1 -226
  40. package/src/presence.js +1 -238
  41. package/src/render.js +1 -515
  42. package/src/screen.js +1 -518
  43. package/src/screens.js +1 -896
  44. package/src/secret.js +1 -59
  45. package/src/securefs.js +1 -359
  46. package/src/settings.js +1 -155
  47. package/src/shared.js +1 -52
  48. package/src/sharedpaths.js +1 -53
  49. package/src/signup.js +1 -156
  50. package/src/summarize.js +1 -95
  51. package/src/sysdiag.js +1 -585
  52. package/src/system.js +1 -40
  53. package/src/theme.js +1 -570
  54. package/src/title.js +1 -220
  55. package/src/todos.js +1 -115
  56. package/src/tokens.js +1 -263
  57. package/src/topup.js +1 -210
  58. package/src/update.js +1 -181
  59. package/vendor/client/aegis.js +1 -2179
  60. package/vendor/client/attest.js +1 -442
  61. package/vendor/client/authorship-key.js +1 -410
  62. package/vendor/client/auto-provision.js +1 -134
  63. package/vendor/client/brain-catalog.js +1 -268
  64. package/vendor/client/byok-catalog.js +1 -230
  65. package/vendor/client/credentials.js +1 -494
  66. package/vendor/client/device-fingerprint.js +1 -141
  67. package/vendor/client/drive-connect.js +1 -110
  68. package/vendor/client/drive-upload.js +1 -174
  69. package/vendor/client/env-file.js +1 -1273
  70. package/vendor/client/fingerprint.js +1 -1064
  71. package/vendor/client/foreign-memory.js +1 -669
  72. package/vendor/client/google-signin.js +1 -133
  73. package/vendor/client/hooks.js +1 -430
  74. package/vendor/client/model-discovery.js +1 -373
  75. package/vendor/client/platform.js +1 -937
  76. package/vendor/client/prefs.js +1 -351
  77. package/vendor/client/presence-constants.js +1 -107
  78. package/vendor/client/presence.js +1 -438
  79. package/vendor/client/record-vault.js +3 -1055
  80. package/vendor/client/session-store.js +1 -548
  81. package/vendor/client/topup.js +1 -297
  82. package/vendor/client/touch.js +1 -458
  83. package/vendor/client/update.js +1 -704
  84. package/vendor/client/user-models.js +1 -381
  85. package/vendor/desktop/lib/local/agents.js +1 -105
  86. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  87. package/vendor/desktop/lib/local/claude-pro.js +1 -993
  88. package/vendor/desktop/lib/local/context.js +1 -95
  89. package/vendor/desktop/lib/local/engine.js +1 -3301
  90. package/vendor/desktop/lib/local/entitlement.js +1 -660
  91. package/vendor/desktop/lib/local/git-scope.js +1 -228
  92. package/vendor/desktop/lib/local/local.js +1 -2135
  93. package/vendor/desktop/lib/local/prompt.js +1 -275
  94. package/vendor/desktop/lib/local/queue.js +1 -560
  95. package/vendor/desktop/lib/local/session-rounds.js +1 -208
  96. package/vendor/desktop/lib/local/shell.js +1 -680
  97. package/vendor/desktop/lib/local/tools.js +1 -1238
  98. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  99. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  100. package/vendor/desktop/lib/settings.js +1 -890
  101. package/vendor/desktop/renderer/usage.js +1 -1239
  102. package/vendor/hosts/install.js +1 -638
  103. package/vendor/hosts/openai-shim.js +1 -515
  104. package/vendor/hosts/spec.js +1 -164
  105. package/vendor/hosts/targets.js +1 -346
  106. package/vendor/mcp/server.js +1 -221
  107. package/vendor/mcp/tools.js +1 -408
  108. package/vendor/one/src/child.js +1 -285
  109. package/vendor/one/src/permissions.js +1 -369
package/src/history.js CHANGED
@@ -1,403 +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
- * 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
- function appendHistory({ sessionId, prompt, reply, status, usage, title }) {
63
- try {
64
- const entry = {
65
- ts: new Date().toISOString(),
66
- sessionId,
67
- cwd: process.cwd(),
68
- prompt,
69
- reply,
70
- status, // 'done' | 'stopped' | 'error'
71
- tokens: usage
72
- ? {
73
- input: usage.input || 0,
74
- output: usage.output || 0,
75
- cacheRead: usage.cacheRead || 0,
76
- cacheWrite: usage.cacheWrite || 0,
77
- real: true,
78
- }
79
- : { input: estimateTokens(prompt), output: estimateTokens(reply || ''), real: false },
80
- };
81
- if (usage && typeof usage.costUsd === 'number') entry.costUsd = usage.costUsd;
82
- const clean = String(title || '').trim();
83
- if (clean) entry.title = clean;
84
- return appendHistoryEntries([entry]);
85
- } catch (e) {
86
- // Persistence is best-effort; never crash the session over it.
87
- if (process.env.AEGIS_HIST_DEBUG) console.error('[history] write failed:', e);
88
- return 0;
89
- }
90
- }
91
-
92
- /**
93
- * Append a batch of already-shaped entries in ONE read/trim/write pass.
94
- *
95
- * `appendHistory` re-reads and rewrites the whole file per exchange, which is
96
- * fine for one turn at a time but quadratic for a caller with a list of them —
97
- * importing 50 pulled sessions would rewrite the file 50 times, each pass
98
- * re-parsing everything the previous pass just wrote. The single writer (and
99
- * therefore the single place the file format is defined) stays here.
100
- *
101
- * @returns {number} entries written
102
- */
103
- function appendHistoryEntries(entries) {
104
- const list = (Array.isArray(entries) ? entries : []).filter(Boolean);
105
- if (!list.length) return 0;
106
- try {
107
- ensureHistoryDir();
108
- const p = historyPath();
109
- const prev = fs.existsSync(p) ? fs.readFileSync(p, 'utf8').split('\n').filter(Boolean) : [];
110
- const lines = [...prev, ...list.map((e) => JSON.stringify(e))];
111
- const trimmed = lines.slice(Math.max(0, lines.length - HISTORY_LIMIT));
112
- // 0600: this file is every prompt and reply the session has ever had.
113
- writePrivateFile(p, trimmed.join('\n') + '\n');
114
- mirrorToSharedStore(list);
115
- return list.length;
116
- } catch (e) {
117
- // Persistence is best-effort; never crash the session over it.
118
- if (process.env.AEGIS_HIST_DEBUG) console.error('[history] write failed:', e);
119
- return 0;
120
- }
121
- }
122
-
123
- /**
124
- * Mirror freshly-recorded exchanges into the shared session store, so the
125
- * desktop and the MCP plugin can see this host's sessions.
126
- *
127
- * Only *writes* mirror — a read of history.jsonl never re-imports itself, which
128
- * is what would otherwise duplicate every exchange on every launch. A mirror
129
- * failure must never cost the user the history line it accompanies, so this is
130
- * called after the ledger write and swallows its own errors.
131
- */
132
- function mirrorToSharedStore(entries) {
133
- for (const e of entries) {
134
- try {
135
- sessionStore.recordExchange(aegisDir(), {
136
- sessionId: e.sessionId,
137
- prompt: e.prompt,
138
- reply: e.reply,
139
- status: e.status,
140
- cwd: e.cwd,
141
- ts: e.ts,
142
- tokens: e.tokens,
143
- costUsd: e.costUsd,
144
- origin: SOURCE,
145
- });
146
- } catch (err) {
147
- if (process.env.AEGIS_HIST_DEBUG) console.error('[history] mirror failed:', err);
148
- }
149
- }
150
- }
151
-
152
- function readEntries() {
153
- try {
154
- const raw = fs.readFileSync(historyPath(), 'utf8');
155
- return raw
156
- .split('\n')
157
- .map((l) => l.trim())
158
- .filter(Boolean)
159
- .map((l) => { try { return JSON.parse(l); } catch { return null; } })
160
- .filter(Boolean);
161
- } catch {
162
- return [];
163
- }
164
- }
165
-
166
- /** Every history record, oldest first. Public name for other modules. */
167
- function readHistoryEntries() {
168
- return readEntries();
169
- }
170
-
171
- /** Newest-first list of own sessions, one per distinct sessionId. */
172
- function readOwnSessions(limit = 8) {
173
- const entries = readEntries();
174
- const byId = new Map();
175
- for (const e of entries) {
176
- const cur = byId.get(e.sessionId);
177
- if (!cur) {
178
- byId.set(e.sessionId, e);
179
- continue;
180
- }
181
- // Prefer a record that carries the conversation's name — naming lands one
182
- // model round after the first exchange is persisted, so the newest record
183
- // is not necessarily the titled one. Failing that, the newest wins.
184
- if (!cur.title && e.title) byId.set(e.sessionId, e);
185
- else if (!cur.title === !e.title && String(e.ts) > String(cur.ts)) byId.set(e.sessionId, e);
186
- }
187
- const items = [...byId.values()]
188
- .sort((a, b) => (a.ts < b.ts ? 1 : -1))
189
- .slice(0, limit)
190
- .map((e) => ({
191
- id: e.sessionId,
192
- cwd: cwdName(e.cwd),
193
- // The conversation's own name when it has one (naming.js), else the old
194
- // raw-prompt fallback so a session recorded before naming existed is
195
- // still identifiable.
196
- summary: (e.title || e.prompt || '').slice(0, 60),
197
- time: e.ts,
198
- own: true,
199
- }));
200
- return items;
201
- }
202
-
203
- /**
204
- * Rebuild the transcript (user/assistant pairs) of a session, oldest first.
205
- *
206
- * history.jsonl wins when it has records for the id (this host's own ledger,
207
- * complete with the exchanges the shared store may have trimmed). Otherwise the
208
- * session came from another host — a desktop thread — and the shared store is
209
- * the only place its messages exist, so /resume can open it too.
210
- */
211
- function readSessionTranscript(sessionId) {
212
- const own = readEntries()
213
- .filter((e) => e.sessionId === sessionId)
214
- .flatMap((e) => [
215
- { role: 'user', text: e.prompt },
216
- { role: 'assistant', text: e.reply || '(no response)' },
217
- ]);
218
- if (own.length) return own;
219
- try {
220
- return sessionStore.readTranscript(aegisDir(), sessionId);
221
- } catch {
222
- return [];
223
- }
224
- }
225
-
226
- /** Sessions in the shared store written by another host (the desktop app). */
227
- function readSharedStoreSessions(limit = 8) {
228
- try {
229
- return sessionStore.listSummaries(aegisDir(), limit);
230
- } catch {
231
- return [];
232
- }
233
- }
234
-
235
- /** All history records for one session, oldest first (power /cost). */
236
- function sessionHistoryEntries(sessionId) {
237
- return readEntries().filter((e) => e.sessionId === sessionId);
238
- }
239
-
240
- /**
241
- * Stamp a conversation's name onto every record this session already has.
242
- *
243
- * Naming is one model round, run off the critical path, so it usually lands
244
- * *after* the first exchange was written to history.jsonl. Without this the
245
- * resume list would show the raw first prompt for the rest of the session's
246
- * life, because readOwnSessions() would find no `title` anywhere.
247
- *
248
- * Best-effort, like every other writer here: a failed rewrite costs a name in a
249
- * picker, never a turn. Records are rewritten to the same 0600 file via
250
- * securefs, and only the session's own lines are touched.
251
- */
252
- function setSessionTitle(sessionId, title) {
253
- const clean = String(title || '').trim();
254
- if (!clean) return 0;
255
- // The shared store is the other surface a name is read from: the desktop app
256
- // and the MCP plugin list sessions from `sessions.json`, so a name that lived
257
- // only in history.jsonl would name the session in `/resume` and leave it
258
- // unnamed in the GUI. Stamped first and unconditionally — the store may hold
259
- // this session even when the ledger does not. Best-effort, like everything
260
- // else here.
261
- try {
262
- sessionStore.setTitle(aegisDir(), sessionId, clean);
263
- } catch {
264
- /* the store is optional; the ledger below is the CLI's own */
265
- }
266
- try {
267
- const p = historyPath();
268
- if (!fs.existsSync(p)) return 0;
269
- let touched = 0;
270
- const out = fs
271
- .readFileSync(p, 'utf8')
272
- .split('\n')
273
- .map((l) => l.trim())
274
- .filter(Boolean)
275
- .map((l) => {
276
- try {
277
- const j = JSON.parse(l);
278
- if (j.sessionId !== sessionId || j.title === clean) return l;
279
- j.title = clean;
280
- touched++;
281
- return JSON.stringify(j);
282
- } catch {
283
- return l;
284
- }
285
- });
286
- if (!touched) return 0;
287
- writePrivateFile(p, out.join('\n') + '\n');
288
- return touched;
289
- } catch (e) {
290
- if (process.env.AEGIS_HIST_DEBUG) console.error('[history] title write failed:', e);
291
- return 0;
292
- }
293
- }
294
-
295
- /** The conversation's name, if any record for it carries one. */
296
- function readSessionTitle(sessionId) {
297
- const hit = readEntries().find((e) => e.sessionId === sessionId && e.title);
298
- return hit ? String(hit.title) : '';
299
- }
300
-
301
- /**
302
- * Drop every history record for a session. /clear
303
- * calls this so /cost stops summing old rows — the sessionId stays stable, so
304
- * rewind checkpoints and the transcript lineage are unaffected.
305
- */
306
- function pruneSessionHistory(sessionId) {
307
- try {
308
- const p = historyPath();
309
- if (!fs.existsSync(p)) return;
310
- const kept = fs
311
- .readFileSync(p, 'utf8')
312
- .split('\n')
313
- .map((l) => l.trim())
314
- .filter(Boolean)
315
- .filter((l) => {
316
- try { return JSON.parse(l).sessionId !== sessionId; } catch { return true; }
317
- });
318
- writePrivateFile(p, kept.length ? kept.join('\n') + '\n' : '');
319
- } catch (e) {
320
- if (process.env.AEGIS_HIST_DEBUG) console.error('[history] prune failed:', e);
321
- }
322
- }
323
-
324
- /**
325
- * Sum a session's token records across history.jsonl. Compacted-away exchanges
326
- * still count because /compact writes a summary exchange, it never deletes the
327
- * file. `real` is true only when every record carries live CLI usage numbers.
328
- */
329
- function aggregateSessionUsage(sessionId) {
330
- const entries = sessionHistoryEntries(sessionId);
331
- const usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
332
- let real = entries.length > 0;
333
- let costUsd = 0;
334
- for (const e of entries) {
335
- const t = e.tokens || {};
336
- if (!t.real) real = false;
337
- usage.input += t.input || 0;
338
- usage.output += t.output || 0;
339
- usage.cacheRead += t.cacheRead || 0;
340
- usage.cacheWrite += t.cacheWrite || 0;
341
- if (typeof e.costUsd === 'number') costUsd += e.costUsd;
342
- }
343
- return { entries: entries.length, usage, real, costUsd };
344
- }
345
-
346
- /**
347
- * Sessions for the /resume overlay: own Aegiscode sessions, sessions written
348
- * into the shared store by another host (the desktop app), and real Claude Code
349
- * sessions from ~/.claude/history.jsonl — newest first, deduplicated by id.
350
- *
351
- * The dedup matters: an own session is mirrored into the shared store, so
352
- * without it every terminal session would be listed twice, once from each
353
- * source.
354
- */
355
- function readResumeList(limit = 8, ownLimit = 5, claudeLimit = 8) {
356
- const items = readOwnSessions(ownLimit);
357
- const seen = new Set(items.map((i) => i.id));
358
- const sharedItems = readSharedStoreSessions(ownLimit).filter((i) => {
359
- if (seen.has(i.id)) return false;
360
- seen.add(i.id);
361
- return true;
362
- });
363
- const claudeItems = [];
364
- const histPath = `${os.homedir()}/.claude/history.jsonl`;
365
- try {
366
- const raw = fs.readFileSync(histPath, 'utf8');
367
- const lines = raw.trim().split('\n').reverse().slice(0, claudeLimit);
368
- for (const l of lines) {
369
- try {
370
- const j = JSON.parse(l);
371
- const meta = j.extra && JSON.parse(j.extra);
372
- if (meta && meta.sessionId && !seen.has(meta.sessionId)) {
373
- seen.add(meta.sessionId);
374
- const c = cwdName(j.cwd);
375
- const t = (j.summary || '').slice(0, 60);
376
- claudeItems.push({ id: meta.sessionId, cwd: c, summary: t, time: j.timestamp, own: false });
377
- }
378
- } catch {}
379
- }
380
- } catch {}
381
- return [...items, ...sharedItems, ...claudeItems]
382
- .sort((a, b) => (String(a.time || '') < String(b.time || '') ? 1 : -1))
383
- .slice(0, limit);
384
- }
385
-
386
- module.exports = {
387
- HISTORY_LIMIT,
388
- SOURCE,
389
- historyPath,
390
- ensureHistoryDir,
391
- appendHistory,
392
- appendHistoryEntries,
393
- readHistoryEntries,
394
- readOwnSessions,
395
- readSessionTranscript,
396
- readSharedStoreSessions,
397
- sessionHistoryEntries,
398
- pruneSessionHistory,
399
- aggregateSessionUsage,
400
- readResumeList,
401
- setSessionTitle,
402
- readSessionTitle,
403
- };
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}){try{const o={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&&(o.costUsd=i.costUsd);const a=String(n||"").trim();return a&&(o.title=a),appendHistoryEntries([o])}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,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};
package/src/init.js CHANGED
@@ -1,177 +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
- * /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
- };
3
+ const t=require("node:fs"),e=require("node:path"),{execSync:s}=require("node:child_process"),{pathName:n}=require("./format.js");function o(s,...n){return n.some((n=>t.existsSync(e.join(s,n))))}function i(t){try{const e=s("git config --get remote.origin.url",{encoding:"utf8",cwd:t,stdio:["ignore","pipe","ignore"]}).trim(),o=n(e).replace(/\.git$/,"");if(o)return o}catch{}try{return n(t)||"this project"}catch{return"this project"}}function u(t){const e=t,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: ${e.name}`),s.push(`- Language: ${e.lang}`),e.toolchain.length&&s.push(`- Toolchain: ${[...new Set(e.toolchain)].join(", ")}`),s.push(""),s.push("## Commands"),s.push(""),s.push("Run these to build, test, and lint:"),s.push("```bash"),e.build&&s.push(e.build+" # build"),e.test&&s.push(e.test+" # test"),e.lint&&s.push(e.lint+" # lint"),e.dev&&s.push(e.dev+" # dev server"),s.push("```"),s.push(""),e.structure.length){s.push("## Project structure"),s.push("");for(const t of e.structure)s.push(`- \`${t}/\` — ${"src"===t||"lib"===t?"source code":"tests"===t||"test"===t||"spec"===t?"tests":t}`);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:function(s=process.cwd()){const n=function(s,n){try{return JSON.parse(t.readFileSync(e.join(n,"package.json"),"utf8"))}catch{return null}}(0,s),u={name:n&&n.name?n.name:i(s),lang:"unknown",build:null,test:null,lint:null,dev:null,structure:[],toolchain:[]};if(n){u.lang="JavaScript/TypeScript (Node.js)",u.toolchain.push("Node.js");const t=n.scripts||{};t.build&&(u.build="npm run build"),t.test&&(u.test="npm test"),t.lint&&(u.lint="npm run lint"),(t.dev||t.start||t.watch)&&(u.dev=t.dev?"npm run dev":"npm start"),n.packageManager&&u.toolchain.push(n.packageManager)}else o(s,"go.mod")?(u.lang="Go",u.toolchain.push("Go"),u.build="go build ./...",u.test="go test ./...",u.lint="golangci-lint run",u.dev="go run ."):o(s,"Cargo.toml")?(u.lang="Rust",u.toolchain.push("Cargo"),u.build="cargo build",u.test="cargo test",u.lint="cargo clippy -- -D warnings",u.dev="cargo run"):o(s,"pyproject.toml","setup.py","requirements.txt")?(u.lang="Python",u.toolchain.push("Python"),u.test=o(s,"pytest.ini","tox.ini")?"pytest":"python -m pytest",u.lint="ruff check ."):o(s,"Makefile")?(u.lang="C/C++ or make-driven",u.toolchain.push("make"),u.build="make",u.test="make test",u.dev="make run"):o(s,"pom.xml","build.gradle")?(u.lang="Java",u.toolchain.push("Maven/Gradle"),u.build=o(s,"pom.xml")?"mvn package":"gradle build",u.test=o(s,"pom.xml")?"mvn test":"gradle test"):o(s,"Gemfile")?(u.lang="Ruby",u.toolchain.push("Ruby"),u.test="bundle exec rspec",u.build="bundle exec rake build"):o(s,"composer.json")?(u.lang="PHP",u.toolchain.push("Composer"),u.test="composer test"):o(s,".csproj")&&(u.lang="C#/.NET",u.toolchain.push(".NET"),u.build="dotnet build",u.test="dotnet test");for(const n of["src","lib","app","tests","test","spec","docs","scripts"])t.existsSync(e.join(s,n))&&u.structure.push(n);for(const n of["eslint.config.js",".eslintrc",".prettierrc","biome.json","tsconfig.json",".github/workflows"])t.existsSync(e.join(s,n))&&u.toolchain.push(n.split("/")[0]);return u},buildAegisMd:u,buildClaudeMd:u};