@causyne/agent 1.20.120 → 1.20.121
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/package.json +1 -1
- package/src/agent/errorClassifier.js +113 -0
- package/src/agent/errorClassifier.ts +161 -0
- package/src/agent/promptIntent.js +200 -0
- package/src/agent/promptIntent.ts +203 -0
- package/src/agent/toolArgValidator.js +97 -0
- package/src/agent/toolArgValidator.ts +112 -0
- package/src/agentLoop.js +22 -339
- package/src/agentLoop.ts +40 -347
- package/src/autoUpdate.js +111 -8
- package/src/autoUpdate.ts +144 -8
- package/src/cliMode.js +16 -2
- package/src/commands.js +10 -9
- package/src/config.js +42 -63
- package/src/configVault.js +204 -0
- package/src/configVault.ts +213 -0
- package/src/core/contextCompactor.js +70 -11
- package/src/core/contextCompactor.ts +83 -11
- package/src/dynamicCatalogue.js +42 -73
- package/src/dynamicCatalogue.ts +74 -60
- package/src/entrypoint.js +77 -4
- package/src/headlessCli.js +304 -0
- package/src/headlessCli.ts +380 -0
- package/src/mcp/mcpClient.js +38 -11
- package/src/mcp/mcpClient.ts +44 -11
- package/src/mcp/mcpRegistry.js +2 -5
- package/src/mcp/mcpRegistry.ts +2 -5
- package/src/mcp/mcpSecurity.js +189 -0
- package/src/mcp/mcpSecurity.ts +190 -0
- package/src/osKeychain.js +209 -0
- package/src/osKeychain.ts +245 -0
- package/src/providers/anthropic.js +28 -11
- package/src/providers/byokHttp.js +354 -0
- package/src/providers/byokHttp.ts +454 -0
- package/src/providers/byokStream.js +657 -0
- package/src/providers/byokStream.ts +759 -0
- package/src/providers/dashscope-byok.js +34 -25
- package/src/providers/deepseek.js +31 -22
- package/src/providers/gemini.js +40 -13
- package/src/providers/moonshot.js +31 -22
- package/src/providers/muse.js +10 -10
- package/src/providers/ollama.js +25 -10
- package/src/providers/openai-compatible.js +46 -14
- package/src/providers/openrouter.js +63 -29
- package/src/providers/openrouter.ts +73 -29
- package/src/providers/qwen-byok.js +33 -16
- package/src/providers/xai.js +31 -22
- package/src/sandbox.js +77 -56
- package/src/sandboxPolicy.js +1208 -0
- package/src/sandboxPolicy.ts +1300 -0
- package/src/sessionJournal.js +47 -0
- package/src/sessionJournal.ts +49 -0
- package/src/tools/osSandbox.js +473 -0
- package/src/tools/osSandbox.ts +554 -0
- package/src/tools/persistentShell.js +8 -3
- package/src/tools/subprocessEnv.js +197 -0
- package/src/tools/subprocessEnv.ts +212 -0
- package/src/tools/sysRun.js +39 -6
- package/src/tools/sysRun.ts +53 -7
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Causyne Agent — Atomic Config Vault & AES-256-GCM Secret Protection
|
|
3
|
+
*
|
|
4
|
+
* Hardens local BYOK credential storage (`~/.causyne/config.json` & `.vault_key`):
|
|
5
|
+
* 1. Atomic write-temp-chmod-rename (`atomicWriteSecretFileSync`) to prevent
|
|
6
|
+
* truncated/corrupted config files on crash or concurrent writes.
|
|
7
|
+
* 2. Strict `0o700` vault directory and `0o600` secret file permissions on POSIX.
|
|
8
|
+
* 3. NIST SP 800-38D standard 12-byte (96-bit) IV for new AES-256-GCM ciphertexts,
|
|
9
|
+
* while preserving full decryption compatibility with legacy 16-byte IV records.
|
|
10
|
+
*/
|
|
11
|
+
import crypto from 'node:crypto';
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import { loadVaultKeyFromKeychain, resolveKeychainMode, saveVaultKeyToKeychain } from './osKeychain.js';
|
|
15
|
+
export const VAULT_KEY_BYTES = 32;
|
|
16
|
+
export const VAULT_GCM_IV_BYTES = 12;
|
|
17
|
+
export const VAULT_LEGACY_GCM_IV_BYTES = 16;
|
|
18
|
+
export const VAULT_GCM_AUTH_TAG_BYTES = 16;
|
|
19
|
+
export const VAULT_ENC_PREFIX = 'ENC:';
|
|
20
|
+
export function isEncryptedVaultSecret(value) {
|
|
21
|
+
return typeof value === 'string' && value.startsWith(VAULT_ENC_PREFIX);
|
|
22
|
+
}
|
|
23
|
+
export function ensureVaultDir(dir) {
|
|
24
|
+
const resolved = path.resolve(dir);
|
|
25
|
+
if (!fs.existsSync(resolved)) {
|
|
26
|
+
fs.mkdirSync(resolved, { recursive: true, mode: 0o700 });
|
|
27
|
+
}
|
|
28
|
+
if (process.platform !== 'win32') {
|
|
29
|
+
try {
|
|
30
|
+
fs.chmodSync(resolved, 0o700);
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
// Best-effort permission tightening on platforms that restrict chmod
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Atomically writes a secret-bearing file (`config.json` or `.vault_key`) using
|
|
39
|
+
* a unique sibling temporary file with mode `0o600` followed by atomic rename.
|
|
40
|
+
*/
|
|
41
|
+
export function atomicWriteSecretFileSync(targetPath, content) {
|
|
42
|
+
const resolved = path.resolve(targetPath);
|
|
43
|
+
const dir = path.dirname(resolved);
|
|
44
|
+
ensureVaultDir(dir);
|
|
45
|
+
const suffix = `${process.pid}.${crypto.randomBytes(6).toString('hex')}`;
|
|
46
|
+
const tempPath = path.join(dir, `.${path.basename(resolved)}.${suffix}.tmp`);
|
|
47
|
+
try {
|
|
48
|
+
if (typeof content === 'string') {
|
|
49
|
+
fs.writeFileSync(tempPath, content, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
fs.writeFileSync(tempPath, content, { mode: 0o600, flag: 'wx' });
|
|
53
|
+
}
|
|
54
|
+
if (process.platform !== 'win32') {
|
|
55
|
+
try {
|
|
56
|
+
fs.chmodSync(tempPath, 0o600);
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
// Ignore chmod errors on non-POSIX mounts
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
fs.renameSync(tempPath, resolved);
|
|
63
|
+
if (process.platform !== 'win32') {
|
|
64
|
+
try {
|
|
65
|
+
fs.chmodSync(resolved, 0o600);
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
// Ignore chmod errors on non-POSIX mounts
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
catch (err) {
|
|
73
|
+
try {
|
|
74
|
+
if (fs.existsSync(tempPath))
|
|
75
|
+
fs.unlinkSync(tempPath);
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
// Ignore temp cleanup failure
|
|
79
|
+
}
|
|
80
|
+
throw err;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Loads or atomically initializes the 256-bit local vault key with `0o600` permissions.
|
|
85
|
+
* When `CAUSYNE_KEYCHAIN=on|auto|strict` is enabled, uses the OS Keychain backend
|
|
86
|
+
* first (migrating an existing file key if present) and fails closed on `strict`.
|
|
87
|
+
*/
|
|
88
|
+
export function getOrCreateVaultKey(keyFilePath, keychainOptions) {
|
|
89
|
+
const resolved = path.resolve(keyFilePath);
|
|
90
|
+
const vaultDir = path.dirname(resolved);
|
|
91
|
+
ensureVaultDir(vaultDir);
|
|
92
|
+
const keychainMode = resolveKeychainMode(keychainOptions?.env ?? process.env);
|
|
93
|
+
if (keychainMode !== 'off') {
|
|
94
|
+
const fromKeychain = loadVaultKeyFromKeychain(vaultDir, keychainOptions);
|
|
95
|
+
if (fromKeychain && fromKeychain.length === VAULT_KEY_BYTES) {
|
|
96
|
+
return fromKeychain;
|
|
97
|
+
}
|
|
98
|
+
// If a file key already exists, migrate it cleanly into the OS Keychain
|
|
99
|
+
if (fs.existsSync(resolved)) {
|
|
100
|
+
const existingFileKey = fs.readFileSync(resolved);
|
|
101
|
+
if (existingFileKey.length === VAULT_KEY_BYTES) {
|
|
102
|
+
const stored = saveVaultKeyToKeychain(vaultDir, existingFileKey, keychainOptions);
|
|
103
|
+
if (stored || keychainMode !== 'strict') {
|
|
104
|
+
return existingFileKey;
|
|
105
|
+
}
|
|
106
|
+
throw new Error('Strict OS keychain mode requested (CAUSYNE_KEYCHAIN=strict) but storing the vault key failed.');
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
// Generate a fresh key and persist into OS Keychain
|
|
110
|
+
const generated = crypto.randomBytes(VAULT_KEY_BYTES);
|
|
111
|
+
if (saveVaultKeyToKeychain(vaultDir, generated, keychainOptions)) {
|
|
112
|
+
return generated;
|
|
113
|
+
}
|
|
114
|
+
if (keychainMode === 'strict') {
|
|
115
|
+
throw new Error('Strict OS keychain mode requested (CAUSYNE_KEYCHAIN=strict) but OS keychain storage is unavailable.');
|
|
116
|
+
}
|
|
117
|
+
// Non-strict (`on`/`auto`) degrades cleanly to atomic 0600 file storage below
|
|
118
|
+
}
|
|
119
|
+
if (fs.existsSync(resolved)) {
|
|
120
|
+
if (process.platform !== 'win32') {
|
|
121
|
+
try {
|
|
122
|
+
fs.chmodSync(resolved, 0o600);
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
// Ignore chmod errors on non-POSIX mounts
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
const existing = fs.readFileSync(resolved);
|
|
129
|
+
if (existing.length !== VAULT_KEY_BYTES) {
|
|
130
|
+
throw new Error(`Invalid vault key length (${existing.length} bytes; expected ${VAULT_KEY_BYTES}).`);
|
|
131
|
+
}
|
|
132
|
+
return existing;
|
|
133
|
+
}
|
|
134
|
+
const freshKey = crypto.randomBytes(VAULT_KEY_BYTES);
|
|
135
|
+
try {
|
|
136
|
+
// Exclusive create first so concurrent startups do not clobber each other's key
|
|
137
|
+
fs.writeFileSync(resolved, freshKey, { mode: 0o600, flag: 'wx' });
|
|
138
|
+
if (process.platform !== 'win32') {
|
|
139
|
+
try {
|
|
140
|
+
fs.chmodSync(resolved, 0o600);
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
// Ignore chmod errors
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return freshKey;
|
|
147
|
+
}
|
|
148
|
+
catch (err) {
|
|
149
|
+
const code = typeof err === 'object' && err !== null && 'code' in err ? String(err.code) : '';
|
|
150
|
+
if (code === 'EEXIST') {
|
|
151
|
+
const raced = fs.readFileSync(resolved);
|
|
152
|
+
if (raced.length === VAULT_KEY_BYTES)
|
|
153
|
+
return raced;
|
|
154
|
+
}
|
|
155
|
+
throw err;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Encrypts a plaintext secret using AES-256-GCM with a NIST-standard 12-byte IV.
|
|
160
|
+
*/
|
|
161
|
+
export function encryptVaultSecret(text, keyFilePath) {
|
|
162
|
+
if (!text)
|
|
163
|
+
return text;
|
|
164
|
+
if (isEncryptedVaultSecret(text))
|
|
165
|
+
return text;
|
|
166
|
+
const key = getOrCreateVaultKey(keyFilePath);
|
|
167
|
+
const iv = crypto.randomBytes(VAULT_GCM_IV_BYTES);
|
|
168
|
+
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
|
|
169
|
+
let encrypted = cipher.update(text, 'utf8', 'hex');
|
|
170
|
+
encrypted += cipher.final('hex');
|
|
171
|
+
const authTag = cipher.getAuthTag().toString('hex');
|
|
172
|
+
return `${VAULT_ENC_PREFIX}${iv.toString('hex')}:${authTag}:${encrypted}`;
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Decrypts an `ENC:` secret produced with either the standard 12-byte GCM IV
|
|
176
|
+
* or legacy 16-byte GCM IV. Returns empty string on authentication failure.
|
|
177
|
+
*/
|
|
178
|
+
export function decryptVaultSecret(encryptedText, keyFilePath) {
|
|
179
|
+
if (!encryptedText || !isEncryptedVaultSecret(encryptedText))
|
|
180
|
+
return encryptedText;
|
|
181
|
+
try {
|
|
182
|
+
const parts = encryptedText.split(':');
|
|
183
|
+
if (parts.length !== 4)
|
|
184
|
+
return '';
|
|
185
|
+
const ivHex = parts[1] ?? '';
|
|
186
|
+
const authTagHex = parts[2] ?? '';
|
|
187
|
+
const ciphertextHex = parts[3] ?? '';
|
|
188
|
+
const iv = Buffer.from(ivHex, 'hex');
|
|
189
|
+
const authTag = Buffer.from(authTagHex, 'hex');
|
|
190
|
+
if ((iv.length !== VAULT_GCM_IV_BYTES && iv.length !== VAULT_LEGACY_GCM_IV_BYTES) ||
|
|
191
|
+
authTag.length !== VAULT_GCM_AUTH_TAG_BYTES) {
|
|
192
|
+
return '';
|
|
193
|
+
}
|
|
194
|
+
const key = getOrCreateVaultKey(keyFilePath);
|
|
195
|
+
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
|
|
196
|
+
decipher.setAuthTag(authTag);
|
|
197
|
+
let decrypted = decipher.update(ciphertextHex, 'hex', 'utf8');
|
|
198
|
+
decrypted += decipher.final('utf8');
|
|
199
|
+
return decrypted;
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
return '';
|
|
203
|
+
}
|
|
204
|
+
}
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Causyne Agent — Atomic Config Vault & AES-256-GCM Secret Protection
|
|
3
|
+
*
|
|
4
|
+
* Hardens local BYOK credential storage (`~/.causyne/config.json` & `.vault_key`):
|
|
5
|
+
* 1. Atomic write-temp-chmod-rename (`atomicWriteSecretFileSync`) to prevent
|
|
6
|
+
* truncated/corrupted config files on crash or concurrent writes.
|
|
7
|
+
* 2. Strict `0o700` vault directory and `0o600` secret file permissions on POSIX.
|
|
8
|
+
* 3. NIST SP 800-38D standard 12-byte (96-bit) IV for new AES-256-GCM ciphertexts,
|
|
9
|
+
* while preserving full decryption compatibility with legacy 16-byte IV records.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import crypto from 'node:crypto';
|
|
13
|
+
import fs from 'node:fs';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import {
|
|
16
|
+
loadVaultKeyFromKeychain,
|
|
17
|
+
resolveKeychainMode,
|
|
18
|
+
saveVaultKeyToKeychain,
|
|
19
|
+
type KeychainSpawnOptions
|
|
20
|
+
} from './osKeychain.js';
|
|
21
|
+
|
|
22
|
+
export const VAULT_KEY_BYTES = 32;
|
|
23
|
+
export const VAULT_GCM_IV_BYTES = 12;
|
|
24
|
+
export const VAULT_LEGACY_GCM_IV_BYTES = 16;
|
|
25
|
+
export const VAULT_GCM_AUTH_TAG_BYTES = 16;
|
|
26
|
+
export const VAULT_ENC_PREFIX = 'ENC:';
|
|
27
|
+
|
|
28
|
+
export function isEncryptedVaultSecret(value: unknown): value is string {
|
|
29
|
+
return typeof value === 'string' && value.startsWith(VAULT_ENC_PREFIX);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function ensureVaultDir(dir: string): void {
|
|
33
|
+
const resolved = path.resolve(dir);
|
|
34
|
+
if (!fs.existsSync(resolved)) {
|
|
35
|
+
fs.mkdirSync(resolved, { recursive: true, mode: 0o700 });
|
|
36
|
+
}
|
|
37
|
+
if (process.platform !== 'win32') {
|
|
38
|
+
try {
|
|
39
|
+
fs.chmodSync(resolved, 0o700);
|
|
40
|
+
} catch {
|
|
41
|
+
// Best-effort permission tightening on platforms that restrict chmod
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Atomically writes a secret-bearing file (`config.json` or `.vault_key`) using
|
|
48
|
+
* a unique sibling temporary file with mode `0o600` followed by atomic rename.
|
|
49
|
+
*/
|
|
50
|
+
export function atomicWriteSecretFileSync(targetPath: string, content: string | Buffer): void {
|
|
51
|
+
const resolved = path.resolve(targetPath);
|
|
52
|
+
const dir = path.dirname(resolved);
|
|
53
|
+
ensureVaultDir(dir);
|
|
54
|
+
|
|
55
|
+
const suffix = `${process.pid}.${crypto.randomBytes(6).toString('hex')}`;
|
|
56
|
+
const tempPath = path.join(dir, `.${path.basename(resolved)}.${suffix}.tmp`);
|
|
57
|
+
|
|
58
|
+
try {
|
|
59
|
+
if (typeof content === 'string') {
|
|
60
|
+
fs.writeFileSync(tempPath, content, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
|
|
61
|
+
} else {
|
|
62
|
+
fs.writeFileSync(tempPath, content, { mode: 0o600, flag: 'wx' });
|
|
63
|
+
}
|
|
64
|
+
if (process.platform !== 'win32') {
|
|
65
|
+
try {
|
|
66
|
+
fs.chmodSync(tempPath, 0o600);
|
|
67
|
+
} catch {
|
|
68
|
+
// Ignore chmod errors on non-POSIX mounts
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
fs.renameSync(tempPath, resolved);
|
|
72
|
+
if (process.platform !== 'win32') {
|
|
73
|
+
try {
|
|
74
|
+
fs.chmodSync(resolved, 0o600);
|
|
75
|
+
} catch {
|
|
76
|
+
// Ignore chmod errors on non-POSIX mounts
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
} catch (err: unknown) {
|
|
80
|
+
try {
|
|
81
|
+
if (fs.existsSync(tempPath)) fs.unlinkSync(tempPath);
|
|
82
|
+
} catch {
|
|
83
|
+
// Ignore temp cleanup failure
|
|
84
|
+
}
|
|
85
|
+
throw err;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Loads or atomically initializes the 256-bit local vault key with `0o600` permissions.
|
|
91
|
+
* When `CAUSYNE_KEYCHAIN=on|auto|strict` is enabled, uses the OS Keychain backend
|
|
92
|
+
* first (migrating an existing file key if present) and fails closed on `strict`.
|
|
93
|
+
*/
|
|
94
|
+
export function getOrCreateVaultKey(
|
|
95
|
+
keyFilePath: string,
|
|
96
|
+
keychainOptions?: KeychainSpawnOptions
|
|
97
|
+
): Buffer {
|
|
98
|
+
const resolved = path.resolve(keyFilePath);
|
|
99
|
+
const vaultDir = path.dirname(resolved);
|
|
100
|
+
ensureVaultDir(vaultDir);
|
|
101
|
+
|
|
102
|
+
const keychainMode = resolveKeychainMode(keychainOptions?.env ?? process.env);
|
|
103
|
+
if (keychainMode !== 'off') {
|
|
104
|
+
const fromKeychain = loadVaultKeyFromKeychain(vaultDir, keychainOptions);
|
|
105
|
+
if (fromKeychain && fromKeychain.length === VAULT_KEY_BYTES) {
|
|
106
|
+
return fromKeychain;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// If a file key already exists, migrate it cleanly into the OS Keychain
|
|
110
|
+
if (fs.existsSync(resolved)) {
|
|
111
|
+
const existingFileKey = fs.readFileSync(resolved);
|
|
112
|
+
if (existingFileKey.length === VAULT_KEY_BYTES) {
|
|
113
|
+
const stored = saveVaultKeyToKeychain(vaultDir, existingFileKey, keychainOptions);
|
|
114
|
+
if (stored || keychainMode !== 'strict') {
|
|
115
|
+
return existingFileKey;
|
|
116
|
+
}
|
|
117
|
+
throw new Error('Strict OS keychain mode requested (CAUSYNE_KEYCHAIN=strict) but storing the vault key failed.');
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Generate a fresh key and persist into OS Keychain
|
|
122
|
+
const generated = crypto.randomBytes(VAULT_KEY_BYTES);
|
|
123
|
+
if (saveVaultKeyToKeychain(vaultDir, generated, keychainOptions)) {
|
|
124
|
+
return generated;
|
|
125
|
+
}
|
|
126
|
+
if (keychainMode === 'strict') {
|
|
127
|
+
throw new Error('Strict OS keychain mode requested (CAUSYNE_KEYCHAIN=strict) but OS keychain storage is unavailable.');
|
|
128
|
+
}
|
|
129
|
+
// Non-strict (`on`/`auto`) degrades cleanly to atomic 0600 file storage below
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
if (fs.existsSync(resolved)) {
|
|
133
|
+
if (process.platform !== 'win32') {
|
|
134
|
+
try {
|
|
135
|
+
fs.chmodSync(resolved, 0o600);
|
|
136
|
+
} catch {
|
|
137
|
+
// Ignore chmod errors on non-POSIX mounts
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
const existing = fs.readFileSync(resolved);
|
|
141
|
+
if (existing.length !== VAULT_KEY_BYTES) {
|
|
142
|
+
throw new Error(`Invalid vault key length (${existing.length} bytes; expected ${VAULT_KEY_BYTES}).`);
|
|
143
|
+
}
|
|
144
|
+
return existing;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const freshKey = crypto.randomBytes(VAULT_KEY_BYTES);
|
|
148
|
+
try {
|
|
149
|
+
// Exclusive create first so concurrent startups do not clobber each other's key
|
|
150
|
+
fs.writeFileSync(resolved, freshKey, { mode: 0o600, flag: 'wx' });
|
|
151
|
+
if (process.platform !== 'win32') {
|
|
152
|
+
try {
|
|
153
|
+
fs.chmodSync(resolved, 0o600);
|
|
154
|
+
} catch {
|
|
155
|
+
// Ignore chmod errors
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return freshKey;
|
|
159
|
+
} catch (err: unknown) {
|
|
160
|
+
const code = typeof err === 'object' && err !== null && 'code' in err ? String(err.code) : '';
|
|
161
|
+
if (code === 'EEXIST') {
|
|
162
|
+
const raced = fs.readFileSync(resolved);
|
|
163
|
+
if (raced.length === VAULT_KEY_BYTES) return raced;
|
|
164
|
+
}
|
|
165
|
+
throw err;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Encrypts a plaintext secret using AES-256-GCM with a NIST-standard 12-byte IV.
|
|
171
|
+
*/
|
|
172
|
+
export function encryptVaultSecret(text: string, keyFilePath: string): string {
|
|
173
|
+
if (!text) return text;
|
|
174
|
+
if (isEncryptedVaultSecret(text)) return text;
|
|
175
|
+
const key = getOrCreateVaultKey(keyFilePath);
|
|
176
|
+
const iv = crypto.randomBytes(VAULT_GCM_IV_BYTES);
|
|
177
|
+
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
|
|
178
|
+
let encrypted = cipher.update(text, 'utf8', 'hex');
|
|
179
|
+
encrypted += cipher.final('hex');
|
|
180
|
+
const authTag = cipher.getAuthTag().toString('hex');
|
|
181
|
+
return `${VAULT_ENC_PREFIX}${iv.toString('hex')}:${authTag}:${encrypted}`;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Decrypts an `ENC:` secret produced with either the standard 12-byte GCM IV
|
|
186
|
+
* or legacy 16-byte GCM IV. Returns empty string on authentication failure.
|
|
187
|
+
*/
|
|
188
|
+
export function decryptVaultSecret(encryptedText: string, keyFilePath: string): string {
|
|
189
|
+
if (!encryptedText || !isEncryptedVaultSecret(encryptedText)) return encryptedText;
|
|
190
|
+
try {
|
|
191
|
+
const parts = encryptedText.split(':');
|
|
192
|
+
if (parts.length !== 4) return '';
|
|
193
|
+
const ivHex = parts[1] ?? '';
|
|
194
|
+
const authTagHex = parts[2] ?? '';
|
|
195
|
+
const ciphertextHex = parts[3] ?? '';
|
|
196
|
+
const iv = Buffer.from(ivHex, 'hex');
|
|
197
|
+
const authTag = Buffer.from(authTagHex, 'hex');
|
|
198
|
+
if (
|
|
199
|
+
(iv.length !== VAULT_GCM_IV_BYTES && iv.length !== VAULT_LEGACY_GCM_IV_BYTES) ||
|
|
200
|
+
authTag.length !== VAULT_GCM_AUTH_TAG_BYTES
|
|
201
|
+
) {
|
|
202
|
+
return '';
|
|
203
|
+
}
|
|
204
|
+
const key = getOrCreateVaultKey(keyFilePath);
|
|
205
|
+
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
|
|
206
|
+
decipher.setAuthTag(authTag);
|
|
207
|
+
let decrypted = decipher.update(ciphertextHex, 'hex', 'utf8');
|
|
208
|
+
decrypted += decipher.final('utf8');
|
|
209
|
+
return decrypted;
|
|
210
|
+
} catch {
|
|
211
|
+
return '';
|
|
212
|
+
}
|
|
213
|
+
}
|
|
@@ -12,11 +12,50 @@
|
|
|
12
12
|
*/
|
|
13
13
|
import { pruneStaleToolObservations, shortenOversizedToolObservations, pruneExecutedToolArguments, buildRecoverableDroppedSummary } from '../historyPruner.js';
|
|
14
14
|
import { compactInPlace, measureMessages, CHARS_PER_TOKEN } from '../contextManager.js';
|
|
15
|
+
/**
|
|
16
|
+
* Adjusts a candidate compaction split index so compaction NEVER severs a
|
|
17
|
+
* `role: 'tool'` result from its preceding `role: 'assistant'` `tool_calls`
|
|
18
|
+
* message (which would cause HTTP 400 invalid tool-turn errors on OpenAI,
|
|
19
|
+
* Anthropic, and Gemini).
|
|
20
|
+
*
|
|
21
|
+
* Returns a safe `splitIndex` in `[1, messages.length - 2]`, or `-1` if no
|
|
22
|
+
* safe split exists.
|
|
23
|
+
*/
|
|
24
|
+
export function findSafeCompactionSplitIndex(messages, targetSplitIndex) {
|
|
25
|
+
const maxSplit = messages.length - 2;
|
|
26
|
+
if (maxSplit < 1)
|
|
27
|
+
return -1;
|
|
28
|
+
let split = Math.min(Math.max(1, targetSplitIndex), maxSplit);
|
|
29
|
+
// If the first retained message (`split + 1`) is a `tool` result, walk back
|
|
30
|
+
// until the owning `assistant` message with `tool_calls` is also retained.
|
|
31
|
+
if (messages[split + 1]?.role === 'tool') {
|
|
32
|
+
let back = split;
|
|
33
|
+
while (back >= 1 && messages[back + 1]?.role === 'tool') {
|
|
34
|
+
back -= 1;
|
|
35
|
+
}
|
|
36
|
+
// Also retain the owning `assistant` message if `back + 1` was still `tool`
|
|
37
|
+
if (back >= 1 && messages[back]?.role === 'assistant' && Array.isArray(messages[back]?.tool_calls)) {
|
|
38
|
+
back -= 1;
|
|
39
|
+
}
|
|
40
|
+
if (back >= 1 && messages[back + 1]?.role !== 'tool') {
|
|
41
|
+
return back;
|
|
42
|
+
}
|
|
43
|
+
// Otherwise walk forward past the contiguous `tool` results while keeping at least 1 recent message
|
|
44
|
+
let forward = split;
|
|
45
|
+
while (forward < maxSplit && messages[forward + 1]?.role === 'tool') {
|
|
46
|
+
forward += 1;
|
|
47
|
+
}
|
|
48
|
+
if (forward <= maxSplit && messages[forward + 1]?.role !== 'tool') {
|
|
49
|
+
return forward;
|
|
50
|
+
}
|
|
51
|
+
return -1;
|
|
52
|
+
}
|
|
53
|
+
return split;
|
|
54
|
+
}
|
|
15
55
|
/**
|
|
16
56
|
* Extracts a high-fidelity, structured state summary from dropped message history.
|
|
17
|
-
* Mirrors the state preservation architecture of OpenAI Codex and Claude Code.
|
|
18
57
|
*/
|
|
19
|
-
export function buildCodexStyleSummary(droppedMessages, originalPrompt) {
|
|
58
|
+
export function buildCodexStyleSummary(droppedMessages, originalPrompt, extra) {
|
|
20
59
|
const createdFiles = new Set();
|
|
21
60
|
const modifiedFiles = new Set();
|
|
22
61
|
const inspectedFiles = new Set();
|
|
@@ -35,12 +74,12 @@ export function buildCodexStyleSummary(droppedMessages, originalPrompt) {
|
|
|
35
74
|
if (typeof rawArgs === 'string') {
|
|
36
75
|
const parsed = JSON.parse(rawArgs);
|
|
37
76
|
if (parsed && typeof parsed === 'object') {
|
|
38
|
-
const target = String(parsed.path || parsed.file_path || parsed.target || '');
|
|
77
|
+
const target = String(parsed.path || parsed.file_path || parsed.target || parsed.destination || '');
|
|
39
78
|
if (target) {
|
|
40
79
|
if (['fs_write', 'write_to_file', 'writeFile'].includes(fnName)) {
|
|
41
80
|
createdFiles.add(target);
|
|
42
81
|
}
|
|
43
|
-
else if (['fs_edit', 'replace_file_content', 'multi_replace_file_content'].includes(fnName)) {
|
|
82
|
+
else if (['fs_edit', 'MultiEdit', 'multi_edit', 'fs_move', 'replace_file_content', 'multi_replace_file_content'].includes(fnName)) {
|
|
44
83
|
modifiedFiles.add(target);
|
|
45
84
|
}
|
|
46
85
|
else if (['fs_read', 'view_file', 'readFile'].includes(fnName)) {
|
|
@@ -124,6 +163,21 @@ export function buildCodexStyleSummary(droppedMessages, originalPrompt) {
|
|
|
124
163
|
if (failures.size > 0) {
|
|
125
164
|
sections.push(`**Prior Failures Handled:** ${[...failures].slice(0, 4).join(' | ')}`);
|
|
126
165
|
}
|
|
166
|
+
if (Array.isArray(extra?.activePlan) && extra.activePlan.length > 0) {
|
|
167
|
+
const planLines = extra.activePlan
|
|
168
|
+
.slice(0, 12)
|
|
169
|
+
.map(item => {
|
|
170
|
+
const label = String(item.step || item.title || '').trim();
|
|
171
|
+
if (!label)
|
|
172
|
+
return '';
|
|
173
|
+
const status = String(item.status || 'pending').trim();
|
|
174
|
+
return `- [${status}] ${label}`;
|
|
175
|
+
})
|
|
176
|
+
.filter(Boolean);
|
|
177
|
+
if (planLines.length > 0) {
|
|
178
|
+
sections.push(`**Active Implementation Plan:**\n${planLines.join('\n')}`);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
127
181
|
sections.push('**Directive for Continuation:** Completed workspace files and session artifacts on disk are preserved. '
|
|
128
182
|
+ 'Do not re-scan or repeat verified setup steps. Continue forward execution and complete the remaining requirements.');
|
|
129
183
|
return sections.join('\n\n');
|
|
@@ -162,9 +216,10 @@ export function compactSessionMessages(messages, options = {}) {
|
|
|
162
216
|
threshold: 1500,
|
|
163
217
|
taskId: options.taskId ?? 'compaction'
|
|
164
218
|
});
|
|
165
|
-
// Calculate split index for physical compaction:
|
|
219
|
+
// Calculate turn-boundary-safe split index for physical compaction:
|
|
166
220
|
// Messages from index 1 to splitIndex will be collapsed into a single summary
|
|
167
|
-
|
|
221
|
+
// without ever orphaning a `role: 'tool'` result from its `assistant` `tool_calls`.
|
|
222
|
+
const splitIndex = findSafeCompactionSplitIndex(messages, messages.length - keepRecentTurns - 1);
|
|
168
223
|
if (splitIndex < 1) {
|
|
169
224
|
return {
|
|
170
225
|
compacted: false,
|
|
@@ -174,14 +229,16 @@ export function compactSessionMessages(messages, options = {}) {
|
|
|
174
229
|
initialChars,
|
|
175
230
|
finalChars: measureMessages(messages),
|
|
176
231
|
summaryText: '',
|
|
177
|
-
reason: 'Split index out of range.'
|
|
232
|
+
reason: 'Split index out of range or would break an active tool-call turn.'
|
|
178
233
|
};
|
|
179
234
|
}
|
|
180
235
|
const dropped = messages.slice(1, splitIndex + 1);
|
|
181
236
|
const rootPrompt = typeof messages[0]?.content === 'string'
|
|
182
237
|
? messages[0].content
|
|
183
238
|
: options.originalPrompt;
|
|
184
|
-
const structuredSummary = buildCodexStyleSummary(dropped, rootPrompt
|
|
239
|
+
const structuredSummary = buildCodexStyleSummary(dropped, rootPrompt, {
|
|
240
|
+
activePlan: options.activePlan
|
|
241
|
+
});
|
|
185
242
|
const fullRecoverableSummary = buildRecoverableDroppedSummary(dropped, structuredSummary);
|
|
186
243
|
const removed = compactInPlace(messages, splitIndex, fullRecoverableSummary);
|
|
187
244
|
const finalChars = measureMessages(messages);
|
|
@@ -212,7 +269,8 @@ export function autoCompactIfUnderPressure(loop, options = {}) {
|
|
|
212
269
|
const result = compactSessionMessages(loop.messages, {
|
|
213
270
|
keepRecentTurns: 4,
|
|
214
271
|
taskId: loop.taskId,
|
|
215
|
-
originalPrompt: loop.currentTaskPrompt || loop.userPrompt
|
|
272
|
+
originalPrompt: loop.currentTaskPrompt || loop.userPrompt,
|
|
273
|
+
activePlan: Array.isArray(loop._implementationPlan) ? loop._implementationPlan : undefined
|
|
216
274
|
});
|
|
217
275
|
if (result.compacted) {
|
|
218
276
|
if (loop.memoryManager && typeof loop.memoryManager.saveHistory === 'function') {
|
|
@@ -249,7 +307,8 @@ export async function runCompactSlashCommand(_argv, ctx) {
|
|
|
249
307
|
const result = compactSessionMessages(loop.messages, {
|
|
250
308
|
keepRecentTurns: 4,
|
|
251
309
|
taskId: loop.taskId || 'manual-compact',
|
|
252
|
-
originalPrompt: loop.currentTaskPrompt || loop.userPrompt
|
|
310
|
+
originalPrompt: loop.currentTaskPrompt || loop.userPrompt,
|
|
311
|
+
activePlan: Array.isArray(loop._implementationPlan) ? loop._implementationPlan : undefined
|
|
253
312
|
});
|
|
254
313
|
if (!result.compacted) {
|
|
255
314
|
return {
|
|
@@ -263,7 +322,7 @@ export async function runCompactSlashCommand(_argv, ctx) {
|
|
|
263
322
|
const reclaimedKb = (result.reclaimedChars / 1024).toFixed(1);
|
|
264
323
|
const finalKb = (result.finalChars / 1024).toFixed(1);
|
|
265
324
|
const report = [
|
|
266
|
-
'✔ Context successfully compacted (
|
|
325
|
+
'✔ Context successfully compacted (Causyne structured state model).',
|
|
267
326
|
'',
|
|
268
327
|
` • Earlier messages condensed: ${result.removedCount}`,
|
|
269
328
|
` • Memory reclaimed: ${reclaimedKb} KB (~${result.reclaimedTokens.toLocaleString()} tokens)`,
|