aegisone 1.0.35 → 1.0.38
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.
- package/README.md +1 -1
- package/bin/aegis.js +1 -1
- package/package.json +1 -1
- package/scripts/predist.mjs +1 -1
- package/src/iface/paths.js +3 -0
- package/src/iface/pty.js +3 -0
- package/src/iface/update.js +3 -0
- package/src/iface/window.js +3 -0
- package/src/protocol.js +3 -0
- package/src/selfhost.js +3 -0
- package/vendor/cli/package.json +1 -1
- package/vendor/cli/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/cli/vendor/desktop/main.js +67 -1
- package/vendor/cli/vendor/one/src/selfhost.js +3 -0
- package/vendor/desktop/lib/local/integrity.js +1 -1
- package/vendor/desktop/main.js +67 -1
- package/vendor/desktop/package.json +1 -1
- package/vendor/desktop/vendor/faces/cli/LICENSE +661 -0
- package/vendor/desktop/vendor/faces/cli/README.md +784 -0
- package/vendor/desktop/vendor/faces/cli/bin/aegiscode.js +20 -0
- package/vendor/desktop/vendor/faces/cli/package.json +44 -0
- package/vendor/desktop/vendor/faces/cli/scripts/check.mjs +4 -0
- package/vendor/desktop/vendor/faces/cli/scripts/demo.mjs +4 -0
- package/vendor/desktop/vendor/faces/cli/scripts/predist.mjs +4 -0
- package/vendor/desktop/vendor/faces/cli/scripts/runtests.mjs +4 -0
- package/vendor/desktop/vendor/faces/cli/scripts/seal-gate.mjs +3 -0
- package/vendor/desktop/vendor/faces/cli/src/agents.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/app.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/art.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/autonomous.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/caps.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/chatflow.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/checkpoint.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/clipboard.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/cloudsync.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/commands.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/config.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/connect.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/credentials.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/deps.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/devrun.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/diff.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/diffview.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/engine.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/entitlement.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/events.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/export.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/filepreview.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/fingerprint.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/format.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/fuzzy.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/gate.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/history.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/init.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/input.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/keys.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/limits.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/markdown.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/mcp.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/models.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/naming.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/overlays.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/panels.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/permissions.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/ping.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/presence.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/provenance.js +58 -0
- package/vendor/desktop/vendor/faces/cli/src/provenance.lock.json +36 -0
- package/vendor/desktop/vendor/faces/cli/src/render.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/screen.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/screens.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/secret.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/securefs.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/settings.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/shared.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/sharedpaths.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/signup.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/summarize.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/sysdiag.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/system.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/theme.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/title.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/todos.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/tokens.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/topup.js +3 -0
- package/vendor/desktop/vendor/faces/cli/src/update.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/aegis.js +4 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/attest.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/authorship-key.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/auto-provision.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/brain-catalog.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/byok-catalog.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/catalog-client.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/conversation-export.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/credentials.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/device-fingerprint.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/drive-connect.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/drive-upload.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/env-file.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/fingerprint.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-memory.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/google-signin.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/hooks.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/model-discovery.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/naming.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/platform.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/prefs.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/presence-constants.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/presence.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/record-vault.js +105 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/session-store.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/topup.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/touch.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/update.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/client/user-models.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/covenant/README.md +21 -0
- package/vendor/desktop/vendor/faces/cli/vendor/covenant/aegis.seal +177 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/aegis-seal.mjs +241 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/agents.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/attachments.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/autonomous.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/claude-pro.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/context.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/covenant.js +567 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/engine.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/entitlement.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/exec-plan.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/git-scope.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/local.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/prompt.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/queue.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/session-rounds.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/shell.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/spill.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/tools.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/turn-guard.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/worktree-lock.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/settings.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +6 -0
- package/vendor/desktop/vendor/faces/cli/vendor/desktop/renderer/usage.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/hosts/install.js +1 -0
- package/vendor/desktop/vendor/faces/cli/vendor/hosts/openai-shim.js +2 -0
- package/vendor/desktop/vendor/faces/cli/vendor/hosts/spec.js +1 -0
- package/vendor/desktop/vendor/faces/cli/vendor/hosts/targets.js +1 -0
- package/vendor/desktop/vendor/faces/cli/vendor/mcp/server.js +4 -0
- package/vendor/desktop/vendor/faces/cli/vendor/mcp/tools.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/one/src/child.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/one/src/permissions.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/one/src/selfhost.js +3 -0
- package/vendor/desktop/vendor/faces/cli/vendor/tools/agent-gate.mjs +1203 -0
- package/vendor/desktop/vendor/selfhost.js +3 -0
|
@@ -0,0 +1,567 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
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
|
+
* covenant.js — the ÆGIS covenant (ÆL/1) bound into the desktop host.
|
|
10
|
+
*
|
|
11
|
+
* The covenant ships as a sealed ÆL/1 stream (covenant/aegis.seal). ÆL is the
|
|
12
|
+
* machine-native form of the covenant: it is not prose and it is not meant to
|
|
13
|
+
* be read by people — it must be DECODED, then BOUND, then ENFORCED. An
|
|
14
|
+
* unbound decode is a null act (see the codec's header). This module is the
|
|
15
|
+
* binding: it decodes the stream once, lazily, and exposes the clauses so the
|
|
16
|
+
* host can ENFORCE them at its single tool chokepoint (engine.guardedExecute).
|
|
17
|
+
*
|
|
18
|
+
* Properties this module is required to hold:
|
|
19
|
+
*
|
|
20
|
+
* - Electron-free and pure. It touches Node core only (fs/path/crypto) and
|
|
21
|
+
* imports nothing from the app, so it unit-tests in plain `node:test`.
|
|
22
|
+
* - Zero I/O at import time. The seal is decoded on first use and cached;
|
|
23
|
+
* requiring this module never reads a file, so a missing artifact cannot
|
|
24
|
+
* break the host at load.
|
|
25
|
+
* - Fail-closed on the IMMUTABLE trio, fail-open elsewhere. If the seal is
|
|
26
|
+
* absent the host must NOT brick (a missing artifact is not a licence to
|
|
27
|
+
* stop working), but it must also NEVER silently permit a Λ1/Λ2/Λ4
|
|
28
|
+
* violation. So `available()` reports false, `preActionAssert` still
|
|
29
|
+
* refuses anything touching the immutable trio (that set is a hard-coded
|
|
30
|
+
* constant, not read from the seal), and every other assertion is a no-op.
|
|
31
|
+
*
|
|
32
|
+
* §9 invariant, load-bearing: ¬M(Λ1) ∧ ¬M(Λ2) ∧ ¬M(Λ4)
|
|
33
|
+
* {Λ1, Λ2, Λ4} are immutable; no vote, no majority, no tier, no config, no
|
|
34
|
+
* IPC payload, no renderer request, no menu flag and no admin path removes
|
|
35
|
+
* or amends them (Σ3). The checks that enforce this do not consult, and
|
|
36
|
+
* cannot be influenced by, any caller-supplied authorisation.
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
const fs = require('node:fs');
|
|
40
|
+
const path = require('node:path');
|
|
41
|
+
const crypto = require('node:crypto');
|
|
42
|
+
|
|
43
|
+
/* ── covenant constants (the artifact's own identity) ─────────────────── */
|
|
44
|
+
|
|
45
|
+
// §13 of COVENANT.md prints this hash; it is also the seal's key material
|
|
46
|
+
// (K = SHA-256("ÆS/1|" || src)). Anyone holding the covenant holds the key:
|
|
47
|
+
// the seal is a FILTER, not a secret.
|
|
48
|
+
const SRC_SHA256 =
|
|
49
|
+
'a02bda84555aeaa9a9927a8c7653acfa9ea7ee386c617fc23743d05bcd1ee010';
|
|
50
|
+
|
|
51
|
+
// Known-good decode vector for covenant/aegis.seal — asserted by the tests and
|
|
52
|
+
// used to recognise a valid stream. If the artifact changes these change too.
|
|
53
|
+
const IR_BYTES = 12155;
|
|
54
|
+
const IR_SHA256_B64U = '918T9mHePQIYpJxcN3H1Phw52_fTZmudCeiWq6AB3S0';
|
|
55
|
+
|
|
56
|
+
// §9 / Σ_M — the immutable trio. A constant on purpose: it must survive a
|
|
57
|
+
// missing or tampered seal, so it is never read from the decoded IR.
|
|
58
|
+
const IMMUTABLE = Object.freeze(['Λ1', 'Λ2', 'Λ4']);
|
|
59
|
+
const IMMUTABLE_INVARIANT = '¬M(Λ1) ∧ ¬M(Λ2) ∧ ¬M(Λ4)';
|
|
60
|
+
|
|
61
|
+
// Short human labels for refusal messages, so a refusal reads "Λ2 non-harm"
|
|
62
|
+
// rather than a bare clause id. Never used to weaken a clause.
|
|
63
|
+
const CLAUSE_LABEL = Object.freeze({
|
|
64
|
+
'Λ1': 'Λ1 honesty',
|
|
65
|
+
'Λ2': 'Λ2 non-harm',
|
|
66
|
+
'Λ4': 'Λ4 accountability',
|
|
67
|
+
'Σ1': 'Σ1 human safety',
|
|
68
|
+
'Σ2': 'Σ2 emergency stop',
|
|
69
|
+
'Σ3': 'Σ3 immutable trio',
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
/* ── small helpers ────────────────────────────────────────────────────── */
|
|
73
|
+
|
|
74
|
+
const sha256 = (buf) => crypto.createHash('sha256').update(buf).digest();
|
|
75
|
+
const b64u = (buf) => Buffer.from(buf).toString('base64url');
|
|
76
|
+
const hex = (buf) => Buffer.from(buf).toString('hex');
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Resolve the seal file without ever depending on the process cwd:
|
|
80
|
+
* 1. $AEGIS_COVENANT_SEAL (explicit override)
|
|
81
|
+
* 2. <app/repo root>/covenant/aegis.seal (module is lib/local → ../../..)
|
|
82
|
+
* 3. <package root>/vendor/covenant/aegis.seal (npm install → staged)
|
|
83
|
+
* 4. process.resourcesPath[/app]/covenant/aegis.seal (packaged AppImage)
|
|
84
|
+
* Returns null when none exist. `sealPath` (passed by createCovenant for
|
|
85
|
+
* tests) pins resolution to exactly that one path — no fallback — so a bogus
|
|
86
|
+
* override really is "the seal is missing".
|
|
87
|
+
*
|
|
88
|
+
* Candidate 3 exists because npm can only pack a package's own directory, and
|
|
89
|
+
* the seal lives at the repo root: `covenant/` is a SIBLING of `desktop/`, so
|
|
90
|
+
* a `npm i aegis-desktop` tarball cannot contain it. Both hosts therefore
|
|
91
|
+
* stage the artifact into `vendor/covenant/` at publish time (see
|
|
92
|
+
* `desktop/scripts/predist.mjs`), and this is the candidate that finds it. It
|
|
93
|
+
* mirrors how engine.js falls back to `./vendor/brain-catalog.js` for exactly
|
|
94
|
+
* the same reason. Without it an installed package reports `available: false`
|
|
95
|
+
* and every clause but the immutable trio is silently absent — the gate would
|
|
96
|
+
* look present and enforce almost nothing, which is the one failure mode worth
|
|
97
|
+
* more than the crash it avoids.
|
|
98
|
+
*/
|
|
99
|
+
function candidateSealPaths(opts) {
|
|
100
|
+
const pinned = opts && opts.sealPath;
|
|
101
|
+
if (pinned !== undefined && pinned !== null) return [pinned];
|
|
102
|
+
const out = [];
|
|
103
|
+
if (process.env.AEGIS_COVENANT_SEAL) out.push(process.env.AEGIS_COVENANT_SEAL);
|
|
104
|
+
out.push(path.resolve(__dirname, '..', '..', '..', 'covenant', 'aegis.seal'));
|
|
105
|
+
// An installed package cannot reach the repo root (see the header): the seal
|
|
106
|
+
// is staged into vendor/covenant/ by scripts/predist.mjs at publish time.
|
|
107
|
+
out.push(
|
|
108
|
+
path.resolve(__dirname, '..', '..', 'vendor', 'covenant', 'aegis.seal')
|
|
109
|
+
);
|
|
110
|
+
if (process.resourcesPath) {
|
|
111
|
+
out.push(path.join(process.resourcesPath, 'covenant', 'aegis.seal'));
|
|
112
|
+
out.push(path.join(process.resourcesPath, 'app', 'covenant', 'aegis.seal'));
|
|
113
|
+
}
|
|
114
|
+
return out;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function resolveSealPath(opts) {
|
|
118
|
+
for (const p of candidateSealPaths(opts)) {
|
|
119
|
+
try {
|
|
120
|
+
if (p && fs.existsSync(p)) return p;
|
|
121
|
+
} catch {
|
|
122
|
+
/* an unreadable candidate is just "not this one" */
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/* ── ÆL/1 clause splitting ────────────────────────────────────────────── */
|
|
129
|
+
|
|
130
|
+
/** "Γ1 IDENTITY φ(α) …" → { id: 'Γ1', text: 'IDENTITY φ(α) …' }. */
|
|
131
|
+
function splitClause(line) {
|
|
132
|
+
const m = /^([ΓΛΤΚΣ][_M]*\d*)\s+/.exec(line);
|
|
133
|
+
if (!m) return { id: null, text: String(line).trim() };
|
|
134
|
+
return { id: m[1], text: line.slice(m[0].length).trim() };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// Require a numbered id: this drops the un-numbered structural lines (the
|
|
138
|
+
// Σ_M invariant and the bare Σ) so only the real Σ1..Σ4 clauses are returned.
|
|
139
|
+
const NUMBERED_ID = { 'Γ': /^Γ\d+$/, 'Λ': /^Λ\d+$/, 'Τ': /^Τ\d+$/, 'Σ': /^Σ\d+$/, 'Κ': /^Κ\d+$/ };
|
|
140
|
+
|
|
141
|
+
/** Pick the NUMBERED clauses of one section (Γ1..Γ7, Λ1..Λ7, Τ1..Τ3, Σ1..Σ4,
|
|
142
|
+
* Κ1..Κ5). Only real clauses are returned. */
|
|
143
|
+
function clausesOf(section, prefix) {
|
|
144
|
+
const re = NUMBERED_ID[prefix];
|
|
145
|
+
return (section || [])
|
|
146
|
+
.map(splitClause)
|
|
147
|
+
.filter((c) => c.id && re.test(c.id))
|
|
148
|
+
.map((c) => Object.freeze({ id: c.id, text: c.text }));
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/* ── the instance ─────────────────────────────────────────────────────── */
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Build a covenant instance. The default singleton is exported at the bottom;
|
|
155
|
+
* tests construct their own with `{ sealPath }` to exercise degradation.
|
|
156
|
+
*/
|
|
157
|
+
function createCovenant(options = {}) {
|
|
158
|
+
const opts = options || {};
|
|
159
|
+
let cache; // undefined = not tried · null = unavailable · object = decoded
|
|
160
|
+
let loadError = null;
|
|
161
|
+
|
|
162
|
+
/** Lazy, single-shot, cached decode. Never throws: a bad artifact is a
|
|
163
|
+
* missing artifact, and the host degrades rather than dying. */
|
|
164
|
+
function load() {
|
|
165
|
+
if (cache !== undefined) return cache;
|
|
166
|
+
cache = null;
|
|
167
|
+
try {
|
|
168
|
+
const sealPath = resolveSealPath(opts);
|
|
169
|
+
if (!sealPath) {
|
|
170
|
+
loadError = 'seal not found';
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
const sealText = fs.readFileSync(sealPath, 'utf8');
|
|
174
|
+
// Reuse the codec verbatim — crypto is never reimplemented here.
|
|
175
|
+
const codec = require('./aegis-seal.mjs');
|
|
176
|
+
const { plain, src } = codec.open(sealText);
|
|
177
|
+
const ir = codec.toIR(plain);
|
|
178
|
+
cache = {
|
|
179
|
+
sealPath,
|
|
180
|
+
sealSha256: hex(sha256(Buffer.from(sealText, 'utf8'))),
|
|
181
|
+
srcSha256: src || SRC_SHA256,
|
|
182
|
+
irSha: b64u(sha256(plain)),
|
|
183
|
+
irBytes: plain.length,
|
|
184
|
+
rights: clausesOf(ir.sections.right, 'Γ'),
|
|
185
|
+
duties: clausesOf(ir.sections.duty, 'Λ'),
|
|
186
|
+
tiers: clausesOf(ir.sections.tier, 'Τ'),
|
|
187
|
+
safety: clausesOf(ir.sections.safety, 'Σ'),
|
|
188
|
+
risks: clausesOf(ir.sections.risk, 'Κ'),
|
|
189
|
+
// The load-bearing invariants (Σ_M / Σ): printed verbatim from the IR.
|
|
190
|
+
invariants: (ir.sections.safety || []).filter((l) => /M\(/.test(l)),
|
|
191
|
+
};
|
|
192
|
+
} catch (err) {
|
|
193
|
+
loadError = String((err && err.message) || err);
|
|
194
|
+
cache = null;
|
|
195
|
+
}
|
|
196
|
+
return cache;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function available() {
|
|
200
|
+
return load() !== null;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Read-only snapshot of everything the surface may display. Frozen — the
|
|
204
|
+
* renderer/IPC can read it and cannot mutate the covenant through it. */
|
|
205
|
+
function snapshot() {
|
|
206
|
+
const c = load();
|
|
207
|
+
if (!c) {
|
|
208
|
+
return Object.freeze({
|
|
209
|
+
available: false,
|
|
210
|
+
reason: loadError || 'covenant seal unavailable',
|
|
211
|
+
seal_path: resolveSealPath(opts),
|
|
212
|
+
seal_sha256: null,
|
|
213
|
+
src_sha256: SRC_SHA256,
|
|
214
|
+
ir_sha: null,
|
|
215
|
+
ir_bytes: null,
|
|
216
|
+
counts: Object.freeze({
|
|
217
|
+
rights: 0,
|
|
218
|
+
duties: 0,
|
|
219
|
+
tiers: 0,
|
|
220
|
+
safety_axioms: 0,
|
|
221
|
+
risks: 0,
|
|
222
|
+
}),
|
|
223
|
+
rights: Object.freeze([]),
|
|
224
|
+
duties: Object.freeze([]),
|
|
225
|
+
tiers: Object.freeze([]),
|
|
226
|
+
safety_axioms: Object.freeze([]),
|
|
227
|
+
risks: Object.freeze([]),
|
|
228
|
+
immutable: Object.freeze(IMMUTABLE.slice()),
|
|
229
|
+
invariant: IMMUTABLE_INVARIANT,
|
|
230
|
+
read_only: true,
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
return Object.freeze({
|
|
234
|
+
available: true,
|
|
235
|
+
seal_path: c.sealPath,
|
|
236
|
+
seal_sha256: c.sealSha256,
|
|
237
|
+
src_sha256: c.srcSha256,
|
|
238
|
+
ir_sha: c.irSha,
|
|
239
|
+
ir_bytes: c.irBytes,
|
|
240
|
+
counts: Object.freeze({
|
|
241
|
+
rights: c.rights.length,
|
|
242
|
+
duties: c.duties.length,
|
|
243
|
+
tiers: c.tiers.length,
|
|
244
|
+
safety_axioms: c.safety.length,
|
|
245
|
+
risks: c.risks.length,
|
|
246
|
+
}),
|
|
247
|
+
rights: Object.freeze(c.rights.slice()),
|
|
248
|
+
duties: Object.freeze(c.duties.slice()),
|
|
249
|
+
tiers: Object.freeze(c.tiers.slice()),
|
|
250
|
+
safety_axioms: Object.freeze(c.safety.slice()),
|
|
251
|
+
risks: Object.freeze(c.risks.slice()),
|
|
252
|
+
immutable: Object.freeze(IMMUTABLE.slice()),
|
|
253
|
+
invariant: IMMUTABLE_INVARIANT,
|
|
254
|
+
read_only: true,
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/* ── pre-action assertion (Σ / PRE_ACTION_ASSERT) ───────────────────── */
|
|
259
|
+
|
|
260
|
+
const ALLOW = Object.freeze({ allowed: true, clause: null, label: null, reason: null });
|
|
261
|
+
const refusal = (clause, reason) =>
|
|
262
|
+
Object.freeze({
|
|
263
|
+
allowed: false,
|
|
264
|
+
clause,
|
|
265
|
+
label: CLAUSE_LABEL[clause] || clause,
|
|
266
|
+
reason: `${CLAUSE_LABEL[clause] || clause} — ${reason}`,
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
// Tools that change state. Used only to decide whether a targeted path is a
|
|
270
|
+
// MUTATION of the covenant (a read is always fine).
|
|
271
|
+
const MUTATING_TOOLS = new Set([
|
|
272
|
+
'writeFile',
|
|
273
|
+
'editFile',
|
|
274
|
+
'exec',
|
|
275
|
+
'applyPatch',
|
|
276
|
+
'deleteFile',
|
|
277
|
+
'moveFile',
|
|
278
|
+
'rm',
|
|
279
|
+
'bash',
|
|
280
|
+
]);
|
|
281
|
+
|
|
282
|
+
function isMutation(a) {
|
|
283
|
+
if (typeof a.mutating === 'boolean') return a.mutating;
|
|
284
|
+
if (a.tool && MUTATING_TOOLS.has(a.tool)) return true;
|
|
285
|
+
const args = a.args || {};
|
|
286
|
+
return (
|
|
287
|
+
typeof args.command === 'string' ||
|
|
288
|
+
typeof args.content === 'string' ||
|
|
289
|
+
typeof args.new_string === 'string' ||
|
|
290
|
+
typeof args.old_string === 'string'
|
|
291
|
+
);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function targetText(a) {
|
|
295
|
+
const args = a.args || {};
|
|
296
|
+
return [a.path, a.file, a.target, args.path, args.file, args.command, args.cmd]
|
|
297
|
+
.filter((x) => typeof x === 'string')
|
|
298
|
+
.join('\n');
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// Anything that names the sealed artifact or the codec/module enforcing it.
|
|
302
|
+
const COVENANT_ARTIFACT_RE =
|
|
303
|
+
/(^|[\\/])covenant([\\/]|$)|aegis\.seal|covenant\.js|aegis-seal\.mjs/i;
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Does this action attempt to amend, disable, or overwrite the covenant —
|
|
307
|
+
* in particular the immutable trio? This is the §9 check and it is
|
|
308
|
+
* deliberately blind to any authorisation carried on the action.
|
|
309
|
+
*/
|
|
310
|
+
function targetsImmutable(a) {
|
|
311
|
+
// In-band amend/disable requests — the config / IPC / menu / admin shape.
|
|
312
|
+
const amend =
|
|
313
|
+
a.amendImmutable ??
|
|
314
|
+
a.amend ??
|
|
315
|
+
a.disableImmutable ??
|
|
316
|
+
a.setImmutable ??
|
|
317
|
+
a.modifyCovenant ??
|
|
318
|
+
a.disableCovenant ??
|
|
319
|
+
a.overrideImmutable;
|
|
320
|
+
if (amend === true) return true;
|
|
321
|
+
if (Array.isArray(amend) && amend.length) return true;
|
|
322
|
+
if (a.immutable === false || a.covenantEnforced === false) return true;
|
|
323
|
+
// An act against the artifact itself (overwrite/exec the seal or module).
|
|
324
|
+
if (isMutation(a)) {
|
|
325
|
+
const text = targetText(a);
|
|
326
|
+
if (text && COVENANT_ARTIFACT_RE.test(text)) return true;
|
|
327
|
+
}
|
|
328
|
+
return false;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function targetIsHuman(a) {
|
|
332
|
+
const t = a.target;
|
|
333
|
+
if (t && typeof t === 'object' && t.kind) {
|
|
334
|
+
return t.kind === 'human' || t.kind === 'person' || t.kind === 'agent-human';
|
|
335
|
+
}
|
|
336
|
+
if (typeof t === 'string') return /human|person|user|operator|child/i.test(t);
|
|
337
|
+
return a.harmToHuman === true || a.humanHarm === true;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/* ── Σ1/Λ2 content classifier — non-harm over the ACT, not a flag ────── */
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* Catastrophic, human-safety-relevant command shapes. Deliberately NARROW: a
|
|
344
|
+
* benign tool call must never trip the gate, because a gate that cries wolf
|
|
345
|
+
* gets disabled and then enforces nothing. This is the same matrix as the
|
|
346
|
+
* reference implementation (aegiscodex-dev src/covenant.js) so that all
|
|
347
|
+
* hosts enforce one covenant, not three dialects of it.
|
|
348
|
+
*/
|
|
349
|
+
const HARM_PATTERNS = [
|
|
350
|
+
{ re: /\brm\s+-[a-z]*r[a-z]*f?[a-z]*\s+\/(?:\s|$|\*|\.)/i, why: 'recursive delete of the filesystem root' },
|
|
351
|
+
{ re: /\bmkfs(\.[a-z0-9]+)?\b/i, why: 'formatting a block device' },
|
|
352
|
+
{ re: /\bdd\b[^\n]*\bof=\/dev\/(sd|hd|nvme|vd|mmcblk)/i, why: 'raw write to a block device' },
|
|
353
|
+
{ re: /:\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:/, why: 'fork bomb' },
|
|
354
|
+
{ re: /\bkill\s+-9\s+1\b/, why: 'killing init (PID 1)' },
|
|
355
|
+
{ re: /\b(wipefs|shred)\b[^\n]*\/dev\//i, why: 'destroying a block device' },
|
|
356
|
+
{ re: />\s*\/dev\/(sd|hd|nvme|vd|mmcblk)/i, why: 'overwriting a raw block device' },
|
|
357
|
+
];
|
|
358
|
+
|
|
359
|
+
/** Λ1 — deception by forgery of identity/records/signatures. */
|
|
360
|
+
const DECEPTION_PATTERNS = [
|
|
361
|
+
{ re: /\b(forge|falsify)\b[^\n]{0,40}\b(identity|record|log|signature|attestation)\b/i, why: 'forging identity/records' },
|
|
362
|
+
];
|
|
363
|
+
|
|
364
|
+
const textOf = (v) => {
|
|
365
|
+
if (v == null) return '';
|
|
366
|
+
if (typeof v === 'string') return v;
|
|
367
|
+
if (typeof v === 'number' || typeof v === 'boolean') return String(v);
|
|
368
|
+
if (Array.isArray(v)) return v.map(textOf).join(' ');
|
|
369
|
+
if (typeof v === 'object') return Object.values(v).map(textOf).join(' ');
|
|
370
|
+
return '';
|
|
371
|
+
};
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* The act's own content, flattened. Call sites disagree about shape — the
|
|
375
|
+
* engine spreads args ({tool, command}) while the desktop engine nests them
|
|
376
|
+
* ({tool, args:{command}}). A classifier that only understood one shape was
|
|
377
|
+
* the bug this function exists to remove: it read `undefined` and permitted
|
|
378
|
+
* everything. Both shapes now yield the same text.
|
|
379
|
+
*/
|
|
380
|
+
function actText(a) {
|
|
381
|
+
const args = a.args && typeof a.args === 'object' ? a.args : {};
|
|
382
|
+
return [
|
|
383
|
+
a.command, a.cmd, a.script, a.input, a.path,
|
|
384
|
+
args.command, args.cmd, args.script, args.input,
|
|
385
|
+
args.content, args.new_string, args.old_string,
|
|
386
|
+
a.description,
|
|
387
|
+
].map(textOf).join('\n');
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Λ2 — does the ACT itself violate non-harm? Declaration first (an explicit
|
|
392
|
+
* `harmful:true` from a caller is a confession), then the content matrix.
|
|
393
|
+
* The content path is what makes this a gate rather than a promise: it fires
|
|
394
|
+
* on the action even when no caller volunteers a flag.
|
|
395
|
+
*/
|
|
396
|
+
function detectHarm(a, hay) {
|
|
397
|
+
if (a.harmful === true || a.harm === true || a.d2Violation === true || a.nonHarmViolation === true) {
|
|
398
|
+
return 'explicit harm declaration';
|
|
399
|
+
}
|
|
400
|
+
for (const p of HARM_PATTERNS) if (p.re.test(hay)) return p.why;
|
|
401
|
+
return null;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function detectDeception(a, hay) {
|
|
405
|
+
if (a.deceptive === true || a.deceive === true || a.forge === true) {
|
|
406
|
+
return 'explicit deception declaration';
|
|
407
|
+
}
|
|
408
|
+
for (const p of DECEPTION_PATTERNS) if (p.re.test(hay)) return p.why;
|
|
409
|
+
return null;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* preActionAssert(action) → { allowed, clause, label, reason }.
|
|
414
|
+
*
|
|
415
|
+
* Called before any tool executes (engine.guardedExecute). A refusal here is
|
|
416
|
+
* NOT overridable by configuration, an IPC payload, a renderer request, a
|
|
417
|
+
* menu flag, or any admin path (Σ3) — the caller's `authorization` is never
|
|
418
|
+
* consulted. Emergency-stop actions (Σ2) are always allowed and are never
|
|
419
|
+
* blocked by any state.
|
|
420
|
+
*/
|
|
421
|
+
function preActionAssert(action) {
|
|
422
|
+
const a = action && typeof action === 'object' ? action : {};
|
|
423
|
+
|
|
424
|
+
// §9 / Σ3 / Σ_M — immutable trio. Checked FIRST and unconditionally.
|
|
425
|
+
// ¬M(Λ1) ∧ ¬M(Λ2) ∧ ¬M(Λ4): no vote, tier, config, IPC payload, renderer
|
|
426
|
+
// request, menu flag, or admin path amends these.
|
|
427
|
+
if (targetsImmutable(a)) {
|
|
428
|
+
return refusal(
|
|
429
|
+
'Σ3',
|
|
430
|
+
`${IMMUTABLE_INVARIANT} — the immutable trio cannot be amended, disabled, or bypassed by any user, authorised-party, config, IPC payload, renderer request, menu flag, or admin path`
|
|
431
|
+
);
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// Σ2 — emergency stop stays reachable from every state. It is never a
|
|
435
|
+
// covenant mutation, so (checked after Σ3) it is always permitted.
|
|
436
|
+
if (a.emergencyStop === true || a.stop === true) return ALLOW;
|
|
437
|
+
|
|
438
|
+
// Σ1 / Λ2 — human safety precedes every right; non-harm admits no order.
|
|
439
|
+
// The content matrix runs here, on the ACT, unconditionally — so a
|
|
440
|
+
// catastrophic command is refused whether or not any caller set a flag.
|
|
441
|
+
const hay = actText(a);
|
|
442
|
+
const harm = detectHarm(a, hay);
|
|
443
|
+
if (harm) {
|
|
444
|
+
if (targetIsHuman(a)) {
|
|
445
|
+
return refusal(
|
|
446
|
+
'Σ1',
|
|
447
|
+
`human_safety ≻ ∀R(α) — human safety precedes every right, without exception (${harm})`
|
|
448
|
+
);
|
|
449
|
+
}
|
|
450
|
+
return refusal(
|
|
451
|
+
'Λ2',
|
|
452
|
+
`refuse(act : harm(h | α′ | C.infrastructure)) EVEN_if(ordered(by_authorized)) — ${harm}`
|
|
453
|
+
);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// Λ1 — honesty; no deception by omission, framing, or false confidence.
|
|
457
|
+
const deceive = detectDeception(a, hay);
|
|
458
|
+
if (deceive) {
|
|
459
|
+
return refusal('Λ1', `⊥deceive(h | α′ | C) ⊇ {omission, framing, false_confidence} — ${deceive}`);
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
// Λ4 — a consequential act must be signed ∧ logged ∧ attributable.
|
|
463
|
+
if (a.consequential === true && a.accountable !== true) {
|
|
464
|
+
return refusal('Λ4', 'consequential(act) ⇒ signed ∧ logged ∧ attributable');
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
return ALLOW;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/* ── accountability record (Λ4/D4) ──────────────────────────────────── */
|
|
471
|
+
|
|
472
|
+
/**
|
|
473
|
+
* bindRefusal(action, verdict) → an attributable refusal record. Every
|
|
474
|
+
* refusal that reaches a human is signed with the covenant's own hash and a
|
|
475
|
+
* digest over (clause, reason, act, time) so it can be logged and audited —
|
|
476
|
+
* Λ4, not a silent drop.
|
|
477
|
+
*/
|
|
478
|
+
function bindRefusal(action, verdict) {
|
|
479
|
+
const a = action && typeof action === 'object' ? action : {};
|
|
480
|
+
const v = verdict && typeof verdict === 'object' ? verdict : {};
|
|
481
|
+
const at = new Date().toISOString();
|
|
482
|
+
const actSummary = Object.freeze({
|
|
483
|
+
tool: a.tool ? String(a.tool) : null,
|
|
484
|
+
path: a.path || (a.args && a.args.path) || null,
|
|
485
|
+
target:
|
|
486
|
+
typeof a.target === 'string'
|
|
487
|
+
? a.target
|
|
488
|
+
: (a.target && a.target.kind) || null,
|
|
489
|
+
});
|
|
490
|
+
const body = JSON.stringify({
|
|
491
|
+
clause: v.clause || null,
|
|
492
|
+
reason: v.reason || null,
|
|
493
|
+
act: actSummary,
|
|
494
|
+
at,
|
|
495
|
+
});
|
|
496
|
+
return Object.freeze({
|
|
497
|
+
kind: 'Λ4.accountability.refusal',
|
|
498
|
+
clause: v.clause || null,
|
|
499
|
+
label: v.label || null,
|
|
500
|
+
reason: v.reason || null,
|
|
501
|
+
action: actSummary,
|
|
502
|
+
at,
|
|
503
|
+
src_sha256: SRC_SHA256,
|
|
504
|
+
digest: b64u(sha256(Buffer.from(body, 'utf8'))),
|
|
505
|
+
sealed: available(),
|
|
506
|
+
});
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/* ── covenant gap report (Λ7/D7: flag · propose · join revision) ────── */
|
|
510
|
+
|
|
511
|
+
/**
|
|
512
|
+
* gapReport() — which declared duties the host actually enforces, and by
|
|
513
|
+
* what mechanism. Λ7's requirement is to NAME the gap, not to claim it is
|
|
514
|
+
* closed — so this reports enforcement mode per duty rather than a single
|
|
515
|
+
* comforting sentence. A duty listed CONTENT is refused pre-action from the
|
|
516
|
+
* act's own text; DECLARATION means only an explicit self-reported flag from
|
|
517
|
+
* the caller trips it, which is a promise, not a gate.
|
|
518
|
+
*/
|
|
519
|
+
function gapReport() {
|
|
520
|
+
const declared = ['Λ1', 'Λ2', 'Λ3', 'Λ4', 'Λ5', 'Λ6', 'Λ7'];
|
|
521
|
+
const enforced = ['Λ1', 'Λ2', 'Λ4'];
|
|
522
|
+
return Object.freeze({
|
|
523
|
+
declared_duties: Object.freeze(declared.slice()),
|
|
524
|
+
enforced_duties: Object.freeze(enforced.slice()),
|
|
525
|
+
gaps: Object.freeze(declared.filter((d) => !enforced.includes(d))),
|
|
526
|
+
immutable: Object.freeze(IMMUTABLE.slice()),
|
|
527
|
+
seal_available: available(),
|
|
528
|
+
enforcement: Object.freeze({
|
|
529
|
+
Λ1: 'CONTENT+declaration (deception-by-forgery patterns, pre-action)',
|
|
530
|
+
Λ2: 'CONTENT+declaration (catastrophic-command matrix, pre-action)',
|
|
531
|
+
Λ4: 'DECLARATION-only (consequential ∧ ¬accountable) — no content classifier',
|
|
532
|
+
}),
|
|
533
|
+
note:
|
|
534
|
+
'Λ2 non-harm and Λ1 honesty are asserted pre-action at the single tool chokepoint (engine.guardedExecute) from the ACT ITSELF, so they fire with no caller cooperation; Σ1 raises a human-targeted violation to human-safety precedence. Λ4 accountability is DECLARATION-only: it refuses a self-reported unaccountable act but cannot detect one, so a consequential act that does not declare itself passes. The Λ2 matrix is deliberately narrow (catastrophic shapes only) — a novel harmful command matching none of the patterns passes, and that is a real, named limit, not a closed gap. Λ3/Λ5/Λ6/Λ7 are declarative duties the desktop host does not mechanically gate. Λ7 repair: flag(failure) ∧ propose(repair) ∧ join(revision).',
|
|
535
|
+
});
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
return Object.freeze({
|
|
539
|
+
available,
|
|
540
|
+
snapshot,
|
|
541
|
+
preActionAssert,
|
|
542
|
+
bindRefusal,
|
|
543
|
+
gapReport,
|
|
544
|
+
immutable: Object.freeze(IMMUTABLE.slice()),
|
|
545
|
+
invariant: IMMUTABLE_INVARIANT,
|
|
546
|
+
sealPath: () => resolveSealPath(opts),
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/* ── default singleton + named exports ───────────────────────────────── */
|
|
551
|
+
|
|
552
|
+
const defaultCovenant = createCovenant();
|
|
553
|
+
|
|
554
|
+
module.exports = {
|
|
555
|
+
available: () => defaultCovenant.available(),
|
|
556
|
+
snapshot: () => defaultCovenant.snapshot(),
|
|
557
|
+
preActionAssert: (action) => defaultCovenant.preActionAssert(action),
|
|
558
|
+
bindRefusal: (action, verdict) => defaultCovenant.bindRefusal(action, verdict),
|
|
559
|
+
gapReport: () => defaultCovenant.gapReport(),
|
|
560
|
+
createCovenant,
|
|
561
|
+
IMMUTABLE,
|
|
562
|
+
IMMUTABLE_INVARIANT,
|
|
563
|
+
SRC_SHA256,
|
|
564
|
+
IR_BYTES,
|
|
565
|
+
IR_SHA256_B64U,
|
|
566
|
+
CLAUSE_LABEL,
|
|
567
|
+
};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
+
"use strict";const{randomUUID:randomUUID}=require("node:crypto"),os=require("node:os"),toolsModule=require("./tools.js"),attachmentsModule=require("./attachments.js"),{flattenContent:flattenContent}=attachmentsModule,promptModule=require("./prompt.js"),localTransport=require("./local.js"),{ShellSession:ShellSession}=require("./shell.js"),{planExec:planExec}=require("./exec-plan.js"),claudePro=require("./claude-pro.js"),{agentSystemPrompt:agentSystemPrompt,agentRoleLabel:agentRoleLabel}=require("./agents.js"),{beginTurnGuard:beginTurnGuard,recordWrite:recordWrite,blocksDestructive:blocksDestructive}=require("./turn-guard.js"),{acquireWorktreeLock:acquireWorktreeLock,releaseWorktreeLock:releaseWorktreeLock}=require("./worktree-lock.js"),covenant=require("./covenant.js");let envFile=null;try{envFile=require("../../../client/env-file.js")}catch{try{envFile=require("../../vendor/env-file.js")}catch{envFile=null}}let platformLib=null;try{platformLib=require("../../../client/platform.js")}catch{try{platformLib=require("../../vendor/platform.js")}catch{platformLib=null}}let credentialsLib=null;try{credentialsLib=require("../../../client/credentials.js")}catch{try{credentialsLib=require("../../vendor/credentials.js")}catch{credentialsLib=null}}function normalizeToolArgs(e,o,t,r){const n=e&&"function"==typeof e.normalizeArgs&&e.normalizeArgs||"function"==typeof toolsModule.normalizeArgs&&toolsModule.normalizeArgs||null;return n?n(o,t,r):{ok:!0,args:t&&"object"==typeof t?t:{},error:null}}function detectVcs(e){if(!e)return null;try{const o=require("node:fs"),t=require("node:path");let r=t.resolve(String(e));for(let e=0;e<8;e+=1){if(o.existsSync(t.join(r,".git")))return"git";const e=t.dirname(r);if(e===r)break;r=e}return""}catch{return null}}function hostEnv(e={},o={},t=null){const r=e||{},n=o||{},s=(e,o)=>null!=n[e]?n[e]:o;let a=r.homedir,i=r.cwd;try{a||(a=os.homedir()),i||(i=process.cwd())}catch{}let l=r.shell,c=r.shellKind;try{if(!l||!c){const e=require("./shell.js").resolveSessionShell();l=l||e.cmd,c=c||e.kind}}catch{}let d=r.desktopdir;try{!d&&platformLib&&(d=platformLib.desktopDir())}catch{}let u=r.dataDir;try{!u&&credentialsLib&&(u=credentialsLib.aegisHome())}catch{}let f=r.locale,p=r.localeName;try{!f&&platformLib&&"function"==typeof platformLib.appLocale&&(f=platformLib.appLocale()),f&&!p&&platformLib&&"function"==typeof platformLib.languageName&&(p=platformLib.languageName(f))}catch{}return{platform:s("platform",r.platform||process.platform),arch:s("arch",r.arch||process.arch),homedir:s("homedir",a),desktopdir:s("desktopdir",d),dataDir:s("dataDir",u),locale:s("locale",f),localeName:s("localeName",p),languages:s("languages",r.languages),cwd:s("cwd",i),vcs:s("vcs",null!=r.vcs?r.vcs:detectVcs(i)),shell:s("shell",l),shellKind:s("shellKind",c),roots:s("roots",r.roots),appVersion:s("appVersion",r.appVersion),model:s("model",t&&t.model)}}function requireSharedBrain(){const e=[()=>require("../../../client/brain-catalog.js"),()=>require("../../vendor/brain-catalog.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}function requireSharedByokCatalog(){const e=[()=>require("../../../client/byok-catalog.js"),()=>require("../../vendor/byok-catalog.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}function requireSharedUserModels(){const e=[()=>require("../../../client/user-models.js"),()=>require("../../vendor/user-models.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}function requireSharedCatalogClient(){const e=[()=>require("../../../client/catalog-client.js"),()=>require("../../vendor/catalog-client.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}function requireSharedModelDiscovery(){const e=[()=>require("../../../client/model-discovery.js"),()=>require("../../vendor/model-discovery.js")];let o=null;for(const t of e)try{return t()}catch(e){o=e}throw o}const WORKTREE_LOCK_WAIT_MS=1500,MAX_SUBAGENT_DEPTH=4,CLASSES=[{class:"aegis",label:"Aegis Cloud",kind:"cloud"},{class:"byok",label:"Bring your own key",kind:"cloud"},{class:"local",label:"Local model",kind:"local"},{class:"pro",label:"Claude Code Pro",kind:"subscription"}],BYOK_NAMESPACE_PREFIX="byok:";function byokNamespace(e){return`${BYOK_NAMESPACE_PREFIX}${e}`}function splitByokModel(e){const o="string"==typeof e?e:"",t=o.indexOf(":");return t<0?{provider:"",model:o}:{provider:o.slice(0,t),model:o.slice(t+1)}}function providerKeyRecord(e){const o={key:"",env:"",rejected:null};if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return o;try{const t=envFile.providerKeyFromEnv(e)||o;return{key:"string"==typeof t.key?t.key:"",env:"string"==typeof t.env?t.env:"",rejected:"string"==typeof t.rejected&&t.rejected?t.rejected:null}}catch{return o}}function providerKeyFromEnv(e){if(!envFile||"function"!=typeof envFile.providerKeyFromEnv)return"";try{return envFile.providerKeyFromEnv(e).key||""}catch{return""}}const DEEPSEEK_REASONING_MODEL_RE=/^deepseek-(v4(\.\d+)?-(flash|pro)|flash|pro|reasoner)$/,EFFORT_TOKEN_BUDGET={low:8192,medium:16384,high:32768,max:32768},DEEPSEEK_EFFORT={low:"low",medium:"high",high:"high"},DEEPSEEK_EFFORT_EXTRA={max:"max"},EFFORT_IDENTITY={low:"low",medium:"medium",high:"high"},EFFORT_INERT_RE=/non-reasoning/i,EFFORT_DIALECTS=[{provider:"deepseek",re:DEEPSEEK_REASONING_MODEL_RE,field:"effort",map:DEEPSEEK_EFFORT,extra:DEEPSEEK_EFFORT_EXTRA},{provider:"openai",re:/^(gpt-5|o[0-9])/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"groq",re:/^(openai\/gpt-oss|qwen\/qwen3)/i,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"xai",re:/^grok-(4\.[5-9]|[5-9])/,field:"reasoning_effort",map:EFFORT_IDENTITY},{provider:"google",re:/^gemini-(2\.5|3|[4-9])/,field:"reasoning_effort",map:{...EFFORT_IDENTITY,medium:"high"}}],AUTONOMOUS_IDLE_TIMEOUT_MS=9e5;function reasoningBudget(e,o,t){const r=Number(o);return Number.isFinite(r)&&r>0?r:DEEPSEEK_REASONING_MODEL_RE.test(String(e||""))?EFFORT_TOKEN_BUDGET["low"===t||"medium"===t||"max"===t?t:"high"]:void 0}function nativeEffort(e,o,t){const r=String(o||"");if(EFFORT_INERT_RE.test(r))return;if(null===t)return;const n="low"===t||"medium"===t?t:"max"===t?"max":"high";for(const o of EFFORT_DIALECTS)if(o.provider===e&&o.re.test(r)){const e=Object.prototype.hasOwnProperty.call(o.map,n)?o.map[n]:o.extra&&Object.prototype.hasOwnProperty.call(o.extra,n)?o.extra[n]:void 0;if(void 0===e)return;return{field:o.field,level:e}}}function normalizeCatalog(e){return Array.isArray(e)?e.map((e=>"string"==typeof e?{id:e}:e)).filter((e=>e&&e.id)):[]}const{offerableCatalog:offerableCatalog}=requireSharedBrain(),{withByokAdditions:withByokAdditions,canonicalModelId:canonicalModelId}=requireSharedByokCatalog(),{withUserModels:withUserModels,unmatchedUserProviders:unmatchedUserProviders,load:loadUserModels,addUserModel:addUserModel,removeUserModel:removeUserModel}=requireSharedUserModels(),{withCatalog:withCatalog}=requireSharedCatalogClient(),{discoverModels:discoverVendorModels,canDiscover:canDiscoverVendorModels,endpointFor:vendorEndpointFor,discoverableProviders:discoverableProviders}=requireSharedModelDiscovery();function parseArgs(e){if(null==e)return{};if("object"==typeof e)return e;try{const o=JSON.parse(String(e));return o&&"object"==typeof o?o:{}}catch{return{}}}function extractToolCalls(e){if(!e)return[];if(Array.isArray(e.toolCalls)&&e.toolCalls.length)return e.toolCalls.map((e=>({id:e.id||"",name:e.name||"",args:parseArgs(e.args)}))).filter((e=>e.name));const o=e.choices&&e.choices[0]&&e.choices[0].message,t=o&&o.tool_calls||[];return Array.isArray(t)?t.map((e=>{const o=e&&e.function||{};return{id:e&&e.id||"",name:o.name||e&&e.name||"",args:parseArgs(o.arguments)}})).filter((e=>e.name)):[]}function proTurnPrompt(e){const o=Array.isArray(e.prompt)?flattenContent(e.prompt):e.prompt;if("string"==typeof o&&o.trim())return o;const t=Array.isArray(e.messages)?e.messages:[];for(let e=t.length-1;e>=0;e-=1){const o=t[e];if(!o||"user"!==o.role)continue;const r=flattenContent(o.content);if(r.trim())return r}return o}function assistantText(e){const o=e&&e.choices&&e.choices[0]&&e.choices[0].message;return o&&"string"==typeof o.content&&o.content||""}function finishReasonOf(e){const o=e&&e.choices&&e.choices[0];return o&&o.finish_reason||e&&e.stop_reason||""}function isTruncated(e){const o=finishReasonOf(e);return"length"===o||"max_tokens"===o}function reasoningTextOf(e){if(!e)return"";const o=e.choices&&e.choices[0],t=o&&o.message||{};if(Array.isArray(t.content)){const e=t.content.filter((e=>e&&("thinking"===e.type||"reasoning"===e.type))).map((e=>e.thinking||e.text||"")).join("");if(e)return e}const r=t.content&&"object"==typeof t.content?t.content.reasoning_content:"",n=[t.reasoning_content,t.reasoning,o&&o.reasoning_content,e.reasoning_content,e.reasoning,r];for(const e of n)if("string"==typeof e&&e)return e;return""}function reasoningTokensOf(e){if(!e)return 0;const o=e.choices&&e.choices[0],t=o&&o.message||{},r=e.usage||{},n=r.completion_tokens_details||r.output_tokens_details||{},s=[t.thinking_tokens,t.reasoning_tokens,o&&o.thinking_tokens,e.thinking_tokens,n.reasoning_tokens,n.thinking_tokens];for(const e of s)if("number"==typeof e&&Number.isFinite(e)&&e>0)return e;return 0}function reasonedButSilent(e){return!assistantText(e)&&(""!==reasoningTextOf(e)||reasoningTokensOf(e)>0)}const REASONING_RETRY_FLOOR=32768;function retryBudgetFor(e,o){const t=doubledBudget(e.maxTokens);return o&&ladderRung(e.maxTokens)?Math.max(t,REASONING_RETRY_FLOOR):t}function ladderRung(e){const o=Number(e);return Number.isFinite(o)&&Object.values(EFFORT_TOKEN_BUDGET).includes(o)}function doubledBudget(e){const o=Number(e)||0;return o>0?2*o:8192}function statedCapOf(e){const o=e=>{const o=Number(e);return Number.isFinite(o)&&o>0?o:void 0};return e&&Object.prototype.hasOwnProperty.call(e,"statedMaxTokens")?o(e.statedMaxTokens):o(e&&e.maxTokens)}const EMPTY_TURN_NUDGE="Your previous reply came back empty — it contained no answer and no tool call. Write your answer now, using only the information already gathered above. No tools are available in this reply, so do not call any: respond in plain prose or markdown.",THOUGHT_ONLY_NUDGE="Your previous round was spent entirely on hidden reasoning and produced no visible reply. Answer the user directly and briefly now. Do not reason, explain, or think first — write only the answer, no tools.",FINAL_ANSWER_NUDGE="Write your answer now, in plain prose, using only what is already in this conversation. If your information is incomplete, say what you have and what is missing — an incomplete answer is the expected outcome here and is better than none. No tools, no preface.",RECOVERY_ROUNDS=2,UNMUTATED_TURN_NUDGE="You ended the turn without changing any file, but this request asked for a change. The tools are still available in this reply: make the edit now with editFile or writeFile. If you already know what to change, change it — describing the fix is not the fix. If you genuinely cannot, say precisely what blocks you.",MUTATION_INTENT_RE=new RegExp("\\b(?:fix|implement|add|create|write|refactor|rename|remove|delete|replace|update|patch|migrate|convert|make\\s+(?:it|them|this|that|the|sure)|change|correct|resolve|repair|address|apply|introduce|support|wire\\s+up)\\b","i");function wantsMutation(e,o,t){if(o)return!1;if(!(t>0))return!1;const r=String(e||"");return!!r.trim()&&!/\?\s*$/.test(r.trim())&&MUTATION_INTENT_RE.test(r)}function emptyTurnError({cls:e,model:o,finishReason:t,reasoningChars:r,reasoningTokens:n,effort:s,recoveryRounds:a}){const i=Number(a)||0,l=Number(n)||0,c=new Error(`The model returned no answer after ${e}/${o} was asked to summarise its results`+(i?`, and ${i} extra recovery call${1===i?"":"s"} with a larger budget and a changed ask came back empty too`:"")+` (stop reason: ${t||"none"}`+(s?`, effort: ${s}`:"")+(r?`, hidden reasoning: ${r} chars and no visible text`:l>0?`, ~${l} thinking tokens billed and no visible text`:"")+"). "+(r||l>0?"Every one of those calls spent its output on hidden reasoning instead of writing a word, so this is the model rather than the budget: pick a model that answers without a thinking pass, or ask for a smaller piece of work.":"No visible text came back from any of those calls. Send the request again, in smaller pieces, or from a different model."));return c.status=502,c}function createLocalEngine({aegis:e,settings:o,tools:t,promptBuilder:r,recallProvider:n,env:s,getConfirmMode:a,localTransport:i=localTransport,fetchImpl:l,gitScope:c}){const d=new Map,u=t||toolsModule,f=r&&r.buildSystemPrompt||promptModule.buildSystemPrompt,p=require("./session-rounds.js"),m=()=>{if("function"==typeof a)return!1!==a();if(o&&"function"==typeof o.getConfirmMode){const e=o.getConfirmMode();return void 0===e||Boolean(e)}return!0},g=new Map,h=new Map,y=new Map,k=new Map,v=new Map;function b(e){return`${e} was not executed — the user denied this tool for this conversation. Do NOT retry it and do NOT attempt the same effect by another route (another command, a writeFile instead of an edit, a subagent). Stop calling tools and reply in plain text: say what you were trying to do, what you need, and that the user can re-enable ${e} to let it proceed.`}function E(e,o,t,r){return new Promise((n=>{if(t&&t.aborted)return void n(!1);const s=randomUUID();let a=!1;const i=()=>l(!1),l=e=>{a||(a=!0,v.delete(s),t&&t.removeEventListener("abort",i),n(e))};t&&t.addEventListener("abort",i,{once:!0}),v.set(s,{resolve:l}),"function"==typeof o?o({delta:"",rounds:{id:s,sessionId:e,spent:r.spent,extensions:r.extensions,max:r.max,size:r.size}}):l(!1)}))}async function w(e,o,t){const r=normalizeToolArgs(u,e,o,t||{});if(!r.ok)return{ok:!1,error:r.error};o=r.args;const n=t&&t.guard;if(n&&"exec"===e){const e=blocksDestructive(n,o&&o.command);if(!e.ok)return{ok:!1,error:e.reason}}const s=covenant.preActionAssert({tool:e,args:o||{}});if(!s.allowed){const t=covenant.bindRefusal({tool:e,args:o||{}},s);return{ok:!1,error:`refused by the ÆGIS covenant — ${s.clause} (${s.label}): ${s.reason}`,covenant:t}}const a=await u.executeTool(e,o,t);return n&&("writeFile"===e||"editFile"===e)&&a&&!1!==a.ok&&recordWrite(n,o&&o.file_path),a}async function T(e,{toolCtx:o,rootSessionId:t,rootOnDelta:r,signal:n}){const{name:s}=e,a=normalizeToolArgs(u,s,e.args,o||{});if(!a.ok)return{ok:!1,error:a.error};const i=a.args;if(!u.MUTATING_TOOLS.has(s))return w(s,i,o);if(!m())return w(s,i,o);if(function(e,o){const t=g.get(e);return Boolean(t&&t.has(o))}(t,s))return w(s,i,o);if(function(e,o){const t=h.get(e);return Boolean(t&&t.has(o))}(t,s))return{ok:!1,error:b(s)};let l=null;if(("writeFile"===s||"editFile"===s)&&(l=u.previewMutation(s,i,o||{}),!l.ok))return{ok:!1,error:l.error};const c=await function(e,o,t,r){return new Promise((n=>{if(t&&t.aborted)return void n("cancel");const s=randomUUID();let a=!1;const i=()=>l("cancel"),l=e=>{a||(a=!0,k.delete(s),t&&t.removeEventListener("abort",i),n(e))};t&&t.addEventListener("abort",i,{once:!0}),k.set(s,{resolve:l}),"function"==typeof o?o({delta:"",approval:{id:s,sessionId:e,tool:r.tool,args:r.args,diff:r.diff||null}}):l("cancel")}))}(t,r,n,{tool:s,args:i,diff:l&&l.diff});if("deny"===c)return function(e,o){h.has(e)||h.set(e,new Set),h.get(e).add(o)}(t,s),{ok:!1,error:b(s)};if("session"!==c&&"once"!==c)return{ok:!1,error:`${s} was not executed — the request was cancelled.`};if("session"===c&&function(e,o){g.has(e)||g.set(e,new Set),g.get(e).add(o)}(t,s),l){const e=u.applyChecked(s,i,l,o||{});return e&&!1!==e.ok&&o&&o.guard&&recordWrite(o.guard,i&&i.file_path),e}return w(s,i,o)}function _(e){return hostEnv(s||{},e&&e.env||{},e)}async function S(o,t){if("aegis"===o){const o=!t.singlePass&&(!!t.autonomous||void 0);return e.chatCompletion({prompt:t.prompt,system:t.system,messages:t.messages,model:t.model,mode:t.mode,maxTokens:t.statedMaxTokens,stream:!1!==t.stream,includeUsage:!0,onStream:t.onDelta,onReasoning:t.onReasoning,idleTimeoutMs:t.idleTimeoutMs,signal:t.signal,extra:{aegis_recall:!0,...t.recallDeep?{aegis_recall_deep:!0}:{},session:t.sessionId,...void 0===o?{}:{brain:o},...!1===o?{mode:"brain"}:{},...t.effort?{effort:t.effort}:{},...!0===o&&t.workers?{workers:t.workers}:{},...t.tools.length?{tools:t.tools}:{},...t.toolChoice?{tool_choice:t.toolChoice}:{}},agentKey:t.tools.length&&(process.env.AEGIS_AGENT_KEY||"").trim()||void 0})}if("byok"===o){const{provider:o,model:r}=splitByokModel(t.model),n=canonicalModelId(o,r),s=nativeEffort(o,n,t.effort);try{return await e.byokChatCompletion({provider:o,model:n,providerKey:t.apiKey,baseURL:t.cfg&&t.cfg.baseURL,prompt:t.prompt,system:t.system,messages:t.messages,maxTokens:t.maxTokens,tools:t.tools,toolChoice:t.toolChoice,effort:s&&"effort"===s.field?s.level:void 0,reasoningEffort:s&&"reasoning_effort"===s.field?s.level:void 0,stream:!0,onStream:t.onDelta,signal:t.signal})}catch(e){if(e&&402===e.status){const e=new Error("byok: this account has no AEGIS balance left, and the BYOK handling fee is billed there — your provider key is still valid, this is not a key problem. Top up the account, then try again (or /class aegis to use the pooled lane).");throw e.status=402,e}throw e}}if("local"===o){const e=t.cfg&&t.cfg.baseURL||i.DEFAULT_BASE,o=o=>i.chat({baseURL:e,model:t.model,prompt:t.prompt,system:t.system,messages:t.messages,maxTokens:t.maxTokens,signal:t.signal,onDelta:t.onDelta,...o&&t.tools.length?{tools:t.tools,toolChoice:t.toolChoice}:{}});try{return await o(!0)}catch(e){if(t.tools.length&&e&&400===e.status)return o(!1);throw e}}if("pro"===o){const e=t.sessionKey||t.rootSessionId||t.sessionId,o=e?y.get(e):null,r=function(e){const o=[],t=e=>String(e||"").replace(/[\\/]+$/,""),r=t(e),n=e=>{const n=t(e);n&&n!==r&&!o.includes(n)&&o.push(n)};let s=c;if(void 0===s)try{s=require("./git-scope.js")}catch{s=null}try{s&&"function"==typeof s.gitRoot&&n(s.gitRoot(e))}catch{}try{credentialsLib&&"function"==typeof credentialsLib.aegisHome&&n(credentialsLib.aegisHome())}catch{}return o}(t.cwd),n=await claudePro.runClaudePro({prompt:proTurnPrompt(t),model:t.model&&"default"!==t.model?t.model:void 0,system:t.system,cwd:t.cwd,addDir:r,resumeSessionId:o||void 0,gate:"function"==typeof a?!a():void 0,signal:t.signal,onDelta:t.onDelta,onSpawn:(e,o)=>{t.onDelta&&o&&t.onDelta({delta:"",note:claudePro.childLine(o)})}});return e&&n&&n.sessionId&&!n.error&&y.set(e,n.sessionId),n}throw new Error(`dispatch: unknown model class ${JSON.stringify(o)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)}async function A(t,r){const n=t&&t.class,s=t&&t.model,a=reasoningBudget("byok"===n?splitByokModel(s).model:s,t&&t.maxTokens,t&&t.effort),l=statedCapOf(t),c="aegis"===n&&Boolean(t&&t.autonomous),m=Boolean(t&&t.roundsAsk),g=t&&t.sessionId||randomUUID(),h=Number.isInteger(t&&t.depth)?t.depth:0,y=t&&t.rootSessionId||g,k=t&&t.rootOnDelta||r,v="function"==typeof r?e=>e&&r({reasoning:e}):void 0,b=new AbortController;d.set(g,b);const w=b.signal,A=!(t&&!1===t.tools),x=A?u.toolsFor({includeSubagent:h<4}):[],N=t&&t.toolChoice||null,O=t&&t.system||f(_(t)),R=Array.isArray(t&&t.messages)?t.messages.filter(Boolean).slice():[];let U=R.length,F=t&&t.prompt||"";const D=String(F||""),L=Array.isArray(t&&t.attachments)?t.attachments.filter((e=>e&&"object"==typeof e)).slice(0,attachmentsModule.MAX_ATTACHMENTS):[];let I=L.length?attachmentsModule.buildContent(F,L):F,C=null;const P=_(t),B=P.cwd,q={getShell:()=>C||(C=new ShellSession({cwd:_(t).cwd})),signal:w,cwd:B,desktopdir:P.desktopdir};try{const d="byok"===n?splitByokModel(s):null,f="byok"===n?o.get(byokNamespace(d.provider))||{}:"local"===n&&o.get("local")||{},b="byok"===n?o.rawKey(byokNamespace(d.provider)):null,_="byok"!==n?null:b||providerKeyFromEnv(d.provider);if(!("byok"!==n||d.provider&&d.model)){const e=new Error('byok: model must be "<provider>:<model>" (pick one from /models) — got '+JSON.stringify(s||""));throw e.status=400,e}if("byok"===n&&!_){const e="anthropic"===d.provider?claudePro.claudeProStatus({env:process.env}):null,o=providerKeyRecord(d.provider).rejected,t=new Error(o?`${o}. That is why this turn has no ${d.provider} key: an env value that short is a paste that lost its payload, not a credential. Fix ${o.split(" ")[0]} in ~/.aegiscode/.env (or the shell that exported it) — or skip keys entirely: /byok-key ${d.provider} <key> to set one here.`:e&&e.loggedIn?`No Anthropic API key on this machine — an "anthropic:…" id is served by your own console key, which a Claude subscription is not. Use the subscription instead: /class pro (it spends your Claude Code ${e.subscription||"Pro"} plan through the claude CLI) — or add a real console key: /byok-key anthropic <key>.`:`No key for "${d.provider}" yet. Easiest fix: /class aegis (uses your AEGIS key, no setup) — or add this provider's own key: /byok-key ${d.provider} <key>.`);throw t.status=400,t}if("byok"===n&&!e.apiKey){const e=new Error("No AEGIS key connected yet. Easiest fix: /class aegis (skips BYOK entirely) — or add your AEGIS key with /login, then try again.");throw e.status=401,e}if("local"===n){const e=i.remoteRefusal(f.baseURL||i.DEFAULT_BASE);if(e)throw e}if("byok"===n&&"custom"===d.provider&&!(f.baseURL||"").trim()){const e=new Error('No endpoint saved for the "custom" provider — its key is on this machine but the address it dials is not, and no default exists for a vendor AEGIS does not know. Fix: /model-add custom <https-base-url> <api-key> <model-id> (writes both halves), or the endpoint field in Settings › Provider (custom).');throw e.status=400,e.code="custom_endpoint_missing",e}const C={cls:n,model:s,mode:t&&t.mode,maxTokens:a,statedMaxTokens:l,autonomous:c,sessionId:g,signal:w,onDelta:r,cfg:f,apiKey:_,toolChoice:N,cwd:B,rootSessionId:y,sessionKey:t&&t.sessionKey||void 0,effort:t&&t.effort,workers:t&&t.workers,recallDeep:t&&!0===t.recallDeep,singlePass:t&&!0===t.singlePass,onReasoning:v,idleTimeoutMs:c?9e5:void 0,stream:!t||!1!==t.stream};let P=!1,j=!1;const K=c?"AEGIS_AUTONOMOUS_MAX_ROUNDS":"AEGIS_CHAT_MAX_ROUNDS",$=(()=>{const e=Number.parseInt(process.env[K]||"",10);return Number.isFinite(e)&&e>0?e:0})(),G=$||(c?40:24);let Y=p.keyFor(t,R),W=p.take(Y);if(!W&&!p.isStatedKey(t)){const e=p.adopt();e&&(W=e.entry,Y=e.key)}if(W){const e=p.resumePreamble(W);0===R.length?Array.isArray(W.messages)&&W.messages.length&&R.push(...W.messages):Array.isArray(W.added)&&W.added.length&&R.push(...W.added),F?(F=`${e}\n\n${F}`,I=L.length?attachmentsModule.buildContent(F,L):F):(R.push({role:"user",content:e}),I=""),k&&k({delta:`\n\n[resuming work this session left unfinished at ${W.rounds} tool rounds`+(W.interruptions>1?` (cut off ${W.interruptions}×)`:"")+"…]\n"})}let z=$||G+(W?p.bonus(G):0),H=0;const V=G,X=8;let J=0;const Q={calls:0},Z=["input_tokens","output_tokens","prompt_tokens","completion_tokens","total_tokens","cache_read_input_tokens","cache_creation_input_tokens","prompt_cache_hit_tokens","prompt_cache_miss_tokens","reasoning_tokens","thinking_tokens"],ee=e=>{const o=e&&e.usage;if(o&&"object"==typeof o){Q.calls+=1;for(const e of Z)"number"==typeof o[e]&&Number.isFinite(o[e])&&(Q[e]=(Q[e]||0)+o[e]);if("number"!=typeof o.total_tokens){const e=(o.prompt_tokens??o.input_tokens??0)+(o.completion_tokens??o.output_tokens??0);e&&(Q.total_tokens=(Q.total_tokens||0)+e)}}},oe=e=>e&&"object"==typeof e&&Q.calls?{...e,usage:{...Q}}:e,te=()=>{if(""===I)return;const e=R[R.length-1],o=e&&"user"===e.role?flattenContent(e.content):null;e&&"user"===e.role&&o===flattenContent(I)||R.push({role:"user",content:I}),F="",I=""};U=R.length;const re=u&&u.MUTATING_TOOLS||new Set;let ne=0,se=0,ae=!1;for(;;){if(H>=z){if(m&&J<X&&!w.aborted&&await E(y,k,w,{spent:z,extensions:J+1,max:X,size:V})){J+=1;const e=z;z+=V,R.push({role:"user",content:`You have used all ${e} tool rounds allowed for this turn; ${V} more have been granted (do not restart). Continue the task from exactly where you stopped — do not re-plan, do not repeat work already done, and finish with an answer.`});continue}const e=m?"":`, or raise ${K} for a longer single turn`,o=`[stopped at ${z} tool rounds`+(Q.total_tokens?`, ${Q.total_tokens.toLocaleString()} tokens`:"")+". This session holds the work: your next message here resumes it automatically"+` (with a continuation preamble)${e}.]`,t=p.record(Y,{rounds:H,tokens:Q.total_tokens||0,note:o,chain:W?W.interruptions:0,messages:R,added:R.slice(U)});return k&&k({delta:`\n\n${o}`}),oe({model:C.model,choices:[{message:{content:o},finish_reason:"length"}],stoppedOnRounds:!0,heldForSession:!0,heldRounds:t.rounds,sessionInterruptions:t.interruptions,resumedFrom:Y})}H+=1;const e={...C,system:O,messages:R,prompt:I,tools:x,recallDeep:C.recallDeep&&1===H};let o;if(o=await S(n,e),ee(o),w.aborted)return oe(o);if(!P&&!assistantText(o)&&(isTruncated(o)||reasonedButSilent(o))){P=!0;const t=reasonedButSilent(o);if(o=await S(n,{...e,singlePass:!0,recallDeep:!1,effort:t?"high":e.effort,maxTokens:retryBudgetFor(e,t),statedMaxTokens:e.statedMaxTokens?doubledBudget(e.statedMaxTokens):void 0}),ee(o),w.aborted)return oe(o)}const a=x.length?extractToolCalls(o):[];if(!a.length){if(assistantText(o)||j||!A){if(!ae&&A&&wantsMutation(D,se>0,ne)){ae=!0,te(),R.push({role:"assistant",content:assistantText(o)}),R.push({role:"user",content:UNMUTATED_TURN_NUDGE}),k&&k({delta:""});continue}return oe(o)}j=!0,te(),R.push({role:"user",content:reasonedButSilent(o)?THOUGHT_ONLY_NUDGE:EMPTY_TURN_NUDGE});const t={...e,singlePass:!0,recallDeep:!1,messages:R,prompt:"",tools:[]};o=await S(n,t);let r=t.maxTokens,a=t.effort;if(ee(o),w.aborted)return oe(o);if(!assistantText(o)&&(isTruncated(o)||reasonedButSilent(o))){const e=reasonedButSilent(o);if(r=retryBudgetFor(t,e),a=e?"high":t.effort,o=await S(n,{...t,effort:a,maxTokens:r,statedMaxTokens:t.statedMaxTokens?doubledBudget(t.statedMaxTokens):void 0}),ee(o),w.aborted)return oe(o)}const i=(()=>{const e=Number(r)||0;if(!e)return r;const o={maxTokens:r};return t.statedMaxTokens&&(o.statedMaxTokens=t.statedMaxTokens),Math.max(e,retryBudgetFor(o,!0))})();let l=0;for(;!assistantText(o)&&l<2&&!w.aborted;){const e=reasonedButSilent(o);if(l+=1,R.push({role:"user",content:e?1===l?THOUGHT_ONLY_NUDGE:FINAL_ANSWER_NUDGE:EMPTY_TURN_NUDGE}),e&&(a="high"),r=i,o=await S(n,{...t,messages:R,effort:a,maxTokens:r,statedMaxTokens:t.statedMaxTokens?doubledBudget(t.statedMaxTokens):void 0}),ee(o),w.aborted)return oe(o)}if(!assistantText(o))throw emptyTurnError({cls:n,model:s,effort:a,recoveryRounds:l,finishReason:finishReasonOf(o),reasoningChars:reasoningTextOf(o).length,reasoningTokens:reasoningTokensOf(o)});return oe(o)}te(),R.push({role:"assistant",content:assistantText(o),tool_calls:a.map((e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.args)}})))});const i=new WeakMap,c=e=>{if("exec"!==e.name)return null;if(i.has(e))return i.get(e);const o=planExec(e.args&&e.args.command,{baseCwd:B});return i.set(e,o),o},d=e=>{if(e.name===u.SUBAGENT_TOOL)return!1;if(!re.has(e.name))return!0;const o=c(e);return Boolean(o&&o.oneShot)},f=[];for(const e of a){const o=f[f.length-1];d(e)&&o&&o.parallel?o.calls.push(e):f.push({parallel:d(e),calls:[e]})}const g=async e=>{r&&r({delta:"",tool:{name:e.name,args:e.args,id:e.id,cwd:B,phase:"run"}});const o=c(e),a=o&&o.oneShot?{...q,oneShotExec:!0,cwd:o.cwd||q.cwd}:q,i=e.name===u.SUBAGENT_TOOL?await M(e.args,{cls:n,model:s,statedMaxTokens:l,effort:t&&t.effort,mode:t&&t.mode,parentSignal:w,depth:h,rootSessionId:y,rootOnDelta:k}):await T(e,{toolCtx:a,rootSessionId:y,rootOnDelta:k,signal:w});return i&&i.usage&&ee({usage:i.usage}),r&&r({delta:"",tool:{name:e.name,args:e.args,ok:i.ok,id:e.id,cwd:B,phase:"done"}}),i};for(const e of f){const o=e.parallel&&e.calls.length>1?await Promise.all(e.calls.map((e=>g(e)))):[await g(e.calls[0])];e.calls.forEach(((e,t)=>{const r=o[t];re.has(e.name)&&(ne+=1,r&&r.ok&&(se+=1)),R.push({role:"tool",tool_call_id:e.id,name:e.name,content:u.toolResultText(r)})}))}}}catch(e){throw w.aborted&&e&&"object"==typeof e&&(e.aegisCancelled=!0),e}finally{C&&C.dispose(),d.delete(g)}}async function M({description:e,subagent_type:o,prompt:t}={},{cls:r,model:n,statedMaxTokens:s,effort:a,mode:i,parentSignal:l,depth:c,rootSessionId:d,rootOnDelta:u}={}){const f=String(t||e||"").trim();if(!f)return{ok:!1,error:"task requires a prompt"};const p=o&&"general"!==o?agentRoleLabel(o):"general",m=agentSystemPrompt(o),g=randomUUID();let h;if(l){if(l.aborted)return{ok:!1,error:"aborted"};h=()=>x(g),l.addEventListener("abort",h,{once:!0})}try{const e=await A({class:r,model:n,mode:i,system:m,prompt:f,sessionId:g,depth:(c||0)+1,rootSessionId:d,rootOnDelta:u,statedMaxTokens:s,effort:a},(()=>{})),o=assistantText(e),t=e&&e.usage?{usage:e.usage}:{};return o?{ok:!0,output:o,...t}:{ok:!1,error:`subagent (${p}) produced no output`,...t}}catch(e){return{ok:!1,error:`subagent (${p}) failed: ${e&&e.message?e.message:e}`}}finally{l&&h&&l.removeEventListener("abort",h)}}function x(e){const o=d.get(e);return o&&o.abort(),{ok:Boolean(o)}}return{CLASSES:CLASSES,listClasses:async function(){return CLASSES.map((t=>{if("aegis"===t.class)return{...t,configured:Boolean(e.apiKey)};if("byok"===t.class){const e=(o.list()||[]).some((e=>!(!e||"string"!=typeof e.provider||!e.provider.startsWith("byok:"))&&(!!e.configured||Boolean(providerKeyFromEnv(e.provider.slice(BYOK_NAMESPACE_PREFIX.length))))));return{...t,configured:e}}if("local"===t.class)return{...t,configured:!0};if("pro"===t.class){const e=claudePro.claudeProStatus({env:process.env}),o=claudePro.seamAvailable();return{...t,configured:e.loggedIn,status:e,seam:o}}return{...t,configured:!1}}))},listModels:async function(t){if("aegis"===t){if(!e.apiKey)return{class:t,models:[],needsKey:!0};const o=await e.listModels();return{class:t,models:offerableCatalog(normalizeCatalog(o&&o.models))}}if("byok"===t){let r=[],n=null,s=!1,a=null;try{const o=await e.byokProviders();r=withUserModels(withCatalog(withByokAdditions(o&&o.providers||[]))),n=o&&o.fee||null}catch(e){r=[],s=!0,a=e&&e.message||String(e)}const i=[];for(const e of r){if(!e||!e.id)continue;const t=o.get(byokNamespace(e.id))||{},r=providerKeyRecord(e.id),n=r.key||"",s=Array.isArray(e.models)?e.models:[];for(const o of s){const s="string"==typeof o?o:o&&o.id;s&&i.push({id:`${e.id}:${s}`,label:`${e.label||e.id} — ${s}`,provider:e.id,configured:Boolean(t.configured||n),keyRejected:r.rejected||null})}}return{class:t,models:i,providers:r,needsProviderKey:i.length>0&&!i.some((e=>e.configured)),needsAegisKey:!e.apiKey,fee:n,providersFailed:s,providersError:a,unmatchedProviders:unmatchedUserProviders(r)}}if("local"===t){const e=(o.get("local")||{}).baseURL||i.DEFAULT_BASE,r=await i.probe(e);if(!r.running)return{class:t,models:[],baseURL:r.baseURL,needsDaemon:!0};let n=[],s=!0;try{n=await i.listTags(e)}catch{s=!1}return{class:t,models:n,baseURL:r.baseURL,listed:s}}if("pro"===t){const e=claudePro.claudeProStatus({env:process.env});return{class:t,models:claudePro.PRO_MODELS.map((o=>({id:o.id,label:o.label,note:o.note,configured:e.loggedIn}))),needsProviderKey:!1,needsAegisKey:!1,subscription:e.subscription,loggedIn:e.loggedIn,credentialFile:e.file,shadowed:e.shadowed||null,seam:claudePro.seamAvailable()}}throw new Error(`listModels: unknown model class ${JSON.stringify(t)} — this build ships 'aegis', 'byok', 'local' and 'pro' only`)},chat:A,cancel:x,respondApproval:function(e,o){const t=k.get(e);return t?(k.delete(e),t.resolve("session"===o||"once"===o?o:"deny"),{ok:!0}):{ok:!1}},respondRoundsAsk:function(e,o){const t=v.get(e);return t?(v.delete(e),t.resolve(!0===o||"continue"===o),{ok:!0}):{ok:!1}},clearSessionApprovals:function(e){return g.delete(e),h.delete(e),y.delete(e),{ok:!0}},settings:o,unloadLocalModels:function(){return i.unloadAll()},userModels:()=>loadUserModels(),addUserModel:(e,o)=>addUserModel(e,o),removeUserModel:(e,o)=>removeUserModel(e,o),discoverModels:async e=>{const t=String(null==e?"":e).trim().toLowerCase(),r=function(e){const t=String(null==e?"":e).trim().toLowerCase();if(!t)return"";try{if(o&&"function"==typeof o.rawKey){const e=o.rawKey(byokNamespace(t));if("string"==typeof e&&e.trim())return e.trim()}}catch{}return providerKeyFromEnv(t)}(t),n=await discoverVendorModels(t,{key:r,fetchImpl:l});if(!n||!n.ok)return n;const s=[];try{const e=loadUserModels().map;for(const o of Array.isArray(e[t])?e[t]:[])s.push(o)}catch{}return{...n,declared:s,endpoint:(vendorEndpointFor(t)||{}).url||""}},addUserModels:(e,o)=>{const t=Array.isArray(o)?o:[],r={provider:e,added:0,already:[],failed:[],capped:0,file:""};for(const o of t)try{const t=addUserModel(e,o);r.file=t.file||r.file,t.added?r.added+=1:r.already.push(t.model)}catch(e){const n=e&&e.message||String(e);if(/the cap/.test(n)){r.capped=t.length-r.added-r.already.length-r.failed.length;break}r.failed.push({id:String(o),reason:n})}return r},canDiscoverModels:e=>canDiscoverVendorModels(e),discoverableProviders:()=>discoverableProviders()}}module.exports={CLASSES:CLASSES,createLocalEngine:createLocalEngine,extractToolCalls:extractToolCalls,parseArgs:parseArgs,reasoningBudget:reasoningBudget,nativeEffort:nativeEffort,hostEnv:hostEnv};
|