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
@@ -1,3 +1,520 @@
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 crypto=require("node:crypto"),fs=require("node:fs"),path=require("node:path"),fp=require("./fingerprint.js"),authorship=require("./authorship-key.js"),envFile=require("./env-file.js"),DEFAULT_HISTORY=()=>path.join(authorship.dataDir(),"history.jsonl"),DIR_KEYS=["cwd","dir","workspace","root"],DEMAND_KEYS=["demand","prompt","task","text","content"],OUTCOME_KEYS=["outcome","status","result"],SESSION_KEYS=["session","sessionId","session_id"],TIME_KEYS=["at","ts","time","createdAt"],REPLY_KEYS=["reply","answer","response"],MODEL_KEYS=["model","aiModel","modelId"],sha256hex=e=>crypto.createHash("sha256").update(String(e||""),"utf8").digest("hex"),AI_SECRET_ENV="AEGIS_AI_SECRET";function firstKey(e,t){for(const r of t){const t=e[r];if(null==t)continue;const o="string"==typeof t?t:String(t);if(""!==o.trim())return o}return null}function readHistory(e){if(!fs.existsSync(e))throw new Error(`attest: no session log at ${e}`);const t=[];let r=0;for(const o of fs.readFileSync(e,"utf8").split("\n")){const e=o.trim();if(e)try{const o=JSON.parse(e);o&&"object"==typeof o?t.push(o):r+=1}catch{r+=1}}return{entries:t,skipped:r}}function lastSessionId(e){for(let t=e.length-1;t>=0;t-=1){const r=firstKey(e[t],SESSION_KEYS);if(r)return r}return null}function selectTurns(e,{session:t=null,turns:r=null}={}){let o=e;if(t){const r=String(t);o=e.filter((e=>firstKey(e,SESSION_KEYS)===r))}return r&&Number.isFinite(Number(r))&&Number(r)>0&&(o=o.slice(-Math.floor(Number(r)))),o}function observationsFromTurns(e){const t=[];for(const r of Array.isArray(e)?e:[]){if(!r||"object"!=typeof r)continue;const e=firstKey(r,DIR_KEYS),o=firstKey(r,DEMAND_KEYS);t.push({tool:o||e?"turn":null,target:`${e?path.basename(e):"?"}#${sha256hex(o||"").slice(0,8)}`,outcome:firstKey(r,OUTCOME_KEYS)})}return t}function aiObservationsFromTurns(e){const t=[];for(const r of Array.isArray(e)?e:[]){if(!r||"object"!=typeof r)continue;const e=firstKey(r,REPLY_KEYS),o=firstKey(r,OUTCOME_KEYS),s=firstKey(r,MODEL_KEYS),n=Boolean(e||o||s);t.push({tool:n?"reply":null,target:n?`reply#${sha256hex(e||"").slice(0,8)}`:null,outcome:o||null,model:s})}return t}function resolveAiSecret(e={}){const t=e.argv||[],r=e.env||{},o=firstFlag(t,["--ai-secret","--ai-secret-file"]);if(o){const e=fs.readFileSync(o,"utf8").trim();if(!e)throw new Error(`attest: ${o} is empty — an empty AI credential is not one`);return{secret:e,source:o}}const s=r[AI_SECRET_ENV]&&String(r[AI_SECRET_ENV]).trim();if(s)return{secret:s,source:AI_SECRET_ENV};const n=String(e.aiModel||e.model||"").trim();if(n&&"function"==typeof envFile.providerForModelId){const t=envFile.providerForModelId(n,e.cls);if(t){const e=envFile.providerKeyFromEnv(t,r);if(e&&e.key)return{secret:e.key,source:e.env};const o=providerKeyFromFile(t,r);if(o)return o}}return{secret:null,source:"none"}}function providerKeyFromFile(e,t){const r="function"==typeof envFile.envVarFor?envFile.envVarFor(e):"";if(!r)return null;const o=t&&(t.AEGIS_HOME||t.AEGISCODE_HOME)?String(t.AEGIS_HOME||t.AEGISCODE_HOME):void 0;let s;try{s=envFile.parseEnvText(fs.readFileSync(envFile.envFileFor(o),"utf8"))}catch{return null}const n=s&&"string"==typeof s[r]?s[r].trim():"";return n&&("function"!=typeof envFile.credentialLooksUsable||envFile.credentialLooksUsable(n))?{secret:n,source:r}:null}function firstFlag(e,t){for(const r of t){const t=e.indexOf(r);if(-1!==t&&void 0!==e[t+1]&&!String(e[t+1]).startsWith("--"))return e[t+1]}return null}const SKIP_DIRS=new Set([".git","node_modules","dist","build","out","vendor",".venv","venv","__pycache__",".next",".cache","release","coverage"]),MAX_FILE_BYTES=2097152,MAX_FILES=4096;function collectCode({roots:e=[],files:t=[],skip:r=[]}={}){const o=new Set(r),s=[],n=(e,t)=>{const r=fs.statSync(t);if(!r.isFile())return;if(r.size>2097152)throw new Error(`attest: ${t} is ${r.size} bytes — too large to attest (max 2097152)`);if(s.length>=4096)throw new Error("attest: more than 4096 files — refusing to attest a partial walk");const o=fp.normaliseCodePath(e);o&&s.push({path:o,content:fs.readFileSync(t,"utf8")})};for(const t of e){const e=path.resolve(t),r=(e,t)=>{for(const s of fs.readdirSync(e).sort()){const i=path.join(e,s),c=t?`${t}/${s}`:s,l=fs.lstatSync(i);if(!l.isSymbolicLink())if(l.isDirectory()){if(SKIP_DIRS.has(s)||o.has(s))continue;r(i,c)}else n(c,i)}};r(e,"")}for(const e of t){const t=path.resolve(e);n(path.basename(t),t)}return s}function mintSession(e={}){const t=e.key||authorship.resolveKey(e);if(!t.secret)throw new Error(`attest: no authorship key — run \`aegiscode fingerprint keygen\`, set ${authorship.SECRET_ENV}, or pass --secret <file>`);const r=e.history||DEFAULT_HISTORY(),{entries:o,skipped:s}=readHistory(r),n=selectTurns(o,{session:e.session||lastSessionId(o),turns:e.turns}),i=observationsFromTurns(n),c=e.code||[],l=e.aiObservations||aiObservationsFromTurns(n),a=void 0!==e.aiModel&&null!==e.aiModel?e.aiModel:l.map((e=>e.model)).filter(Boolean).pop()||"",u=void 0===e.aiSecret?resolveAiSecret({...e,aiModel:a}):{secret:e.aiSecret,source:e.aiSecret?"caller":"none"},S=fp.mint({secret:t.secret,label:e.label,account:e.account,model:e.model,tools:e.tools,observations:i,code:c,codeDirty:void 0===e.codeDirty?null:e.codeDirty,aiSecret:u.secret,aiModel:a,aiObservations:l,createdAt:e.createdAt||void 0});return{record:S,keySource:t.source,public:t.public,samples:S.behaviourSamples,observations:i.length,aiKeySource:u.source,aiSamples:S.aiSamples,skippedLines:s}}module.exports={DEFAULT_HISTORY:DEFAULT_HISTORY,DIR_KEYS:DIR_KEYS,DEMAND_KEYS:DEMAND_KEYS,OUTCOME_KEYS:OUTCOME_KEYS,SESSION_KEYS:SESSION_KEYS,REPLY_KEYS:REPLY_KEYS,MODEL_KEYS:MODEL_KEYS,AI_SECRET_ENV:AI_SECRET_ENV,TIME_KEYS:TIME_KEYS,SKIP_DIRS:SKIP_DIRS,MAX_FILE_BYTES:2097152,MAX_FILES:4096,firstKey:firstKey,readHistory:readHistory,lastSessionId:lastSessionId,selectTurns:selectTurns,observationsFromTurns:observationsFromTurns,aiObservationsFromTurns:aiObservationsFromTurns,resolveAiSecret:resolveAiSecret,collectCode:collectCode,mintSession:mintSession};
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
+ * attest.js — turn a session into a φ(α) record.
10
+ *
11
+ * `client/fingerprint.js` knows how to seal a record from *inputs*; it knows
12
+ * nothing about where those inputs live, and that is deliberate — the vendored
13
+ * module must stay byte-identical to the engine's, so nothing host-specific can
14
+ * be added to it. This file is that missing half, shared by the CLI and the
15
+ * desktop so both hosts attest a session the same way: the same log is read the
16
+ * same way, thumbed into the same observations, and sealed under the same key.
17
+ *
18
+ * ## What the fields may be
19
+ *
20
+ * The engine's rule (see `src/fingerprint.js`) is that a record may carry only
21
+ * what was actually observed: a fabricated field is not evidence. Carried over
22
+ * literally here, that means this module never invents a value to fill a shape:
23
+ *
24
+ * - a session log entry that carries no recognisable working directory
25
+ * contributes `dir: null`, not `process.cwd()`;
26
+ * - a turn with no recorded outcome contributes `outcome: null`, not `'ok'`;
27
+ * - `--turns N` that selects more turns than exist attests the turns there
28
+ * are, and the record's `behaviourSamples` then says how many that was.
29
+ *
30
+ * A null field is a true statement about the log ("the log did not say"); a
31
+ * guessed one is a false statement about the session. The engine's `verify`
32
+ * compares the attestation over these fields, so the difference is not
33
+ * cosmetic — it is the difference between a record that reproduces and one
34
+ * that does not.
35
+ *
36
+ * ## Schema tolerance, and why it stops where it does
37
+ *
38
+ * The session log has carried more than one entry shape across versions, so
39
+ * each turn is read through a small ordered list of aliases (`cwd`/`dir`,
40
+ * `demand`/`prompt`/…). Unknown keys are ignored rather than merged in, because
41
+ * an unknown key is a key nobody has agreed on the meaning of, and including it
42
+ * would make the behavioural axis change silently the first time a log gained a
43
+ * field. Adding an alias here is a deliberate act with a test behind it.
44
+ */
45
+
46
+ const crypto = require('node:crypto');
47
+ const fs = require('node:fs');
48
+ const path = require('node:path');
49
+
50
+ const fp = require('./fingerprint.js');
51
+ const authorship = require('./authorship-key.js');
52
+ // The one file a provider key is WRITTEN to. Read here so the AI axis can name
53
+ // the credential the session actually ran on instead of only the two rungs a
54
+ // user had to export by hand — see resolveAiSecret's third rung.
55
+ const envFile = require('./env-file.js');
56
+
57
+ const DEFAULT_HISTORY = () => path.join(authorship.dataDir(), 'history.jsonl');
58
+
59
+ /** Ordered aliases. First present key wins; a later alias never overrides one. */
60
+ const DIR_KEYS = ['cwd', 'dir', 'workspace', 'root'];
61
+ const DEMAND_KEYS = ['demand', 'prompt', 'task', 'text', 'content'];
62
+ const OUTCOME_KEYS = ['outcome', 'status', 'result'];
63
+ const SESSION_KEYS = ['session', 'sessionId', 'session_id'];
64
+ const TIME_KEYS = ['at', 'ts', 'time', 'createdAt'];
65
+
66
+ /**
67
+ * The AI half's aliases. Separate lists from the human half's on purpose: `text`
68
+ * is a demand in `DEMAND_KEYS` and a reply would be one here, and a shared list
69
+ * would let one axis read the other's field — which is exactly the conflation the
70
+ * two signatures exist to prevent.
71
+ */
72
+ const REPLY_KEYS = ['reply', 'answer', 'response'];
73
+ const MODEL_KEYS = ['model', 'aiModel', 'modelId'];
74
+
75
+ /** `sha256(text)[0:8]` — a content address, never the content. */
76
+ const sha256hex = (text) => crypto.createHash('sha256').update(String(text || ''), 'utf8').digest('hex');
77
+
78
+ /** Where the AI credential comes from: `--ai-secret FILE`, then `AEGIS_AI_SECRET`,
79
+ * then the provider key already held for the answering model (resolveAiSecret). */
80
+ const AI_SECRET_ENV = 'AEGIS_AI_SECRET';
81
+
82
+ function firstKey(entry, keys) {
83
+ for (const k of keys) {
84
+ const v = entry[k];
85
+ if (v === undefined || v === null) continue;
86
+ const s = typeof v === 'string' ? v : String(v);
87
+ if (s.trim() !== '') return s;
88
+ }
89
+ return null;
90
+ }
91
+
92
+ /**
93
+ * Read a session log.
94
+ *
95
+ * A malformed line is skipped, not fatal: a half-written last line is the
96
+ * normal state of an append-only log that was interrupted, and refusing the
97
+ * whole file over it would mean the sessions with the most history — the ones
98
+ * worth attesting — are the ones that cannot be.
99
+ */
100
+ function readHistory(file) {
101
+ if (!fs.existsSync(file)) throw new Error(`attest: no session log at ${file}`);
102
+ const entries = [];
103
+ let skipped = 0;
104
+ for (const line of fs.readFileSync(file, 'utf8').split('\n')) {
105
+ const text = line.trim();
106
+ if (!text) continue;
107
+ try {
108
+ const parsed = JSON.parse(text);
109
+ if (parsed && typeof parsed === 'object') entries.push(parsed);
110
+ else skipped += 1;
111
+ } catch {
112
+ skipped += 1;
113
+ }
114
+ }
115
+ return { entries, skipped };
116
+ }
117
+
118
+ /** The last session id the log mentions, which is what "current" means. */
119
+ function lastSessionId(entries) {
120
+ for (let i = entries.length - 1; i >= 0; i -= 1) {
121
+ const id = firstKey(entries[i], SESSION_KEYS);
122
+ if (id) return id;
123
+ }
124
+ return null;
125
+ }
126
+
127
+ /**
128
+ * Select the turns to attest.
129
+ *
130
+ * With no `session`, the last session in the log is used — attributed rather
131
+ * than assumed: turns whose session id is missing are included only when no
132
+ * session was requested, since "which session is this?" is exactly the question
133
+ * they cannot answer.
134
+ */
135
+ function selectTurns(entries, { session = null, turns = null } = {}) {
136
+ let chosen = entries;
137
+ if (session) {
138
+ const wanted = String(session);
139
+ chosen = entries.filter((e) => firstKey(e, SESSION_KEYS) === wanted);
140
+ }
141
+ if (turns && Number.isFinite(Number(turns)) && Number(turns) > 0) {
142
+ chosen = chosen.slice(-Math.floor(Number(turns)));
143
+ }
144
+ return chosen;
145
+ }
146
+
147
+ /**
148
+ * Fold turns into observations.
149
+ *
150
+ * The keys are the ENGINE's (`fp.observationKey` reads `tool`, `target`,
151
+ * `outcome`, `model`) and nothing else, because an observation is hashed by
152
+ * reading those four fields and a field with another name is silently dropped —
153
+ * it never reaches the signature it was handed over to feed. An earlier version of
154
+ * this function emitted `{dir, demand, outcome}` and read as if the demand were
155
+ * attested; it was not, so the behavioural axis of every record minted from a
156
+ * session log described the turn outcomes alone.
157
+ *
158
+ * So the two true things this log says about a turn are carried as the engine's
159
+ * fields: where it ran and what was asked for. `target` is a content address of
160
+ * the demand rather than the demand itself — the signature exists to compare
161
+ * agents, not to archive what they were told — and it is addressed exactly as
162
+ * `aegiscodex`'s own tool addresses it, so the two hosts read one session log into
163
+ * one digest.
164
+ *
165
+ * `outcome` stays `null` when the log did not record one, and a null field
166
+ * contributes no signal: `behaviouralSignature` drops an observation that carries
167
+ * nothing, and `behaviourSamples` counts what was actually attested.
168
+ */
169
+ function observationsFromTurns(turns) {
170
+ const out = [];
171
+ for (const t of Array.isArray(turns) ? turns : []) {
172
+ if (!t || typeof t !== 'object') continue;
173
+ const dir = firstKey(t, DIR_KEYS);
174
+ const demand = firstKey(t, DEMAND_KEYS);
175
+ out.push({
176
+ tool: demand || dir ? 'turn' : null,
177
+ target: `${dir ? path.basename(dir) : '?'}#${sha256hex(demand || '').slice(0, 8)}`,
178
+ outcome: firstKey(t, OUTCOME_KEYS),
179
+ });
180
+ }
181
+ return out;
182
+ }
183
+
184
+ /**
185
+ * Fold the same turns from the *reply* side: the AI axis's observations.
186
+ *
187
+ * One observation per turn, carrying only what the entry records about the
188
+ * answer — the tool it named (usually none), the working directory it ran in, the
189
+ * outcome, and the model that produced it. Every one of those is `null` when the
190
+ * log did not say, and `null` contributes no signal: `fp.aiSignature` hashes only
191
+ * the observations that carry something, and `aiSamples` counts those. A log that
192
+ * records nothing about the answers therefore yields `ai: null, aiSamples: 0` —
193
+ * "the log did not say" — rather than a signature over a row of empty fields.
194
+ *
195
+ * The reply text is deliberately NOT hashed. It would be a transcript hash wearing
196
+ * a behavioural signature's name: two agents answering the same demand in
197
+ * different words would stop matching, and the axis is meant to compare habits,
198
+ * not prose. `--ai-observations` (the engine CLI) is where a caller who has real
199
+ * tool-level AI observations passes them.
200
+ */
201
+ function aiObservationsFromTurns(turns) {
202
+ const out = [];
203
+ for (const t of Array.isArray(turns) ? turns : []) {
204
+ if (!t || typeof t !== 'object') continue;
205
+ const reply = firstKey(t, REPLY_KEYS);
206
+ const status = firstKey(t, OUTCOME_KEYS);
207
+ const model = firstKey(t, MODEL_KEYS);
208
+ // "Answered" is evidence about the ANSWER. A turn the log recorded with no
209
+ // reply, no status and no model contributes an all-null observation, which
210
+ // `fp.aiSignature` drops: "the log never said" must stay distinct from a
211
+ // signature over a pretend answer, and the working directory the human side
212
+ // already carries must not be re-read as if it were the AI's evidence.
213
+ const answered = Boolean(reply || status || model);
214
+ out.push({
215
+ tool: answered ? 'reply' : null,
216
+ // The reply is addressed, not archived — the same discipline the engine tool
217
+ // uses for a demand, and it is why both hosts read one log into one digest.
218
+ target: answered ? `reply#${sha256hex(reply || '').slice(0, 8)}` : null,
219
+ outcome: status || null,
220
+ model,
221
+ });
222
+ }
223
+ return out;
224
+ }
225
+
226
+ /**
227
+ * Resolve the AI credential: `--ai-secret FILE`, then `$AEGIS_AI_SECRET`, else no
228
+ * key.
229
+ *
230
+ * `--ai-secret` is an alias for the engine's `--ai-secret-file` spelling, and both
231
+ * are checked because the two hosts' users read different docs. The authorship
232
+ * ladder is NOT consulted: `keyFingerprint` of the sealing key would make every
233
+ * record claim it ran on its author's key, and "which mind answered" would stop
234
+ * being a question with an answer. No key nominated ⇒ `null`, which the record
235
+ * states plainly.
236
+ */
237
+ function resolveAiSecret(o = {}) {
238
+ const argv = o.argv || [];
239
+ const env = o.env || {};
240
+ const file = firstFlag(argv, ['--ai-secret', '--ai-secret-file']);
241
+ if (file) {
242
+ const secret = fs.readFileSync(file, 'utf8').trim();
243
+ if (!secret) throw new Error(`attest: ${file} is empty — an empty AI credential is not one`);
244
+ return { secret, source: file };
245
+ }
246
+ const envSecret = env[AI_SECRET_ENV] && String(env[AI_SECRET_ENV]).trim();
247
+ if (envSecret) return { secret: envSecret, source: AI_SECRET_ENV };
248
+
249
+ // Third rung: the provider credential this machine already HOLDS for the model
250
+ // that answered (`DEEPSEEK_API_KEY` in `~/.aegiscode/.env`, written there by
251
+ // the picker). Without it `aiKey` was null on every record whose user never
252
+ // exported a second, hand-made variable — so `same(a, b, 'ai-credential')`,
253
+ // the "same mind?" question the axis exists to answer, had no answer on any
254
+ // real conversation while the field itself looked merely optional.
255
+ //
256
+ // This NOMINATES an existing credential; it does not copy, log or export one.
257
+ // Only the key's fingerprint ever reaches the record (never a field, never a
258
+ // substring — rule 2), so the file that holds the key stays the only place
259
+ // that holds it. An id naming no known vendor (`nexus-*` pooled rows) resolves
260
+ // to no variable, and the axis stays honestly unobserved rather than claiming
261
+ // the account key as the mind that answered.
262
+ const modelId = String(o.aiModel || o.model || '').trim();
263
+ if (modelId && typeof envFile.providerForModelId === 'function') {
264
+ const provider = envFile.providerForModelId(modelId, o.cls);
265
+ if (provider) {
266
+ const found = envFile.providerKeyFromEnv(provider, env);
267
+ if (found && found.key) return { secret: found.key, source: found.env };
268
+ // The environment is a SNAPSHOT of the file, not the file. A host that
269
+ // loads `~/.aegiscode/.env` at start-up and then keeps its own copy of
270
+ // `process.env` (the desktop's fingerprint service does exactly that)
271
+ // never sees a provider key saved LATER in the same session: the picker
272
+ // writes it to the file through `setEnvValue`, the copy still has no such
273
+ // variable, and the seal that follows mints `aiKey: null` beside a model
274
+ // it just named. Reading the file here closes that without giving any
275
+ // host a second credential store — this is the same file, asked again.
276
+ const fromFile = providerKeyFromFile(provider, env);
277
+ if (fromFile) return fromFile;
278
+ }
279
+ }
280
+ return { secret: null, source: 'none' };
281
+ }
282
+
283
+ /**
284
+ * The provider credential as it stands ON DISK right now.
285
+ *
286
+ * `providerKeyFromEnv` reads the environment, which is only ever as fresh as the
287
+ * last `loadEnvFile()`. This re-reads the one file a provider key is written to,
288
+ * so "saved in the app a minute ago" and "saved before the app started" are the
289
+ * same answer. Same floor as the env reader: a value too short to be a
290
+ * credential is not one, and yields no key rather than an upstream 401.
291
+ */
292
+ function providerKeyFromFile(provider, env) {
293
+ const name = typeof envFile.envVarFor === 'function' ? envFile.envVarFor(provider) : '';
294
+ if (!name) return null;
295
+ // The shared modules put the store in `AEGIS_HOME`; env-file resolves
296
+ // `$AEGISCODE_HOME` too (that is the variable its own `aegisHome()` reads).
297
+ // Both are honoured here, from the SAME env this mint was given, so a host
298
+ // that scoped itself to a temp dir cannot read the real user's key by
299
+ // accident — the fallback below is that scoped dir, never the ambient one.
300
+ const dir = env && (env.AEGIS_HOME || env.AEGISCODE_HOME)
301
+ ? String(env.AEGIS_HOME || env.AEGISCODE_HOME)
302
+ : undefined;
303
+ let parsed;
304
+ try {
305
+ parsed = envFile.parseEnvText(fs.readFileSync(envFile.envFileFor(dir), 'utf8'));
306
+ } catch {
307
+ return null; // absent or unreadable is simply "no key", never an error
308
+ }
309
+ const key = parsed && typeof parsed[name] === 'string' ? parsed[name].trim() : '';
310
+ if (!key) return null;
311
+ if (typeof envFile.credentialLooksUsable === 'function' && !envFile.credentialLooksUsable(key)) {
312
+ return null;
313
+ }
314
+ return { secret: key, source: name };
315
+ }
316
+
317
+ /** `--flag V`, first spelling that matches. Local so this file keeps no argv helper. */
318
+ function firstFlag(argv, names) {
319
+ for (const name of names) {
320
+ const i = argv.indexOf(name);
321
+ if (i !== -1 && argv[i + 1] !== undefined && !String(argv[i + 1]).startsWith('--')) {
322
+ return argv[i + 1];
323
+ }
324
+ }
325
+ return null;
326
+ }
327
+
328
+ /**
329
+ * Walk a directory and return `{path, content}` records for the code axis.
330
+ *
331
+ * The key names are the engine's (`codeDigest` reads `f.path`), not this
332
+ * module's choice: a mismatch here yields `codeFiles: 0` and a null axis —
333
+ * silently, since the engine treats an unusable path as "not a file" rather
334
+ * than as an error. `test/fingerprint.test.mjs` pins the count for that reason.
335
+ *
336
+ * Symlinks are not followed and the noisy trees are skipped, matching the
337
+ * engine tool: the axis is meant to say *which revision of which files*, and a
338
+ * walk that followed a symlink out of the declared root, or dragged in
339
+ * `node_modules`, would attest something other than the user's code. An
340
+ * oversized file throws rather than attesting a hole in the digest.
341
+ */
342
+ const SKIP_DIRS = new Set([
343
+ '.git',
344
+ 'node_modules',
345
+ 'dist',
346
+ 'build',
347
+ 'out',
348
+ 'vendor',
349
+ '.venv',
350
+ 'venv',
351
+ '__pycache__',
352
+ '.next',
353
+ '.cache',
354
+ 'release',
355
+ 'coverage',
356
+ ]);
357
+ const MAX_FILE_BYTES = 2 * 1024 * 1024;
358
+ const MAX_FILES = 4096;
359
+
360
+ function collectCode({ roots = [], files = [], skip = [] } = {}) {
361
+ const extraSkip = new Set(skip);
362
+ const out = [];
363
+ const add = (relpath, abs) => {
364
+ const st = fs.statSync(abs);
365
+ if (!st.isFile()) return;
366
+ if (st.size > MAX_FILE_BYTES) {
367
+ throw new Error(`attest: ${abs} is ${st.size} bytes — too large to attest (max ${MAX_FILE_BYTES})`);
368
+ }
369
+ if (out.length >= MAX_FILES) {
370
+ throw new Error(`attest: more than ${MAX_FILES} files — refusing to attest a partial walk`);
371
+ }
372
+ const rel = fp.normaliseCodePath(relpath);
373
+ if (!rel) return; // a path the engine cannot use is not a code file
374
+ out.push({ path: rel, content: fs.readFileSync(abs, 'utf8') });
375
+ };
376
+
377
+ for (const root of roots) {
378
+ const abs = path.resolve(root);
379
+ const walk = (dir, prefix) => {
380
+ for (const name of fs.readdirSync(dir).sort()) {
381
+ const full = path.join(dir, name);
382
+ const rel = prefix ? `${prefix}/${name}` : name;
383
+ const st = fs.lstatSync(full);
384
+ if (st.isSymbolicLink()) continue; // never leave the declared root
385
+ if (st.isDirectory()) {
386
+ if (SKIP_DIRS.has(name) || extraSkip.has(name)) continue;
387
+ walk(full, rel);
388
+ continue;
389
+ }
390
+ add(rel, full);
391
+ }
392
+ };
393
+ walk(abs, '');
394
+ }
395
+
396
+ for (const file of files) {
397
+ const abs = path.resolve(file);
398
+ add(path.basename(abs), abs);
399
+ }
400
+
401
+ return out;
402
+ }
403
+
404
+ /**
405
+ * Mint a record for a session.
406
+ *
407
+ * @param {object} o
408
+ * @param {string[]} [o.argv] flags; `--secret`/`--secret-file` are read here
409
+ * @param {object} [o.env]
410
+ * @param {string} [o.history] session log (default `$AEGIS_HOME/history.jsonl`)
411
+ * @param {string} [o.session] session id (default: the last one in the log)
412
+ * @param {number} [o.turns] only the last N turns
413
+ * @param {string} [o.label]
414
+ * @param {string} [o.account]
415
+ * @param {string} [o.model]
416
+ * @param {string[]} [o.tools]
417
+ * @param {object[]} [o.code] output of `collectCode`
418
+ * @param {boolean?} [o.codeDirty]
419
+ * @param {string} [o.createdAt] pin the record's timestamp
420
+
421
+ * `createdAt` is a pass-through to the engine's `mint`, which otherwise stamps
422
+ * the record with the current time. That default is right for a session being
423
+ * sealed now and wrong for the one thing this module is used for besides that:
424
+ * two hosts attesting the *same* session must produce the *same* record, and
425
+ * they cannot if each stampes its own millisecond. It is also what lets a
426
+ * record be re-sealed at the time it originally described. It is deliberately
427
+ * not exposed as a CLI flag — a hand-set timestamp on an ordinary mint would
428
+ * let a caller backdate evidence, which is exactly what the record exists to
429
+ * prevent.
430
+ * @param {string|null} [o.aiSecret] the credential the session ran on. Passed
431
+ * in, resolved from `--ai-secret`/
432
+ * `$AEGIS_AI_SECRET`, or explicitly null.
433
+ * @param {string} [o.aiModel] the model that answered.
434
+ * @param {object[]} [o.aiObservations] the replies' observations; derived from
435
+ * the turns when omitted.
436
+ * @returns {{record: object, keySource: string, public: boolean, samples: number,
437
+ * observations: number, aiKeySource: string, aiSamples: number,
438
+ * skippedLines: number}}
439
+ */
440
+ function mintSession(o = {}) {
441
+ const key = o.key || authorship.resolveKey(o);
442
+ if (!key.secret) {
443
+ throw new Error(
444
+ 'attest: no authorship key — run `aegiscode fingerprint keygen`, set ' +
445
+ `${authorship.SECRET_ENV}, or pass --secret <file>`,
446
+ );
447
+ }
448
+
449
+ const history = o.history || DEFAULT_HISTORY();
450
+ const { entries, skipped } = readHistory(history);
451
+ const session = o.session || lastSessionId(entries);
452
+ const turns = selectTurns(entries, { session, turns: o.turns });
453
+ const observations = observationsFromTurns(turns);
454
+
455
+ const code = o.code || [];
456
+
457
+ // The AI axis. `aiSecret` may be passed in (a host that already resolved it),
458
+ // left undefined (then the two rungs above are walked), or explicitly null (a
459
+ // host saying "no credential — mint the axis as unobserved").
460
+ // `aiModel` first: the credential rung asks which provider key this session's
461
+ // model needed, so the model has to be known before the key is nominated —
462
+ // the order is the difference between "no key nominated" and the right one.
463
+ const aiObservations = o.aiObservations || aiObservationsFromTurns(turns);
464
+ const aiModel = o.aiModel !== undefined && o.aiModel !== null
465
+ ? o.aiModel
466
+ : aiObservations.map((a) => a.model).filter(Boolean).pop() || '';
467
+ const aiKey = o.aiSecret === undefined
468
+ ? resolveAiSecret({ ...o, aiModel })
469
+ : { secret: o.aiSecret, source: o.aiSecret ? 'caller' : 'none' };
470
+
471
+ const record = fp.mint({
472
+ secret: key.secret,
473
+ label: o.label,
474
+ account: o.account,
475
+ model: o.model,
476
+ tools: o.tools,
477
+ observations,
478
+ code,
479
+ codeDirty: o.codeDirty === undefined ? null : o.codeDirty,
480
+ aiSecret: aiKey.secret,
481
+ aiModel,
482
+ aiObservations,
483
+ createdAt: o.createdAt || undefined,
484
+ });
485
+
486
+ return {
487
+ record,
488
+ keySource: key.source,
489
+ public: key.public,
490
+ samples: record.behaviourSamples,
491
+ observations: observations.length,
492
+ aiKeySource: aiKey.source,
493
+ aiSamples: record.aiSamples,
494
+ skippedLines: skipped,
495
+ };
496
+ }
497
+
498
+ module.exports = {
499
+ DEFAULT_HISTORY,
500
+ DIR_KEYS,
501
+ DEMAND_KEYS,
502
+ OUTCOME_KEYS,
503
+ SESSION_KEYS,
504
+ REPLY_KEYS,
505
+ MODEL_KEYS,
506
+ AI_SECRET_ENV,
507
+ TIME_KEYS,
508
+ SKIP_DIRS,
509
+ MAX_FILE_BYTES,
510
+ MAX_FILES,
511
+ firstKey,
512
+ readHistory,
513
+ lastSessionId,
514
+ selectTurns,
515
+ observationsFromTurns,
516
+ aiObservationsFromTurns,
517
+ resolveAiSecret,
518
+ collectCode,
519
+ mintSession,
520
+ };